repo
string
commit
string
message
string
diff
string
msparks/arduino-ds1302
f41c40c14afcf47d53d77606481ac96595a71623
Remove individual component read and write support for safety.
diff --git a/DS1302.cpp b/DS1302.cpp index fdaf025..5a2e8d5 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,236 +1,177 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" namespace { // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } uint8_t hourFromRegisterValue(const uint8_t value) { uint8_t adj; if (value & 128) // 12-hour mode adj = 12 * ((value & 32) >> 5); else // 24-hour mode adj = 10 * ((value & (32 + 16)) >> 4); return (value & 15) + adj; } } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } void DS1302::registerDecToBcd(const Register reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = readRegister(reg); // Convert value to bcd in place. value = decToBcd(value); // Replace high bits of register if needed. value &= mask; value |= (regv &= ~mask); writeRegister(reg, value); } void DS1302::registerDecToBcd(const Register reg, const uint8_t value) { registerDecToBcd(reg, value, 7); } uint8_t DS1302::readRegister(const Register reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const Register reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } -uint8_t DS1302::seconds() { - // Bit 7 is the Clock Halt (CH) flag. Remove it before decoding. - return bcdToDec(readRegister(kSecondReg) & 0x7F); -} - -uint8_t DS1302::minutes() { - return bcdToDec(readRegister(kMinuteReg)); -} - -uint8_t DS1302::hour() { - return hourFromRegisterValue(readRegister(kHourReg)); -} - -uint8_t DS1302::date() { - return bcdToDec(readRegister(kDateReg)); -} - -uint8_t DS1302::month() { - return bcdToDec(readRegister(kMonthReg)); -} - -Time::Day DS1302::day() { - return static_cast<Time::Day>(bcdToDec(readRegister(kDayReg))); -} - -uint16_t DS1302::year() { - return 2000 + bcdToDec(readRegister(kYearReg)); -} - Time DS1302::time() { Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); const uint8_t cmd_byte = 0xBF; // Clock burst read. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); t.sec = bcdToDec(readIn() & 0x7F); t.min = bcdToDec(readIn()); t.hr = hourFromRegisterValue(readIn()); t.date = bcdToDec(readIn()); t.mon = bcdToDec(readIn()); t.day = static_cast<Time::Day>(bcdToDec(readIn())); t.yr = 2000 + bcdToDec(readIn()); digitalWrite(ce_pin_, LOW); return t; } -void DS1302::seconds(const uint8_t sec) { - registerDecToBcd(kSecondReg, sec, 6); -} - -void DS1302::minutes(const uint8_t min) { - registerDecToBcd(kMinuteReg, min, 6); -} - -void DS1302::hour(const uint8_t hr) { - writeRegister(kHourReg, 0); // set 24-hour mode - registerDecToBcd(kHourReg, hr, 5); -} - -void DS1302::date(const uint8_t date) { - registerDecToBcd(kDateReg, date, 5); -} - -void DS1302::month(const uint8_t mon) { - registerDecToBcd(kMonthReg, mon, 4); -} - -void DS1302::day(const Time::Day day) { - registerDecToBcd(kDayReg, static_cast<int>(day), 2); -} - -void DS1302::year(uint16_t yr) { - yr -= 2000; - registerDecToBcd(kYearReg, yr); -} - void DS1302::time(const Time t) { // We want to maintain the Clock Halt flag if it is set. const uint8_t ch_value = readRegister(kSecondReg) & 0x80; const uint8_t cmd_byte = 0xBE; // Clock burst write. digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(ch_value | decToBcd(t.sec)); writeOut(decToBcd(t.min)); writeOut(decToBcd(t.hr)); writeOut(decToBcd(t.date)); writeOut(decToBcd(t.mon)); writeOut(decToBcd(static_cast<uint8_t>(t.day))); writeOut(decToBcd(t.yr - 2000)); writeOut(0); // Write protection register. digitalWrite(ce_pin_, LOW); } diff --git a/DS1302.h b/DS1302.h index 10af525..9c1cdb1 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,160 +1,144 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; - -// Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. +// An interface to the Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. +// +// Accessing and setting individual components of the time are not supported in +// this interface as doing so can lead to errors if the time changes as it is +// being read or modified. Instead, using DS1302::time() guarantees safe reads +// and writes using the DS1302's burst mode feature. class DS1302 { public: enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(Register reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(Register reg, uint8_t value); // Enables or disables write protection on chip. // // Args: // enable: true to enable, false to disable. void writeProtect(bool enable); // Set or clear clock halt flag. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); - // Returns an individual piece of the time and date. - uint8_t seconds(); - uint8_t minutes(); - uint8_t hour(); - uint8_t date(); - uint8_t month(); - Time::Day day(); - uint16_t year(); - // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); - // Individually sets pieces of the date and time. - // - // The arguments here follow the rules specified above in Time::Time(...). - void seconds(uint8_t sec); - void minutes(uint8_t min); - void hour(uint8_t hr); - void date(uint8_t date); - void month(uint8_t mon); - void day(Time::Day day); - void year(uint16_t yr); - // Sets the time and date to the instant specified in a given Time object. // // Args: // t: Time object to use void time(Time t); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value void registerDecToBcd(Register reg, uint8_t value, uint8_t high_bit); void registerDecToBcd(Register reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
856e3cb1f82f8ea71582e5b3d6f1594347487a39
Implement clock/calendar burst read and write.
diff --git a/DS1302.cpp b/DS1302.cpp index e1c4758..fdaf025 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,208 +1,236 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" namespace { // Returns the decoded decimal value from a binary-coded decimal (BCD) byte. // Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in // the upper 4 MSBs. uint8_t bcdToDec(const uint8_t bcd) { return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); } // Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. uint8_t decToBcd(const uint8_t dec) { const uint8_t tens = dec / 10; const uint8_t ones = dec % 10; return (tens << 4) | ones; } +uint8_t hourFromRegisterValue(const uint8_t value) { + uint8_t adj; + if (value & 128) // 12-hour mode + adj = 12 * ((value & 32) >> 5); + else // 24-hour mode + adj = 10 * ((value & (32 + 16)) >> 4); + return (value & 15) + adj; +} + } // namespace Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } void DS1302::registerDecToBcd(const Register reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = readRegister(reg); // Convert value to bcd in place. value = decToBcd(value); // Replace high bits of register if needed. value &= mask; value |= (regv &= ~mask); writeRegister(reg, value); } void DS1302::registerDecToBcd(const Register reg, const uint8_t value) { registerDecToBcd(reg, value, 7); } uint8_t DS1302::readRegister(const Register reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const Register reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } uint8_t DS1302::seconds() { // Bit 7 is the Clock Halt (CH) flag. Remove it before decoding. return bcdToDec(readRegister(kSecondReg) & 0x7F); } uint8_t DS1302::minutes() { return bcdToDec(readRegister(kMinuteReg)); } uint8_t DS1302::hour() { - uint8_t hr = readRegister(kHourReg); - uint8_t adj; - if (hr & 128) // 12-hour mode - adj = 12 * ((hr & 32) >> 5); - else // 24-hour mode - adj = 10 * ((hr & (32 + 16)) >> 4); - hr = (hr & 15) + adj; - return hr; + return hourFromRegisterValue(readRegister(kHourReg)); } uint8_t DS1302::date() { return bcdToDec(readRegister(kDateReg)); } uint8_t DS1302::month() { return bcdToDec(readRegister(kMonthReg)); } Time::Day DS1302::day() { return static_cast<Time::Day>(bcdToDec(readRegister(kDayReg))); } uint16_t DS1302::year() { return 2000 + bcdToDec(readRegister(kYearReg)); } Time DS1302::time() { - return Time(year(), month(), date(), - hour(), minutes(), seconds(), - day()); + Time t(2099, 1, 1, 0, 0, 0, Time::kSunday); + + const uint8_t cmd_byte = 0xBF; // Clock burst read. + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); + writeOut(cmd_byte); + + t.sec = bcdToDec(readIn() & 0x7F); + t.min = bcdToDec(readIn()); + t.hr = hourFromRegisterValue(readIn()); + t.date = bcdToDec(readIn()); + t.mon = bcdToDec(readIn()); + t.day = static_cast<Time::Day>(bcdToDec(readIn())); + t.yr = 2000 + bcdToDec(readIn()); + + digitalWrite(ce_pin_, LOW); + + return t; } void DS1302::seconds(const uint8_t sec) { registerDecToBcd(kSecondReg, sec, 6); } void DS1302::minutes(const uint8_t min) { registerDecToBcd(kMinuteReg, min, 6); } void DS1302::hour(const uint8_t hr) { writeRegister(kHourReg, 0); // set 24-hour mode registerDecToBcd(kHourReg, hr, 5); } void DS1302::date(const uint8_t date) { registerDecToBcd(kDateReg, date, 5); } void DS1302::month(const uint8_t mon) { registerDecToBcd(kMonthReg, mon, 4); } void DS1302::day(const Time::Day day) { registerDecToBcd(kDayReg, static_cast<int>(day), 2); } void DS1302::year(uint16_t yr) { yr -= 2000; registerDecToBcd(kYearReg, yr); } void DS1302::time(const Time t) { - seconds(t.sec); - minutes(t.min); - hour(t.hr); - date(t.date); - month(t.mon); - day(t.day); - year(t.yr); + // We want to maintain the Clock Halt flag if it is set. + const uint8_t ch_value = readRegister(kSecondReg) & 0x80; + + const uint8_t cmd_byte = 0xBE; // Clock burst write. + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); + writeOut(cmd_byte); + + writeOut(ch_value | decToBcd(t.sec)); + writeOut(decToBcd(t.min)); + writeOut(decToBcd(t.hr)); + writeOut(decToBcd(t.date)); + writeOut(decToBcd(t.mon)); + writeOut(decToBcd(static_cast<uint8_t>(t.day))); + writeOut(decToBcd(t.yr - 2000)); + writeOut(0); // Write protection register. + + digitalWrite(ce_pin_, LOW); }
msparks/arduino-ds1302
34eae14f43d7c5d5b3a28459a023f173899ba0e6
Refactor: remove registerBcdToDec and use static helper functions.
diff --git a/DS1302.cpp b/DS1302.cpp index 12c7bad..e1c4758 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,204 +1,208 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" +namespace { + +// Returns the decoded decimal value from a binary-coded decimal (BCD) byte. +// Assumes 'bcd' is coded with 4-bits per digit, with the tens place digit in +// the upper 4 MSBs. +uint8_t bcdToDec(const uint8_t bcd) { + return (10 * ((bcd & 0xF0) >> 4) + (bcd & 0x0F)); +} + +// Returns the binary-coded decimal of 'dec'. Inverse of bcdToDec. +uint8_t decToBcd(const uint8_t dec) { + const uint8_t tens = dec / 10; + const uint8_t ones = dec % 10; + return (tens << 4) | ones; +} + +} // namespace + Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } - DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } -uint8_t DS1302::registerBcdToDec(const Register reg, const uint8_t high_bit) { - const uint8_t mask = (1 << (high_bit + 1)) - 1; - uint8_t val = readRegister(reg); - val &= mask; - val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); - return val; -} - -uint8_t DS1302::registerBcdToDec(const Register reg) { - return registerBcdToDec(reg, 7); -} - void DS1302::registerDecToBcd(const Register reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = readRegister(reg); // Convert value to bcd in place. - uint8_t tvalue = value / 10; - value = value % 10; - value |= (tvalue << 4); + value = decToBcd(value); - // Replace high bits of value if needed. + // Replace high bits of register if needed. value &= mask; value |= (regv &= ~mask); writeRegister(reg, value); } void DS1302::registerDecToBcd(const Register reg, const uint8_t value) { registerDecToBcd(reg, value, 7); } uint8_t DS1302::readRegister(const Register reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const Register reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } uint8_t DS1302::seconds() { - return registerBcdToDec(kSecondReg, 6); + // Bit 7 is the Clock Halt (CH) flag. Remove it before decoding. + return bcdToDec(readRegister(kSecondReg) & 0x7F); } uint8_t DS1302::minutes() { - return registerBcdToDec(kMinuteReg); + return bcdToDec(readRegister(kMinuteReg)); } uint8_t DS1302::hour() { uint8_t hr = readRegister(kHourReg); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { - return registerBcdToDec(kDateReg, 5); + return bcdToDec(readRegister(kDateReg)); } uint8_t DS1302::month() { - return registerBcdToDec(kMonthReg, 4); + return bcdToDec(readRegister(kMonthReg)); } Time::Day DS1302::day() { - return static_cast<Time::Day>(registerBcdToDec(kDayReg, 2)); + return static_cast<Time::Day>(bcdToDec(readRegister(kDayReg))); } uint16_t DS1302::year() { - return 2000 + registerBcdToDec(kYearReg); + return 2000 + bcdToDec(readRegister(kYearReg)); } Time DS1302::time() { return Time(year(), month(), date(), hour(), minutes(), seconds(), day()); } void DS1302::seconds(const uint8_t sec) { registerDecToBcd(kSecondReg, sec, 6); } void DS1302::minutes(const uint8_t min) { registerDecToBcd(kMinuteReg, min, 6); } void DS1302::hour(const uint8_t hr) { writeRegister(kHourReg, 0); // set 24-hour mode registerDecToBcd(kHourReg, hr, 5); } void DS1302::date(const uint8_t date) { registerDecToBcd(kDateReg, date, 5); } void DS1302::month(const uint8_t mon) { registerDecToBcd(kMonthReg, mon, 4); } void DS1302::day(const Time::Day day) { registerDecToBcd(kDayReg, static_cast<int>(day), 2); } void DS1302::year(uint16_t yr) { yr -= 2000; registerDecToBcd(kYearReg, yr); } void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); } diff --git a/DS1302.h b/DS1302.h index 830f1b5..10af525 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,171 +1,160 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. class DS1302 { public: enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(Register reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(Register reg, uint8_t value); // Enables or disables write protection on chip. // // Args: // enable: true to enable, false to disable. void writeProtect(bool enable); // Set or clear clock halt flag. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns an individual piece of the time and date. uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); Time::Day day(); uint16_t year(); // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Individually sets pieces of the date and time. // // The arguments here follow the rules specified above in Time::Time(...). void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(Time::Day day); void year(uint16_t yr); // Sets the time and date to the instant specified in a given Time object. // // Args: // t: Time object to use void time(Time t); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); - // Gets a binary-coded decimal register and returns it in decimal. - // - // Args: - // reg: register number - // high_bit: number of the bit containing the last BCD value ({0, ..., 7}) - // - // Returns: - // decimal value - uint8_t registerBcdToDec(Register reg, uint8_t high_bit); - uint8_t registerBcdToDec(Register reg); - // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value void registerDecToBcd(Register reg, uint8_t value, uint8_t high_bit); void registerDecToBcd(Register reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
56c90a6f86c6ca615e1f5a38ab8c2012275660b8
Mention crystal frequency.
diff --git a/examples/set_clock/README.md b/examples/set_clock/README.md index 21b05f6..864b366 100644 --- a/examples/set_clock/README.md +++ b/examples/set_clock/README.md @@ -1,6 +1,9 @@ # DS1302 library examples Try the `set_clock.ino` sketch to understand how to use the DS1302 library. The hardware configuration for the sketch is as follows: ![set_clock.ino hardware configuration.](set_clock_bb.png) + +The crystal oscillator connected between pins 2 and 3 of the DS1302 must be +32.768KHz.
msparks/arduino-ds1302
5af7cab97083215b8232abcb8f49f5615cfafe63
Linkify the set_clock example.
diff --git a/README.md b/README.md index 1e80b78..3777071 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ # DS1302 RTC library for Arduino This project is a library for the [Arduino](http://arduino.cc) platform. It provides a simple interface to the [Maxim DS1302](http://www.maxim-ic.com/quick_view2.cfm/qv_pk/2685/t/al) timekeeping chip. It allows Arduino projects to keep accurate time easily. ## Installing Place the `DS1302` directory in the `libraries` subdirectory of your Arduino sketch directory. On OS X, for example, your sketch directory might be: /Users/you/Documents/Arduino In that case, you should put the `DS1302` directory at: /Users/you/Documents/Arduino/libraries/DS1302 -A simple example is included with the code. +A simple example, [set_clock](examples/set_clock), is included.
msparks/arduino-ds1302
c8d3756bbb4aecdd21415047e76fd8833e3919dd
Add breadboard configuration for sketch.
diff --git a/examples/set_clock/README.md b/examples/set_clock/README.md new file mode 100644 index 0000000..21b05f6 --- /dev/null +++ b/examples/set_clock/README.md @@ -0,0 +1,6 @@ +# DS1302 library examples + +Try the `set_clock.ino` sketch to understand how to use the DS1302 library. The +hardware configuration for the sketch is as follows: + +![set_clock.ino hardware configuration.](set_clock_bb.png) diff --git a/examples/set_clock/set_clock.fzz b/examples/set_clock/set_clock.fzz new file mode 100644 index 0000000..bd58765 Binary files /dev/null and b/examples/set_clock/set_clock.fzz differ diff --git a/examples/set_clock/set_clock_bb.png b/examples/set_clock/set_clock_bb.png new file mode 100644 index 0000000..113ebfa Binary files /dev/null and b/examples/set_clock/set_clock_bb.png differ
msparks/arduino-ds1302
b9137f246c3bbe1844a112791cc47590bd8f4d77
Whitespace.
diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index 3b28751..cf7bfad 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,78 +1,78 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <DS1302.h> namespace { // Set the appropriate digital I/O pin connections. These are the pin // assignments for the Arduino as well for as the DS1302 chip. See the DS1302 // datasheet: // -// http://datasheets.maximintegrated.com/en/ds/DS1302.pdf +// http://datasheets.maximintegrated.com/en/ds/DS1302.pdf const int kCePin = 5; // Chip Enable const int kIoPin = 6; // Input/Output const int kSclkPin = 7; // Serial Clock // Create a DS1302 object. DS1302 rtc(kCePin, kIoPin, kSclkPin); String dayAsString(const Time::Day day) { switch (day) { case Time::kSunday: return "Sunday"; case Time::kMonday: return "Monday"; case Time::kTuesday: return "Tuesday"; case Time::kWednesday: return "Wednesday"; case Time::kThursday: return "Thursday"; case Time::kFriday: return "Friday"; case Time::kSaturday: return "Saturday"; } return "(unknown day)"; } void printTime() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. const String day = dayAsString(t.day); // Format the time and date and insert into the temporary buffer. char buf[50]; snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } } // namespace void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. rtc.writeProtect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, Time::kSunday); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. void loop() { printTime(); delay(1000); }
msparks/arduino-ds1302
5f1693015756b249b29d8ab53f4c683bdabb3208
Remove default constructor for Time.
diff --git a/DS1302.cpp b/DS1302.cpp index ca60072..12c7bad 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,214 +1,204 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } -Time::Time() { - Time(2000, 1, 1, 0, 0, 0, kSaturday); -} - DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } uint8_t DS1302::registerBcdToDec(const Register reg, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t val = readRegister(reg); val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } uint8_t DS1302::registerBcdToDec(const Register reg) { return registerBcdToDec(reg, 7); } void DS1302::registerDecToBcd(const Register reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = readRegister(reg); // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); writeRegister(reg, value); } void DS1302::registerDecToBcd(const Register reg, const uint8_t value) { registerDecToBcd(reg, value, 7); } uint8_t DS1302::readRegister(const Register reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } void DS1302::writeRegister(const Register reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); writeRegister(kSecondReg, sec); } uint8_t DS1302::seconds() { return registerBcdToDec(kSecondReg, 6); } uint8_t DS1302::minutes() { return registerBcdToDec(kMinuteReg); } uint8_t DS1302::hour() { uint8_t hr = readRegister(kHourReg); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { return registerBcdToDec(kDateReg, 5); } uint8_t DS1302::month() { return registerBcdToDec(kMonthReg, 4); } Time::Day DS1302::day() { return static_cast<Time::Day>(registerBcdToDec(kDayReg, 2)); } uint16_t DS1302::year() { return 2000 + registerBcdToDec(kYearReg); } Time DS1302::time() { - Time t; - t.sec = seconds(); - t.min = minutes(); - t.hr = hour(); - t.date = date(); - t.mon = month(); - t.day = day(); - t.yr = year(); - return t; + return Time(year(), month(), date(), + hour(), minutes(), seconds(), + day()); } void DS1302::seconds(const uint8_t sec) { registerDecToBcd(kSecondReg, sec, 6); } void DS1302::minutes(const uint8_t min) { registerDecToBcd(kMinuteReg, min, 6); } void DS1302::hour(const uint8_t hr) { writeRegister(kHourReg, 0); // set 24-hour mode registerDecToBcd(kHourReg, hr, 5); } void DS1302::date(const uint8_t date) { registerDecToBcd(kDateReg, date, 5); } void DS1302::month(const uint8_t mon) { registerDecToBcd(kMonthReg, mon, 4); } void DS1302::day(const Time::Day day) { registerDecToBcd(kDayReg, static_cast<int>(day), 2); } void DS1302::year(uint16_t yr) { yr -= 2000; registerDecToBcd(kYearReg, yr); } void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); } diff --git a/DS1302.h b/DS1302.h index f8f35c3..830f1b5 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,175 +1,171 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; - // Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. - // The date and time can be changed by editing the instance variables. - Time(); - // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. class DS1302 { public: enum Register { kSecondReg = 0, kMinuteReg = 1, kHourReg = 2, kDateReg = 3, kMonthReg = 4, kDayReg = 5, kYearReg = 6, kWriteProtectReg = 7 }; // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t readRegister(Register reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void writeRegister(Register reg, uint8_t value); // Enables or disables write protection on chip. // // Args: // enable: true to enable, false to disable. void writeProtect(bool enable); // Set or clear clock halt flag. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns an individual piece of the time and date. uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); Time::Day day(); uint16_t year(); - // Get the current time and date in a Time object. + // Returns the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Individually sets pieces of the date and time. // // The arguments here follow the rules specified above in Time::Time(...). void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(Time::Day day); void year(uint16_t yr); // Sets the time and date to the instant specified in a given Time object. // // Args: // t: Time object to use void time(Time t); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); // Gets a binary-coded decimal register and returns it in decimal. // // Args: // reg: register number // high_bit: number of the bit containing the last BCD value ({0, ..., 7}) // // Returns: // decimal value uint8_t registerBcdToDec(Register reg, uint8_t high_bit); uint8_t registerBcdToDec(Register reg); // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value void registerDecToBcd(Register reg, uint8_t value, uint8_t high_bit); void registerDecToBcd(Register reg, uint8_t value); }; #endif // DS1302_H_ diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index 815f33d..3b28751 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,74 +1,78 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <DS1302.h> +namespace { + // Set the appropriate digital I/O pin connections. These are the pin // assignments for the Arduino as well for as the DS1302 chip. See the DS1302 // datasheet: // // http://datasheets.maximintegrated.com/en/ds/DS1302.pdf -static const int kCePin = 5; // Chip Enable -static const int kIoPin = 6; // Input/Output -static const int kSclkPin = 7; // Serial Clock +const int kCePin = 5; // Chip Enable +const int kIoPin = 6; // Input/Output +const int kSclkPin = 7; // Serial Clock // Create a DS1302 object. -static DS1302 rtc(kCePin, kIoPin, kSclkPin); +DS1302 rtc(kCePin, kIoPin, kSclkPin); String dayAsString(const Time::Day day) { switch (day) { case Time::kSunday: return "Sunday"; case Time::kMonday: return "Monday"; case Time::kTuesday: return "Tuesday"; case Time::kWednesday: return "Wednesday"; case Time::kThursday: return "Thursday"; case Time::kFriday: return "Friday"; case Time::kSaturday: return "Saturday"; } return "(unknown day)"; } -void print_time() { +void printTime() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. const String day = dayAsString(t.day); // Format the time and date and insert into the temporary buffer. char buf[50]; snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } +} // namespace + void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. rtc.writeProtect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, Time::kSunday); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. void loop() { - print_time(); + printTime(); delay(1000); }
msparks/arduino-ds1302
3dcaaa269b0c58756f4463067a1a46326034254f
Registers as enum values.
diff --git a/DS1302.cpp b/DS1302.cpp index 19055f9..ca60072 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,214 +1,214 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } Time::Time() { Time(2000, 1, 1, 0, 0, 0, kSaturday); } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { ce_pin_ = ce_pin; io_pin_ = io_pin; sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::writeOut(const uint8_t value) { pinMode(io_pin_, OUTPUT); shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(io_pin_); input_value |= (bit << i); digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); digitalWrite(sclk_pin_, LOW); } return input_value; } -uint8_t DS1302::registerBcdToDec(const reg_t reg, const uint8_t high_bit) { +uint8_t DS1302::registerBcdToDec(const Register reg, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t val = readRegister(reg); val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } -uint8_t DS1302::registerBcdToDec(const reg_t reg) { +uint8_t DS1302::registerBcdToDec(const Register reg) { return registerBcdToDec(reg, 7); } -void DS1302::registerDecToBcd(const reg_t reg, uint8_t value, - const uint8_t high_bit) { +void DS1302::registerDecToBcd(const Register reg, uint8_t value, + const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = readRegister(reg); // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); writeRegister(reg, value); } -void DS1302::registerDecToBcd(const reg_t reg, const uint8_t value) { +void DS1302::registerDecToBcd(const Register reg, const uint8_t value) { registerDecToBcd(reg, value, 7); } -uint8_t DS1302::readRegister(const reg_t reg) { +uint8_t DS1302::readRegister(const Register reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); reg_value = readIn(); digitalWrite(ce_pin_, LOW); return reg_value; } -void DS1302::writeRegister(const reg_t reg, const uint8_t value) { +void DS1302::writeRegister(const Register reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(sclk_pin_, LOW); digitalWrite(ce_pin_, HIGH); writeOut(cmd_byte); writeOut(value); digitalWrite(ce_pin_, LOW); } void DS1302::writeProtect(const bool enable) { - writeRegister(WP_REG, (enable << 7)); + writeRegister(kWriteProtectReg, (enable << 7)); } void DS1302::halt(const bool enable) { - uint8_t sec = readRegister(SEC_REG); + uint8_t sec = readRegister(kSecondReg); sec &= ~(1 << 7); sec |= (enable << 7); - writeRegister(SEC_REG, sec); + writeRegister(kSecondReg, sec); } uint8_t DS1302::seconds() { - return registerBcdToDec(SEC_REG, 6); + return registerBcdToDec(kSecondReg, 6); } uint8_t DS1302::minutes() { - return registerBcdToDec(MIN_REG); + return registerBcdToDec(kMinuteReg); } uint8_t DS1302::hour() { - uint8_t hr = readRegister(HR_REG); + uint8_t hr = readRegister(kHourReg); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { - return registerBcdToDec(DATE_REG, 5); + return registerBcdToDec(kDateReg, 5); } uint8_t DS1302::month() { - return registerBcdToDec(MON_REG, 4); + return registerBcdToDec(kMonthReg, 4); } Time::Day DS1302::day() { - return static_cast<Time::Day>(registerBcdToDec(DAY_REG, 2)); + return static_cast<Time::Day>(registerBcdToDec(kDayReg, 2)); } uint16_t DS1302::year() { - return 2000 + registerBcdToDec(YR_REG); + return 2000 + registerBcdToDec(kYearReg); } Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } void DS1302::seconds(const uint8_t sec) { - registerDecToBcd(SEC_REG, sec, 6); + registerDecToBcd(kSecondReg, sec, 6); } void DS1302::minutes(const uint8_t min) { - registerDecToBcd(MIN_REG, min, 6); + registerDecToBcd(kMinuteReg, min, 6); } void DS1302::hour(const uint8_t hr) { - writeRegister(HR_REG, 0); // set 24-hour mode - registerDecToBcd(HR_REG, hr, 5); + writeRegister(kHourReg, 0); // set 24-hour mode + registerDecToBcd(kHourReg, hr, 5); } void DS1302::date(const uint8_t date) { - registerDecToBcd(DATE_REG, date, 5); + registerDecToBcd(kDateReg, date, 5); } void DS1302::month(const uint8_t mon) { - registerDecToBcd(MON_REG, mon, 4); + registerDecToBcd(kMonthReg, mon, 4); } void DS1302::day(const Time::Day day) { - registerDecToBcd(DAY_REG, static_cast<int>(day), 2); + registerDecToBcd(kDayReg, static_cast<int>(day), 2); } void DS1302::year(uint16_t yr) { yr -= 2000; - registerDecToBcd(YR_REG, yr); + registerDecToBcd(kYearReg, yr); } void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); } diff --git a/DS1302.h b/DS1302.h index dd2cc49..f8f35c3 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,177 +1,175 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ -// Convenience register constants. -#define SEC_REG 0 -#define MIN_REG 1 -#define HR_REG 2 -#define DATE_REG 3 -#define MON_REG 4 -#define DAY_REG 5 -#define YR_REG 6 -#define WP_REG 7 - -// Type for a register number. -typedef uint8_t reg_t; - // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. // The date and time can be changed by editing the instance variables. Time(); // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. class DS1302 { public: + enum Register { + kSecondReg = 0, + kMinuteReg = 1, + kHourReg = 2, + kDateReg = 3, + kMonthReg = 4, + kDayReg = 5, + kYearReg = 6, + kWriteProtectReg = 7 + }; + // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value - uint8_t readRegister(reg_t reg); + uint8_t readRegister(Register reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write - void writeRegister(reg_t reg, uint8_t value); + void writeRegister(Register reg, uint8_t value); // Enables or disables write protection on chip. // // Args: // enable: true to enable, false to disable. void writeProtect(bool enable); // Set or clear clock halt flag. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns an individual piece of the time and date. uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); Time::Day day(); uint16_t year(); // Get the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Individually sets pieces of the date and time. // // The arguments here follow the rules specified above in Time::Time(...). void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(Time::Day day); void year(uint16_t yr); // Sets the time and date to the instant specified in a given Time object. // // Args: // t: Time object to use void time(Time t); private: uint8_t ce_pin_; uint8_t io_pin_; uint8_t sclk_pin_; // Shifts out a value to the IO pin. // // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out void writeOut(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in uint8_t readIn(); // Gets a binary-coded decimal register and returns it in decimal. // // Args: // reg: register number // high_bit: number of the bit containing the last BCD value ({0, ..., 7}) // // Returns: // decimal value - uint8_t registerBcdToDec(reg_t reg, uint8_t high_bit); - uint8_t registerBcdToDec(reg_t reg); + uint8_t registerBcdToDec(Register reg, uint8_t high_bit); + uint8_t registerBcdToDec(Register reg); // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value - void registerDecToBcd(reg_t reg, uint8_t value, uint8_t high_bit); - void registerDecToBcd(reg_t reg, uint8_t value); + void registerDecToBcd(Register reg, uint8_t value, uint8_t high_bit); + void registerDecToBcd(Register reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
0c02e2f87f9357d6b5172d915a373c83836db604
Change function names and variable names to match Google C++ style.
diff --git a/DS1302.cpp b/DS1302.cpp index 0760a88..19055f9 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,214 +1,214 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } Time::Time() { Time(2000, 1, 1, 0, 0, 0, kSaturday); } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { - _ce_pin = ce_pin; - _io_pin = io_pin; - _sclk_pin = sclk_pin; + ce_pin_ = ce_pin; + io_pin_ = io_pin; + sclk_pin_ = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } -void DS1302::_write_out(const uint8_t value) { - pinMode(_io_pin, OUTPUT); - shiftOut(_io_pin, _sclk_pin, LSBFIRST, value); +void DS1302::writeOut(const uint8_t value) { + pinMode(io_pin_, OUTPUT); + shiftOut(io_pin_, sclk_pin_, LSBFIRST, value); } -uint8_t DS1302::_read_in() { +uint8_t DS1302::readIn() { uint8_t input_value = 0; uint8_t bit = 0; - pinMode(_io_pin, INPUT); + pinMode(io_pin_, INPUT); for (int i = 0; i < 8; ++i) { - bit = digitalRead(_io_pin); + bit = digitalRead(io_pin_); input_value |= (bit << i); - digitalWrite(_sclk_pin, HIGH); + digitalWrite(sclk_pin_, HIGH); delayMicroseconds(1); - digitalWrite(_sclk_pin, LOW); + digitalWrite(sclk_pin_, LOW); } return input_value; } -uint8_t DS1302::_register_bcd_to_dec(const reg_t reg, const uint8_t high_bit) { +uint8_t DS1302::registerBcdToDec(const reg_t reg, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; - uint8_t val = read_register(reg); + uint8_t val = readRegister(reg); val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } -uint8_t DS1302::_register_bcd_to_dec(const reg_t reg) { - return _register_bcd_to_dec(reg, 7); +uint8_t DS1302::registerBcdToDec(const reg_t reg) { + return registerBcdToDec(reg, 7); } -void DS1302::_register_dec_to_bcd(const reg_t reg, uint8_t value, +void DS1302::registerDecToBcd(const reg_t reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; - uint8_t regv = read_register(reg); + uint8_t regv = readRegister(reg); // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); - write_register(reg, value); + writeRegister(reg, value); } -void DS1302::_register_dec_to_bcd(const reg_t reg, const uint8_t value) { - _register_dec_to_bcd(reg, value, 7); +void DS1302::registerDecToBcd(const reg_t reg, const uint8_t value) { + registerDecToBcd(reg, value, 7); } -uint8_t DS1302::read_register(const reg_t reg) { +uint8_t DS1302::readRegister(const reg_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); - digitalWrite(_sclk_pin, LOW); - digitalWrite(_ce_pin, HIGH); + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); - _write_out(cmd_byte); - reg_value = _read_in(); + writeOut(cmd_byte); + reg_value = readIn(); - digitalWrite(_ce_pin, LOW); + digitalWrite(ce_pin_, LOW); return reg_value; } -void DS1302::write_register(const reg_t reg, const uint8_t value) { +void DS1302::writeRegister(const reg_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); - digitalWrite(_sclk_pin, LOW); - digitalWrite(_ce_pin, HIGH); + digitalWrite(sclk_pin_, LOW); + digitalWrite(ce_pin_, HIGH); - _write_out(cmd_byte); - _write_out(value); + writeOut(cmd_byte); + writeOut(value); - digitalWrite(_ce_pin, LOW); + digitalWrite(ce_pin_, LOW); } -void DS1302::write_protect(const bool enable) { - write_register(WP_REG, (enable << 7)); +void DS1302::writeProtect(const bool enable) { + writeRegister(WP_REG, (enable << 7)); } void DS1302::halt(const bool enable) { - uint8_t sec = read_register(SEC_REG); + uint8_t sec = readRegister(SEC_REG); sec &= ~(1 << 7); sec |= (enable << 7); - write_register(SEC_REG, sec); + writeRegister(SEC_REG, sec); } uint8_t DS1302::seconds() { - return _register_bcd_to_dec(SEC_REG, 6); + return registerBcdToDec(SEC_REG, 6); } uint8_t DS1302::minutes() { - return _register_bcd_to_dec(MIN_REG); + return registerBcdToDec(MIN_REG); } uint8_t DS1302::hour() { - uint8_t hr = read_register(HR_REG); + uint8_t hr = readRegister(HR_REG); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { - return _register_bcd_to_dec(DATE_REG, 5); + return registerBcdToDec(DATE_REG, 5); } uint8_t DS1302::month() { - return _register_bcd_to_dec(MON_REG, 4); + return registerBcdToDec(MON_REG, 4); } Time::Day DS1302::day() { - return static_cast<Time::Day>(_register_bcd_to_dec(DAY_REG, 2)); + return static_cast<Time::Day>(registerBcdToDec(DAY_REG, 2)); } uint16_t DS1302::year() { - return 2000 + _register_bcd_to_dec(YR_REG); + return 2000 + registerBcdToDec(YR_REG); } Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } void DS1302::seconds(const uint8_t sec) { - _register_dec_to_bcd(SEC_REG, sec, 6); + registerDecToBcd(SEC_REG, sec, 6); } void DS1302::minutes(const uint8_t min) { - _register_dec_to_bcd(MIN_REG, min, 6); + registerDecToBcd(MIN_REG, min, 6); } void DS1302::hour(const uint8_t hr) { - write_register(HR_REG, 0); // set 24-hour mode - _register_dec_to_bcd(HR_REG, hr, 5); + writeRegister(HR_REG, 0); // set 24-hour mode + registerDecToBcd(HR_REG, hr, 5); } void DS1302::date(const uint8_t date) { - _register_dec_to_bcd(DATE_REG, date, 5); + registerDecToBcd(DATE_REG, date, 5); } void DS1302::month(const uint8_t mon) { - _register_dec_to_bcd(MON_REG, mon, 4); + registerDecToBcd(MON_REG, mon, 4); } void DS1302::day(const Time::Day day) { - _register_dec_to_bcd(DAY_REG, static_cast<int>(day), 2); + registerDecToBcd(DAY_REG, static_cast<int>(day), 2); } void DS1302::year(uint16_t yr) { yr -= 2000; - _register_dec_to_bcd(YR_REG, yr); + registerDecToBcd(YR_REG, yr); } void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); } diff --git a/DS1302.h b/DS1302.h index c824ccf..dd2cc49 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,177 +1,177 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Convenience register constants. #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 // Type for a register number. typedef uint8_t reg_t; // Class representing a particular time and date. class Time { public: enum Day { kSunday = 1, kMonday = 2, kTuesday = 3, kWednesday = 4, kThursday = 5, kFriday = 6, kSaturday = 7 }; // Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. // The date and time can be changed by editing the instance variables. Time(); // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; Day day; uint16_t yr; }; // Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. class DS1302 { public: // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value - uint8_t read_register(reg_t reg); + uint8_t readRegister(reg_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write - void write_register(reg_t reg, uint8_t value); + void writeRegister(reg_t reg, uint8_t value); // Enables or disables write protection on chip. // // Args: // enable: true to enable, false to disable. - void write_protect(bool enable); + void writeProtect(bool enable); // Set or clear clock halt flag. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns an individual piece of the time and date. uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); Time::Day day(); uint16_t year(); // Get the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Individually sets pieces of the date and time. // // The arguments here follow the rules specified above in Time::Time(...). void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(Time::Day day); void year(uint16_t yr); // Sets the time and date to the instant specified in a given Time object. // // Args: // t: Time object to use void time(Time t); private: - uint8_t _ce_pin; - uint8_t _io_pin; - uint8_t _sclk_pin; + uint8_t ce_pin_; + uint8_t io_pin_; + uint8_t sclk_pin_; // Shifts out a value to the IO pin. // - // Side effects: sets _io_pin as OUTPUT. + // Side effects: sets io_pin_ as OUTPUT. // // Args: // value: byte to shift out - void _write_out(uint8_t value); + void writeOut(uint8_t value); // Reads in a byte from the IO pin. // - // Side effects: sets _io_pin to INPUT. + // Side effects: sets io_pin_ to INPUT. // // Returns: // byte read in - uint8_t _read_in(); + uint8_t readIn(); // Gets a binary-coded decimal register and returns it in decimal. // // Args: // reg: register number // high_bit: number of the bit containing the last BCD value ({0, ..., 7}) // // Returns: // decimal value - uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); - uint8_t _register_bcd_to_dec(reg_t reg); + uint8_t registerBcdToDec(reg_t reg, uint8_t high_bit); + uint8_t registerBcdToDec(reg_t reg); // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value - void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); - void _register_dec_to_bcd(reg_t reg, uint8_t value); + void registerDecToBcd(reg_t reg, uint8_t value, uint8_t high_bit); + void registerDecToBcd(reg_t reg, uint8_t value); }; #endif // DS1302_H_ diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index bef7f03..815f33d 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,74 +1,74 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <DS1302.h> // Set the appropriate digital I/O pin connections. These are the pin // assignments for the Arduino as well for as the DS1302 chip. See the DS1302 // datasheet: // // http://datasheets.maximintegrated.com/en/ds/DS1302.pdf static const int kCePin = 5; // Chip Enable static const int kIoPin = 6; // Input/Output static const int kSclkPin = 7; // Serial Clock // Create a DS1302 object. static DS1302 rtc(kCePin, kIoPin, kSclkPin); String dayAsString(const Time::Day day) { switch (day) { case Time::kSunday: return "Sunday"; case Time::kMonday: return "Monday"; case Time::kTuesday: return "Tuesday"; case Time::kWednesday: return "Wednesday"; case Time::kThursday: return "Thursday"; case Time::kFriday: return "Friday"; case Time::kSaturday: return "Saturday"; } return "(unknown day)"; } void print_time() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. const String day = dayAsString(t.day); // Format the time and date and insert into the temporary buffer. char buf[50]; snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. - rtc.write_protect(false); + rtc.writeProtect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, Time::kSunday); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
1c12b803ef6849ce6abc8a88de1435b401f786ed
C++-ify.
diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index 510b2e8..bef7f03 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,88 +1,74 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> -#include <string.h> #include <DS1302.h> // Set the appropriate digital I/O pin connections. These are the pin // assignments for the Arduino as well for as the DS1302 chip. See the DS1302 // datasheet: // // http://datasheets.maximintegrated.com/en/ds/DS1302.pdf static const int kCePin = 5; // Chip Enable static const int kIoPin = 6; // Input/Output static const int kSclkPin = 7; // Serial Clock -// Create buffers. -char buf[50]; -char day[10]; - // Create a DS1302 object. -DS1302 rtc(kCePin, kIoPin, kSclkPin); +static DS1302 rtc(kCePin, kIoPin, kSclkPin); + +String dayAsString(const Time::Day day) { + switch (day) { + case Time::kSunday: return "Sunday"; + case Time::kMonday: return "Monday"; + case Time::kTuesday: return "Tuesday"; + case Time::kWednesday: return "Wednesday"; + case Time::kThursday: return "Thursday"; + case Time::kFriday: return "Friday"; + case Time::kSaturday: return "Saturday"; + } + return "(unknown day)"; +} void print_time() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. - memset(day, 0, sizeof(day)); // clear day buffer - switch (t.day) { - case 1: - strcpy(day, "Sunday"); - break; - case 2: - strcpy(day, "Monday"); - break; - case 3: - strcpy(day, "Tuesday"); - break; - case 4: - strcpy(day, "Wednesday"); - break; - case 5: - strcpy(day, "Thursday"); - break; - case 6: - strcpy(day, "Friday"); - break; - case 7: - strcpy(day, "Saturday"); - break; - } + const String day = dayAsString(t.day); // Format the time and date and insert into the temporary buffer. + char buf[50]; snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", - day, + day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. rtc.write_protect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, Time::kSunday); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
2e1eb2c26164abba2fa1b1178786c43e5c10a624
Add Time::Day enum.
diff --git a/DS1302.cpp b/DS1302.cpp index 86217c9..0760a88 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,214 +1,214 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, - const uint8_t day) { + const Day day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } Time::Time() { - Time(2000, 1, 1, 0, 0, 0, 7); + Time(2000, 1, 1, 0, 0, 0, kSaturday); } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { _ce_pin = ce_pin; _io_pin = io_pin; _sclk_pin = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::_write_out(const uint8_t value) { pinMode(_io_pin, OUTPUT); shiftOut(_io_pin, _sclk_pin, LSBFIRST, value); } uint8_t DS1302::_read_in() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(_io_pin, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(_io_pin); input_value |= (bit << i); digitalWrite(_sclk_pin, HIGH); delayMicroseconds(1); digitalWrite(_sclk_pin, LOW); } return input_value; } uint8_t DS1302::_register_bcd_to_dec(const reg_t reg, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t val = read_register(reg); val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } uint8_t DS1302::_register_bcd_to_dec(const reg_t reg) { return _register_bcd_to_dec(reg, 7); } void DS1302::_register_dec_to_bcd(const reg_t reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = read_register(reg); // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); write_register(reg, value); } void DS1302::_register_dec_to_bcd(const reg_t reg, const uint8_t value) { _register_dec_to_bcd(reg, value, 7); } uint8_t DS1302::read_register(const reg_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); reg_value = _read_in(); digitalWrite(_ce_pin, LOW); return reg_value; } void DS1302::write_register(const reg_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); _write_out(value); digitalWrite(_ce_pin, LOW); } void DS1302::write_protect(const bool enable) { write_register(WP_REG, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = read_register(SEC_REG); sec &= ~(1 << 7); sec |= (enable << 7); write_register(SEC_REG, sec); } uint8_t DS1302::seconds() { return _register_bcd_to_dec(SEC_REG, 6); } uint8_t DS1302::minutes() { return _register_bcd_to_dec(MIN_REG); } uint8_t DS1302::hour() { uint8_t hr = read_register(HR_REG); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { return _register_bcd_to_dec(DATE_REG, 5); } uint8_t DS1302::month() { return _register_bcd_to_dec(MON_REG, 4); } -uint8_t DS1302::day() { - return _register_bcd_to_dec(DAY_REG, 2); +Time::Day DS1302::day() { + return static_cast<Time::Day>(_register_bcd_to_dec(DAY_REG, 2)); } uint16_t DS1302::year() { return 2000 + _register_bcd_to_dec(YR_REG); } Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } void DS1302::seconds(const uint8_t sec) { _register_dec_to_bcd(SEC_REG, sec, 6); } void DS1302::minutes(const uint8_t min) { _register_dec_to_bcd(MIN_REG, min, 6); } void DS1302::hour(const uint8_t hr) { write_register(HR_REG, 0); // set 24-hour mode _register_dec_to_bcd(HR_REG, hr, 5); } void DS1302::date(const uint8_t date) { _register_dec_to_bcd(DATE_REG, date, 5); } void DS1302::month(const uint8_t mon) { _register_dec_to_bcd(MON_REG, mon, 4); } -void DS1302::day(const uint8_t day) { - _register_dec_to_bcd(DAY_REG, day, 2); +void DS1302::day(const Time::Day day) { + _register_dec_to_bcd(DAY_REG, static_cast<int>(day), 2); } void DS1302::year(uint16_t yr) { yr -= 2000; _register_dec_to_bcd(YR_REG, yr); } void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); } diff --git a/DS1302.h b/DS1302.h index dd0f026..c824ccf 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,167 +1,177 @@ // Interface for the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ // Convenience register constants. #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 // Type for a register number. typedef uint8_t reg_t; // Class representing a particular time and date. class Time { public: + enum Day { + kSunday = 1, + kMonday = 2, + kTuesday = 3, + kWednesday = 4, + kThursday = 5, + kFriday = 6, + kSaturday = 7 + }; + // Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. // The date and time can be changed by editing the instance variables. Time(); // Creates a Time object with a given time. // // Args: // yr: year. Range: {2000, ..., 2099}. // mon: month. Range: {1, ..., 12}. // date: date (of the month). Range: {1, ..., 31}. // hr: hour. Range: {0, ..., 23}. // min: minutes. Range: {0, ..., 59}. // sec: seconds. Range: {0, ..., 59}. // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, - uint8_t day); + Day day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; - uint8_t day; + Day day; uint16_t yr; }; // Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. class DS1302 { public: // Prepares to interface with the chip on the given I/O pins. // // Args: // ce_pin: CE pin number // io_pin: IO pin number // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); // Reads register byte value. // // Args: // reg: register number // // Returns: // register value uint8_t read_register(reg_t reg); // Writes byte into register. // // Args: // reg: register number // value: byte to write void write_register(reg_t reg, uint8_t value); // Enables or disables write protection on chip. // // Args: // enable: true to enable, false to disable. void write_protect(bool enable); // Set or clear clock halt flag. // // Args: // value: true to set halt flag, false to clear. void halt(bool value); // Returns an individual piece of the time and date. uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); - uint8_t day(); + Time::Day day(); uint16_t year(); // Get the current time and date in a Time object. // // Returns: // Current time as Time object. Time time(); // Individually sets pieces of the date and time. // // The arguments here follow the rules specified above in Time::Time(...). void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); - void day(uint8_t day); + void day(Time::Day day); void year(uint16_t yr); // Sets the time and date to the instant specified in a given Time object. // // Args: // t: Time object to use void time(Time t); private: uint8_t _ce_pin; uint8_t _io_pin; uint8_t _sclk_pin; // Shifts out a value to the IO pin. // // Side effects: sets _io_pin as OUTPUT. // // Args: // value: byte to shift out void _write_out(uint8_t value); // Reads in a byte from the IO pin. // // Side effects: sets _io_pin to INPUT. // // Returns: // byte read in uint8_t _read_in(); // Gets a binary-coded decimal register and returns it in decimal. // // Args: // reg: register number // high_bit: number of the bit containing the last BCD value ({0, ..., 7}) // // Returns: // decimal value uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); uint8_t _register_bcd_to_dec(reg_t reg); // Sets a register with binary-coded decimal converted from a given value. // // Args: // reg: register number // value: decimal value to convert to BCD // high_bit: highest bit in the register allowed to contain BCD value void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); void _register_dec_to_bcd(reg_t reg, uint8_t value); }; #endif // DS1302_H_ diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index b1df4f1..510b2e8 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,88 +1,88 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <string.h> #include <DS1302.h> // Set the appropriate digital I/O pin connections. These are the pin // assignments for the Arduino as well for as the DS1302 chip. See the DS1302 // datasheet: // // http://datasheets.maximintegrated.com/en/ds/DS1302.pdf static const int kCePin = 5; // Chip Enable static const int kIoPin = 6; // Input/Output static const int kSclkPin = 7; // Serial Clock // Create buffers. char buf[50]; char day[10]; // Create a DS1302 object. DS1302 rtc(kCePin, kIoPin, kSclkPin); void print_time() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. memset(day, 0, sizeof(day)); // clear day buffer switch (t.day) { case 1: strcpy(day, "Sunday"); break; case 2: strcpy(day, "Monday"); break; case 3: strcpy(day, "Tuesday"); break; case 4: strcpy(day, "Wednesday"); break; case 5: strcpy(day, "Thursday"); break; case 6: strcpy(day, "Friday"); break; case 7: strcpy(day, "Saturday"); break; } // Format the time and date and insert into the temporary buffer. snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day, t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. rtc.write_protect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. - Time t(2013, 9, 22, 1, 38, 50, 1); + Time t(2013, 9, 22, 1, 38, 50, Time::kSunday); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
d198cbad28f7bd74248ed5a5f85143aebb8146c9
Whitespace.
diff --git a/DS1302.cpp b/DS1302.cpp index abf9bf6..86217c9 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,215 +1,214 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" - Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, const uint8_t hr, const uint8_t min, const uint8_t sec, const uint8_t day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } Time::Time() { Time(2000, 1, 1, 0, 0, 0, 7); } DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, const uint8_t sclk_pin) { _ce_pin = ce_pin; _io_pin = io_pin; _sclk_pin = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::_write_out(const uint8_t value) { pinMode(_io_pin, OUTPUT); shiftOut(_io_pin, _sclk_pin, LSBFIRST, value); } uint8_t DS1302::_read_in() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(_io_pin, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(_io_pin); input_value |= (bit << i); digitalWrite(_sclk_pin, HIGH); delayMicroseconds(1); digitalWrite(_sclk_pin, LOW); } return input_value; } uint8_t DS1302::_register_bcd_to_dec(const reg_t reg, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t val = read_register(reg); val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } uint8_t DS1302::_register_bcd_to_dec(const reg_t reg) { return _register_bcd_to_dec(reg, 7); } void DS1302::_register_dec_to_bcd(const reg_t reg, uint8_t value, const uint8_t high_bit) { const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = read_register(reg); // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); write_register(reg, value); } void DS1302::_register_dec_to_bcd(const reg_t reg, const uint8_t value) { _register_dec_to_bcd(reg, value, 7); } uint8_t DS1302::read_register(const reg_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); reg_value = _read_in(); digitalWrite(_ce_pin, LOW); return reg_value; } void DS1302::write_register(const reg_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); _write_out(value); digitalWrite(_ce_pin, LOW); } void DS1302::write_protect(const bool enable) { write_register(WP_REG, (enable << 7)); } void DS1302::halt(const bool enable) { uint8_t sec = read_register(SEC_REG); sec &= ~(1 << 7); sec |= (enable << 7); write_register(SEC_REG, sec); } uint8_t DS1302::seconds() { return _register_bcd_to_dec(SEC_REG, 6); } uint8_t DS1302::minutes() { return _register_bcd_to_dec(MIN_REG); } uint8_t DS1302::hour() { uint8_t hr = read_register(HR_REG); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { return _register_bcd_to_dec(DATE_REG, 5); } uint8_t DS1302::month() { return _register_bcd_to_dec(MON_REG, 4); } uint8_t DS1302::day() { return _register_bcd_to_dec(DAY_REG, 2); } uint16_t DS1302::year() { return 2000 + _register_bcd_to_dec(YR_REG); } Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } void DS1302::seconds(const uint8_t sec) { _register_dec_to_bcd(SEC_REG, sec, 6); } void DS1302::minutes(const uint8_t min) { _register_dec_to_bcd(MIN_REG, min, 6); } void DS1302::hour(const uint8_t hr) { write_register(HR_REG, 0); // set 24-hour mode _register_dec_to_bcd(HR_REG, hr, 5); } void DS1302::date(const uint8_t date) { _register_dec_to_bcd(DATE_REG, date, 5); } void DS1302::month(const uint8_t mon) { _register_dec_to_bcd(MON_REG, mon, 4); } void DS1302::day(const uint8_t day) { _register_dec_to_bcd(DAY_REG, day, 2); } void DS1302::year(uint16_t yr) { yr -= 2000; _register_dec_to_bcd(YR_REG, yr); } void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); }
msparks/arduino-ds1302
f82a94198e1c3074927eff16b4d715b802e1b2aa
Const.
diff --git a/DS1302.cpp b/DS1302.cpp index cfa7284..abf9bf6 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,213 +1,215 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" -Time::Time(uint16_t yr, uint8_t mon, uint8_t date, - uint8_t hr, uint8_t min, uint8_t sec, - uint8_t day) { +Time::Time(const uint16_t yr, const uint8_t mon, const uint8_t date, + const uint8_t hr, const uint8_t min, const uint8_t sec, + const uint8_t day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } Time::Time() { Time(2000, 1, 1, 0, 0, 0, 7); } -DS1302::DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin) { +DS1302::DS1302(const uint8_t ce_pin, const uint8_t io_pin, + const uint8_t sclk_pin) { _ce_pin = ce_pin; _io_pin = io_pin; _sclk_pin = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } -void DS1302::_write_out(uint8_t value) { +void DS1302::_write_out(const uint8_t value) { pinMode(_io_pin, OUTPUT); shiftOut(_io_pin, _sclk_pin, LSBFIRST, value); } uint8_t DS1302::_read_in() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(_io_pin, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(_io_pin); input_value |= (bit << i); digitalWrite(_sclk_pin, HIGH); delayMicroseconds(1); digitalWrite(_sclk_pin, LOW); } return input_value; } -uint8_t DS1302::_register_bcd_to_dec(reg_t reg, uint8_t high_bit) { +uint8_t DS1302::_register_bcd_to_dec(const reg_t reg, const uint8_t high_bit) { + const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t val = read_register(reg); - uint8_t mask = (1 << (high_bit + 1)) - 1; val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } -uint8_t DS1302::_register_bcd_to_dec(reg_t reg) { +uint8_t DS1302::_register_bcd_to_dec(const reg_t reg) { return _register_bcd_to_dec(reg, 7); } -void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit) { +void DS1302::_register_dec_to_bcd(const reg_t reg, uint8_t value, + const uint8_t high_bit) { + const uint8_t mask = (1 << (high_bit + 1)) - 1; uint8_t regv = read_register(reg); - uint8_t mask = (1 << (high_bit + 1)) - 1; // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); write_register(reg, value); } -void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value) { +void DS1302::_register_dec_to_bcd(const reg_t reg, const uint8_t value) { _register_dec_to_bcd(reg, value, 7); } -uint8_t DS1302::read_register(reg_t reg) { +uint8_t DS1302::read_register(const reg_t reg) { uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); reg_value = _read_in(); digitalWrite(_ce_pin, LOW); return reg_value; } -void DS1302::write_register(reg_t reg, uint8_t value) { +void DS1302::write_register(const reg_t reg, const uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); _write_out(value); digitalWrite(_ce_pin, LOW); } -void DS1302::write_protect(bool enable) { +void DS1302::write_protect(const bool enable) { write_register(WP_REG, (enable << 7)); } -void DS1302::halt(bool enable) { +void DS1302::halt(const bool enable) { uint8_t sec = read_register(SEC_REG); sec &= ~(1 << 7); sec |= (enable << 7); write_register(SEC_REG, sec); } uint8_t DS1302::seconds() { return _register_bcd_to_dec(SEC_REG, 6); } uint8_t DS1302::minutes() { return _register_bcd_to_dec(MIN_REG); } uint8_t DS1302::hour() { uint8_t hr = read_register(HR_REG); uint8_t adj; if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { return _register_bcd_to_dec(DATE_REG, 5); } uint8_t DS1302::month() { return _register_bcd_to_dec(MON_REG, 4); } uint8_t DS1302::day() { return _register_bcd_to_dec(DAY_REG, 2); } uint16_t DS1302::year() { return 2000 + _register_bcd_to_dec(YR_REG); } Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } -void DS1302::seconds(uint8_t sec) { +void DS1302::seconds(const uint8_t sec) { _register_dec_to_bcd(SEC_REG, sec, 6); } -void DS1302::minutes(uint8_t min) { +void DS1302::minutes(const uint8_t min) { _register_dec_to_bcd(MIN_REG, min, 6); } -void DS1302::hour(uint8_t hr) { +void DS1302::hour(const uint8_t hr) { write_register(HR_REG, 0); // set 24-hour mode _register_dec_to_bcd(HR_REG, hr, 5); } -void DS1302::date(uint8_t date) { +void DS1302::date(const uint8_t date) { _register_dec_to_bcd(DATE_REG, date, 5); } -void DS1302::month(uint8_t mon) { +void DS1302::month(const uint8_t mon) { _register_dec_to_bcd(MON_REG, mon, 4); } -void DS1302::day(uint8_t day) { +void DS1302::day(const uint8_t day) { _register_dec_to_bcd(DAY_REG, day, 2); } void DS1302::year(uint16_t yr) { yr -= 2000; _register_dec_to_bcd(YR_REG, yr); } -void DS1302::time(Time t) { +void DS1302::time(const Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); }
msparks/arduino-ds1302
7850616d1e49424fb4ec1952d572a8481cdd53b9
Comment style.
diff --git a/DS1302.cpp b/DS1302.cpp index 2d6a86d..cfa7284 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,213 +1,213 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" Time::Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, uint8_t day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } Time::Time() { Time(2000, 1, 1, 0, 0, 0, 7); } DS1302::DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin) { _ce_pin = ce_pin; _io_pin = io_pin; _sclk_pin = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } void DS1302::_write_out(uint8_t value) { pinMode(_io_pin, OUTPUT); shiftOut(_io_pin, _sclk_pin, LSBFIRST, value); } uint8_t DS1302::_read_in() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(_io_pin, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(_io_pin); input_value |= (bit << i); digitalWrite(_sclk_pin, HIGH); delayMicroseconds(1); digitalWrite(_sclk_pin, LOW); } return input_value; } uint8_t DS1302::_register_bcd_to_dec(reg_t reg, uint8_t high_bit) { uint8_t val = read_register(reg); uint8_t mask = (1 << (high_bit + 1)) - 1; val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } uint8_t DS1302::_register_bcd_to_dec(reg_t reg) { return _register_bcd_to_dec(reg, 7); } void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit) { uint8_t regv = read_register(reg); uint8_t mask = (1 << (high_bit + 1)) - 1; - /* convert value to bcd in place */ + // Convert value to bcd in place. uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); - /* replace high bits of value if needed */ + // Replace high bits of value if needed. value &= mask; value |= (regv &= ~mask); write_register(reg, value); } void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value) { _register_dec_to_bcd(reg, value, 7); } uint8_t DS1302::read_register(reg_t reg) { - uint8_t cmd_byte = 129; /* 1000 0001 */ + uint8_t cmd_byte = 129; // 1000 0001 uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); reg_value = _read_in(); digitalWrite(_ce_pin, LOW); return reg_value; } void DS1302::write_register(reg_t reg, uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); _write_out(value); digitalWrite(_ce_pin, LOW); } void DS1302::write_protect(bool enable) { write_register(WP_REG, (enable << 7)); } void DS1302::halt(bool enable) { uint8_t sec = read_register(SEC_REG); sec &= ~(1 << 7); sec |= (enable << 7); write_register(SEC_REG, sec); } uint8_t DS1302::seconds() { return _register_bcd_to_dec(SEC_REG, 6); } uint8_t DS1302::minutes() { return _register_bcd_to_dec(MIN_REG); } uint8_t DS1302::hour() { uint8_t hr = read_register(HR_REG); uint8_t adj; - if (hr & 128) /* 12-hour mode */ + if (hr & 128) // 12-hour mode adj = 12 * ((hr & 32) >> 5); - else /* 24-hour mode */ + else // 24-hour mode adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } uint8_t DS1302::date() { return _register_bcd_to_dec(DATE_REG, 5); } uint8_t DS1302::month() { return _register_bcd_to_dec(MON_REG, 4); } uint8_t DS1302::day() { return _register_bcd_to_dec(DAY_REG, 2); } uint16_t DS1302::year() { return 2000 + _register_bcd_to_dec(YR_REG); } Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } void DS1302::seconds(uint8_t sec) { _register_dec_to_bcd(SEC_REG, sec, 6); } void DS1302::minutes(uint8_t min) { _register_dec_to_bcd(MIN_REG, min, 6); } void DS1302::hour(uint8_t hr) { - write_register(HR_REG, 0); /* set 24-hour mode */ + write_register(HR_REG, 0); // set 24-hour mode _register_dec_to_bcd(HR_REG, hr, 5); } void DS1302::date(uint8_t date) { _register_dec_to_bcd(DATE_REG, date, 5); } void DS1302::month(uint8_t mon) { _register_dec_to_bcd(MON_REG, mon, 4); } void DS1302::day(uint8_t day) { _register_dec_to_bcd(DAY_REG, day, 2); } void DS1302::year(uint16_t yr) { yr -= 2000; _register_dec_to_bcd(YR_REG, yr); } void DS1302::time(Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); }
msparks/arduino-ds1302
2b934bfd900c406819ad9d46a9aba15ea3eff8da
Condense code.
diff --git a/DS1302.cpp b/DS1302.cpp index ee593c3..2d6a86d 100644 --- a/DS1302.cpp +++ b/DS1302.cpp @@ -1,277 +1,213 @@ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "DS1302.h" -/*** Time definitions ***/ - Time::Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, - uint8_t day) -{ + uint8_t day) { this->yr = yr; this->mon = mon; this->date = date; this->hr = hr; this->min = min; this->sec = sec; this->day = day; } - -Time::Time() -{ +Time::Time() { Time(2000, 1, 1, 0, 0, 0, 7); } -/*** DS1302 definitions ***/ - -DS1302::DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin) -{ +DS1302::DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin) { _ce_pin = ce_pin; _io_pin = io_pin; _sclk_pin = sclk_pin; pinMode(ce_pin, OUTPUT); pinMode(sclk_pin, OUTPUT); } - -void DS1302::_write_out(uint8_t value) -{ +void DS1302::_write_out(uint8_t value) { pinMode(_io_pin, OUTPUT); shiftOut(_io_pin, _sclk_pin, LSBFIRST, value); } - -uint8_t DS1302::_read_in() -{ +uint8_t DS1302::_read_in() { uint8_t input_value = 0; uint8_t bit = 0; pinMode(_io_pin, INPUT); for (int i = 0; i < 8; ++i) { bit = digitalRead(_io_pin); input_value |= (bit << i); digitalWrite(_sclk_pin, HIGH); delayMicroseconds(1); digitalWrite(_sclk_pin, LOW); } return input_value; } - -uint8_t DS1302::_register_bcd_to_dec(reg_t reg, uint8_t high_bit) -{ +uint8_t DS1302::_register_bcd_to_dec(reg_t reg, uint8_t high_bit) { uint8_t val = read_register(reg); uint8_t mask = (1 << (high_bit + 1)) - 1; val &= mask; val = (val & 15) + 10 * ((val & (15 << 4)) >> 4); return val; } - -uint8_t DS1302::_register_bcd_to_dec(reg_t reg) -{ +uint8_t DS1302::_register_bcd_to_dec(reg_t reg) { return _register_bcd_to_dec(reg, 7); } - -void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit) -{ +void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit) { uint8_t regv = read_register(reg); uint8_t mask = (1 << (high_bit + 1)) - 1; /* convert value to bcd in place */ uint8_t tvalue = value / 10; value = value % 10; value |= (tvalue << 4); /* replace high bits of value if needed */ value &= mask; value |= (regv &= ~mask); write_register(reg, value); } - -void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value) -{ +void DS1302::_register_dec_to_bcd(reg_t reg, uint8_t value) { _register_dec_to_bcd(reg, value, 7); } - -uint8_t DS1302::read_register(reg_t reg) -{ +uint8_t DS1302::read_register(reg_t reg) { uint8_t cmd_byte = 129; /* 1000 0001 */ uint8_t reg_value; cmd_byte |= (reg << 1); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); reg_value = _read_in(); digitalWrite(_ce_pin, LOW); return reg_value; } - -void DS1302::write_register(reg_t reg, uint8_t value) -{ +void DS1302::write_register(reg_t reg, uint8_t value) { uint8_t cmd_byte = (128 | (reg << 1)); digitalWrite(_sclk_pin, LOW); digitalWrite(_ce_pin, HIGH); _write_out(cmd_byte); _write_out(value); digitalWrite(_ce_pin, LOW); } - -void DS1302::write_protect(bool enable) -{ +void DS1302::write_protect(bool enable) { write_register(WP_REG, (enable << 7)); } - -void DS1302::halt(bool enable) -{ +void DS1302::halt(bool enable) { uint8_t sec = read_register(SEC_REG); sec &= ~(1 << 7); sec |= (enable << 7); write_register(SEC_REG, sec); } - -/*** Get time ***/ - -uint8_t DS1302::seconds() -{ +uint8_t DS1302::seconds() { return _register_bcd_to_dec(SEC_REG, 6); } - -uint8_t DS1302::minutes() -{ +uint8_t DS1302::minutes() { return _register_bcd_to_dec(MIN_REG); } - -uint8_t DS1302::hour() -{ +uint8_t DS1302::hour() { uint8_t hr = read_register(HR_REG); uint8_t adj; if (hr & 128) /* 12-hour mode */ adj = 12 * ((hr & 32) >> 5); else /* 24-hour mode */ adj = 10 * ((hr & (32 + 16)) >> 4); hr = (hr & 15) + adj; return hr; } - -uint8_t DS1302::date() -{ +uint8_t DS1302::date() { return _register_bcd_to_dec(DATE_REG, 5); } - -uint8_t DS1302::month() -{ +uint8_t DS1302::month() { return _register_bcd_to_dec(MON_REG, 4); } - -uint8_t DS1302::day() -{ +uint8_t DS1302::day() { return _register_bcd_to_dec(DAY_REG, 2); } - -uint16_t DS1302::year() -{ +uint16_t DS1302::year() { return 2000 + _register_bcd_to_dec(YR_REG); } - -Time DS1302::time() -{ +Time DS1302::time() { Time t; t.sec = seconds(); t.min = minutes(); t.hr = hour(); t.date = date(); t.mon = month(); t.day = day(); t.yr = year(); return t; } - -/*** Set time ***/ - -void DS1302::seconds(uint8_t sec) -{ +void DS1302::seconds(uint8_t sec) { _register_dec_to_bcd(SEC_REG, sec, 6); } - -void DS1302::minutes(uint8_t min) -{ +void DS1302::minutes(uint8_t min) { _register_dec_to_bcd(MIN_REG, min, 6); } - -void DS1302::hour(uint8_t hr) -{ +void DS1302::hour(uint8_t hr) { write_register(HR_REG, 0); /* set 24-hour mode */ _register_dec_to_bcd(HR_REG, hr, 5); } - -void DS1302::date(uint8_t date) -{ +void DS1302::date(uint8_t date) { _register_dec_to_bcd(DATE_REG, date, 5); } - -void DS1302::month(uint8_t mon) -{ +void DS1302::month(uint8_t mon) { _register_dec_to_bcd(MON_REG, mon, 4); } - -void DS1302::day(uint8_t day) -{ +void DS1302::day(uint8_t day) { _register_dec_to_bcd(DAY_REG, day, 2); } - -void DS1302::year(uint16_t yr) -{ +void DS1302::year(uint16_t yr) { yr -= 2000; _register_dec_to_bcd(YR_REG, yr); } - -void DS1302::time(Time t) -{ +void DS1302::time(Time t) { seconds(t.sec); minutes(t.min); hour(t.hr); date(t.date); month(t.mon); day(t.day); year(t.yr); }
msparks/arduino-ds1302
d7bdedb12324236319f48be4f27ba62106959a64
Double-slash comments in header.
diff --git a/DS1302.h b/DS1302.h index 4e6774d..dd0f026 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,231 +1,167 @@ -/* -Copyright (c) 2009, Matt Sparks -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS -OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED -AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. -*/ +// Interface for the DS1302 timekeeping chip. +// +// Copyright (c) 2009, Matt Sparks +// All rights reserved. +// +// Distributed under the 2-clause BSD license. #ifndef DS1302_H_ #define DS1302_H_ -/** - * Convenience register constants. - */ +// Convenience register constants. #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 -/** - * Type for a register number. - */ +// Type for a register number. typedef uint8_t reg_t; - -/** - * Class representing a particular time and date. - */ -class Time -{ -public: - /** - * Default constructor. - * - * Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. - * The date and time can be changed by editing the instance variables. - */ +// Class representing a particular time and date. +class Time { + public: + // Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. + // The date and time can be changed by editing the instance variables. Time(); - /** - * Create a Time object with a given time. - * - * Args: - * yr: year. Range: {2000, ..., 2099}. - * mon: month. Range: {1, ..., 12}. - * date: date (of the month). Range: {1, ..., 31}. - * hr: hour. Range: {0, ..., 23}. - * min: minutes. Range: {0, ..., 59}. - * sec: seconds. Range: {0, ..., 59}. - * day: day of the week. Sunday is 1. Range: {1, ..., 7}. - */ + // Creates a Time object with a given time. + // + // Args: + // yr: year. Range: {2000, ..., 2099}. + // mon: month. Range: {1, ..., 12}. + // date: date (of the month). Range: {1, ..., 31}. + // hr: hour. Range: {0, ..., 23}. + // min: minutes. Range: {0, ..., 59}. + // sec: seconds. Range: {0, ..., 59}. + // day: day of the week. Sunday is 1. Range: {1, ..., 7}. Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, uint8_t day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; uint8_t day; uint16_t yr; }; -/** - * Talk to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. - */ -class DS1302 -{ -public: - /** - * Constructor. - * - * Args: - * ce_pin: CE pin number - * io_pin: IO pin number - * sclk_pin: SCLK pin number - */ +// Talks to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. +class DS1302 { + public: + // Prepares to interface with the chip on the given I/O pins. + // + // Args: + // ce_pin: CE pin number + // io_pin: IO pin number + // sclk_pin: SCLK pin number DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); - /** - * Read register byte value. - * - * Args: - * reg: register number - * - * Returns: - * register value - */ + // Reads register byte value. + // + // Args: + // reg: register number + // + // Returns: + // register value uint8_t read_register(reg_t reg); - /** - * Write byte into register. - * - * Args: - * reg: register number - * value: byte to write - */ + // Writes byte into register. + // + // Args: + // reg: register number + // value: byte to write void write_register(reg_t reg, uint8_t value); - /** - * Enable or disable write protection on chip. - * - * Args: - * enable: true to enable, false to disable. - */ + // Enables or disables write protection on chip. + // + // Args: + // enable: true to enable, false to disable. void write_protect(bool enable); - /** - * Set or clear clock halt flag. - * - * Args: - * value: true to set halt flag, false to clear. - */ + // Set or clear clock halt flag. + // + // Args: + // value: true to set halt flag, false to clear. void halt(bool value); - /** - * Get individual pieces of the time and date. - */ + // Returns an individual piece of the time and date. uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); uint8_t day(); uint16_t year(); - /** - * Get the current time and date in a Time object. - * - * Returns: - * Time object. - */ + // Get the current time and date in a Time object. + // + // Returns: + // Current time as Time object. Time time(); - /** - * Individually set pieces of the date and time. - * - * The arguments here follow the rules specified above in Time::Time(...). - */ + // Individually sets pieces of the date and time. + // + // The arguments here follow the rules specified above in Time::Time(...). void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(uint8_t day); void year(uint16_t yr); - /** - * Set the time and date to the instant specified in a given Time object. - * - * Args: - * t: Time object to use - */ + // Sets the time and date to the instant specified in a given Time object. + // + // Args: + // t: Time object to use void time(Time t); private: uint8_t _ce_pin; uint8_t _io_pin; uint8_t _sclk_pin; - /** - * Shift out a value to the IO pin. - * - * Side effects: sets _io_pin as OUTPUT. - * - * Args: - * value: byte to shift out - */ + // Shifts out a value to the IO pin. + // + // Side effects: sets _io_pin as OUTPUT. + // + // Args: + // value: byte to shift out void _write_out(uint8_t value); - /** - * Read in a byte from the IO pin. - * - * Side effects: sets _io_pin to INPUT. - * - * Returns: - * byte read in - */ + // Reads in a byte from the IO pin. + // + // Side effects: sets _io_pin to INPUT. + // + // Returns: + // byte read in uint8_t _read_in(); - /** - * Get a binary-coded decimal register and return it in decimal. - * - * Args: - * reg: register number - * high_bit: number of the bit containing the last BCD value ({0, ..., 7}) - * - * Returns: - * decimal value - */ + // Gets a binary-coded decimal register and returns it in decimal. + // + // Args: + // reg: register number + // high_bit: number of the bit containing the last BCD value ({0, ..., 7}) + // + // Returns: + // decimal value uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); uint8_t _register_bcd_to_dec(reg_t reg); - /** - * Set a register with binary-coded decimal converted from a given value. - * - * Args: - * reg: register number - * value: decimal value to convert to BCD - * high_bit: highest bit in the register allowed to contain BCD value - */ + // Sets a register with binary-coded decimal converted from a given value. + // + // Args: + // reg: register number + // value: decimal value to convert to BCD + // high_bit: highest bit in the register allowed to contain BCD value void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); void _register_dec_to_bcd(reg_t reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
108f2145a71d1ddf2002a20189f51f98fda9cb40
Static const int for pins.
diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index cf4ee06..b1df4f1 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,84 +1,88 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <string.h> #include <DS1302.h> -// Set the appropriate digital I/O pin connections. -uint8_t CE_PIN = 5; -uint8_t IO_PIN = 6; -uint8_t SCLK_PIN = 7; +// Set the appropriate digital I/O pin connections. These are the pin +// assignments for the Arduino as well for as the DS1302 chip. See the DS1302 +// datasheet: +// +// http://datasheets.maximintegrated.com/en/ds/DS1302.pdf +static const int kCePin = 5; // Chip Enable +static const int kIoPin = 6; // Input/Output +static const int kSclkPin = 7; // Serial Clock // Create buffers. char buf[50]; char day[10]; // Create a DS1302 object. -DS1302 rtc(CE_PIN, IO_PIN, SCLK_PIN); +DS1302 rtc(kCePin, kIoPin, kSclkPin); void print_time() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. memset(day, 0, sizeof(day)); // clear day buffer switch (t.day) { case 1: strcpy(day, "Sunday"); break; case 2: strcpy(day, "Monday"); break; case 3: strcpy(day, "Tuesday"); break; case 4: strcpy(day, "Wednesday"); break; case 5: strcpy(day, "Thursday"); break; case 6: strcpy(day, "Friday"); break; case 7: strcpy(day, "Saturday"); break; } // Format the time and date and insert into the temporary buffer. snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day, t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. rtc.write_protect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, 1); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
2ed858c6013f8b42531c75af75aaaf4e14bc71db
Curlies on the definition lines.
diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index 96bd8aa..cf4ee06 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,87 +1,84 @@ // Example sketch for interfacing with the DS1302 timekeeping chip. // // Copyright (c) 2009, Matt Sparks // All rights reserved. // // http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <string.h> #include <DS1302.h> // Set the appropriate digital I/O pin connections. uint8_t CE_PIN = 5; uint8_t IO_PIN = 6; uint8_t SCLK_PIN = 7; // Create buffers. char buf[50]; char day[10]; // Create a DS1302 object. DS1302 rtc(CE_PIN, IO_PIN, SCLK_PIN); -void print_time() -{ +void print_time() { // Get the current time and date from the chip. Time t = rtc.time(); // Name the day of the week. memset(day, 0, sizeof(day)); // clear day buffer switch (t.day) { case 1: strcpy(day, "Sunday"); break; case 2: strcpy(day, "Monday"); break; case 3: strcpy(day, "Tuesday"); break; case 4: strcpy(day, "Wednesday"); break; case 5: strcpy(day, "Thursday"); break; case 6: strcpy(day, "Friday"); break; case 7: strcpy(day, "Saturday"); break; } // Format the time and date and insert into the temporary buffer. snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day, t.yr, t.mon, t.date, t.hr, t.min, t.sec); // Print the formatted string to serial so we can see the time. Serial.println(buf); } -void setup() -{ +void setup() { Serial.begin(9600); // Initialize a new chip by turning off write protection and clearing the // clock halt flag. These methods needn't always be called. See the DS1302 // datasheet for details. rtc.write_protect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, 1); // Set the time and date on the chip. rtc.time(t); } // Loop and print the time every second. -void loop() -{ +void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
47a237875e80e33513b1870435b14c5c3930d6c8
Convert to double-slash comments.
diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index e0656bb..96bd8aa 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,92 +1,87 @@ -/* -Example sketch for interfacing with the DS1302 timekeeping chip. - -Copyright (c) 2009, Matt Sparks -All rights reserved. - -http://quadpoint.org/projects/arduino-ds1302 -*/ +// Example sketch for interfacing with the DS1302 timekeeping chip. +// +// Copyright (c) 2009, Matt Sparks +// All rights reserved. +// +// http://quadpoint.org/projects/arduino-ds1302 #include <stdio.h> #include <string.h> #include <DS1302.h> -/* Set the appropriate digital I/O pin connections */ +// Set the appropriate digital I/O pin connections. uint8_t CE_PIN = 5; uint8_t IO_PIN = 6; uint8_t SCLK_PIN = 7; -/* Create buffers */ +// Create buffers. char buf[50]; char day[10]; -/* Create a DS1302 object */ +// Create a DS1302 object. DS1302 rtc(CE_PIN, IO_PIN, SCLK_PIN); - void print_time() { - /* Get the current time and date from the chip */ + // Get the current time and date from the chip. Time t = rtc.time(); - /* Name the day of the week */ - memset(day, 0, sizeof(day)); /* clear day buffer */ + // Name the day of the week. + memset(day, 0, sizeof(day)); // clear day buffer switch (t.day) { case 1: strcpy(day, "Sunday"); break; case 2: strcpy(day, "Monday"); break; case 3: strcpy(day, "Tuesday"); break; case 4: strcpy(day, "Wednesday"); break; case 5: strcpy(day, "Thursday"); break; case 6: strcpy(day, "Friday"); break; case 7: strcpy(day, "Saturday"); break; } - /* Format the time and date and insert into the temporary buffer */ + // Format the time and date and insert into the temporary buffer. snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day, t.yr, t.mon, t.date, t.hr, t.min, t.sec); - /* Print the formatted string to serial so we can see the time */ + // Print the formatted string to serial so we can see the time. Serial.println(buf); } - void setup() { Serial.begin(9600); - /* Initialize a new chip by turning off write protection and clearing the - clock halt flag. These methods needn't always be called. See the DS1302 - datasheet for details. */ + // Initialize a new chip by turning off write protection and clearing the + // clock halt flag. These methods needn't always be called. See the DS1302 + // datasheet for details. rtc.write_protect(false); rtc.halt(false); // Make a new time object to set the date and time. // Sunday, September 22, 2013 at 01:38:50. Time t(2013, 9, 22, 1, 38, 50, 1); - /* Set the time and date on the chip */ + // Set the time and date on the chip. rtc.time(t); } - -/* Loop and print the time every second */ +// Loop and print the time every second. void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
12b2cf1be75f1ee1f1432174aa4e52b4fcf9b445
Change time in example to right now.
diff --git a/examples/set_clock/set_clock.pde b/examples/set_clock/set_clock.pde index 51b68e9..e0656bb 100644 --- a/examples/set_clock/set_clock.pde +++ b/examples/set_clock/set_clock.pde @@ -1,92 +1,92 @@ /* Example sketch for interfacing with the DS1302 timekeeping chip. Copyright (c) 2009, Matt Sparks All rights reserved. http://quadpoint.org/projects/arduino-ds1302 */ #include <stdio.h> #include <string.h> #include <DS1302.h> /* Set the appropriate digital I/O pin connections */ uint8_t CE_PIN = 5; uint8_t IO_PIN = 6; uint8_t SCLK_PIN = 7; /* Create buffers */ char buf[50]; char day[10]; /* Create a DS1302 object */ DS1302 rtc(CE_PIN, IO_PIN, SCLK_PIN); void print_time() { /* Get the current time and date from the chip */ Time t = rtc.time(); /* Name the day of the week */ memset(day, 0, sizeof(day)); /* clear day buffer */ switch (t.day) { case 1: strcpy(day, "Sunday"); break; case 2: strcpy(day, "Monday"); break; case 3: strcpy(day, "Tuesday"); break; case 4: strcpy(day, "Wednesday"); break; case 5: strcpy(day, "Thursday"); break; case 6: strcpy(day, "Friday"); break; case 7: strcpy(day, "Saturday"); break; } /* Format the time and date and insert into the temporary buffer */ snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day, t.yr, t.mon, t.date, t.hr, t.min, t.sec); /* Print the formatted string to serial so we can see the time */ Serial.println(buf); } void setup() { Serial.begin(9600); /* Initialize a new chip by turning off write protection and clearing the clock halt flag. These methods needn't always be called. See the DS1302 datasheet for details. */ rtc.write_protect(false); rtc.halt(false); - /* Make a new time object to set the date and time */ - /* Tuesday, May 19, 2009 at 21:16:37. */ - Time t(2009, 5, 19, 21, 16, 37, 3); + // Make a new time object to set the date and time. + // Sunday, September 22, 2013 at 01:38:50. + Time t(2013, 9, 22, 1, 38, 50, 1); /* Set the time and date on the chip */ rtc.time(t); } /* Loop and print the time every second */ void loop() { print_time(); delay(1000); }
msparks/arduino-ds1302
ad894ea3153968357df98f28f884656081dfdeb4
Adding README.md.
diff --git a/README.md b/README.md new file mode 100644 index 0000000..1e80b78 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# DS1302 RTC library for Arduino + +This project is a library for the [Arduino](http://arduino.cc) platform. It +provides a simple interface to the +[Maxim DS1302](http://www.maxim-ic.com/quick_view2.cfm/qv_pk/2685/t/al) +timekeeping chip. It allows Arduino projects to keep accurate time easily. + +## Installing + +Place the `DS1302` directory in the `libraries` subdirectory of your Arduino +sketch directory. On OS X, for example, your sketch directory might be: + + /Users/you/Documents/Arduino + +In that case, you should put the `DS1302` directory at: + + /Users/you/Documents/Arduino/libraries/DS1302 + +A simple example is included with the code.
msparks/arduino-ds1302
24338e100dd5888fe8cb0b44d3505e8169b90b21
Removing unnecessary includes from header file.
diff --git a/DS1302.h b/DS1302.h index c815755..4e6774d 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,237 +1,231 @@ /* Copyright (c) 2009, Matt Sparks All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DS1302_H_ #define DS1302_H_ -#if defined(ARDUINO) && ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - /** * Convenience register constants. */ #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 /** * Type for a register number. */ typedef uint8_t reg_t; /** * Class representing a particular time and date. */ class Time { public: /** * Default constructor. * * Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. * The date and time can be changed by editing the instance variables. */ Time(); /** * Create a Time object with a given time. * * Args: * yr: year. Range: {2000, ..., 2099}. * mon: month. Range: {1, ..., 12}. * date: date (of the month). Range: {1, ..., 31}. * hr: hour. Range: {0, ..., 23}. * min: minutes. Range: {0, ..., 59}. * sec: seconds. Range: {0, ..., 59}. * day: day of the week. Sunday is 1. Range: {1, ..., 7}. */ Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, uint8_t day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; uint8_t day; uint16_t yr; }; /** * Talk to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. */ class DS1302 { public: /** * Constructor. * * Args: * ce_pin: CE pin number * io_pin: IO pin number * sclk_pin: SCLK pin number */ DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); /** * Read register byte value. * * Args: * reg: register number * * Returns: * register value */ uint8_t read_register(reg_t reg); /** * Write byte into register. * * Args: * reg: register number * value: byte to write */ void write_register(reg_t reg, uint8_t value); /** * Enable or disable write protection on chip. * * Args: * enable: true to enable, false to disable. */ void write_protect(bool enable); /** * Set or clear clock halt flag. * * Args: * value: true to set halt flag, false to clear. */ void halt(bool value); /** * Get individual pieces of the time and date. */ uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); uint8_t day(); uint16_t year(); /** * Get the current time and date in a Time object. * * Returns: * Time object. */ Time time(); /** * Individually set pieces of the date and time. * * The arguments here follow the rules specified above in Time::Time(...). */ void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(uint8_t day); void year(uint16_t yr); /** * Set the time and date to the instant specified in a given Time object. * * Args: * t: Time object to use */ void time(Time t); private: uint8_t _ce_pin; uint8_t _io_pin; uint8_t _sclk_pin; /** * Shift out a value to the IO pin. * * Side effects: sets _io_pin as OUTPUT. * * Args: * value: byte to shift out */ void _write_out(uint8_t value); /** * Read in a byte from the IO pin. * * Side effects: sets _io_pin to INPUT. * * Returns: * byte read in */ uint8_t _read_in(); /** * Get a binary-coded decimal register and return it in decimal. * * Args: * reg: register number * high_bit: number of the bit containing the last BCD value ({0, ..., 7}) * * Returns: * decimal value */ uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); uint8_t _register_bcd_to_dec(reg_t reg); /** * Set a register with binary-coded decimal converted from a given value. * * Args: * reg: register number * value: decimal value to convert to BCD * high_bit: highest bit in the register allowed to contain BCD value */ void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); void _register_dec_to_bcd(reg_t reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
5e4d4f7cd416f0a0b62ec0a4317928b7b17abbdd
Periods in comments.
diff --git a/DS1302.h b/DS1302.h index d4e8e77..c815755 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,237 +1,237 @@ /* Copyright (c) 2009, Matt Sparks All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DS1302_H_ #define DS1302_H_ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif /** - * Convenience register constants + * Convenience register constants. */ #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 /** - * Type for a register number + * Type for a register number. */ typedef uint8_t reg_t; /** * Class representing a particular time and date. */ class Time { public: /** * Default constructor. * * Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. * The date and time can be changed by editing the instance variables. */ Time(); /** * Create a Time object with a given time. * * Args: * yr: year. Range: {2000, ..., 2099}. * mon: month. Range: {1, ..., 12}. * date: date (of the month). Range: {1, ..., 31}. * hr: hour. Range: {0, ..., 23}. * min: minutes. Range: {0, ..., 59}. * sec: seconds. Range: {0, ..., 59}. * day: day of the week. Sunday is 1. Range: {1, ..., 7}. */ Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, uint8_t day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; uint8_t day; uint16_t yr; }; /** * Talk to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. */ class DS1302 { public: /** * Constructor. * * Args: * ce_pin: CE pin number * io_pin: IO pin number * sclk_pin: SCLK pin number */ DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); /** * Read register byte value. * * Args: * reg: register number * * Returns: * register value */ uint8_t read_register(reg_t reg); /** * Write byte into register. * * Args: * reg: register number * value: byte to write */ void write_register(reg_t reg, uint8_t value); /** * Enable or disable write protection on chip. * * Args: * enable: true to enable, false to disable. */ void write_protect(bool enable); /** * Set or clear clock halt flag. * * Args: * value: true to set halt flag, false to clear. */ void halt(bool value); /** * Get individual pieces of the time and date. */ uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); uint8_t day(); uint16_t year(); /** * Get the current time and date in a Time object. * * Returns: * Time object. */ Time time(); /** * Individually set pieces of the date and time. * * The arguments here follow the rules specified above in Time::Time(...). */ void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(uint8_t day); void year(uint16_t yr); /** * Set the time and date to the instant specified in a given Time object. * * Args: * t: Time object to use */ void time(Time t); private: uint8_t _ce_pin; uint8_t _io_pin; uint8_t _sclk_pin; /** * Shift out a value to the IO pin. * * Side effects: sets _io_pin as OUTPUT. * * Args: * value: byte to shift out */ void _write_out(uint8_t value); /** * Read in a byte from the IO pin. * * Side effects: sets _io_pin to INPUT. * * Returns: * byte read in */ uint8_t _read_in(); /** * Get a binary-coded decimal register and return it in decimal. * * Args: * reg: register number * high_bit: number of the bit containing the last BCD value ({0, ..., 7}) * * Returns: * decimal value */ uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); uint8_t _register_bcd_to_dec(reg_t reg); /** * Set a register with binary-coded decimal converted from a given value. * * Args: * reg: register number * value: decimal value to convert to BCD * high_bit: highest bit in the register allowed to contain BCD value */ void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); void _register_dec_to_bcd(reg_t reg, uint8_t value); }; #endif // DS1302_H_
msparks/arduino-ds1302
400b81d883759a47e3f67bca8de2632626471bf2
Rename header guard.
diff --git a/DS1302.h b/DS1302.h index 6d6e10b..d4e8e77 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,237 +1,237 @@ /* Copyright (c) 2009, Matt Sparks All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef DS1302_h -#define DS1302_h +#ifndef DS1302_H_ +#define DS1302_H_ #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif /** * Convenience register constants */ #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 /** * Type for a register number */ typedef uint8_t reg_t; /** * Class representing a particular time and date. */ class Time { public: /** * Default constructor. * * Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. * The date and time can be changed by editing the instance variables. */ Time(); /** * Create a Time object with a given time. * * Args: * yr: year. Range: {2000, ..., 2099}. * mon: month. Range: {1, ..., 12}. * date: date (of the month). Range: {1, ..., 31}. * hr: hour. Range: {0, ..., 23}. * min: minutes. Range: {0, ..., 59}. * sec: seconds. Range: {0, ..., 59}. * day: day of the week. Sunday is 1. Range: {1, ..., 7}. */ Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, uint8_t day); uint8_t sec; uint8_t min; uint8_t hr; uint8_t date; uint8_t mon; uint8_t day; uint16_t yr; }; /** * Talk to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. */ class DS1302 { public: /** * Constructor. * * Args: * ce_pin: CE pin number * io_pin: IO pin number * sclk_pin: SCLK pin number */ DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); /** * Read register byte value. * * Args: * reg: register number * * Returns: * register value */ uint8_t read_register(reg_t reg); /** * Write byte into register. * * Args: * reg: register number * value: byte to write */ void write_register(reg_t reg, uint8_t value); /** * Enable or disable write protection on chip. * * Args: * enable: true to enable, false to disable. */ void write_protect(bool enable); /** * Set or clear clock halt flag. * * Args: * value: true to set halt flag, false to clear. */ void halt(bool value); /** * Get individual pieces of the time and date. */ uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); uint8_t day(); uint16_t year(); /** * Get the current time and date in a Time object. * * Returns: * Time object. */ Time time(); /** * Individually set pieces of the date and time. * * The arguments here follow the rules specified above in Time::Time(...). */ void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(uint8_t day); void year(uint16_t yr); /** * Set the time and date to the instant specified in a given Time object. * * Args: * t: Time object to use */ void time(Time t); private: uint8_t _ce_pin; uint8_t _io_pin; uint8_t _sclk_pin; /** * Shift out a value to the IO pin. * * Side effects: sets _io_pin as OUTPUT. * * Args: * value: byte to shift out */ void _write_out(uint8_t value); /** * Read in a byte from the IO pin. * * Side effects: sets _io_pin to INPUT. * * Returns: * byte read in */ uint8_t _read_in(); /** * Get a binary-coded decimal register and return it in decimal. * * Args: * reg: register number * high_bit: number of the bit containing the last BCD value ({0, ..., 7}) * * Returns: * decimal value */ uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); uint8_t _register_bcd_to_dec(reg_t reg); /** * Set a register with binary-coded decimal converted from a given value. * * Args: * reg: register number * value: decimal value to convert to BCD * high_bit: highest bit in the register allowed to contain BCD value */ void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); void _register_dec_to_bcd(reg_t reg, uint8_t value); }; -#endif +#endif // DS1302_H_
msparks/arduino-ds1302
ef0b1f974fba686cdef0b8ea43be55ebd920bc71
Move instance variables below methods in Time class declaration.
diff --git a/DS1302.h b/DS1302.h index 9a62b88..6d6e10b 100644 --- a/DS1302.h +++ b/DS1302.h @@ -1,237 +1,237 @@ /* Copyright (c) 2009, Matt Sparks All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DS1302_h #define DS1302_h #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif /** * Convenience register constants */ #define SEC_REG 0 #define MIN_REG 1 #define HR_REG 2 #define DATE_REG 3 #define MON_REG 4 #define DAY_REG 5 #define YR_REG 6 #define WP_REG 7 /** * Type for a register number */ typedef uint8_t reg_t; /** * Class representing a particular time and date. */ class Time { public: - uint8_t sec; - uint8_t min; - uint8_t hr; - uint8_t date; - uint8_t mon; - uint8_t day; - uint16_t yr; - /** * Default constructor. * * Creates a time object dated to Saturday Jan 1, 2000 at 00:00:00. * The date and time can be changed by editing the instance variables. */ Time(); /** * Create a Time object with a given time. * * Args: * yr: year. Range: {2000, ..., 2099}. * mon: month. Range: {1, ..., 12}. * date: date (of the month). Range: {1, ..., 31}. * hr: hour. Range: {0, ..., 23}. * min: minutes. Range: {0, ..., 59}. * sec: seconds. Range: {0, ..., 59}. * day: day of the week. Sunday is 1. Range: {1, ..., 7}. */ Time(uint16_t yr, uint8_t mon, uint8_t date, uint8_t hr, uint8_t min, uint8_t sec, uint8_t day); + + uint8_t sec; + uint8_t min; + uint8_t hr; + uint8_t date; + uint8_t mon; + uint8_t day; + uint16_t yr; }; /** * Talk to a Dallas Semiconductor DS1302 Real Time Clock (RTC) chip. */ class DS1302 { public: /** * Constructor. * * Args: * ce_pin: CE pin number * io_pin: IO pin number * sclk_pin: SCLK pin number */ DS1302(uint8_t ce_pin, uint8_t io_pin, uint8_t sclk_pin); /** * Read register byte value. * * Args: * reg: register number * * Returns: * register value */ uint8_t read_register(reg_t reg); /** * Write byte into register. * * Args: * reg: register number * value: byte to write */ void write_register(reg_t reg, uint8_t value); /** * Enable or disable write protection on chip. * * Args: * enable: true to enable, false to disable. */ void write_protect(bool enable); /** * Set or clear clock halt flag. * * Args: * value: true to set halt flag, false to clear. */ void halt(bool value); /** * Get individual pieces of the time and date. */ uint8_t seconds(); uint8_t minutes(); uint8_t hour(); uint8_t date(); uint8_t month(); uint8_t day(); uint16_t year(); /** * Get the current time and date in a Time object. * * Returns: * Time object. */ Time time(); /** * Individually set pieces of the date and time. * * The arguments here follow the rules specified above in Time::Time(...). */ void seconds(uint8_t sec); void minutes(uint8_t min); void hour(uint8_t hr); void date(uint8_t date); void month(uint8_t mon); void day(uint8_t day); void year(uint16_t yr); /** * Set the time and date to the instant specified in a given Time object. * * Args: * t: Time object to use */ void time(Time t); private: uint8_t _ce_pin; uint8_t _io_pin; uint8_t _sclk_pin; /** * Shift out a value to the IO pin. * * Side effects: sets _io_pin as OUTPUT. * * Args: * value: byte to shift out */ void _write_out(uint8_t value); /** * Read in a byte from the IO pin. * * Side effects: sets _io_pin to INPUT. * * Returns: * byte read in */ uint8_t _read_in(); /** * Get a binary-coded decimal register and return it in decimal. * * Args: * reg: register number * high_bit: number of the bit containing the last BCD value ({0, ..., 7}) * * Returns: * decimal value */ uint8_t _register_bcd_to_dec(reg_t reg, uint8_t high_bit); uint8_t _register_bcd_to_dec(reg_t reg); /** * Set a register with binary-coded decimal converted from a given value. * * Args: * reg: register number * value: decimal value to convert to BCD * high_bit: highest bit in the register allowed to contain BCD value */ void _register_dec_to_bcd(reg_t reg, uint8_t value, uint8_t high_bit); void _register_dec_to_bcd(reg_t reg, uint8_t value); }; #endif
MatzeB/fluffy
81970c11a80cae983425be780d82a6ca3b4109a1
adapt to latest makereport
diff --git a/test/reportplugin.py b/test/reportplugin.py index 83dfb9e..d750e14 100644 --- a/test/reportplugin.py +++ b/test/reportplugin.py @@ -1,58 +1,65 @@ -# New testclass -class TestFluffy(Test): - def __init__(self, filename, environment): - Test.__init__(self, filename, environment) - def _init_flags(self): - Test._init_flags(self) - environment = self.environment - environment.cflags = "-O3" - environment.ldflags = "" - def compile(self): - environment = self.environment - cmd = "%(compiler)s %(cflags)s %(filename)s %(ldflags)s -o %(executable)s" % environment.__dict__ - self.compile_command = cmd - self.compiling = "" - try: - self.compile_out, self.compile_err, self.compile_retcode = my_execute(cmd, timeout=60) - except SigKill, e: - self.error_msg = "compiler: %s" % e.name - return False - c = self.parse_compiler_output() - if not c: return c - return True - def check_compiler_errors(self): - if self.compile_retcode != 0: - self.error_msg = "compilation not ok (returncode %d)" % self.compile_retcode - self.long_error_msg = "\n".join((self.compile_command, self.compiling)) - return False - return True - -class FluffyShouldFail(TestFluffy): - def __init__(self, filename, environment): - TestFluffy.__init__(self, filename, environment) - - def check_compiler_errors(self): - if len(self.errors) == 0: - self.error_msg = "compiler missed error" - return False - return True - def check_execution(self): - return True # nothing to execute - -test_factories += [ - ( lambda name: name.endswith(".fluffy") and "should_fail" in name, FluffyShouldFail ), - ( lambda name: name.endswith(".fluffy"), TestFluffy ), +from test.test import Test, ensure_dir +from test.steps import execute, step_execute +from test.checks import check_no_errors, check_firm_problems, check_retcode_zero, create_check_reference_output, check_missing_errors +import os + +def step_compile_fluffy(environment): + cmd = "%(flc)s %(filename)s %(flflags)s -o %(executable)s" % environment.__dict__ + return execute(environment, cmd, timeout=30) + +def make_fluffy_test(environment, filename): + environment.filename = filename + environment.executable = environment.builddir + "/" + environment.filename + ".exe" + ensure_dir(os.path.dirname(environment.executable)) + + test = Test(environment, filename) + + compile = test.add_step("compile", step_compile_fluffy) + compile.add_check(check_no_errors) + compile.add_check(check_firm_problems) + compile.add_check(check_retcode_zero) + + execute = test.add_step("execute", step_execute) + execute.add_check(check_retcode_zero) + execute.add_check(create_check_reference_output(environment)) + return test + +def make_fluffy_should_fail(environment, filename): + environment.filename = filename + environment.executable = environment.builddir + "/" + environment.filename + ".exe" + ensure_dir(os.path.dirname(environment.executable)) + + test = Test(environment, filename) + + compile = test.add_step("compile", step_compile_fluffy) + compile.add_check(check_missing_errors) + return test + +test_factories = [ + (lambda name: name.endswith(".fluffy") and "fluffy/should_fail/" in name, make_fluffy_should_fail), +] +wildcard_factories = [ + ("*.fluffy", make_fluffy_test), ] -_EXTENSIONS.append("fluffy") # Configurations -def setup_fluffy(option, opt_str, value, parser): - global _ARCH_DIRS - _ARCH_DIRS = [] - global _DEFAULT_DIRS - _DEFAULT_DIRS = [ "fluffy", "fluffy/should_fail" ] - config = parser.values - config.compiler = "fluffy" - config.expect_url = "fluffy/fail_expectations" - -configurations["fluffy"] = setup_fluffy +def config_fluffy(option, opt_str, value, parser): + config = parser.values + config.arch_dirs = [] + config.default_dirs = [ "fluffy", "fluffy/should_fail" ] + +configurations = { + "fluffy": config_fluffy, +} + +def register_options(opts): + opts.add_option("--flc", dest="flc", + help="Use FKC to compiler fluffy programs", + metavar="FLC") + opts.add_option("--flflags", dest="flflags", + help="Use FLFLAGS to compiler fluffy programs", + metavar="FLFLAGS") + opts.set_defaults( + flc="fluffy", + flflags="-O3", + )
MatzeB/fluffy
e8eb4bcda618a59058cde92488c68bd93cdd1543
remove forced -m32 from Makefile
diff --git a/Makefile b/Makefile index 70d712f..224c530 100644 --- a/Makefile +++ b/Makefile @@ -1,72 +1,72 @@ -include config.mak GOAL = fluffy FIRM_CFLAGS ?= `pkg-config --cflags libfirm` FIRM_LIBS ?= `pkg-config --libs libfirm` CPPFLAGS = -I. CPPFLAGS += $(FIRM_CFLAGS) -DFIRM_BACKEND CFLAGS += -Wall -W -Wextra -Wstrict-prototypes -Wwrite-strings -Wmissing-prototypes -Werror -std=c99 -CFLAGS += -O0 -g3 -m32 +CFLAGS += -O0 -g3 LFLAGS += $(FIRM_LIBS) -ldl SOURCES := \ adt/obstack.c \ adt/obstack_printf.c \ adt/strset.c \ ast.c \ ast2firm.c \ driver/firm_machine.c \ driver/firm_opt.c \ driver/firm_timing.c \ input.c \ lexer.c \ main.c \ mangle.c \ match_type.c \ parser.c \ plugins.c \ semantic.c \ symbol_table.c \ token.c \ type.c \ type_hash.c OBJECTS = $(SOURCES:%.c=build/%.o) Q = @ .PHONY : all clean dirs all: $(GOAL) ifeq ($(findstring $(MAKECMDGOALS), clean depend),) -include .depend endif .depend: $(SOURCES) @echo "===> DEPEND" @rm -f $@ && touch $@ && makedepend -p "$@ build/" -Y -f $@ -- $(CPPFLAGS) -- $(SOURCES) 2> /dev/null && rm [email protected] $(GOAL): $(OBJECTS) | build/driver build/adt @echo "===> LD $@" - $(Q)$(CC) -m32 -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) + $(Q)$(CC) -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) build/adt: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/driver: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/%.o: %.c | build/adt build/driver @echo '===> CC $<' $(Q)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ clean: @echo '===> CLEAN' $(Q)rm -rf build $(GOAL) .depend
MatzeB/fluffy
6f168ba4fefa9b7aad921642d7bc9e671518e1ce
adapt to latest libfirm by copying driver dir from cparser
diff --git a/driver/firm_machine.c b/driver/firm_machine.c index 7e75104..723b50f 100644 --- a/driver/firm_machine.c +++ b/driver/firm_machine.c @@ -1,172 +1,178 @@ +/* + * This file is part of cparser. + * Copyright (C) 2012 Matthias Braun <[email protected]> + */ #include <config.h> #include <assert.h> #include <stdbool.h> #include "firm_machine.h" #include "adt/strutil.h" #include "adt/xmalloc.h" #include <libfirm/firm.h> static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } -static ir_entity *underscore_compilerlib_entity_creator(ident *id, ir_type *mt) +static ident *compilerlib_name_mangle_default(ident *id, ir_type *mt) { - ir_entity *entity = new_entity(get_glob_type(), id, mt); - ident *ldname = id_mangle3("_", id, ""); - - set_entity_visibility(entity, ir_visibility_external); - set_entity_ld_ident(entity, ldname); + (void)mt; + return id; +} - return entity; +static ident *compilerlib_name_mangle_underscore(ident *id, ir_type *mt) +{ + (void)mt; + return id_mangle3("_", id, ""); } bool firm_is_unixish_os(const machine_triple_t *machine) { const char *os = machine->operating_system; return strstr(os, "linux") != NULL || strstr(os, "bsd") != NULL || strstart(os, "solaris"); } bool firm_is_darwin_os(const machine_triple_t *machine) { const char *os = machine->operating_system; return strstart(os, "darwin"); } bool firm_is_windows_os(const machine_triple_t *machine) { const char *os = machine->operating_system; return strstart(os, "mingw") || streq(os, "win32"); } /** * Initialize firm codegeneration for a specific operating system. * The argument is the operating system part of a target-triple */ static bool setup_os_support(const machine_triple_t *machine) { if (firm_is_unixish_os(machine)) { set_be_option("ia32-gasmode=elf"); + set_compilerlib_name_mangle(compilerlib_name_mangle_default); } else if (firm_is_darwin_os(machine)) { set_be_option("ia32-gasmode=macho"); set_be_option("ia32-stackalign=4"); set_be_option("pic=true"); - set_compilerlib_entity_creator(underscore_compilerlib_entity_creator); + set_compilerlib_name_mangle(compilerlib_name_mangle_underscore); } else if (firm_is_windows_os(machine)) { set_be_option("ia32-gasmode=mingw"); - set_compilerlib_entity_creator(underscore_compilerlib_entity_creator); + set_compilerlib_name_mangle(compilerlib_name_mangle_underscore); } else { return false; } return true; } bool setup_firm_for_machine(const machine_triple_t *machine) { const char *cpu = machine->cpu_type; if (streq(cpu, "i386")) { set_be_option("isa=ia32"); set_be_option("ia32-arch=i386"); } else if (streq(cpu, "i486")) { set_be_option("isa=ia32"); set_be_option("ia32-arch=i486"); } else if (streq(cpu, "i586")) { set_be_option("isa=ia32"); set_be_option("ia32-arch=i586"); } else if (streq(cpu, "i686")) { set_be_option("isa=ia32"); set_be_option("ia32-arch=i686"); } else if (streq(cpu, "i786")) { set_be_option("isa=ia32"); set_be_option("ia32-arch=pentium4"); } else if (streq(cpu, "x86_64")) { set_be_option("isa=amd64"); } else if (streq(cpu, "sparc")) { set_be_option("isa=sparc"); } else if (streq(cpu, "arm")) { set_be_option("isa=arm"); } else { fprintf(stderr, "Unknown cpu '%s' in target-triple\n", cpu); return false; } /* process operating system */ if (!setup_os_support(machine)) { fprintf(stderr, "Unknown operating system '%s' in target-triple\n", machine->operating_system); return false; } return true; } machine_triple_t *firm_get_host_machine(void) { machine_triple_t *machine = XMALLOC(machine_triple_t); machine->cpu_type = xstrdup("i386"); machine->manufacturer = xstrdup("unknown"); #if defined(_WIN32) || defined(__CYGWIN__) machine->operating_system = xstrdup("win32"); #elif defined(__APPLE__) machine->operating_system = xstrdup("darwin"); #else machine->operating_system = xstrdup("linux"); #endif return machine; } void firm_free_machine_triple(machine_triple_t *machine) { free(machine->cpu_type); free(machine->manufacturer); free(machine->operating_system); free(machine); } machine_triple_t *firm_parse_machine_triple(const char *triple_string) { const char *manufacturer = strchr(triple_string, '-'); if (manufacturer == NULL) { return NULL; } manufacturer += 1; const char *os = strchr(manufacturer, '-'); if (os == NULL) { return false; } os += 1; /* Note: Triples are more or less defined by what the config.guess and * config.sub scripts from GNU autoconf emit. We have to lookup there what * triples are possible */ const char *cpu = triple_string; machine_triple_t *triple = XMALLOCZ(machine_triple_t); size_t cpu_type_len = manufacturer-cpu; triple->cpu_type = XMALLOCN(char, cpu_type_len); memcpy(triple->cpu_type, cpu, cpu_type_len-1); triple->cpu_type[cpu_type_len-1] = '\0'; /* process manufacturer, alot of people incorrectly leave out the * manufacturer instead of using unknown- */ if (strstart(manufacturer, "linux")) { triple->manufacturer = xstrdup("unknown"); os = manufacturer; } else { size_t manufacturer_len = os-manufacturer; triple->manufacturer = XMALLOCN(char, manufacturer_len); memcpy(triple->manufacturer, manufacturer, manufacturer_len-1); triple->manufacturer[manufacturer_len-1] = '\0'; } triple->operating_system = xstrdup(os); return triple; } diff --git a/driver/firm_machine.h b/driver/firm_machine.h index 47cdfae..c850b07 100644 --- a/driver/firm_machine.h +++ b/driver/firm_machine.h @@ -1,26 +1,30 @@ +/* + * This file is part of cparser. + * Copyright (C) 2012 Matthias Braun <[email protected]> + */ #ifndef FIRM_OS_H #define FIRM_OS_H #include <stdbool.h> typedef struct machine_triple_t { char *cpu_type; char *manufacturer; char *operating_system; } machine_triple_t; machine_triple_t *firm_get_host_machine(void); machine_triple_t *firm_parse_machine_triple(const char *triple_string); void firm_free_machine_triple(machine_triple_t *triple); bool setup_firm_for_machine(const machine_triple_t *machine); bool firm_is_unixish_os(const machine_triple_t *machine); bool firm_is_darwin_os(const machine_triple_t *machine); bool firm_is_windows_os(const machine_triple_t *machine); #endif diff --git a/driver/firm_opt.c b/driver/firm_opt.c index defb7aa..9ccb3e3 100644 --- a/driver/firm_opt.c +++ b/driver/firm_opt.c @@ -1,974 +1,965 @@ +/* + * This file is part of cparser. + * Copyright (C) 2012 Michael Beck <[email protected]> + */ + /** - * (C) 2005-2010 * @file * @author Michael Beck, Matthias Braun * @brief Firm-generating back end optimizations. */ #include <config.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <assert.h> #include <libfirm/firm.h> #include "firm_opt.h" #include "firm_timing.h" #include "ast2firm.h" #include "adt/strutil.h" #include "adt/util.h" /* optimization settings */ struct a_firm_opt { bool const_folding; /**< enable constant folding */ bool cse; /**< enable common-subexpression elimination */ bool confirm; /**< enable Confirm optimization */ bool muls; /**< enable architecture dependent mul optimization */ bool divs; /**< enable architecture dependent div optimization */ bool mods; /**< enable architecture dependent mod optimization */ bool alias_analysis; /**< enable Alias Analysis */ bool strict_alias; /**< enable strict Alias Analysis (using type based AA) */ bool no_alias; /**< no aliasing possible. */ bool verify; /**< Firm verifier setting */ bool check_all; /**< enable checking all Firm phases */ int clone_threshold; /**< The threshold value for procedure cloning. */ unsigned inline_maxsize; /**< Maximum function size for inlining. */ unsigned inline_threshold;/**< Inlining benefice threshold. */ }; /** statistic options */ typedef enum a_firmstat_selection_tag { STAT_NONE = 0x00000000, STAT_BEFORE_OPT = 0x00000001, STAT_AFTER_OPT = 0x00000002, STAT_AFTER_LOWER = 0x00000004, STAT_FINAL_IR = 0x00000008, STAT_FINAL = 0x00000010, } a_firmstat_selection; /* dumping options */ struct a_firm_dump { bool debug_print; /**< enable debug print */ bool all_types; /**< dump the All_types graph */ bool ir_graph; /**< dump all graphs */ bool all_phases; /**< dump the IR graph after all phases */ bool statistic; /**< Firm statistic setting */ - bool stat_pattern; /**< enable Firm statistic pattern */ - bool stat_dag; /**< enable Firm DAG statistic */ }; struct a_firm_be_opt { bool selection; bool node_stat; }; /* optimization settings */ static struct a_firm_opt firm_opt = { .const_folding = true, .cse = true, .confirm = true, .muls = true, .divs = true, .mods = true, .alias_analysis = true, .strict_alias = false, .no_alias = false, .verify = FIRM_VERIFICATION_ON, .check_all = true, .clone_threshold = DEFAULT_CLONE_THRESHOLD, .inline_maxsize = 750, .inline_threshold = 0, }; /* dumping options */ static struct a_firm_dump firm_dump = { .debug_print = false, .all_types = false, .ir_graph = false, .all_phases = false, .statistic = STAT_NONE, - .stat_pattern = 0, - .stat_dag = 0, }; #define X(a) a, sizeof(a)-1 /** Parameter description structure */ static const struct params { const char *option; /**< name of the option */ size_t opt_len; /**< length of the option string */ bool *flag; /**< address of variable to set/reset */ bool set; /**< iff true, variable will be set, else reset */ const char *description; /**< description of this option */ } firm_options[] = { /* firm optimization options */ { X("no-opt"), NULL, 0, "disable all FIRM optimizations" }, { X("cse"), &firm_opt.cse, 1, "enable common subexpression elimination" }, { X("no-cse"), &firm_opt.cse, 0, "disable common subexpression elimination" }, { X("const-fold"), &firm_opt.const_folding, 1, "enable constant folding" }, { X("no-const-fold"), &firm_opt.const_folding, 0, "disable constant folding" }, { X("inline-max-size=<size>"), NULL, 0, "set maximum size for function inlining" }, { X("inline-threshold=<size>"),NULL, 0, "set benefice threshold for function inlining" }, { X("confirm"), &firm_opt.confirm, 1, "enable Confirm optimization" }, { X("no-confirm"), &firm_opt.confirm, 0, "disable Confirm optimization" }, { X("opt-mul"), &firm_opt.muls, 0, "enable multiplication optimization" }, { X("no-opt-mul"), &firm_opt.muls, 0, "disable multiplication optimization" }, { X("opt-div"), &firm_opt.divs, 0, "enable division optimization" }, { X("no-opt-div"), &firm_opt.divs, 0, "disable division optimization" }, { X("opt-mod"), &firm_opt.mods, 0, "enable remainder optimization" }, { X("no-opt-mod"), &firm_opt.mods, 0, "disable remainder optimization" }, { X("opt-alias"), &firm_opt.alias_analysis, 1, "enable alias analysis" }, { X("no-opt-alias"), &firm_opt.alias_analysis, 0, "disable alias analysis" }, { X("alias"), &firm_opt.no_alias, 0, "aliasing occurs" }, { X("no-alias"), &firm_opt.no_alias, 1, "no aliasing occurs" }, { X("strict-aliasing"), &firm_opt.strict_alias, 1, "strict alias rules" }, { X("no-strict-aliasing"), &firm_opt.strict_alias, 0, "strict alias rules" }, { X("clone-threshold=<value>"),NULL, 0, "set clone threshold to <value>" }, /* other firm regarding options */ { X("verify-off"), &firm_opt.verify, FIRM_VERIFICATION_OFF, "disable node verification" }, { X("verify-on"), &firm_opt.verify, FIRM_VERIFICATION_ON, "enable node verification" }, { X("verify-report"), &firm_opt.verify, FIRM_VERIFICATION_REPORT, "node verification, report only" }, - { X("check-all"), &firm_opt.check_all, 1, "enable checking all Firm phases" }, - { X("no-check-all"), &firm_opt.check_all, 0, "disable checking all Firm phases" }, /* dumping */ { X("dump-ir"), &firm_dump.ir_graph, 1, "dump IR graph" }, { X("dump-all-types"), &firm_dump.all_types, 1, "dump graph of all types" }, { X("dump-all-phases"), &firm_dump.all_phases, 1, "dump graphs for all optimization phases" }, { X("dump-filter=<string>"), NULL, 0, "set dumper filter" }, /* misc */ { X("stat-before-opt"), &firm_dump.statistic, STAT_BEFORE_OPT, "Firm statistic output before optimizations" }, { X("stat-after-opt"), &firm_dump.statistic, STAT_AFTER_OPT, "Firm statistic output after optimizations" }, { X("stat-after-lower"), &firm_dump.statistic, STAT_AFTER_LOWER, "Firm statistic output after lowering" }, { X("stat-final-ir"), &firm_dump.statistic, STAT_FINAL_IR, "Firm statistic after final optimization" }, { X("stat-final"), &firm_dump.statistic, STAT_FINAL, "Firm statistic after code generation" }, - { X("stat-pattern"), &firm_dump.stat_pattern, 1, "Firm statistic calculates most used pattern" }, - { X("stat-dag"), &firm_dump.stat_dag, 1, "Firm calculates DAG statistics" }, }; #undef X static ir_timer_t *t_vcg_dump; static ir_timer_t *t_verify; static ir_timer_t *t_all_opt; static ir_timer_t *t_backend; static bool do_irg_opt(ir_graph *irg, const char *name); /** dump all the graphs depending on cond */ static void dump_all(const char *suffix) { if (!firm_dump.ir_graph) return; timer_push(t_vcg_dump); dump_all_ir_graphs(suffix); timer_pop(t_vcg_dump); } /* entities of runtime functions */ ir_entity *rts_entities[rts_max]; /** * Map runtime functions. */ static void rts_map(void) { static const struct { ir_entity **ent; /**< address of the rts entity */ i_mapper_func func; /**< mapper function. */ } mapper[] = { /* integer */ { &rts_entities[rts_abs], i_mapper_abs }, { &rts_entities[rts_labs], i_mapper_abs }, { &rts_entities[rts_llabs], i_mapper_abs }, { &rts_entities[rts_imaxabs], i_mapper_abs }, /* double -> double */ { &rts_entities[rts_fabs], i_mapper_abs }, { &rts_entities[rts_sqrt], i_mapper_sqrt }, { &rts_entities[rts_cbrt], i_mapper_cbrt }, { &rts_entities[rts_pow], i_mapper_pow }, { &rts_entities[rts_exp], i_mapper_exp }, { &rts_entities[rts_exp2], i_mapper_exp }, { &rts_entities[rts_exp10], i_mapper_exp }, { &rts_entities[rts_log], i_mapper_log }, { &rts_entities[rts_log2], i_mapper_log2 }, { &rts_entities[rts_log10], i_mapper_log10 }, { &rts_entities[rts_sin], i_mapper_sin }, { &rts_entities[rts_cos], i_mapper_cos }, { &rts_entities[rts_tan], i_mapper_tan }, { &rts_entities[rts_asin], i_mapper_asin }, { &rts_entities[rts_acos], i_mapper_acos }, { &rts_entities[rts_atan], i_mapper_atan }, { &rts_entities[rts_sinh], i_mapper_sinh }, { &rts_entities[rts_cosh], i_mapper_cosh }, { &rts_entities[rts_tanh], i_mapper_tanh }, /* float -> float */ { &rts_entities[rts_fabsf], i_mapper_abs }, { &rts_entities[rts_sqrtf], i_mapper_sqrt }, { &rts_entities[rts_cbrtf], i_mapper_cbrt }, { &rts_entities[rts_powf], i_mapper_pow }, { &rts_entities[rts_expf], i_mapper_exp }, { &rts_entities[rts_exp2f], i_mapper_exp }, { &rts_entities[rts_exp10f], i_mapper_exp }, { &rts_entities[rts_logf], i_mapper_log }, { &rts_entities[rts_log2f], i_mapper_log2 }, { &rts_entities[rts_log10f], i_mapper_log10 }, { &rts_entities[rts_sinf], i_mapper_sin }, { &rts_entities[rts_cosf], i_mapper_cos }, { &rts_entities[rts_tanf], i_mapper_tan }, { &rts_entities[rts_asinf], i_mapper_asin }, { &rts_entities[rts_acosf], i_mapper_acos }, { &rts_entities[rts_atanf], i_mapper_atan }, { &rts_entities[rts_sinhf], i_mapper_sinh }, { &rts_entities[rts_coshf], i_mapper_cosh }, { &rts_entities[rts_tanhf], i_mapper_tanh }, /* long double -> long double */ { &rts_entities[rts_fabsl], i_mapper_abs }, { &rts_entities[rts_sqrtl], i_mapper_sqrt }, { &rts_entities[rts_cbrtl], i_mapper_cbrt }, { &rts_entities[rts_powl], i_mapper_pow }, { &rts_entities[rts_expl], i_mapper_exp }, { &rts_entities[rts_exp2l], i_mapper_exp }, { &rts_entities[rts_exp10l], i_mapper_exp }, { &rts_entities[rts_logl], i_mapper_log }, { &rts_entities[rts_log2l], i_mapper_log2 }, { &rts_entities[rts_log10l], i_mapper_log10 }, { &rts_entities[rts_sinl], i_mapper_sin }, { &rts_entities[rts_cosl], i_mapper_cos }, { &rts_entities[rts_tanl], i_mapper_tan }, { &rts_entities[rts_asinl], i_mapper_asin }, { &rts_entities[rts_acosl], i_mapper_acos }, { &rts_entities[rts_atanl], i_mapper_atan }, { &rts_entities[rts_sinhl], i_mapper_sinh }, { &rts_entities[rts_coshl], i_mapper_cosh }, { &rts_entities[rts_tanhl], i_mapper_tanh }, /* string */ { &rts_entities[rts_strcmp], i_mapper_strcmp }, { &rts_entities[rts_strncmp], i_mapper_strncmp }, { &rts_entities[rts_strcpy], i_mapper_strcpy }, { &rts_entities[rts_strlen], i_mapper_strlen }, { &rts_entities[rts_memcpy], i_mapper_memcpy }, { &rts_entities[rts_mempcpy], i_mapper_mempcpy }, { &rts_entities[rts_memmove], i_mapper_memmove }, { &rts_entities[rts_memset], i_mapper_memset }, { &rts_entities[rts_memcmp], i_mapper_memcmp } }; i_record rec[lengthof(mapper)]; size_t n_map = 0; for (size_t i = 0; i != lengthof(mapper); ++i) { if (*mapper[i].ent != NULL) { rec[n_map].i_call.kind = INTRINSIC_CALL; rec[n_map].i_call.i_ent = *mapper[i].ent; rec[n_map].i_call.i_mapper = mapper[i].func; rec[n_map].i_call.ctx = NULL; rec[n_map].i_call.link = NULL; ++n_map; } } if (n_map > 0) lower_intrinsics(rec, n_map, /* part_block_used=*/0); } static int *irg_dump_no; +typedef enum opt_target { + OPT_TARGET_IRG, /**< optimization function works on a single graph */ + OPT_TARGET_IRP /**< optimization function works on the complete program */ +} opt_target_t; + +typedef enum opt_flags { + OPT_FLAG_NONE = 0, + OPT_FLAG_ENABLED = 1 << 0, /**< enable the optimization */ + OPT_FLAG_NO_DUMP = 1 << 1, /**< don't dump after transformation */ + OPT_FLAG_NO_VERIFY = 1 << 2, /**< don't verify after transformation */ + OPT_FLAG_HIDE_OPTIONS = 1 << 3, /**< do not automatically process + -foptions for this transformation */ + OPT_FLAG_ESSENTIAL = 1 << 4, /**< output won't work without this pass + so we need it even with -O0 */ +} opt_flags_t; + +typedef void (*transform_irg_func)(ir_graph *irg); +typedef void (*transform_irp_func)(void); + +typedef struct { + opt_target_t target; + const char *name; + union { + transform_irg_func transform_irg; + transform_irp_func transform_irp; + } u; + const char *description; + opt_flags_t flags; + ir_timer_t *timer; +} opt_config_t; + +static opt_config_t *get_opt(const char *name); + static void do_stred(ir_graph *irg) { opt_osr(irg, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift); } static void after_inline_opt(ir_graph *irg) { + opt_config_t *const config = get_opt("inline"); + timer_stop(config->timer); + do_irg_opt(irg, "scalar-replace"); do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); do_irg_opt(irg, "combo"); + + timer_start(config->timer); } static void do_inline(void) { inline_functions(firm_opt.inline_maxsize, firm_opt.inline_threshold, after_inline_opt); } static void do_cloning(void) { proc_cloning((float) firm_opt.clone_threshold); } static void do_lower_mux(ir_graph *irg) { lower_mux(irg, NULL); } static void do_gcse(ir_graph *irg) { set_opt_global_cse(1); optimize_graph_df(irg); set_opt_global_cse(0); } -typedef enum opt_target { - OPT_TARGET_IRG, /**< optimization function works on a single graph */ - OPT_TARGET_IRP /**< optimization function works on the complete program */ -} opt_target_t; - -typedef enum opt_flags { - OPT_FLAG_NONE = 0, - OPT_FLAG_ENABLED = 1 << 0, /**< enable the optimization */ - OPT_FLAG_NO_DUMP = 1 << 1, /**< don't dump after transformation */ - OPT_FLAG_NO_VERIFY = 1 << 2, /**< don't verify after transformation */ - OPT_FLAG_HIDE_OPTIONS = 1 << 3, /**< do not automatically process - -foptions for this transformation */ - OPT_FLAG_ESSENTIAL = 1 << 4, /**< output won't work without this pass - so we need it even with -O0 */ -} opt_flags_t; - -typedef void (*transform_irg_func)(ir_graph *irg); -typedef void (*transform_irp_func)(void); - -typedef struct { - opt_target_t target; - const char *name; - union { - transform_irg_func transform_irg; - transform_irp_func transform_irp; - } u; - const char *description; - opt_flags_t flags; - ir_timer_t *timer; -} opt_config_t; - static opt_config_t opts[] = { #define IRG(a, b, c, d) { OPT_TARGET_IRG, a, .u.transform_irg = (transform_irg_func)b, c, d } #define IRP(a, b, c, d) { OPT_TARGET_IRP, a, .u.transform_irp = b, c, d } IRG("bool", opt_bool, "bool simplification", OPT_FLAG_NONE), IRG("combo", combo, "combined CCE, UCE and GVN", OPT_FLAG_NONE), IRG("confirm", construct_confirms, "confirm optimization", OPT_FLAG_HIDE_OPTIONS), IRG("control-flow", optimize_cf, "optimization of control-flow", OPT_FLAG_HIDE_OPTIONS), IRG("dead", dead_node_elimination, "dead node elimination", OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY), IRG("deconv", conv_opt, "conv node elimination", OPT_FLAG_NONE), IRG("fp-vrp", fixpoint_vrp, "fixpoint value range propagation", OPT_FLAG_NONE), IRG("frame", opt_frame_irg, "remove unused frame entities", OPT_FLAG_NONE), IRG("gvn-pre", do_gvn_pre, "global value numbering partial redundancy elimination", OPT_FLAG_NONE), IRG("if-conversion", opt_if_conv, "if-conversion", OPT_FLAG_NONE), IRG("invert-loops", do_loop_inversion, "loop inversion", OPT_FLAG_NONE), IRG("ivopts", do_stred, "induction variable strength reduction", OPT_FLAG_NONE), IRG("local", local_opts, "local graph optimizations", OPT_FLAG_HIDE_OPTIONS), IRG("lower", lower_highlevel_graph, "lowering", OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL), IRG("lower-mux", do_lower_mux, "mux lowering", OPT_FLAG_NONE), IRG("opt-load-store", optimize_load_store, "load store optimization", OPT_FLAG_NONE), IRG("opt-tail-rec", opt_tail_rec_irg, "tail-recursion eliminiation", OPT_FLAG_NONE), IRG("parallelize-mem", opt_parallelize_mem, "parallelize memory", OPT_FLAG_NONE), IRG("gcse", do_gcse, "global common subexpression eliminiation", OPT_FLAG_NONE), IRG("place", place_code, "code placement", OPT_FLAG_NONE), IRG("reassociation", optimize_reassociation, "reassociation", OPT_FLAG_NONE), IRG("remove-confirms", remove_confirms, "confirm removal", OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY), IRG("remove-phi-cycles", remove_phi_cycles, "removal of phi cycles", OPT_FLAG_HIDE_OPTIONS), IRG("scalar-replace", scalar_replacement_opt, "scalar replacement", OPT_FLAG_NONE), IRG("shape-blocks", shape_blocks, "block shaping", OPT_FLAG_NONE), IRG("thread-jumps", opt_jumpthreading, "path-sensitive jumpthreading", OPT_FLAG_NONE), IRG("unroll-loops", do_loop_unrolling, "loop unrolling", OPT_FLAG_NONE), IRG("vrp", set_vrp_data, "value range propagation", OPT_FLAG_NONE), IRP("inline", do_inline, "inlining", OPT_FLAG_NONE), IRP("lower-const", lower_const_code, "lowering of constant code", OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY | OPT_FLAG_ESSENTIAL), + IRP("local-const", local_opts_const_code, "local optimisation of constant initializers", + OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY | OPT_FLAG_ESSENTIAL), IRP("target-lowering", be_lower_for_target, "lowering necessary for target architecture", OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL), IRP("opt-func-call", optimize_funccalls, "function call optimization", OPT_FLAG_NONE), IRP("opt-proc-clone", do_cloning, "procedure cloning", OPT_FLAG_NONE), IRP("remove-unused", garbage_collect_entities, "removal of unused functions/variables", OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY), IRP("rts", rts_map, "optimization of known library functions", OPT_FLAG_NONE), IRP("opt-cc", mark_private_methods, "calling conventions optimization", OPT_FLAG_NONE), #undef IRP #undef IRG }; #define FOR_EACH_OPT(i) for (opt_config_t *i = opts; i != endof(opts); ++i) static opt_config_t *get_opt(const char *name) { FOR_EACH_OPT(config) { if (streq(config->name, name)) return config; } return NULL; } static void set_opt_enabled(const char *name, bool enabled) { opt_config_t *config = get_opt(name); config->flags = (config->flags & ~OPT_FLAG_ENABLED) | (enabled ? OPT_FLAG_ENABLED : 0); } static bool get_opt_enabled(const char *name) { opt_config_t *config = get_opt(name); return (config->flags & OPT_FLAG_ENABLED) != 0; } /** * perform an optimization on a single graph * * @return true if something changed, false otherwise */ static bool do_irg_opt(ir_graph *irg, const char *name) { opt_config_t *const config = get_opt(name); assert(config != NULL); assert(config->target == OPT_TARGET_IRG); if (! (config->flags & OPT_FLAG_ENABLED)) return false; ir_graph *const old_irg = current_ir_graph; current_ir_graph = irg; - timer_push(config->timer); + timer_start(config->timer); config->u.transform_irg(irg); - timer_pop(config->timer); + timer_stop(config->timer); if (firm_dump.all_phases && firm_dump.ir_graph) { dump_ir_graph(irg, name); } - if (firm_opt.check_all) { + if (firm_opt.verify) { timer_push(t_verify); irg_verify(irg, VERIFY_ENFORCE_SSA); timer_pop(t_verify); } current_ir_graph = old_irg; return true; } static void do_irp_opt(const char *name) { opt_config_t *const config = get_opt(name); assert(config->target == OPT_TARGET_IRP); if (! (config->flags & OPT_FLAG_ENABLED)) return; - timer_push(config->timer); + timer_start(config->timer); config->u.transform_irp(); - timer_pop(config->timer); + timer_stop(config->timer); if (firm_dump.ir_graph && firm_dump.all_phases) { int i; for (i = get_irp_n_irgs() - 1; i >= 0; --i) { ir_graph *irg = get_irp_irg(i); dump_ir_graph(irg, name); } } - if (firm_opt.check_all) { + if (firm_opt.verify) { int i; timer_push(t_verify); for (i = get_irp_n_irgs() - 1; i >= 0; --i) { irg_verify(get_irp_irg(i), VERIFY_ENFORCE_SSA); } timer_pop(t_verify); } } /** * Enable transformations which should be always safe (and cheap) to perform */ static void enable_safe_defaults(void) { set_opt_enabled("remove-unused", true); set_opt_enabled("opt-tail-rec", true); set_opt_enabled("opt-func-call", true); set_opt_enabled("reassociation", true); set_opt_enabled("control-flow", true); set_opt_enabled("local", true); set_opt_enabled("lower-const", true); + set_opt_enabled("local-const", true); set_opt_enabled("scalar-replace", true); set_opt_enabled("place", true); set_opt_enabled("gcse", true); set_opt_enabled("confirm", true); set_opt_enabled("opt-load-store", true); set_opt_enabled("lower", true); set_opt_enabled("deconv", true); set_opt_enabled("remove-confirms", true); set_opt_enabled("ivopts", true); set_opt_enabled("dead", true); set_opt_enabled("remove-phi-cycles", true); set_opt_enabled("frame", true); set_opt_enabled("combo", true); set_opt_enabled("invert-loops", true); set_opt_enabled("target-lowering", true); set_opt_enabled("rts", true); set_opt_enabled("parallelize-mem", true); set_opt_enabled("opt-cc", true); } /** * run all the Firm optimizations * * @param input_filename the name of the (main) source file */ static void do_firm_optimizations(const char *input_filename) { size_t i; unsigned aa_opt; set_opt_alias_analysis(firm_opt.alias_analysis); aa_opt = aa_opt_no_opt; if (firm_opt.strict_alias) aa_opt |= aa_opt_type_based | aa_opt_byte_type_may_alias; if (firm_opt.no_alias) aa_opt = aa_opt_no_alias; set_irp_memory_disambiguator_options(aa_opt); /* parameter passing code should set them directly sometime... */ set_opt_enabled("confirm", firm_opt.confirm); set_opt_enabled("remove-confirms", firm_opt.confirm); /* osr supersedes remove_phi_cycles */ if (get_opt_enabled("ivopts")) set_opt_enabled("remove-phi-cycles", false); - timer_start(t_all_opt); - do_irp_opt("rts"); /* first step: kill dead code */ for (i = 0; i < get_irp_n_irgs(); i++) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "combo"); do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); } do_irp_opt("remove-unused"); for (i = 0; i < get_irp_n_irgs(); ++i) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "opt-tail-rec"); } do_irp_opt("opt-func-call"); do_irp_opt("lower-const"); for (i = 0; i < get_irp_n_irgs(); i++) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "scalar-replace"); do_irg_opt(irg, "invert-loops"); do_irg_opt(irg, "unroll-loops"); do_irg_opt(irg, "local"); do_irg_opt(irg, "reassociation"); do_irg_opt(irg, "local"); do_irg_opt(irg, "gcse"); do_irg_opt(irg, "place"); if (firm_opt.confirm) { /* Confirm construction currently can only handle blocks with only one control flow predecessor. Calling optimize_cf here removes Bad predecessors and help the optimization of switch constructs. */ do_irg_opt(irg, "control-flow"); do_irg_opt(irg, "confirm"); do_irg_opt(irg, "vrp"); do_irg_opt(irg, "local"); } do_irg_opt(irg, "control-flow"); do_irg_opt(irg, "opt-load-store"); do_irg_opt(irg, "fp-vrp"); do_irg_opt(irg, "lower"); do_irg_opt(irg, "deconv"); do_irg_opt(irg, "thread-jumps"); do_irg_opt(irg, "remove-confirms"); do_irg_opt(irg, "gvn-pre"); do_irg_opt(irg, "gcse"); do_irg_opt(irg, "place"); do_irg_opt(irg, "control-flow"); if (do_irg_opt(irg, "if-conversion")) { do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); } /* this doesn't make too much sense but tests the mux destruction... */ do_irg_opt(irg, "lower-mux"); do_irg_opt(irg, "bool"); do_irg_opt(irg, "shape-blocks"); do_irg_opt(irg, "ivopts"); do_irg_opt(irg, "local"); do_irg_opt(irg, "dead"); } do_irp_opt("inline"); do_irp_opt("opt-proc-clone"); for (i = 0; i < get_irp_n_irgs(); i++) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); do_irg_opt(irg, "thread-jumps"); do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); if( do_irg_opt(irg, "vrp") ) { // if vrp is enabled do_irg_opt(irg, "local"); do_irg_opt(irg, "vrp"); do_irg_opt(irg, "local"); do_irg_opt(irg, "vrp"); } } if (firm_dump.ir_graph) { /* recompute backedges for nicer dumps */ for (i = 0; i < get_irp_n_irgs(); i++) construct_cf_backedges(get_irp_irg(i)); } dump_all("opt"); if (firm_dump.statistic & STAT_AFTER_OPT) stat_dump_snapshot(input_filename, "opt"); - - timer_stop(t_all_opt); } /** * do Firm lowering * * @param input_filename the name of the (main) source file */ static void do_firm_lowering(const char *input_filename) { int i; /* enable architecture dependent optimizations */ arch_dep_set_opts((arch_dep_opts_t) ((firm_opt.muls ? arch_dep_mul_to_shift : arch_dep_none) | (firm_opt.divs ? arch_dep_div_by_const : arch_dep_none) | (firm_opt.mods ? arch_dep_mod_by_const : arch_dep_none) )); for (i = get_irp_n_irgs() - 1; i >= 0; --i) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "reassociation"); do_irg_opt(irg, "local"); } do_irp_opt("target-lowering"); if (firm_dump.statistic & STAT_AFTER_LOWER) stat_dump_snapshot(input_filename, "low"); - timer_start(t_all_opt); - for (i = get_irp_n_irgs() - 1; i >= 0; --i) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "local"); do_irg_opt(irg, "deconv"); do_irg_opt(irg, "control-flow"); do_irg_opt(irg, "opt-load-store"); do_irg_opt(irg, "gcse"); do_irg_opt(irg, "place"); do_irg_opt(irg, "control-flow"); if (do_irg_opt(irg, "vrp")) { do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); do_irg_opt(irg, "vrp"); do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); } if (do_irg_opt(irg, "if-conversion")) { do_irg_opt(irg, "local"); do_irg_opt(irg, "control-flow"); } - set_irg_state(irg, IR_GRAPH_STATE_NORMALISATION2); + add_irg_constraints(irg, IR_GRAPH_CONSTRAINT_NORMALISATION2); do_irg_opt(irg, "local"); do_irg_opt(irg, "parallelize-mem"); do_irg_opt(irg, "frame"); } + /* hack so we get global initializers constant folded even at -O0 */ + set_opt_constant_folding(1); + set_opt_algebraic_simplification(1); + do_irp_opt("local-const"); + set_opt_constant_folding(firm_opt.const_folding); + set_opt_algebraic_simplification(firm_opt.const_folding); do_irp_opt("remove-unused"); do_irp_opt("opt-cc"); - timer_stop(t_all_opt); dump_all("low-opt"); if (firm_dump.statistic & STAT_FINAL) { stat_dump_snapshot(input_filename, "final"); } } /** * Initialize for the Firm-generating back end. */ void gen_firm_init(void) { ir_init(); enable_safe_defaults(); FOR_EACH_OPT(i) { i->timer = ir_timer_new(); timer_register(i->timer, i->description); } t_verify = ir_timer_new(); timer_register(t_verify, "Firm: verify pass"); t_vcg_dump = ir_timer_new(); timer_register(t_vcg_dump, "Firm: vcg dumping"); t_all_opt = ir_timer_new(); timer_register(t_all_opt, "Firm: all optimizations"); t_backend = ir_timer_new(); timer_register(t_backend, "Firm: backend"); } -static void init_statistics(void) -{ - unsigned pattern = 0; - - if (firm_dump.stat_pattern) - pattern |= FIRMSTAT_PATTERN_ENABLED; - - if (firm_dump.stat_dag) - pattern |= FIRMSTAT_COUNT_DAG; - - firm_init_stat(firm_dump.statistic == STAT_NONE ? - 0 : FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP - | FIRMSTAT_COUNT_CONSTS | pattern); -} - /** * Called, after the Firm generation is completed, * do all optimizations and backend call here. * * @param out a file handle for the output, may be NULL * @param input_filename the name of the (main) source file */ void generate_code(FILE *out, const char *input_filename) { int i; /* initialize implicit opts, just to be sure because really the frontend * should have called it already before starting graph construction */ init_implicit_optimizations(); - init_statistics(); + firm_init_stat(); do_node_verification((firm_verification_t) firm_opt.verify); /* the general for dumping option must be set, or the others will not work*/ firm_dump.ir_graph = (bool) (firm_dump.ir_graph | firm_dump.all_phases); ir_add_dump_flags(ir_dump_flag_keepalive_edges | ir_dump_flag_consts_local | ir_dump_flag_dominance); ir_remove_dump_flags(ir_dump_flag_loops | ir_dump_flag_ld_names); /* FIXME: cloning might ADD new graphs. */ irg_dump_no = calloc(get_irp_last_idx(), sizeof(*irg_dump_no)); + ir_timer_init_parent(t_verify); + ir_timer_init_parent(t_vcg_dump); + timer_start(t_all_opt); + if (firm_dump.all_types) { dump_ir_prog_ext(dump_typegraph, "types.vcg"); } dump_all(""); - timer_push(t_verify); - tr_verify(); - timer_pop(t_verify); - - /* all graphs are finalized, set the irp phase to high */ - set_irp_phase_state(phase_high); + if (firm_opt.verify) { + timer_push(t_verify); + tr_verify(); + timer_pop(t_verify); + } /* BEWARE: kill unreachable code before doing compound lowering */ for (i = get_irp_n_irgs() - 1; i >= 0; --i) { ir_graph *irg = get_irp_irg(i); do_irg_opt(irg, "control-flow"); } if (firm_dump.statistic & STAT_BEFORE_OPT) { stat_dump_snapshot(input_filename, "noopt"); } do_firm_optimizations(input_filename); do_firm_lowering(input_filename); - /* set the phase to low */ - for (i = get_irp_n_irgs() - 1; i >= 0; --i) - set_irg_phase_state(get_irp_irg(i), phase_low); + timer_stop(t_all_opt); if (firm_dump.statistic & STAT_FINAL_IR) stat_dump_snapshot(input_filename, "final-ir"); /* run the code generator */ timer_start(t_backend); be_main(out, input_filename); timer_stop(t_backend); if (firm_dump.statistic & STAT_FINAL) stat_dump_snapshot(input_filename, "final"); } void gen_firm_finish(void) { ir_finish(); } static void disable_all_opts(void) { firm_opt.cse = false; firm_opt.confirm = false; firm_opt.muls = false; firm_opt.divs = false; firm_opt.mods = false; firm_opt.alias_analysis = false; firm_opt.strict_alias = false; firm_opt.no_alias = false; firm_opt.const_folding = false; FOR_EACH_OPT(config) { if (config->flags & OPT_FLAG_ESSENTIAL) { config->flags |= OPT_FLAG_ENABLED; } else { config->flags &= ~OPT_FLAG_ENABLED; } } } static bool firm_opt_option(const char *opt) { char const* const rest = strstart(opt, "no-"); bool const enable = rest ? opt = rest, false : true; opt_config_t *config = get_opt(opt); if (config == NULL || (config->flags & OPT_FLAG_HIDE_OPTIONS)) return false; config->flags &= ~OPT_FLAG_ENABLED; config->flags |= enable ? OPT_FLAG_ENABLED : 0; return true; } void firm_option_help(print_option_help_func print_option_help) { FOR_EACH_OPT(config) { char buf[1024]; char buf2[1024]; if (config->flags & OPT_FLAG_HIDE_OPTIONS) continue; snprintf(buf, sizeof(buf), "-f%s", config->name); snprintf(buf2, sizeof(buf2), "enable %s", config->description); print_option_help(buf, buf2); snprintf(buf, sizeof(buf), "-fno-%s", config->name); snprintf(buf2, sizeof(buf2), "disable %s", config->description); print_option_help(buf, buf2); } for (size_t k = 0; k != lengthof(firm_options); ++k) { char buf[1024]; char buf2[1024]; snprintf(buf, sizeof(buf), "-f%s", firm_options[k].option); snprintf(buf2, sizeof(buf2), "%s", firm_options[k].description); print_option_help(buf, buf2); } } int firm_option(const char *const opt) { char const* val; if ((val = strstart(opt, "dump-filter="))) { ir_set_dump_filter(val); return 1; } else if ((val = strstart(opt, "clone-threshold="))) { sscanf(val, "%d", &firm_opt.clone_threshold); return 1; } else if ((val = strstart(opt, "inline-max-size="))) { sscanf(val, "%u", &firm_opt.inline_maxsize); return 1; } else if ((val = strstart(opt, "inline-threshold="))) { sscanf(val, "%u", &firm_opt.inline_threshold); return 1; } else if (streq(opt, "no-opt")) { disable_all_opts(); return 1; } size_t const len = strlen(opt); for (size_t i = lengthof(firm_options); i != 0;) { struct params const* const o = &firm_options[--i]; if (len == o->opt_len && memcmp(opt, o->option, len) == 0) { /* statistic options do accumulate */ if (o->flag == &firm_dump.statistic) *o->flag = (bool) (*o->flag | o->set); else *o->flag = o->set; return 1; } } /* maybe this enables/disables optimizations */ if (firm_opt_option(opt)) return 1; return 0; } static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } static void set_option(const char *arg) { int res = firm_option(arg); (void) res; assert(res); } void choose_optimization_pack(int level) { /* apply optimization level */ switch(level) { case 0: set_option("no-opt"); break; case 1: set_option("no-inline"); break; default: case 4: /* use_builtins = true; */ /* fallthrough */ case 3: set_option("thread-jumps"); set_option("if-conversion"); /* fallthrough */ case 2: set_option("strict-aliasing"); set_option("inline"); set_option("fp-vrp"); set_option("deconv"); set_be_option("omitfp"); break; } } void init_implicit_optimizations(void) { set_optimize(1); set_opt_constant_folding(firm_opt.const_folding); set_opt_algebraic_simplification(firm_opt.const_folding); set_opt_cse(firm_opt.cse); set_opt_global_cse(0); } diff --git a/driver/firm_opt.h b/driver/firm_opt.h index 90938cf..294acc9 100644 --- a/driver/firm_opt.h +++ b/driver/firm_opt.h @@ -1,127 +1,131 @@ +/* + * This file is part of cparser. + * Copyright (C) 2012 Michael Beck <[email protected]> + */ #ifndef FIRM_OPT_H #define FIRM_OPT_H #include <stdio.h> #include <libfirm/firm_types.h> #include <libfirm/dbginfo.h> enum rts_names { rts_debugbreak, /**< the name of the __debugbreak() intrinsic */ rts_abort, /**< the name of the abort() function */ rts_abs, /**< the name of the abs() function */ rts_alloca, /**< the name of the alloca() function */ rts_labs, /**< the name of the labs() function */ rts_llabs, /**< the name of the llabs() function */ rts_imaxabs, /**< the name of the imaxabs() function */ /* double -> double functions */ rts_fabs, /**< the name of the fabs() function */ rts_sqrt, /**< the name of the sqrt() function */ rts_cbrt, /**< the name of the cbrt() function */ rts_pow, /**< the name of the pow() function */ rts_exp, /**< the name of the exp() function */ rts_exp2, /**< the name of the exp2() function */ rts_exp10, /**< the name of the exp10() function */ rts_log, /**< the name of the log() function */ rts_log2, /**< the name of the log2() function */ rts_log10, /**< the name of the log10() function */ rts_sin, /**< the name of the sin() function */ rts_cos, /**< the name of the cos() function */ rts_tan, /**< the name of the tan() function */ rts_asin, /**< the name of the asin() function */ rts_acos, /**< the name of the acos() function */ rts_atan, /**< the name of the atan() function */ rts_sinh, /**< the name of the sinh() function */ rts_cosh, /**< the name of the cosh() function */ rts_tanh, /**< the name of the tanh() function */ /* float -> float functions */ rts_fabsf, /**< the name of the fabsf() function */ rts_sqrtf, /**< the name of the sqrtf() function */ rts_cbrtf, /**< the name of the cbrtf() function */ rts_powf, /**< the name of the powf() function */ rts_expf, /**< the name of the expf() function */ rts_exp2f, /**< the name of the exp2f() function */ rts_exp10f, /**< the name of the exp10f() function */ rts_logf, /**< the name of the logf() function */ rts_log2f, /**< the name of the log2f() function */ rts_log10f, /**< the name of the log10f() function */ rts_sinf, /**< the name of the sinf() function */ rts_cosf, /**< the name of the cosf() function */ rts_tanf, /**< the name of the tanf() function */ rts_asinf, /**< the name of the asinf() function */ rts_acosf, /**< the name of the acosf() function */ rts_atanf, /**< the name of the atanf() function */ rts_sinhf, /**< the name of the sinhf() function */ rts_coshf, /**< the name of the coshf() function */ rts_tanhf, /**< the name of the tanhf() function */ /* long double -> long double functions */ rts_fabsl, /**< the name of the fabsl() function */ rts_sqrtl, /**< the name of the sqrtl() function */ rts_cbrtl, /**< the name of the cbrtl() function */ rts_powl, /**< the name of the powl() function */ rts_expl, /**< the name of the expl() function */ rts_exp2l, /**< the name of the exp2l() function */ rts_exp10l, /**< the name of the exp10l() function */ rts_logl, /**< the name of the log() function */ rts_log2l, /**< the name of the log2() function */ rts_log10l, /**< the name of the log10() function */ rts_sinl, /**< the name of the sinl() function */ rts_cosl, /**< the name of the cosl() function */ rts_tanl, /**< the name of the tanl() function */ rts_asinl, /**< the name of the asinl() function */ rts_acosl, /**< the name of the acosl() function */ rts_atanl, /**< the name of the atanl() function */ rts_sinhl, /**< the name of the sinhl() function */ rts_coshl, /**< the name of the coshl() function */ rts_tanhl, /**< the name of the tanhl() function */ /* string functions */ rts_strcmp, /**< the name of the strcmp() function */ rts_strncmp, /**< the name of the strncmp() function */ rts_strcpy, /**< the name of the strcpy() function */ rts_strlen, /**< the name of the strlen() function */ rts_memcpy, /**< the name of the memcpy() function */ rts_mempcpy, /**< the name of the mempcpy() function */ rts_memmove, /**< the name of the memmove() function */ rts_memset, /**< the name of the memset() function */ rts_memcmp, /**< the name of the memcmp() function */ rts_max }; extern ir_entity *rts_entities[rts_max]; /** Initialize for the Firm-generating back end. */ void gen_firm_init(void); /** free resources hold by firm-generating back end */ void gen_firm_finish(void); /** * Transform, optimize and generate code * * @param out a file handle for the output, may be NULL * @param input_filename the name of the (main) source file */ void generate_code(FILE *out, const char *input_filename); /** process optimization commandline option */ int firm_option(const char *opt); typedef void (*print_option_help_func)(const char *name, const char *description); void firm_option_help(print_option_help_func func); /** Choose an optimization level. (Typically used to interpret the -O compiler * switches) */ void choose_optimization_pack(int level); /** * Initialize implicit optimization settings in firm. Frontends should call this * before starting graph construction */ void init_implicit_optimizations(void); #endif diff --git a/driver/firm_timing.c b/driver/firm_timing.c index 8503bc9..ae8f543 100644 --- a/driver/firm_timing.c +++ b/driver/firm_timing.c @@ -1,86 +1,91 @@ +/* + * This file is part of cparser. + * Copyright (C) 2012 Michael Beck <[email protected]> + */ + /** - * @file firm_timing.c -- timing for the Firm compiler - * - * (C) 2006-2009 Michael Beck [email protected] + * @file + * @brief timing for the Firm compiler */ #include "firm_timing.h" #include <libfirm/adt/xmalloc.h> static int timers_inited; typedef struct timer_info_t { struct timer_info_t *next; char *description; ir_timer_t *timer; } timer_info_t; static timer_info_t *infos; static timer_info_t *last_info; void timer_register(ir_timer_t *timer, const char *description) { timer_info_t *info = XMALLOCZ(timer_info_t); info->description = xstrdup(description); info->timer = timer; if (last_info != NULL) { last_info->next = info; } else { infos = info; } last_info = info; } void timer_init(void) { timers_inited = 1; } void timer_term(FILE *f) { timer_info_t *info; timer_info_t *next; for (info = infos; info != NULL; info = next) { ir_timer_t *timer = info->timer; - double val = (double)ir_timer_elapsed_usec(timer) / 1000.0; - const char *description = info->description; - fprintf(f, "%-45s %8.3f msec\n", description, val); + if (f != NULL) { + double val = (double)ir_timer_elapsed_usec(timer) / 1000.0; + const char *description = info->description; + fprintf(f, "%-60s %10.3f msec\n", description, val); + } ir_timer_free(timer); - xfree(info->description); + free(info->description); next = info->next; - xfree(info); + free(info); } infos = NULL; last_info = NULL; timers_inited = 0; } void timer_push(ir_timer_t *timer) { if (timers_inited) ir_timer_push(timer); } void timer_pop(ir_timer_t *timer) { - (void) timer; if (timers_inited) - ir_timer_pop(); + ir_timer_pop(timer); } void timer_start(ir_timer_t *timer) { if (timers_inited) ir_timer_start(timer); } void timer_stop(ir_timer_t *timer) { if (timers_inited) ir_timer_stop(timer); } diff --git a/driver/firm_timing.h b/driver/firm_timing.h index 4a8e011..0a724aa 100644 --- a/driver/firm_timing.h +++ b/driver/firm_timing.h @@ -1,20 +1,24 @@ +/* + * This file is part of cparser. + * Copyright (C) 2012 Michael Beck <[email protected]> + */ + /** - * @file firm_timing.h -- timing for the Firm compiler - * - * (C) 2006 Michael Beck [email protected] + * @file + * @brief timing for the Firm compiler */ #ifndef __FIRM_TIMING_H__ #define __FIRM_TIMING_H__ #include <stdio.h> #include <libfirm/timing.h> void timer_init(void); void timer_register(ir_timer_t *timer, const char *description); void timer_term(FILE *f); void timer_push(ir_timer_t *timer); void timer_pop(ir_timer_t *timer); void timer_start(ir_timer_t *timer); void timer_stop(ir_timer_t *timer); #endif
MatzeB/fluffy
fec749413d8c29a81d5b31a40f62f23dc33e54a0
fix whitespace errors
diff --git a/ast.c b/ast.c index cb1c382..907701a 100644 --- a/ast.c +++ b/ast.c @@ -1,758 +1,758 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for (const char *c = string_const->value; *c != 0; ++c) { switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->function); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->entity == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->entity->base.symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch (unexpr->base.kind) { case EXPR_UNARY_CAST: fprintf(out, "cast<"); print_type(unexpr->base.type); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->base.kind); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch (binexpr->base.kind) { case EXPR_BINARY_ASSIGN: fprintf(out, "<-"); break; case EXPR_BINARY_ADD: fprintf(out, "+"); break; case EXPR_BINARY_SUB: fprintf(out, "-"); break; case EXPR_BINARY_MUL: fprintf(out, "*"); break; case EXPR_BINARY_DIV: fprintf(out, "/"); break; case EXPR_BINARY_NOTEQUAL: fprintf(out, "/="); break; case EXPR_BINARY_EQUAL: fprintf(out, "="); break; case EXPR_BINARY_LESS: fprintf(out, "<"); break; case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; case EXPR_BINARY_GREATER: fprintf(out, ">"); break; case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->base.kind); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->kind) { case EXPR_ERROR: fprintf(out, "*error expression*"); break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_FUNC: /* TODO */ fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { indent++; print_statement(statement); indent--; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->value != NULL) print_expression(statement->value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->label.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_t *label = &statement->label; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable(const variable_t *variable) { fprintf(out, "var"); if (variable->type != NULL) { fprintf(out, "<"); print_type(variable->type); fprintf(out, ">"); } fprintf(out, " %s", variable->base.symbol->string); } static void print_declaration_statement(const declaration_statement_t *statement) { print_variable(&statement->entity); } void print_statement(const statement_t *statement) { print_indent(); switch (statement->kind) { case STATEMENT_BLOCK: print_block_statement(&statement->block); break; case STATEMENT_RETURN: print_return_statement(&statement->returns); break; case STATEMENT_EXPRESSION: print_expression_statement(&statement->expression); break; case STATEMENT_LABEL: print_label_statement(&statement->label); break; case STATEMENT_GOTO: print_goto_statement(&statement->gotos); break; case STATEMENT_IF: print_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: print_declaration_statement(&statement->declaration); break; case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); - + type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_function_parameters(const function_parameter_t *parameters, const function_type_t *function_type) { fprintf(out, "("); int first = 1; const function_parameter_t *parameter = parameters; - const function_parameter_type_t *parameter_type + const function_parameter_type_t *parameter_type = function_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_function(const function_entity_t *function_entity) { const function_t *function = &function_entity->function; function_type_t *type = function->type; fprintf(out, "func "); if (function->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", function_entity->base.symbol->string); print_type_parameters(function->type_parameters); print_function_parameters(function->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (function->statement != NULL) { fprintf(out, ":\n"); print_statement(function->statement); } else { fprintf(out, "\n"); } } static void print_concept_function(const concept_function_t *function) { fprintf(out, "\tfunc "); fprintf(out, "%s", function->base.symbol->string); print_function_parameters(function->parameters, function->type); fprintf(out, " : "); print_type(function->type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_function_t *function = concept->functions; while (function != NULL) { print_concept_function(function); function = function->next; } } static void print_concept_function_instance( concept_function_instance_t *function_instance) { fprintf(out, "\tfunc "); const function_t *function = &function_instance->function; if (function_instance->concept_function != NULL) { concept_function_t *function = function_instance->concept_function; fprintf(out, "%s", function->base.symbol->string); } else { fprintf(out, "?%s", function_instance->symbol->string); } print_function_parameters(function->parameters, function->type); fprintf(out, " : "); print_type(function_instance->function.type->result_type); if (function->statement != NULL) { fprintf(out, ":\n"); print_statement(function->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_function_instance_t *function_instance = instance->function_instances; while (function_instance != NULL) { print_concept_function_instance(function_instance); function_instance = function_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_entity(const entity_t *entity) { print_indent(); switch (entity->kind) { case ENTITY_FUNCTION: print_function(&entity->function); break; case ENTITY_CONCEPT: print_concept(&entity->concept); break; case ENTITY_VARIABLE: print_variable(&entity->variable); break; case ENTITY_TYPEALIAS: print_typealias(&entity->typealias); break; case ENTITY_CONSTANT: print_constant(&entity->constant); break; case ENTITY_CONCEPT_FUNCTION: case ENTITY_FUNCTION_PARAMETER: case ENTITY_ERROR: // TODO fprintf(out, "some entity of type '%s'\n", get_entity_kind_name(entity->kind)); break; case ENTITY_TYPE_VARIABLE: case ENTITY_LABEL: break; case ENTITY_INVALID: fprintf(out, "invalid entity (%s)\n", get_entity_kind_name(entity->kind)); break; } } static void print_context(const context_t *context) { for (entity_t *entity = context->entities; entity != NULL; entity = entity->base.next) { print_entity(entity); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } void print_ast(FILE *new_out, const context_t *context) { indent = 0; out = new_out; print_context(context); assert(indent == 0); out = NULL; } const char *get_entity_kind_name(entity_kind_t type) { switch (type) { case ENTITY_ERROR: return "parse error"; case ENTITY_INVALID: return "invalid reference"; case ENTITY_VARIABLE: return "variable"; case ENTITY_CONSTANT: return "constant"; case ENTITY_FUNCTION_PARAMETER: return "function parameter"; case ENTITY_FUNCTION: return "function"; case ENTITY_CONCEPT: return "concept"; case ENTITY_TYPEALIAS: return "type alias"; case ENTITY_TYPE_VARIABLE: return "type variable"; case ENTITY_LABEL: return "label"; case ENTITY_CONCEPT_FUNCTION: return "concept function"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression(void) { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement(void) { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_entity(void) { static unsigned nextid = ENTITY_LAST; ++nextid; return nextid; } bool is_linktime_constant(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: /* TODO */ return false; case EXPR_ARRAY_ACCESS: /* TODO */ return false; case EXPR_UNARY_DEREFERENCE: return is_constant_expression(expression->unary.value); default: return false; } } bool is_constant_expression(const expression_t *expression) { switch (expression->kind) { case EXPR_INT_CONST: case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_NULL_POINTER: case EXPR_SIZEOF: return true; case EXPR_STRING_CONST: case EXPR_FUNC: case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: case EXPR_UNARY_DEREFERENCE: case EXPR_BINARY_ASSIGN: case EXPR_SELECT: case EXPR_ARRAY_ACCESS: return false; case EXPR_UNARY_TAKE_ADDRESS: return is_linktime_constant(expression->unary.value); case EXPR_REFERENCE: { entity_t *entity = expression->reference.entity; if (entity->kind == ENTITY_CONSTANT) return true; return false; } case EXPR_CALL: /* TODO: we might introduce pure/side effect free calls */ return false; case EXPR_UNARY_CAST: case EXPR_UNARY_NEGATE: case EXPR_UNARY_NOT: case EXPR_UNARY_BITWISE_NOT: return is_constant_expression(expression->unary.value); case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: case EXPR_BINARY_MUL: case EXPR_BINARY_DIV: case EXPR_BINARY_MOD: case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: /* not that lazy and/or are not constant if their value is clear after * evaluating the left side. This is because we can't (always) evaluate the * left hand side until the ast2firm phase, and therefore can't determine * constness */ case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: return is_constant_expression(expression->binary.left) && is_constant_expression(expression->binary.right); case EXPR_ERROR: return true; case EXPR_INVALID: break; } panic("invalid expression in is_constant_expression"); } diff --git a/ast2firm.c b/ast2firm.c index c3d6870..d1c9029 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -295,1570 +295,1570 @@ static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(ir_type_void); type->base.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_node *expression_to_firm(expression_t *expression); static ir_tarval *fold_constant_to_tarval(expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } ir_tarval* tv = get_Const_tarval(cnst); return tv; } long fold_constant_to_int(expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; ir_tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type*)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *type_ir = new_type_struct(id); type->base.firm_type = type_ir; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type *entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(type_ir, ident, entry_ir_type); set_entity_offset(entity, offset); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(type_ir, align_all); set_type_size_bytes(type_ir, offset); set_type_state(type_ir, layout_fixed); return type_ir; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *type_ir = new_type_union(id); type->base.firm_type = type_ir; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type *entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(type_ir, ident, entry_ir_type); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(type_ir, align_all); set_type_size_bytes(type_ir, size); set_type_state(type_ir, layout_fixed); return type_ir; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->base.kind == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->base.firm_type != NULL) { assert(type->base.firm_type != INVALID_TYPE); return type->base.firm_type; } ir_type *firm_type = NULL; switch (type->kind) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, &type->atomic); break; case TYPE_FUNCTION: firm_type = get_function_type(env, &type->function); break; case TYPE_POINTER: firm_type = get_pointer_type(env, &type->pointer); break; case TYPE_ARRAY: firm_type = get_array_type(env, &type->array); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_ANY */ firm_type = new_type_primitive(mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, &type->compound); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, &type->compound); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, &type->reference); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, &type->bind_typevariables); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->base.firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static ir_mode *get_arithmetic_mode(type_t *type) { if (type->kind == TYPE_ATOMIC && type->atomic.akind == ATOMIC_TYPE_BOOL) { return mode_b; } /* TODO: does not work for typealiases, typevariables, etc. */ return get_ir_mode(type); } static instantiate_function_t *queue_function_instantiation( function_t *function, ir_entity *entity) { instantiate_function_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->function = function; instantiate->entity = entity; pdeq_putr(instantiate_functions, instantiate); return instantiate; } static int is_polymorphic_function(const function_t *function) { return function->type_parameters != NULL; } static ir_entity* get_concept_function_instance_entity( concept_function_instance_t *function_instance) { function_t *function = & function_instance->function; if (function->e.entity != NULL) return function->e.entity; function_type_t *function_type = function->type; concept_function_t *concept_function = function_instance->concept_function; concept_t *concept = concept_function->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_function->base.symbol); concept_instance_t *instance = function_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, ir_visibility_local); function->e.entity = entity; return entity; } static ir_entity* get_function_entity(function_t *function, symbol_t *symbol, bool exported) { function_type_t *function_type = function->type; int is_polymorphic = is_polymorphic_function(function); if (!is_polymorphic && function->e.entity != NULL) { return function->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = function->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && function->e.entities != NULL) { int len = ARR_LEN(function->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = function->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (!function->is_extern && !exported) { set_entity_visibility(entity, ir_visibility_local); } if (!is_polymorphic) { function->e.entity = entity; } else { if (function->e.entities == NULL) function->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, function->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *create_symconst(dbg_info *dbgi, ir_entity *entity) { assert(entity != NULL); union symconst_symbol sym; sym.entity_p = entity; return new_d_SymConst(dbgi, mode_P, sym, symconst_addr_ent); } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(1, byte_ir_type); ir_entity *entity = new_entity(global_type, unique_ident("str"), type); add_entity_linkage(entity, IR_LINKAGE_CONSTANT); set_entity_allocation(entity, allocation_static); set_entity_visibility(entity, ir_visibility_private); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; const size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); ir_tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } ir_initializer_t *initializer = create_initializer_compound(slen); for (size_t i = 0; i < slen; ++i) { ir_tarval *tv = new_tarval_from_long(string[i], mode); ir_initializer_t *val = create_initializer_tarval(tv); set_initializer_compound_value(initializer, i, val); } set_entity_initializer(entity, initializer); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return create_symconst(dbgi, entity); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); ir_tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); ir_tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); - dbg_info *dbgi + dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P); return add; } static ir_entity *create_variable_entity(variable_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); if (variable->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = create_symconst(dbgi, entity); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; - if (type->kind == TYPE_COMPOUND_STRUCT + if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; return get_value(variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { entity_t *entity = reference->entity; switch (entity->kind) { case ENTITY_VARIABLE: return variable_addr(&entity->variable); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_FUNCTION: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { - const unary_expression_t *unexpr + const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { - const reference_expression_t *ref + const reference_expression_t *ref = (const reference_expression_t*) dest_expr; entity_t *entity = ref->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = &entity->variable; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; - if (type->kind == TYPE_COMPOUND_STRUCT + if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_Proj(result, mode_M, pn_CopyB_M); set_store(mem); } else { if (get_irn_mode(value) == mode_b) { value = new_Conv(value, get_atomic_mode(ATOMIC_TYPE_BOOL)); } result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_Proj(result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static ir_relation binexpr_kind_to_relation(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return ir_relation_equal; case EXPR_BINARY_NOTEQUAL: return ir_relation_less_greater; case EXPR_BINARY_LESS: return ir_relation_less; case EXPR_BINARY_LESSEQUAL: return ir_relation_less_equal; case EXPR_BINARY_GREATER: return ir_relation_greater; case EXPR_BINARY_GREATEREQUAL: return ir_relation_greater_equal; default: break; } panic("unknown relation"); } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_Proj(cond, mode_X, pn_Cond_true); ir_node *false_proj = new_Proj(cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = new_Pin(new_NoMem()); ir_node *node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); return new_Proj(node, mode, pn_Div_res); } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = new_Pin(new_NoMem()); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); return new_Proj(node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ ir_relation relation = binexpr_kind_to_relation(kind); ir_node *cmp = new_d_Cmp(dbgi, left, right, relation); return cmp; } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); assert(node != NULL); if (to_type == type_void) { return NULL; } else { ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); return new_d_Conv(dbgi, node, mode); } } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_Proj(load, mode_M, pn_Load_M); ir_node *val = new_Proj(load, mode, pn_Load_res); set_store(mem); ir_mode *result_mode = get_arithmetic_mode(type); if (result_mode != mode) val = new_Conv(val, result_mode); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; - if (entry_type->kind == TYPE_COMPOUND_STRUCT + if (entry_type->kind == TYPE_COMPOUND_STRUCT || entry_type->kind == TYPE_COMPOUND_UNION || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(function_entity_t *function_entity, type_argument_t *type_arguments) { assert(function_entity->base.kind == ENTITY_FUNCTION); function_t *function = &function_entity->function; symbol_t *symbol = function_entity->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(function->type_parameters, type_arguments); ir_entity *entity = get_function_entity(function, symbol, function_entity->base.exported); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if (strset_find(&instantiated_functions, name) != NULL) { return entity; } - instantiate_function_t *instantiate + instantiate_function_t *instantiate = queue_function_instantiation(function, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_functions, name); return entity; } static ir_node *function_reference_to_firm(function_entity_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(function, type_arguments); ir_node *symconst = create_symconst(dbgi, entity); return symconst; } static ir_node *concept_function_reference_to_firm(concept_function_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = function->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at function '%s' from '%s'\n", function->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } - concept_function_instance_t *function_instance + concept_function_instance_t *function_instance = get_function_from_concept_instance(instance, function); if (function_instance == NULL) { fprintf(stderr, "panic: no function '%s' in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_function_instance_entity(function_instance); ir_node *symconst = create_symconst(dbgi, entity); pop_type_variable_bindings(old_top); return symconst; } static ir_node *function_parameter_reference_to_firm(function_parameter_t *parameter) { ir_mode *mode = get_ir_mode(parameter->type); return get_value(parameter->value_number, mode); } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); ir_tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *create_conv(dbg_info *dbgi, ir_node *op, ir_mode *dest_mode) { ir_mode *src_mode = get_irn_mode(op); if (src_mode == dest_mode) return op; if (dest_mode == mode_b) { ir_tarval *tv_zero = get_mode_null(src_mode); ir_node *zero = new_Const(tv_zero); return new_d_Cmp(dbgi, op, zero, ir_relation_less_greater); } return new_d_Conv(dbgi, op, dest_mode); } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *function = call->function; ir_node *callee = expression_to_firm(function); assert(function->base.type->kind == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) function->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->kind == TYPE_FUNCTION); function_type_t *function_type = (function_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (function_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (size_t i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_type *irtype = get_ir_type(expression->base.type); ir_node *arg_node = expression_to_firm(expression); ir_mode *mode = get_type_mode(irtype); if (mode != NULL && get_irn_mode(arg_node) != mode) { arg_node = new_Conv(arg_node, mode); } in[n] = arg_node; if (new_method_type != NULL) { set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_Proj(node, mode_M, pn_Call_M); set_store(mem); type_t *result_type = function_type->result_type; ir_node *result = NULL; if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_Proj(node, mode_T, pn_Call_T_result); result = new_Proj(resproj, mode, 0); ir_mode *result_mode = get_arithmetic_mode(result_type); result = create_conv(dbgi, result, result_mode); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { function_t *function = &expression->function; ir_entity *entity = function->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_function_entity(function, symbol, false); } queue_function_instantiation(function, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { entity_t *entity = reference->entity; type_argument_t *type_arguments = reference->type_arguments; const source_position_t *source_position = &reference->base.source_position; switch (entity->kind) { case ENTITY_FUNCTION: return function_reference_to_firm(&entity->function, type_arguments, source_position); case ENTITY_CONCEPT_FUNCTION: return concept_function_reference_to_firm( &entity->concept_function, type_arguments, source_position); case ENTITY_FUNCTION_PARAMETER: return function_parameter_reference_to_firm(&entity->parameter); case ENTITY_CONSTANT: return constant_reference_to_firm(&entity->constant); case ENTITY_VARIABLE: return variable_to_firm(&entity->variable, source_position); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_LABEL: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); expression_t *value = statement->value; ir_node *ret; if (value != NULL) { ir_node *retval = expression_to_firm(value); ir_mode *mode = get_ir_mode(value->base.type); if (get_irn_mode(retval) != mode) { retval = new_d_Conv(dbgi, retval, mode); } ir_node *in[1] = { retval }; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_Proj(cond, mode_X, pn_Cond_true); ir_node *false_proj = new_Proj(cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { - dbg_info *dbgi + dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_t *label = &label_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_function(function_t *function, ir_entity *entity, type_argument_t *type_arguments) { if (function->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_function(function)) { assert(type_arguments != NULL); push_type_variable_bindings(function->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, function->n_local_vars); set_current_ir_graph(irg); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(function->n_local_vars * sizeof(value_numbers[0])); /* create initial values for variables */ ir_node *args = get_irg_args(irg); int parameter_num = 0; for (function_parameter_t *parameter = function->parameters; parameter != NULL; parameter = parameter->next, ++parameter_num) { ir_mode *mode = get_ir_mode(parameter->type); ir_node *proj = new_r_Proj(args, mode, parameter_num); set_r_value(irg, parameter->value_number, proj); } context2firm(&function->context); current_ir_graph = irg; ir_node *firstblock = get_cur_block(); if (function->statement != NULL) statement_to_firm(function->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); - + int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_verify(irg, VERIFY_ENFORCE_SSA); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_function_instance_t *function_instance = instance->function_instances; for ( ; function_instance != NULL; function_instance = function_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ function_t *function = &function_instance->function; /* make sure the function entity is set */ ir_entity *entity = get_concept_function_instance_entity(function_instance); /* we can emit it like a normal function */ queue_function_instantiation(function, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: if (!is_polymorphic_function(&entity->function.function)) { assure_instance(&entity->function, NULL); } break; case ENTITY_VARIABLE: create_variable_entity(&entity->variable); break; case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: break; case ENTITY_INVALID: case ENTITY_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_functions); instantiate_functions = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_functions)) { - instantiate_function_t *instantiate_function + instantiate_function_t *instantiate_function = pdeq_getl(instantiate_functions); assert(typevar_binding_stack_top() == 0); create_function(instantiate_function->function, instantiate_function->entity, instantiate_function->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_functions); obstack_free(&obst, NULL); strset_destroy(&instantiated_functions); } diff --git a/compiler.h b/compiler.h index c033ffe..30effcb 100644 --- a/compiler.h +++ b/compiler.h @@ -1,10 +1,10 @@ #ifndef COMPILER_H #define COMPILER_H #if defined __GNUC__ && __GNUC__ >= 4 -#define WARN_UNUSED __attribute__((warn_unused_result)) +#define WARN_UNUSED __attribute__((warn_unused_result)) #else #define WARN_UNUSED #endif #endif diff --git a/match_type.c b/match_type.c index d90527d..0f8ff7c 100644 --- a/match_type.c +++ b/match_type.c @@ -1,233 +1,233 @@ #include <config.h> #include "match_type.h" #include <assert.h> #include "type_t.h" #include "ast_t.h" #include "semantic_t.h" #include "type_hash.h" #include "adt/error.h" static inline void match_error(type_t *variant, type_t *concrete, const source_position_t source_position) { print_error_prefix(source_position); fprintf(stderr, "can't match variant type "); print_type(variant); fprintf(stderr, " against "); print_type(concrete); fprintf(stderr, "\n"); } static bool matched_type_variable(type_variable_t *type_variable, type_t *type, const source_position_t source_position, bool report_errors) { type_t *current_type = type_variable->current_type; if (current_type != NULL && current_type != type) { if (report_errors) { print_error_prefix(source_position); fprintf(stderr, "ambiguous matches found for type variable '%s': ", type_variable->base.symbol->string); print_type(current_type); fprintf(stderr, ", "); print_type(type); fprintf(stderr, "\n"); } /* are both types normalized? */ assert(typehash_contains(current_type)); assert(typehash_contains(type)); return false; } type_variable->current_type = type; return true; } static bool match_compound_type(compound_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_variable_t *type_parameters = variant_type->type_parameters; if (type_parameters == NULL) { if (concrete_type != (type_t*) variant_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } return true; } if (concrete_type->kind != TYPE_BIND_TYPEVARIABLES) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } - bind_typevariables_type_t *bind_typevariables + bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; - compound_type_t *polymorphic_type + compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if (polymorphic_type != variant_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = bind_typevariables->type_arguments; bool result = true; while (type_parameter != NULL) { assert(type_argument != NULL); if (!matched_type_variable(type_parameter, type_argument->type, source_position, true)) result = false; type_parameter = type_parameter->next; type_argument = type_argument->next; } return result; } static bool match_bind_typevariables(bind_typevariables_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { if (concrete_type->kind != TYPE_BIND_TYPEVARIABLES) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if (polymorphic_type != variant_type->polymorphic_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_argument_t *argument1 = variant_type->type_arguments; type_argument_t *argument2 = bind_typevariables->type_arguments; bool result = true; while (argument1 != NULL) { assert(argument2 != NULL); if (!match_variant_to_concrete_type(argument1->type, argument2->type, source_position, report_errors)) result = false; argument1 = argument1->next; argument2 = argument2->next; } assert(argument2 == NULL); return result; } bool match_variant_to_concrete_type(type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_reference_t *type_ref; type_variable_t *type_var; pointer_type_t *pointer_type_1; pointer_type_t *pointer_type_2; function_type_t *function_type_1; function_type_t *function_type_2; assert(type_valid(variant_type)); assert(type_valid(concrete_type)); variant_type = skip_typeref(variant_type); concrete_type = skip_typeref(concrete_type); switch (variant_type->kind) { case TYPE_REFERENCE_TYPE_VARIABLE: type_ref = (type_reference_t*) variant_type; type_var = type_ref->type_variable; return matched_type_variable(type_var, concrete_type, source_position, report_errors); case TYPE_VOID: case TYPE_ATOMIC: if (concrete_type != variant_type) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return true; case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return match_compound_type((compound_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_POINTER: if (concrete_type->kind != TYPE_POINTER) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } pointer_type_1 = (pointer_type_t*) variant_type; pointer_type_2 = (pointer_type_t*) concrete_type; return match_variant_to_concrete_type(pointer_type_1->points_to, pointer_type_2->points_to, source_position, - report_errors); + report_errors); case TYPE_FUNCTION: if (concrete_type->kind != TYPE_FUNCTION) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } function_type_1 = (function_type_t*) variant_type; function_type_2 = (function_type_t*) concrete_type; bool result = match_variant_to_concrete_type(function_type_1->result_type, function_type_2->result_type, source_position, report_errors); function_parameter_type_t *param1 = function_type_1->parameter_types; function_parameter_type_t *param2 = function_type_2->parameter_types; while (param1 != NULL && param2 != NULL) { if (!match_variant_to_concrete_type(param1->type, param2->type, source_position, report_errors)) result = false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return result; case TYPE_BIND_TYPEVARIABLES: return match_bind_typevariables( (bind_typevariables_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_ARRAY: panic("TODO"); case TYPE_ERROR: return false; case TYPE_TYPEOF: case TYPE_REFERENCE: panic("type reference not resolved in match variant to concrete type"); case TYPE_INVALID: panic("invalid type in match variant to concrete type"); } panic("unknown type in match variant to concrete type"); } diff --git a/parser.c b/parser.c index 4f530b5..03e8d7e 100644 --- a/parser.c +++ b/parser.c @@ -1,2399 +1,2399 @@ #include <config.h> #include "token_t.h" #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers; static parse_statement_function *statement_parsers; static parse_declaration_function *declaration_parsers; static parse_attribute_function *attribute_parsers; static unsigned char token_anchor_set[T_LAST_TOKEN]; static symbol_t *current_module_name; static context_t *current_context; static int error = 0; token_t token; module_t *modules; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_entity_struct_size(entity_kind_t kind) { static const size_t sizes[] = { [ENTITY_ERROR] = sizeof(entity_base_t), [ENTITY_FUNCTION] = sizeof(function_entity_t), [ENTITY_FUNCTION_PARAMETER] = sizeof(function_parameter_t), [ENTITY_VARIABLE] = sizeof(variable_t), [ENTITY_CONSTANT] = sizeof(constant_t), [ENTITY_TYPE_VARIABLE] = sizeof(type_variable_t), [ENTITY_TYPEALIAS] = sizeof(typealias_t), [ENTITY_CONCEPT] = sizeof(concept_t), [ENTITY_CONCEPT_FUNCTION] = sizeof(concept_function_t), [ENTITY_LABEL] = sizeof(label_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } entity_t *allocate_entity(entity_kind_t kind) { size_t size = get_entity_struct_size(kind); entity_t *entity = allocate_ast_zero(size); entity->kind = kind; return entity; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { [EXPR_ERROR] = sizeof(expression_base_t), [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } static size_t get_statement_struct_size(statement_kind_t kind) { static const size_t sizes[] = { [STATEMENT_ERROR] = sizeof(statement_base_t), [STATEMENT_BLOCK] = sizeof(block_statement_t), [STATEMENT_RETURN] = sizeof(return_statement_t), [STATEMENT_DECLARATION] = sizeof(declaration_statement_t), [STATEMENT_IF] = sizeof(if_statement_t), [STATEMENT_EXPRESSION] = sizeof(expression_statement_t), [STATEMENT_GOTO] = sizeof(goto_statement_t), [STATEMENT_LABEL] = sizeof(label_statement_t), }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; }; static statement_t *allocate_statement(statement_kind_t kind) { size_t size = get_statement_struct_size(kind); statement_t *statement = allocate_ast_zero(size); statement->kind = kind; return statement; } static size_t get_type_struct_size(type_kind_t kind) { static const size_t sizes[] = { [TYPE_ERROR] = sizeof(type_base_t), [TYPE_VOID] = sizeof(type_base_t), [TYPE_ATOMIC] = sizeof(atomic_type_t), [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t), [TYPE_COMPOUND_UNION] = sizeof(compound_type_t), [TYPE_FUNCTION] = sizeof(function_type_t), [TYPE_POINTER] = sizeof(pointer_type_t), [TYPE_ARRAY] = sizeof(array_type_t), [TYPE_TYPEOF] = sizeof(typeof_type_t), [TYPE_REFERENCE] = sizeof(type_reference_t), [TYPE_REFERENCE_TYPE_VARIABLE] = sizeof(type_reference_t), [TYPE_BIND_TYPEVARIABLES] = sizeof(bind_typevariables_type_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } type_t *allocate_type(type_kind_t kind) { size_t size = get_type_struct_size(kind); type_t *type = obstack_alloc(type_obst, size); memset(type, 0, size); type->kind = kind; return type; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(token_type_t token_type) { assert(token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(token_type_t token_type) { assert(token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(token_type_t type) { token_type_t end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ - } while (0) + } while (0) static void parse_function(function_t *function); static statement_t *parse_block(void); static void parse_parameter_declarations(function_type_t *function_type, function_parameter_t **parameters); static atomic_type_kind_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: - parse_error_expected("couldn't parse type", T_byte, T_short, T_int, + parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_kind_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: - parse_error_expected("couldn't parse type", T_byte, T_short, T_int, + parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_kind_t akind; switch (token.type) { case T_unsigned: next_token(); akind = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: akind = parse_signed_atomic_type(); break; } type_t *type = allocate_type(TYPE_ATOMIC); type->atomic.akind = akind; type_t *result = typehash_insert(type); if (result != type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { type_t *type = allocate_type(TYPE_TYPEOF); eat(T_typeof); expect('(', end_error); add_anchor_token(')'); type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_t *type = allocate_type(TYPE_REFERENCE); type->reference.symbol = token.v.symbol; type->reference.source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return type; } static type_t *create_error_type(void) { return allocate_type(TYPE_ERROR); } static type_t *parse_function_type(void) { eat(T_func); type_t *type = allocate_type(TYPE_FUNCTION); parse_parameter_declarations(&type->function, NULL); expect(':', end_error); type->function.result_type = parse_type(); return type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); eat_until_matching_token(T_NEWLINE); next_token(); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); type_t *type = allocate_type(TYPE_COMPOUND_UNION); type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); - - add_anchor_token(T_DEDENT); + + add_anchor_token(T_DEDENT); type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return type; } static type_t *parse_struct_type(void) { eat(T_struct); type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); - + add_anchor_token(T_DEDENT); type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return type; } static type_t *make_pointer_type_no_hash(type_t *points_to) { type_t *type = allocate_type(TYPE_POINTER); type->pointer.points_to = points_to; - return type; + return type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_function_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); expression_t *size = parse_expression(); rem_anchor_token(']'); expect(']', end_error); type_t *array_type = allocate_type(TYPE_ARRAY); array_type->array.element_type = type; array_type->array.size_expression = size; type = array_type; break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); parse_function(&expression->func.function); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); type_t *type = allocate_type(TYPE_TYPEOF); add_anchor_token(')'); type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); expression->sizeofe.type = type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, token_type_t token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, token_type_t token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { expression_t *expression = allocate_expression(EXPR_CALL); expression->call.function = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \ return expression; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); - register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, - T_LESSLESS, PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, + T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); register_expression_parser(parse_EXPR_UNARY_NOT, '!'); register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type == T_ERROR) { return expected_expression_error(); } - expression_parse_function_t *parser + expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; - + if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->base.source_position = start; while (true) { if (token.type == T_ERROR) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->base.source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { eat(T_return); statement_t *return_statement = allocate_statement(STATEMENT_RETURN); if (token.type != T_NEWLINE) { return_statement->returns.value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return return_statement; } static statement_t *create_error_statement(void) { return allocate_statement(STATEMENT_ERROR); } static statement_t *parse_goto_statement(void) { eat(T_goto); statement_t *goto_statement = allocate_statement(STATEMENT_GOTO); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->gotos.label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); statement_t *label = allocate_statement(STATEMENT_LABEL); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->label.label.base.kind = ENTITY_LABEL; label->label.label.base.source_position = source_position; label->label.label.base.symbol = token.v.symbol; next_token(); add_entity((entity_t*) &label->label.label); expect(T_NEWLINE, end_error); return label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if (token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if (token.type != T_INDENT) { /* create an empty block */ statement_t *block = allocate_statement(STATEMENT_BLOCK); return block; } - + return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if (token.type == T_else) { next_token(); if (token.type == ':') next_token(); false_statement = parse_sub_block(); } statement_t *if_statement = allocate_statement(STATEMENT_IF); if_statement->ifs.condition = condition; if_statement->ifs.true_statement = true_statement; if_statement->ifs.false_statement = false_statement; return if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = symbol; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.source_position = source_position; assign->binary.left = expression; assign->binary.right = parse_expression(); statement_t *expr_statement = allocate_statement(STATEMENT_EXPRESSION); expr_statement->expression.expression = assign; return expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } statement_t *statement = allocate_statement(STATEMENT_DECLARATION); entity_t *entity = (entity_t*) &statement->declaration.entity; symbol_t *symbol = token.v.symbol; entity->base.kind = ENTITY_VARIABLE; entity->base.source_position = source_position; entity->base.symbol = symbol; next_token(); add_entity(entity); if (token.type == ':') { next_token(); entity->variable.type = parse_type(); } /* append multiple variable declarations */ if (last_statement != NULL) { last_statement->base.next = statement; } else { first_statement = statement; } last_statement = statement; /* do we have an assignment expression? */ if (token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(symbol); last_statement->base.next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if (token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { statement_t *statement = allocate_statement(STATEMENT_EXPRESSION); statement->expression.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: return statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if (token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; parse_statement_function parser = NULL; if (token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; add_anchor_token(T_NEWLINE); if (parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if (token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if (declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } rem_anchor_token(T_NEWLINE); if (statement == NULL) return NULL; statement->base.source_position = start; statement_t *next = statement->base.next; while (next != NULL) { next->base.source_position = start; next = next->base.next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); statement_t *block_statement = allocate_statement(STATEMENT_BLOCK); - + context_t *last_context = current_context; current_context = &block_statement->block.context; add_anchor_token(T_DEDENT); statement_t *last_statement = NULL; while (token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if (statement == NULL) continue; if (last_statement != NULL) { last_statement->base.next = statement; } else { block_statement->block.statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while (last_statement->base.next != NULL) last_statement = last_statement->base.next; } assert(current_context == &block_statement->block.context); current_context = last_context; block_statement->block.end_position = source_position; rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: return block_statement; } static void parse_parameter_declarations(function_type_t *function_type, function_parameter_t **parameters) { assert(function_type != NULL); function_parameter_type_t *last_type = NULL; function_parameter_t *last_parameter = NULL; if (parameters != NULL) *parameters = NULL; expect('(', end_error2); if (token.type == ')') { next_token(); return; } add_anchor_token(')'); add_anchor_token(','); while (true) { if (token.type == T_DOTDOTDOT) { function_type->variable_arguments = 1; next_token(); if (token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); goto end_error; } break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); function_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if (last_type != NULL) { last_type->next = param_type; } else { function_type->parameter_types = param_type; } last_type = param_type; if (parameters != NULL) { entity_t *entity = allocate_entity(ENTITY_FUNCTION_PARAMETER); entity->base.kind = ENTITY_FUNCTION_PARAMETER; entity->base.symbol = symbol; entity->base.source_position = source_position; entity->parameter.type = param_type->type; if (last_parameter != NULL) { last_parameter->next = &entity->parameter; } else { *parameters = &entity->parameter; } last_parameter = &entity->parameter; } if (token.type != ',') break; next_token(); } - + rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error2); return; end_error: rem_anchor_token(','); rem_anchor_token(')'); end_error2: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while (token.type == T_IDENTIFIER) { - type_constraint_t *constraint + type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if (last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static entity_t *parse_type_parameter(void) { entity_t *entity = allocate_entity(ENTITY_TYPE_VARIABLE); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } entity->base.source_position = source_position; entity->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); entity->type_variable.constraints = parse_type_constraints(); } return entity; } static type_variable_t *parse_type_parameters(context_t *context) { entity_t *first_variable = NULL; entity_t *last_variable = NULL; while (true) { entity_t *type_variable = parse_type_parameter(); if (last_variable != NULL) { last_variable->type_variable.next = &type_variable->type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if (context != NULL) { type_variable->base.next = context->entities; context->entities = type_variable; } if (token.type != ',') break; next_token(); } return &first_variable->type_variable; } void add_entity(entity_t *entity) { assert(entity != NULL); assert(entity->base.source_position.input_name != NULL); assert(current_context != NULL); entity->base.next = current_context->entities; current_context->entities = entity; } static void parse_function(function_t *function) { type_t *type = allocate_type(TYPE_FUNCTION); context_t *last_context = current_context; current_context = &function->context; if (token.type == '<') { next_token(); add_anchor_token('>'); function->type_parameters = parse_type_parameters(current_context); rem_anchor_token('>'); expect('>', end_error); } parse_parameter_declarations(&type->function, &function->parameters); function->type = &type->function; /* add parameters to context */ function_parameter_t *parameter = function->parameters; for ( ; parameter != NULL; parameter = parameter->next) { add_entity((entity_t*) parameter); } type->function.result_type = type_void; if (token.type == ':') { next_token(); if (token.type == T_NEWLINE) { function->statement = parse_sub_block(); goto function_parser_end; } type->function.result_type = parse_type(); if (token.type == ':') { next_token(); function->statement = parse_sub_block(); goto function_parser_end; } } expect(T_NEWLINE, end_error); function_parser_end: assert(current_context == &function->context); current_context = last_context; end_error: ; } static void parse_function_declaration(void) { eat(T_func); entity_t *declaration = allocate_entity(ENTITY_FUNCTION); if (token.type == T_extern) { declaration->function.function.is_extern = true; next_token(); } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_function(&declaration->function.function); add_entity(declaration); } static void parse_global_variable(void) { eat(T_var); entity_t *declaration = allocate_entity(ENTITY_VARIABLE); declaration->variable.is_global = true; if (token.type == T_extern) { next_token(); declaration->variable.is_extern = true; } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); declaration->variable.type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_entity(declaration); } static void parse_constant(void) { eat(T_const); entity_t *declaration = allocate_entity(ENTITY_CONSTANT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } - declaration->base.source_position = source_position; + declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->constant.type = parse_type(); } expect('=', end_error); declaration->constant.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_entity(declaration); } static void parse_typealias(void) { eat(T_typealias); entity_t *declaration = allocate_entity(ENTITY_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); expect('=', end_error); declaration->typealias.type = parse_type(); expect(T_NEWLINE, end_error); end_error: add_entity(declaration); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if (token.type == T_ERROR) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if (token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if (parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if (parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while (token.type == '$') { attribute_t *attribute = parse_attribute(); if (attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_struct(void) { eat(T_struct); entity_t *declaration = allocate_entity(ENTITY_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); type->compound.symbol = declaration->base.symbol; if (token.type == '<') { next_token(); - type->compound.type_parameters + type->compound.type_parameters = parse_type_parameters(&type->compound.context); expect('>', end_error); } type->compound.attributes = parse_attributes(); declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } add_entity(declaration); end_error: ; } static void parse_union(void) { eat(T_union); entity_t *declaration = allocate_entity(ENTITY_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); type_t *type = allocate_type(TYPE_COMPOUND_UNION); type->compound.symbol = declaration->base.symbol; type->compound.attributes = parse_attributes(); declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } end_error: add_entity(declaration); } static concept_function_t *parse_concept_function(void) { expect(T_func, end_error); - entity_t *declaration + entity_t *declaration = allocate_entity(ENTITY_CONCEPT_FUNCTION); type_t *type = allocate_type(TYPE_FUNCTION); - + if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept function", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_parameter_declarations(&type->function, &declaration->concept_function.parameters); if (token.type == ':') { next_token(); type->function.result_type = parse_type(); } else { type->function.result_type = type_void; } expect(T_NEWLINE, end_error); declaration->concept_function.type = &type->function; add_entity(declaration); return &declaration->concept_function; end_error: return NULL; } static void parse_concept(void) { eat(T_concept); entity_t *declaration = allocate_entity(ENTITY_CONCEPT); - + if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); context_t *context = &declaration->concept.context; add_anchor_token('>'); declaration->concept.type_parameters = parse_type_parameters(context); rem_anchor_token('>'); expect('>', end_error); } expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_function_t *last_function = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_function_t *function = parse_concept_function(); function->concept = &declaration->concept; if (last_function != NULL) { last_function->next = function; } else { declaration->concept.functions = function; } last_function = function; } next_token(); end_of_parse_concept: add_entity(declaration); return; end_error: ; } static concept_function_instance_t *parse_concept_function_instance(void) { concept_function_instance_t *function_instance = allocate_ast_zero(sizeof(function_instance[0])); expect(T_func, end_error); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept function " "instance", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } function_instance->source_position = source_position; function_instance->symbol = token.v.symbol; next_token(); parse_function(&function_instance->function); return function_instance; end_error: return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect('>', end_error); } instance->type_arguments = parse_type_arguments(); - + expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_function_instance_t *last_function = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if (token.type == T_NEWLINE) { next_token(); continue; } concept_function_instance_t *function = parse_concept_function_instance(); if (function == NULL) continue; if (last_function != NULL) { last_function->next = function; } else { instance->function_instances = function; } last_function = function; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; return; end_error: ; } static void skip_declaration(void) { next_token(); } static void parse_import(void) { eat(T_import); if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing import directive", T_STRING_LITERAL, 0); eat_until_anchor(); return; } symbol_t *modulename = symbol_table_insert(token.v.string); next_token(); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing import directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } import_t *import = allocate_ast_zero(sizeof(import[0])); import->module = modulename; import->symbol = token.v.symbol; import->source_position = source_position; - + import->next = current_context->imports; current_context->imports = import; next_token(); if (token.type != ',') break; eat(','); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_export(void) { eat(T_export); while (true) { if (token.type == T_NEWLINE) { break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if (token.type != ',') { break; } next_token(); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_module(void) { eat(T_module); /* a simple URL string without a protocol */ if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing module", T_STRING_LITERAL, 0); return; } symbol_t *new_module_name = symbol_table_insert(token.v.string); next_token(); if (current_module_name != NULL && current_module_name != new_module_name) { parser_print_error_prefix(); fprintf(stderr, "new module name '%s' overrides old name '%s'\n", new_module_name->string, current_module_name->string); } current_module_name = new_module_name; expect(T_NEWLINE, end_error); end_error: ; } void parse_declaration(void) { if (token.type == T_EOF) return; if (token.type == T_ERROR) { /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parse = NULL; if (token.type < ARR_LEN(declaration_parsers)) parse = declaration_parsers[token.type]; if (parse == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_anchor(); return; } parse(); } static void register_declaration_parsers(void) { register_declaration_parser(parse_function_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); register_declaration_parser(parse_import, T_import); register_declaration_parser(parse_module, T_module); register_declaration_parser(skip_declaration, T_NEWLINE); } static module_t *get_module(symbol_t *name) { if (name == NULL) { name = symbol_table_insert(""); } /* search for an existing module */ module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } if (module == NULL) { module = allocate_ast_zero(sizeof(module[0])); module->name = name; module->next = modules; modules = module; } return module; } static void append_context(context_t *dest, const context_t *source) { entity_t *last = dest->entities; if (last != NULL) { while (last->base.next != NULL) { last = last->base.next; } last->base.next = source->entities; } else { dest->entities = source->entities; } concept_instance_t *last_concept_instance = dest->concept_instances; if (last_concept_instance != NULL) { while (last_concept_instance->next != NULL) { last_concept_instance = last_concept_instance->next; } last_concept_instance->next = source->concept_instances; } else { dest->concept_instances = source->concept_instances; } export_t *last_export = dest->exports; if (last_export != NULL) { while (last_export->next != NULL) { last_export = last_export->next; } last_export->next = source->exports; } else { dest->exports = source->exports; } import_t *last_import = dest->imports; if (last_import != NULL) { while (last_import->next != NULL) { last_import = last_import->next; } last_import->next = source->imports; } else { dest->imports = source->imports; } } bool parse_file(FILE *in, const char *input_name) { memset(token_anchor_set, 0, sizeof(token_anchor_set)); /* get the lexer running */ input_t *input = input_from_stream(in, NULL); lexer_init(input, input_name); next_token(); context_t file_context; memset(&file_context, 0, sizeof(file_context)); assert(current_context == NULL); current_context = &file_context; current_module_name = NULL; add_anchor_token(T_EOF); while (token.type != T_EOF) { parse_declaration(); } rem_anchor_token(T_EOF); assert(current_context == &file_context); current_context = NULL; /* append stuff to module */ module_t *module = get_module(current_module_name); append_context(&module->context, &file_context); /* check that we have matching rem_anchor_token calls for each add */ #ifndef NDEBUG for (int i = 0; i < T_LAST_TOKEN; ++i) { if (token_anchor_set[i] > 0) { panic("leaked token"); } } #endif lexer_destroy(); input_free(input); return !error; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); } diff --git a/plugins.c b/plugins.c index 04986b0..cd1f5f5 100644 --- a/plugins.c +++ b/plugins.c @@ -1,91 +1,91 @@ #include <config.h> #include "plugins_t.h" #include <stdio.h> #include <stdlib.h> #ifndef _WIN32 #include <dlfcn.h> #include <glob.h> #endif #include "adt/xmalloc.h" plugin_t *plugins = NULL; static void load_plugin(const char *filename) { #ifdef _WIN32 // TODO... #else //printf("Opening plugin '%s'...\n", filename); void *handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL); if (handle == NULL) { fprintf(stderr, "Couldn't load plugin '%s': %s\n", filename, dlerror()); return; } void *init_func = dlsym(handle, "init_plugin"); if (init_func == NULL) { dlclose(handle); fprintf(stderr, "Plugin '%s' has no init_plugin function.\n", filename); return; } plugin_t *plugin = xmalloc(sizeof(plugin[0])); plugin->init_function = (init_plugin_function) init_func; plugin->dlhandle = handle; plugin->next = plugins; - plugins = plugin; + plugins = plugin; #endif } void search_plugins(void) { #ifndef _WIN32 /* search for plugins */ glob_t globbuf; if (glob("plugins/plugin_*.dylib", 0, NULL, &globbuf) == 0) { for (size_t i = 0; i < globbuf.gl_pathc; ++i) { const char *filename = globbuf.gl_pathv[i]; load_plugin(filename); } globfree(&globbuf); } #endif } void initialize_plugins(void) { /* execute plugin initializers */ plugin_t *plugin = plugins; while (plugin != NULL) { plugin->init_function(); plugin = plugin->next; } } void free_plugins(void) { #ifndef _WIN32 /* close dl handles */ plugin_t *plugin = plugins; while (plugin != NULL) { void *handle = plugin->dlhandle; if (handle != NULL) { dlclose(handle); plugin->dlhandle = NULL; } plugin = plugin->next; } #endif } diff --git a/semantic.c b/semantic.c index fc33cb1..46961a4 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2585 +1,2585 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; entity_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static function_t *current_function = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_function(function_t *function, symbol_t *symbol, const source_position_t source_position); static void resolve_function_types(function_t *function); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static void environment_push(entity_t *entity, const void *context) { - environment_entry_t *entry + environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = entity->base.symbol; assert(entity != symbol->entity); if (symbol->context == context) { assert(symbol->entity != NULL); print_error_prefix(entity->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->entity->base.source_position); fprintf(stderr, "this is the location of the previous entity.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->entity; entry->up_context = symbol->context; entry->symbol = symbol; symbol->entity = entity; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; entity_t *entity = symbol->entity; if (entity->base.refs == 0 && !entity->base.exported) { switch (entity->kind) { /* only warn for functions/variables at the moment, we don't count refs on types yet */ case ENTITY_FUNCTION: case ENTITY_VARIABLE: print_warning_prefix(entity->base.source_position); fprintf(stderr, "%s '%s' was declared but never read\n", get_entity_kind_name(entity->kind), symbol->string); default: break; } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->entity = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return type_invalid; } if (entity->kind == ENTITY_TYPE_VARIABLE) { type_variable_t *type_variable = &entity->type_variable; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->base.kind = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (entity->kind != ENTITY_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias or type variable, but '%s' is a '%s'\n", symbol->string, get_entity_kind_name(entity->kind)); return type_invalid; } typealias_t *typealias = &entity->typealias; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } - /* check that type arguments match type parameters + /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } - + type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->base.kind = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); type->size_expression = check_expression(type->size_expression); return typehash_insert((type_t*) type); } static type_t *normalize_function_type(function_type_t *function_type) { function_type->result_type = normalize_type(function_type->result_type); function_parameter_type_t *parameter = function_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) function_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->kind == TYPE_COMPOUND_STRUCT || polymorphic_type->kind == TYPE_COMPOUND_UNION); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_FUNCTION: return normalize_function_type((function_type_t*) type); case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(entity_t *entity, const source_position_t source_position) { type_t *type; entity->base.refs++; switch (entity->kind) { case ENTITY_VARIABLE: type = entity->variable.type; if (type == NULL) return NULL; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { entity->variable.needs_entity = true; } return type; case ENTITY_FUNCTION: return make_pointer_type((type_t*) entity->function.function.type); case ENTITY_CONSTANT: { constant_t *constant = &entity->constant; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; } case ENTITY_FUNCTION_PARAMETER: assert(entity->parameter.type != NULL); return entity->parameter.type; case ENTITY_CONCEPT_FUNCTION: return make_pointer_type((type_t*) entity->concept_function.type); case ENTITY_LABEL: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", entity->base.symbol->string, get_entity_kind_name(entity->kind)); return NULL; case ENTITY_ERROR: found_errors = true; return NULL; case ENTITY_INVALID: panic("reference to invalid declaration type encountered"); } panic("reference to unknown declaration type encountered"); } static entity_t *create_error_entity(symbol_t *symbol) { entity_t *entity = allocate_entity(ENTITY_ERROR); entity->base.symbol = symbol; entity->base.exported = true; return entity; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); entity = create_error_entity(symbol); } normalize_type_arguments(ref->type_arguments); ref->entity = entity; type_t *type = check_reference(entity, ref->base.source_position); ref->base.type = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const entity_t *entity = reference->entity; if (entity->kind == ENTITY_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; entity_t *entity = reference->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = (variable_t*) entity; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->base.refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; - /* TODO: - test which types can be implicitely casted... + /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of function call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->kind == TYPE_POINTER) { if (dest_type->kind == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->kind == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->kind == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->kind == TYPE_ATOMIC) { if (dest_type->kind != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = &from_type->atomic; atomic_type_kind_t from_akind = from_type_atomic->akind; atomic_type_t *dest_type_atomic = &dest_type->atomic; atomic_type_kind_t dest_akind = dest_type_atomic->akind; switch (from_akind) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_BYTE) || (dest_akind == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_USHORT) || (dest_akind == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_UINT) || (dest_akind == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_ULONG) || (dest_akind == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_ULONGLONG) || (dest_akind == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_akind == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; - type_t *righttype = right->base.type; + type_t *righttype = right->base.type; if (lefttype->kind != TYPE_POINTER && righttype->kind != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ if (lefttype->kind == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } if (lefttype->kind == TYPE_POINTER && righttype->kind == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } - + argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_function_instance_t *get_function_from_concept_instance( concept_instance_t *instance, concept_function_t *function) { concept_function_instance_t *function_instance = instance->function_instances; while (function_instance != NULL) { if (function_instance->concept_function == function) { return function_instance; } function_instance = function_instance->next; } return NULL; } static void resolve_concept_function_instance(reference_expression_t *reference) { entity_t *entity = reference->entity; assert(entity->kind == ENTITY_CONCEPT_FUNCTION); concept_function_t *concept_function = &entity->concept_function; concept_t *concept = concept_function->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept functions are invoked inside polymorphic * functions. We can't resolve the function right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using function '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_function->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->base.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 - concept_function_instance_t *function_instance + concept_function_instance_t *function_instance = get_function_from_concept_instance(instance, concept_function); if (function_instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "no instance of function '%s' found in concept " "instance?\n", concept_function->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) function_instance->function.type; type_t *pointer_type = make_pointer_type(type); reference->base.type = pointer_type; reference->declaration = (declaration_t*) &function_instance->function; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->base.symbol->string, concept->base.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; - - concept_instance_t *instance + + concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "function doesn't match type constraints:\n", type_var->base.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->base.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); switch (type->kind) { case TYPE_ATOMIC: atomic_type = &type->atomic; switch (atomic_type->akind) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_FUNCTION: print_error_prefix(source_position); fprintf(stderr, "function type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return error_type; case TYPE_ERROR: return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->function = check_expression(call->function); expression_t *function = call->function; type_t *type = function->base.type; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if (type == NULL) return; /* determine function type */ if (type->kind != TYPE_POINTER) { print_error_prefix(call->base.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if (type->kind != TYPE_FUNCTION) { print_error_prefix(call->base.source_position); fprintf(stderr, "trying to call a non-function value of type"); print_type(type); fprintf(stderr, "\n"); return; } function_type_t *function_type = (function_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if (function->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) function; entity_t *entity = reference->entity; if (entity->kind == ENTITY_CONCEPT_FUNCTION) { concept_function_t *concept_function = &entity->concept_function; concept_t *concept = concept_function->concept; - + type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if (entity->kind == ENTITY_FUNCTION) { function_entity_t *function_entity = &entity->function; type_variables = function_entity->function.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if (type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while (type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if (type_argument != NULL || type_var != NULL) { error_at(function->base.source_position, "wrong number of type arguments on function reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; function_parameter_type_t *param_type = function_type->parameter_types; int i = 0; while (argument != NULL) { if (param_type == NULL && !function_type->variable_arguments) { error_at(call->base.source_position, "too much arguments for function call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->base.type; if (param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->base.source_position); } /* match type of argument against type variables */ if (type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->base.source_position, true); } else if (expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; - expression_t *new_expression + expression_t *new_expression = make_cast(expression, wanted_type, expression->base.source_position, lenient); if (new_expression == NULL) { print_error_prefix(expression->base.source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->base.type); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if (param_type != NULL) param_type = param_type->next; ++i; } if (param_type != NULL) { error_at(call->base.source_position, "too few arguments for function call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while (type_var != NULL) { if (type_var->current_type == NULL) { print_error_prefix(call->base.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->base.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->base.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } - + /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = function_type->result_type; if (type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) function; entity_t *entity = ref->entity; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if (entity->kind == ENTITY_CONCEPT_FUNCTION) { /* we might be able to resolve the concept_function_instance now */ resolve_concept_function_instance(ref); concept_function_t *concept_function = &entity->concept_function; concept_t *concept = concept_function->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(entity->kind == ENTITY_FUNCTION); check_type_constraints(type_variables, call->base.source_position); function_entity_t *function_entity = &entity->function; type_parameters = function_entity->function.type_parameters; } /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->base.type = create_concrete_type(ref->base.type); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->base.type = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->base.type == NULL) { panic("Cast expression needs a datatype!"); } cast->base.type = normalize_type(cast->base.type); cast->value = check_expression(cast->value); if (cast->value->base.type == type_void) { error_at(cast->base.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->base.type == NULL) { error_at(dereference->base.source_position, "can't derefence expression with unknown datatype\n"); return; } if (value->base.type->kind != TYPE_POINTER) { error_at(dereference->base.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->base.type; type_t *dereferenced_type = pointer_type->points_to; dereference->base.type = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->base.source_position, "can only take address of l-values\n"); return; } if (value->kind == EXPR_REFERENCE) { reference_expression_t *reference = &value->reference; entity_t *entity = reference->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = &entity->variable; variable->needs_entity = true; } } expression->base.type = result_type; } static bool is_arithmetic_type(type_t *type) { if (type->kind != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static expression_t *lower_incdec_expression(expression_t *expression_) { unary_expression_t *expression = (unary_expression_t*) expression_; expression_t *value = check_expression(expression->value); type_t *type = value->base.type; expression_kind_t kind = expression->base.kind; if (!is_type_numeric(type) && type->kind != TYPE_POINTER) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression needs an lvalue\n", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->kind == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->akind == ATOMIC_TYPE_FLOAT || atomic_type->akind == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { constant = allocate_expression(EXPR_INT_CONST); constant->base.type = type; constant->int_const.value = 1; } else { constant = allocate_expression(EXPR_FLOAT_CONST); constant->base.type = type; constant->float_const.value = 1.0; } expression_t *add = allocate_expression(kind == EXPR_UNARY_INCREMENT ? EXPR_BINARY_ADD : EXPR_BINARY_SUB); add->base.type = type; add->binary.left = value; add->binary.right = constant; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.type = type; assign->binary.left = value; assign->binary.right = add; return assign; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type != type_bool) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static entity_t *find_entity(const context_t *context, symbol_t *symbol) { entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { if (entity->base.symbol == symbol) break; } return entity; } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->base.type; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->kind == TYPE_COMPOUND_STRUCT || datatype->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) datatype; } else { if (datatype->kind != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; - + type_t *points_to = pointer_type->points_to; if (points_to->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->kind == TYPE_COMPOUND_STRUCT || points_to->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ entity_t *entity = find_entity(&compound_type->context, symbol); if (entity != NULL) { type_t *type = check_reference(entity, select->base.source_position); select->base.type = type; select->entity = entity; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; - if (type == NULL || + if (type == NULL || (type->kind != TYPE_POINTER && type->kind != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->kind == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { function_t *function = & expression->function; resolve_function_types(function); check_function(function, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) function->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { - lower_expression_function lowerer + lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { function_t *function = current_function; type_t *function_result_type = function->type->result_type; statement->value = check_expression(statement->value); expression_t *return_value = statement->value; last_statement_was_return = true; if (return_value != NULL) { if (function_result_type == type_void && return_value->base.type != type_void) { error_at(statement->base.source_position, "return with value in void function\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != function_result_type) { return_value = make_cast(return_value, function_result_type, statement->base.source_position, false); statement->value = return_value; } } else { if (function_result_type != type_void) { error_at(statement->base.source_position, "missing return value in non-void function\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->base.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { environment_push(entity, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->base.next; statement = check_statement(statement); assert(statement->base.next == next || statement->base.next == NULL); statement->base.next = next; if (last != NULL) { last->base.next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(declaration_statement_t *statement) { function_t *function = current_function; variable_t *variable = &statement->entity; assert(function != NULL); variable->value_number = function->n_local_vars; function->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ variable->base.refs = 0; if (variable->type != NULL) { variable->type = normalize_type(variable->type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->base.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->base.source_position, "unresolved anonymous goto\n"); return; } entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (entity->kind != ENTITY_LABEL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_entity_kind_name(entity->kind)); return; } label_t *label = &entity->label; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->kind < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->kind]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->kind) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement(&statement->block); break; case STATEMENT_RETURN: check_return_statement(&statement->returns); break; case STATEMENT_GOTO: check_goto_statement(&statement->gotos); break; case STATEMENT_LABEL: check_label_statement(&statement->label); break; case STATEMENT_IF: check_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: check_variable_declaration(&statement->declaration); break; case STATEMENT_EXPRESSION: check_expression_statement(&statement->expression); break; default: panic("Unknown statement found"); break; } return statement; } static void check_function(function_t *function, symbol_t *symbol, const source_position_t source_position) { if (function->is_extern) return; int old_top = environment_top(); push_context(&function->context); function_t *last_function = current_function; current_function = function; /* set function parameter numbers */ function_parameter_t *parameter = function->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->value_number = function->n_local_vars++; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (function->statement != NULL) { function->statement = check_statement(function->statement); } if (!last_statement_was_return) { type_t *result_type = function->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_function = last_function; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (entity->kind != ENTITY_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_entity_kind_name(entity->kind)); return; } constraint->concept = &entity->concept; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_function_types(function_t *function) { int old_top = environment_top(); /* push type variables */ push_context(&function->context); resolve_type_variable_constraints(function->type_parameters); /* normalize parameter types */ function_parameter_t *parameter = function->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } function->type = (function_type_t*) normalize_type((type_t*)function->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { - concept_function_instance_t *function_instance + concept_function_instance_t *function_instance = instance->function_instances; while (function_instance != NULL) { function_t *function = &function_instance->function; resolve_function_types(function); check_function(function, function_instance->symbol, function_instance->source_position); function_instance = function_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { entity_t *entity = (entity_t*) type_parameter; environment_push(entity, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize function types */ concept_function_t *concept_function = concept->functions; for (; concept_function!=NULL; concept_function = concept_function->next) { - type_t *normalized_type + type_t *normalized_type = normalize_type((type_t*) concept_function->type); assert(normalized_type->kind == TYPE_FUNCTION); concept_function->type = (function_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (entity->kind != ENTITY_CONCEPT) { print_error_prefix(entity->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_entity_kind_name(entity->kind)); return; } concept_t *concept = &entity->concept; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { entity_t *entity = (entity_t*) type_parameter; environment_push(entity, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link functions and normalize their types */ size_t n_concept_functions = 0; concept_function_t *function = concept->functions; for ( ; function != NULL; function = function->next) { ++n_concept_functions; } bool have_function[n_concept_functions]; memset(&have_function, 0, sizeof(have_function)); concept_function_instance_t *function_instance = instance->function_instances; - for (; function_instance != NULL; + for (; function_instance != NULL; function_instance = function_instance->next) { /* find corresponding concept function */ int n = 0; for (function = concept->functions; function != NULL; function = function->next, ++n) { if (function->base.symbol == function_instance->symbol) break; } if (function == NULL) { print_warning_prefix(function_instance->source_position); fprintf(stderr, "concept '%s' does not declare a function '%s'\n", concept->base.symbol->string, function->base.symbol->string); } else { function_instance->concept_function = function; function_instance->concept_instance = instance; if (have_function[n]) { print_error_prefix(function_instance->source_position); fprintf(stderr, "multiple implementations of function '%s' found in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); } have_function[n] = true; } function_t *ifunction = & function_instance->function; if (ifunction->type_parameters != NULL) { print_error_prefix(function_instance->source_position); fprintf(stderr, "instance function '%s' must not have type parameters\n", function_instance->symbol->string); } - - ifunction->type + + ifunction->type = (function_type_t*) normalize_type((type_t*) ifunction->type); } size_t n = 0; for (function = concept->functions; function != NULL; function = function->next, ++n) { if (!have_function[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "function '%s'\n", concept->base.symbol->string, function->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } entity->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_VARIABLE: entity->variable.type = normalize_type(entity->variable.type); break; case ENTITY_FUNCTION: resolve_function_types(&entity->function.function); break; case ENTITY_TYPEALIAS: { type_t *type = normalize_type(entity->typealias.type); if (type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } entity->typealias.type = type; break; } case ENTITY_CONCEPT: resolve_concept_types(&entity->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } - + /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in functions */ entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: { check_function(&entity->function.function, entity->base.symbol, entity->base.source_position); break; } case ENTITY_CONSTANT: check_constant(&entity->constant); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; entity_t *entity; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); entity = create_error_entity(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); entity = create_error_entity(symbol); } else { check_module(ref_module); entity = find_entity(&ref_module->context, symbol); if (entity == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); entity = create_error_entity(symbol); } else { ref_context = &ref_module->context; } } } if (!entity->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->entity == entity) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(entity, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/type.c b/type.c index cb60ee7..fe18113 100644 --- a/type.c +++ b/type.c @@ -1,573 +1,573 @@ #include <config.h> #include "type_t.h" #include "ast_t.h" #include "type_hash.h" #include "adt/error.h" #include "adt/array.h" //#define DEBUG_TYPEVAR_BINDING typedef struct typevar_binding_t typevar_binding_t; struct typevar_binding_t { type_variable_t *type_variable; type_t *old_current_type; }; static typevar_binding_t *typevar_binding_stack = NULL; static struct obstack _type_obst; struct obstack *type_obst = &_type_obst; static type_base_t type_void_ = { TYPE_VOID, NULL }; static type_base_t type_invalid_ = { TYPE_INVALID, NULL }; type_t *type_void = (type_t*) &type_void_; type_t *type_invalid = (type_t*) &type_invalid_; static FILE* out; void init_type_module() { obstack_init(type_obst); typevar_binding_stack = NEW_ARR_F(typevar_binding_t, 0); out = stderr; } void exit_type_module() { DEL_ARR_F(typevar_binding_stack); obstack_free(type_obst, NULL); } static void print_atomic_type(const atomic_type_t *type) { switch (type->akind) { case ATOMIC_TYPE_INVALID: fputs("INVALIDATOMIC", out); break; case ATOMIC_TYPE_BOOL: fputs("bool", out); break; case ATOMIC_TYPE_BYTE: fputs("byte", out); break; case ATOMIC_TYPE_UBYTE: fputs("unsigned byte", out); break; case ATOMIC_TYPE_INT: fputs("int", out); break; case ATOMIC_TYPE_UINT: fputs("unsigned int", out); break; case ATOMIC_TYPE_SHORT: fputs("short", out); break; case ATOMIC_TYPE_USHORT: fputs("unsigned short", out); break; case ATOMIC_TYPE_LONG: fputs("long", out); break; case ATOMIC_TYPE_ULONG: fputs("unsigned long", out); break; case ATOMIC_TYPE_LONGLONG: fputs("long long", out); break; case ATOMIC_TYPE_ULONGLONG: fputs("unsigned long long", out); break; case ATOMIC_TYPE_FLOAT: fputs("float", out); break; case ATOMIC_TYPE_DOUBLE: fputs("double", out); break; default: fputs("UNKNOWNATOMIC", out); break; } } static void print_function_type(const function_type_t *type) { fputs("<", out); fputs("func(", out); function_parameter_type_t *param_type = type->parameter_types; int first = 1; while (param_type != NULL) { if (first) { first = 0; } else { fputs(", ", out); } print_type(param_type->type); param_type = param_type->next; } fputs(")", out); if (type->result_type != NULL && type->result_type->kind != TYPE_VOID) { fputs(" : ", out); print_type(type->result_type); } fputs(">", out); } static void print_pointer_type(const pointer_type_t *type) { print_type(type->points_to); fputs("*", out); } static void print_array_type(const array_type_t *type) { print_type(type->element_type); fputs("[", out); print_expression(type->size_expression); fputs("]", out); } static void print_type_reference(const type_reference_t *type) { fprintf(out, "<?%s>", type->symbol->string); } static void print_type_variable(const type_variable_t *type_variable) { if (type_variable->current_type != NULL) { print_type(type_variable->current_type); return; } fprintf(out, "%s:", type_variable->base.symbol->string); type_constraint_t *constraint = type_variable->constraints; int first = 1; while (constraint != NULL) { if (first) { first = 0; } else { fprintf(out, ", "); } fprintf(out, "%s", constraint->concept_symbol->string); constraint = constraint->next; } } static void print_type_reference_variable(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; print_type_variable(type_variable); } static void print_compound_type(const compound_type_t *type) { fprintf(out, "%s", type->symbol->string); type_variable_t *type_parameter = type->type_parameters; if (type_parameter != NULL) { fprintf(out, "<"); while (type_parameter != NULL) { if (type_parameter != type->type_parameters) { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } fprintf(out, ">"); } } static void print_bind_type_variables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); print_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void print_type(const type_t *type) { if (type == NULL) { fputs("nil type", out); return; } switch (type->kind) { case TYPE_INVALID: fputs("invalid", out); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; fputs("typeof(", out); print_expression(typeof_type->expression); fputs(")", out); return; } case TYPE_ERROR: fputs("error", out); return; case TYPE_VOID: fputs("void", out); return; case TYPE_ATOMIC: print_atomic_type(&type->atomic); return; case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: print_compound_type(&type->compound); return; case TYPE_FUNCTION: print_function_type(&type->function); return; case TYPE_POINTER: print_pointer_type(&type->pointer); return; case TYPE_ARRAY: print_array_type(&type->array); return; case TYPE_REFERENCE: print_type_reference(&type->reference); return; case TYPE_REFERENCE_TYPE_VARIABLE: print_type_reference_variable(&type->reference); return; case TYPE_BIND_TYPEVARIABLES: print_bind_type_variables(&type->bind_typevariables); return; } fputs("unknown", out); } int type_valid(const type_t *type) { switch (type->kind) { case TYPE_INVALID: case TYPE_REFERENCE: return 0; default: return 1; } } int is_type_int(const type_t *type) { if (type->kind != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return 1; default: return 0; } } int is_type_numeric(const type_t *type) { if (type->kind != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return 1; default: return 0; } } type_t* make_atomic_type(atomic_type_kind_t akind) { type_t *type = allocate_type(TYPE_ATOMIC); type->atomic.akind = akind; type_t *normalized_type = typehash_insert(type); if (normalized_type != type) { obstack_free(type_obst, type); } return normalized_type; } type_t* make_pointer_type(type_t *points_to) { type_t *type = allocate_type(TYPE_POINTER); type->pointer.points_to = points_to; type_t *normalized_type = typehash_insert(type); if (normalized_type != type) { obstack_free(type_obst, type); } return normalized_type; } static type_t *create_concrete_compound_type(compound_type_t *type) { /* TODO: handle structs with typevars */ return (type_t*) type; } static type_t *create_concrete_function_type(function_type_t *type) { int need_new_type = 0; type_t *new_type = allocate_type(TYPE_FUNCTION); type_t *result_type = create_concrete_type(type->result_type); if (result_type != type->result_type) need_new_type = 1; new_type->function.result_type = result_type; function_parameter_type_t *parameter_type = type->parameter_types; function_parameter_type_t *last_parameter_type = NULL; while (parameter_type != NULL) { type_t *param_type = parameter_type->type; type_t *new_param_type = create_concrete_type(param_type); if (new_param_type != param_type) need_new_type = 1; function_parameter_type_t *new_parameter_type = obstack_alloc(type_obst, sizeof(new_parameter_type[0])); memset(new_parameter_type, 0, sizeof(new_parameter_type[0])); new_parameter_type->type = new_param_type; if (last_parameter_type != NULL) { last_parameter_type->next = new_parameter_type; } else { new_type->function.parameter_types = new_parameter_type; } last_parameter_type = new_parameter_type; parameter_type = parameter_type->next; } if (!need_new_type) { obstack_free(type_obst, new_type); new_type = (type_t*) type; } return new_type; } static type_t *create_concrete_pointer_type(pointer_type_t *type) { type_t *points_to = create_concrete_type(type->points_to); if (points_to == type->points_to) return (type_t*) type; type_t *new_type = allocate_type(TYPE_POINTER); new_type->pointer.points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_type_variable_reference_type(type_reference_t *type) { type_variable_t *type_variable = type->type_variable; type_t *current_type = type_variable->current_type; if (current_type != NULL) return current_type; return (type_t*) type; } static type_t *create_concrete_array_type(array_type_t *type) { type_t *element_type = create_concrete_type(type->element_type); if (element_type == type->element_type) return (type_t*) type; type_t *new_type = allocate_type(TYPE_ARRAY); new_type->array.element_type = element_type; new_type->array.size_expression = type->size_expression; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_typevar_binding_type(bind_typevariables_type_t *type) { int changed = 0; type_argument_t *new_arguments; type_argument_t *last_argument = NULL; type_argument_t *type_argument = type->type_arguments; while (type_argument != NULL) { type_t *type = type_argument->type; type_t *new_type = create_concrete_type(type); if (new_type != type) { changed = 1; } - type_argument_t *new_argument + type_argument_t *new_argument = obstack_alloc(type_obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = new_type; if (last_argument != NULL) { last_argument->next = new_argument; } else { new_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } if (!changed) { assert(new_arguments != NULL); obstack_free(type_obst, new_arguments); return (type_t*) type; } type_t *new_type = allocate_type(TYPE_BIND_TYPEVARIABLES); new_type->bind_typevariables.polymorphic_type = type->polymorphic_type; new_type->bind_typevariables.type_arguments = new_arguments; type_t *normalized_type = typehash_insert(new_type); if (normalized_type != new_type) { obstack_free(type_obst, new_type); } return normalized_type; } type_t *create_concrete_type(type_t *type) { switch (type->kind) { case TYPE_INVALID: return type_invalid; case TYPE_VOID: return type_void; case TYPE_ERROR: case TYPE_ATOMIC: return type; case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return create_concrete_compound_type((compound_type_t*) type); case TYPE_FUNCTION: return create_concrete_function_type((function_type_t*) type); case TYPE_POINTER: return create_concrete_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return create_concrete_array_type((array_type_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return create_concrete_type_variable_reference_type( (type_reference_t*) type); case TYPE_BIND_TYPEVARIABLES: return create_concrete_typevar_binding_type( (bind_typevariables_type_t*) type); case TYPE_TYPEOF: panic("TODO: concrete type for typeof()"); case TYPE_REFERENCE: panic("trying to normalize unresolved type reference"); break; } return type; } int typevar_binding_stack_top() { return ARR_LEN(typevar_binding_stack); } void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments) { type_variable_t *type_parameter; type_argument_t *type_argument; if (type_parameters == NULL || type_arguments == NULL) return; /* we have to take care that all rebinding happens atomically, so we first * create the structures on the binding stack and misuse the * old_current_type value to temporarily save the new! current_type. * We can then walk the list and set the new types */ type_parameter = type_parameters; type_argument = type_arguments; int old_top = typevar_binding_stack_top(); int top = ARR_LEN(typevar_binding_stack) + 1; while (type_parameter != NULL) { type_t *type = type_argument->type; while (type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) type; type_variable_t *var = ref->type_variable; if (var->current_type == NULL) { break; } type = var->current_type; } top = ARR_LEN(typevar_binding_stack) + 1; ARR_RESIZE(typevar_binding_t, typevar_binding_stack, top); typevar_binding_t *binding = & typevar_binding_stack[top-1]; binding->type_variable = type_parameter; binding->old_current_type = type; type_parameter = type_parameter->next; type_argument = type_argument->next; } assert(type_parameter == NULL && type_argument == NULL); for (int i = old_top+1; i <= top; ++i) { typevar_binding_t *binding = & typevar_binding_stack[i-1]; type_variable_t *type_variable = binding->type_variable; type_t *new_type = binding->old_current_type; binding->old_current_type = type_variable->current_type; type_variable->current_type = new_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "binding '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, type_variable->current_type); fprintf(stderr, "\n"); #endif } } void pop_type_variable_bindings(int new_top) { int top = ARR_LEN(typevar_binding_stack) - 1; for (int i = top; i >= new_top; --i) { typevar_binding_t *binding = & typevar_binding_stack[i]; type_variable_t *type_variable = binding->type_variable; type_variable->current_type = binding->old_current_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "reset binding of '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, binding->old_current_type); fprintf(stderr, "\n"); #endif } ARR_SHRINKLEN(typevar_binding_stack, new_top); } type_t *skip_typeref(type_t *type) { if (type->kind == TYPE_TYPEOF) { typeof_type_t *typeof_type = &type->typeof; return skip_typeref(typeof_type->expression->base.type); } return type; } diff --git a/type_hash.c b/type_hash.c index 81ea72b..34216c7 100644 --- a/type_hash.c +++ b/type_hash.c @@ -1,279 +1,279 @@ #include <config.h> #include <stdbool.h> #include "type_hash.h" #include "adt/error.h" #include "type_t.h" #include <assert.h> #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #include "adt/hashset.h" #undef ValueType #undef HashSetIterator #undef HashSet typedef struct type_hash_iterator_t type_hash_iterator_t; typedef struct type_hash_t type_hash_t; static unsigned hash_ptr(const void *ptr) { unsigned ptr_int = ((const char*) ptr - (const char*) NULL); return ptr_int >> 3; } static unsigned hash_atomic_type(const atomic_type_t *type) { unsigned some_prime = 27644437; return type->akind * some_prime; } static unsigned hash_pointer_type(const pointer_type_t *type) { return hash_ptr(type->points_to); } static unsigned hash_array_type(const array_type_t *type) { return hash_ptr(type->element_type) ^ hash_ptr(type->size_expression); } static unsigned hash_compound_type(const compound_type_t *type) { unsigned result = hash_ptr(type->symbol); return result; } static unsigned hash_type(const type_t *type); static unsigned hash_function_type(const function_type_t *type) { unsigned result = hash_ptr(type->result_type); function_parameter_type_t *parameter = type->parameter_types; while (parameter != NULL) { result ^= hash_ptr(parameter->type); parameter = parameter->next; } if (type->variable_arguments) result = ~result; return result; } static unsigned hash_type_reference_type_variable(const type_reference_t *type) { return hash_ptr(type->type_variable); } static unsigned hash_bind_typevariables_type_t(const bind_typevariables_type_t *type) { unsigned hash = hash_compound_type(type->polymorphic_type); type_argument_t *argument = type->type_arguments; while (argument != NULL) { hash ^= hash_type(argument->type); argument = argument->next; } return hash; } static unsigned hash_type(const type_t *type) { switch (type->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: panic("internalizing void or invalid types not possible"); case TYPE_REFERENCE_TYPE_VARIABLE: return hash_type_reference_type_variable(&type->reference); case TYPE_ATOMIC: return hash_atomic_type(&type->atomic); case TYPE_TYPEOF: { return hash_ptr(type->typeof.expression); } case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return hash_compound_type(&type->compound); case TYPE_FUNCTION: return hash_function_type(&type->function); case TYPE_POINTER: return hash_pointer_type(&type->pointer); case TYPE_ARRAY: return hash_array_type(&type->array); case TYPE_BIND_TYPEVARIABLES: return hash_bind_typevariables_type_t( &type->bind_typevariables); } abort(); } static bool atomic_types_equal(const atomic_type_t *type1, const atomic_type_t *type2) { return type1->akind == type2->akind; } static bool compound_types_equal(const compound_type_t *type1, const compound_type_t *type2) { if (type1->symbol != type2->symbol) return false; /* TODO: check type parameters? */ return true; } static bool function_types_equal(const function_type_t *type1, const function_type_t *type2) { if (type1->result_type != type2->result_type) return false; if (type1->variable_arguments != type2->variable_arguments) return false; function_parameter_type_t *param1 = type1->parameter_types; function_parameter_type_t *param2 = type2->parameter_types; while (param1 != NULL && param2 != NULL) { if (param1->type != param2->type) return false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) return false; return true; } static bool pointer_types_equal(const pointer_type_t *type1, const pointer_type_t *type2) { return type1->points_to == type2->points_to; } static bool array_types_equal(const array_type_t *type1, const array_type_t *type2) { return type1->element_type == type2->element_type && type1->size_expression == type2->size_expression; } static bool type_references_type_variable_equal(const type_reference_t *type1, const type_reference_t *type2) { return type1->type_variable == type2->type_variable; } static bool bind_typevariables_type_equal(const bind_typevariables_type_t*type1, const bind_typevariables_type_t*type2) { if (type1->polymorphic_type != type2->polymorphic_type) return false; type_argument_t *argument1 = type1->type_arguments; type_argument_t *argument2 = type2->type_arguments; while (argument1 != NULL) { if (argument2 == NULL) return false; if (argument1->type != argument2->type) return false; argument1 = argument1->next; argument2 = argument2->next; } if (argument2 != NULL) return false; return true; } static bool types_equal(const type_t *type1, const type_t *type2) { if (type1 == type2) return true; if (type1->kind != type2->kind) return false; switch (type1->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: return false; case TYPE_TYPEOF: { const typeof_type_t *typeof_type1 = (const typeof_type_t*) type1; const typeof_type_t *typeof_type2 = (const typeof_type_t*) type2; return typeof_type1->expression == typeof_type2->expression; } case TYPE_REFERENCE_TYPE_VARIABLE: return type_references_type_variable_equal( &type1->reference, &type2->reference); case TYPE_ATOMIC: return atomic_types_equal(&type1->atomic, &type2->atomic); case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return compound_types_equal(&type1->compound, &type2->compound); case TYPE_FUNCTION: return function_types_equal(&type1->function, &type2->function); case TYPE_POINTER: return pointer_types_equal(&type1->pointer, &type2->pointer); case TYPE_ARRAY: return array_types_equal(&type1->array, &type2->array); case TYPE_BIND_TYPEVARIABLES: return bind_typevariables_type_equal( - &type1->bind_typevariables, &type2->bind_typevariables); + &type1->bind_typevariables, &type2->bind_typevariables); } panic("invalid type encountered"); } #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #define NullValue NULL #define DeletedValue ((type_t*)-1) #define Hash(this, key) hash_type(key) #define KeysEqual(this,key1,key2) types_equal(key1, key2) #define SetRangeEmpty(ptr,size) memset(ptr, 0, (size) * sizeof(*(ptr))) #define hashset_init _typehash_init #define hashset_init_size _typehash_init_size #define hashset_destroy _typehash_destroy #define hashset_insert _typehash_insert #define hashset_remove typehash_remove #define hashset_find typehash_find #define hashset_size typehash_size #define hashset_iterator_init typehash_iterator_init #define hashset_iterator_next typehash_iterator_next #define hashset_remove_iterator typehash_remove_iterator #define SCALAR_RETURN #include "adt/hashset.c" static type_hash_t typehash; void init_typehash(void) { _typehash_init(&typehash); } void exit_typehash(void) { _typehash_destroy(&typehash); } type_t *typehash_insert(type_t *type) { return _typehash_insert(&typehash, type); } int typehash_contains(type_t *type) { return typehash_find(&typehash, type) != NULL; }
MatzeB/fluffy
1b0022cb6c22f2e6c946ecfcbb1dd108d2fc656a
add missing file
diff --git a/unicode.h b/unicode.h new file mode 100644 index 0000000..18b19d5 --- /dev/null +++ b/unicode.h @@ -0,0 +1,67 @@ +#ifndef UNICODE_H +#define UNICODE_H + +#include <assert.h> +#include "adt/obst.h" + +typedef unsigned int utf32; +#define UTF32_PRINTF_FORMAT "%u" + +/** + * "parse" an utf8 character from a string. + * Warning: This function only works for valid utf-8 inputs. The behaviour + * is undefined for invalid utf-8 input. + * + * @param p A pointer to a pointer into the string. The pointer + * is incremented for each consumed char + */ +static inline utf32 read_utf8_char(const char **p) +{ + const unsigned char *c = (const unsigned char *) *p; + utf32 result; + + if ((*c & 0x80) == 0) { + /* 1 character encoding: 0b0??????? */ + result = *c++; + } else if ((*c & 0xE0) == 0xC0) { + /* 2 character encoding: 0b110?????, 0b10?????? */ + result = *c++ & 0x1F; + result = (result << 6) | (*c++ & 0x3F); + } else if ((*c & 0xF0) == 0xE0) { + /* 3 character encoding: 0b1110????, 0b10??????, 0b10?????? */ + result = *c++ & 0x0F; + result = (result << 6) | (*c++ & 0x3F); + result = (result << 6) | (*c++ & 0x3F); + } else { + /* 4 character enc.: 0b11110???, 0b10??????, 0b10??????, 0b10?????? */ + assert((*c & 0xF8) == 0xF0); + result = *c++ & 0x07; + result = (result << 6) | (*c++ & 0x3F); + result = (result << 6) | (*c++ & 0x3F); + result = (result << 6) | (*c++ & 0x3F); + } + + *p = (const char*) c; + return result; +} + +static inline void obstack_grow_symbol(struct obstack *obstack, utf32 const tc) +{ + if (tc < 0x80U) { + obstack_1grow(obstack, tc); + } else if (tc < 0x800) { + obstack_1grow(obstack, 0xC0 | (tc >> 6)); + obstack_1grow(obstack, 0x80 | (tc & 0x3F)); + } else if (tc < 0x10000) { + obstack_1grow(obstack, 0xE0 | ( tc >> 12)); + obstack_1grow(obstack, 0x80 | ((tc >> 6) & 0x3F)); + obstack_1grow(obstack, 0x80 | ( tc & 0x3F)); + } else { + obstack_1grow(obstack, 0xF0 | ( tc >> 18)); + obstack_1grow(obstack, 0x80 | ((tc >> 12) & 0x3F)); + obstack_1grow(obstack, 0x80 | ((tc >> 6) & 0x3F)); + obstack_1grow(obstack, 0x80 | ( tc & 0x3F)); + } +} + +#endif
MatzeB/fluffy
6e106a066fcc97a7b114e08012ea1dbced771661
use new input API from cparser
diff --git a/Makefile b/Makefile index 512ee56..70d712f 100644 --- a/Makefile +++ b/Makefile @@ -1,71 +1,72 @@ -include config.mak GOAL = fluffy FIRM_CFLAGS ?= `pkg-config --cflags libfirm` FIRM_LIBS ?= `pkg-config --libs libfirm` CPPFLAGS = -I. CPPFLAGS += $(FIRM_CFLAGS) -DFIRM_BACKEND -CFLAGS += -Wall -W -Wstrict-prototypes -Wmissing-prototypes -Werror -std=c99 +CFLAGS += -Wall -W -Wextra -Wstrict-prototypes -Wwrite-strings -Wmissing-prototypes -Werror -std=c99 CFLAGS += -O0 -g3 -m32 LFLAGS += $(FIRM_LIBS) -ldl SOURCES := \ - adt/strset.c \ adt/obstack.c \ adt/obstack_printf.c \ + adt/strset.c \ ast.c \ - type.c \ - parser.c \ ast2firm.c \ + driver/firm_machine.c \ + driver/firm_opt.c \ + driver/firm_timing.c \ + input.c \ lexer.c \ main.c \ mangle.c \ match_type.c \ + parser.c \ plugins.c \ semantic.c \ symbol_table.c \ token.c \ - type_hash.c \ - driver/firm_opt.c \ - driver/firm_machine.c \ - driver/firm_timing.c + type.c \ + type_hash.c OBJECTS = $(SOURCES:%.c=build/%.o) Q = @ .PHONY : all clean dirs all: $(GOAL) ifeq ($(findstring $(MAKECMDGOALS), clean depend),) -include .depend endif .depend: $(SOURCES) @echo "===> DEPEND" @rm -f $@ && touch $@ && makedepend -p "$@ build/" -Y -f $@ -- $(CPPFLAGS) -- $(SOURCES) 2> /dev/null && rm [email protected] $(GOAL): $(OBJECTS) | build/driver build/adt @echo "===> LD $@" $(Q)$(CC) -m32 -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) build/adt: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/driver: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/%.o: %.c | build/adt build/driver @echo '===> CC $<' $(Q)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ clean: @echo '===> CLEAN' $(Q)rm -rf build $(GOAL) .depend diff --git a/input.c b/input.c new file mode 100644 index 0000000..8c5d892 --- /dev/null +++ b/input.c @@ -0,0 +1,345 @@ +#include "config.h" + +#include "input.h" + +#include <ctype.h> +#include "lexer.h" + +typedef size_t (*decode_func)(input_t *input, utf32 *buffer, size_t buffer_size); + +typedef enum { + INPUT_FILE, + INPUT_STRING +} input_kind_t; + +struct input_t { + input_kind_t kind; + union { + FILE *file; + const char *string; + } in; + decode_func decode; + + /* state for utf-8 decoder */ + utf32 utf8_part_decoded_min_code; + utf32 utf8_part_decoded_char; + size_t utf8_part_decoded_rest_len; +}; + +static input_error_callback_func input_error; + +void set_input_error_callback(input_error_callback_func new_func) +{ + input_error = new_func; +} + +static size_t read_block(input_t *input, unsigned char *const read_buf, + size_t const n) +{ + if (input->kind == INPUT_FILE) { + FILE *file = input->in.file; + size_t const s = fread(read_buf, 1, n, file); + if (s == 0) { + /* on OS/X ferror appears to return true on eof as well when running + * the application in gdb... */ + if (!feof(file) && ferror(file)) + input_error(0, 0, "read from input failed"); + return 0; + } + return s; + } else { + assert(input->kind == INPUT_STRING); + size_t len = strlen(input->in.string); + if (len > n) + len = n; + memcpy(read_buf, input->in.string, len); + input->in.string += len; + return len; + } +} + +static size_t decode_iso_8859_1(input_t *input, utf32 *buffer, + size_t buffer_size) +{ + unsigned char read_buf[buffer_size]; + size_t const s = read_block(input, read_buf, sizeof(read_buf)); + + unsigned char const *src = read_buf; + unsigned char const *end = read_buf + s; + utf32 *dst = buffer; + while (src != end) + *dst++ = *src++; + + return s; +} + +static size_t decode_iso_8859_15(input_t *input, utf32 *buffer, + size_t buffer_size) +{ + unsigned char read_buf[buffer_size]; + size_t const s = read_block(input, read_buf, sizeof(read_buf)); + + unsigned char const *src = read_buf; + unsigned char const *end = read_buf + s; + utf32 *dst = buffer; + while (src != end) { + utf32 tc = *src++; + switch (tc) { + case 0xA4: tc = 0x20AC; break; // € + case 0xA6: tc = 0x0160; break; // Å  + case 0xA8: tc = 0x0161; break; // Å¡ + case 0xB4: tc = 0x017D; break; // Ž + case 0xB8: tc = 0x017E; break; // ž + case 0xBC: tc = 0x0152; break; // Œ + case 0xBD: tc = 0x0153; break; // œ + case 0xBE: tc = 0x0178; break; // Ÿ + } + *dst++ = tc; + } + + return s; +} + +static size_t decode_utf8(input_t *input, utf32 *buffer, size_t buffer_size) +{ + unsigned char read_buf[buffer_size]; + + while (true) { + size_t const s = read_block(input, read_buf, sizeof(read_buf)); + if (s == 0) { + if (input->utf8_part_decoded_rest_len > 0) + input_error(0, 0, "incomplete input char at end of input"); + return 0; + } + + unsigned char const *src = read_buf; + unsigned char const *end = read_buf + s; + utf32 *dst = buffer; + utf32 decoded; + utf32 min_code; + + if (input->utf8_part_decoded_rest_len != 0) { + min_code = input->utf8_part_decoded_min_code; + decoded = input->utf8_part_decoded_char; + size_t const rest_len = input->utf8_part_decoded_rest_len; + input->utf8_part_decoded_rest_len = 0; + switch (rest_len) { + case 4: goto realign; + case 3: goto three_more; + case 2: goto two_more; + default: goto one_more; + } + } + + while (src != end) { + if ((*src & 0x80) == 0) { + decoded = *src++; + } else if ((*src & 0xE0) == 0xC0) { + min_code = 0x80; + decoded = *src++ & 0x1F; +one_more: + if (src == end) { + input->utf8_part_decoded_min_code = min_code; + input->utf8_part_decoded_char = decoded; + input->utf8_part_decoded_rest_len = 1; + break; + } + if ((*src & 0xC0) == 0x80) { + decoded = (decoded << 6) | (*src++ & 0x3F); + } else { + goto invalid_char; + } + if (decoded < min_code || + decoded > 0x10FFFF || + (0xD800 <= decoded && decoded < 0xE000) || // high/low surrogates + (0xFDD0 <= decoded && decoded < 0xFDF0) || // noncharacters + (decoded & 0xFFFE) == 0xFFFE) { // noncharacters + input_error(0, 0, "invalid byte sequence in input"); + } + } else if ((*src & 0xF0) == 0xE0) { + min_code = 0x800; + decoded = *src++ & 0x0F; +two_more: + if (src == end) { + input->utf8_part_decoded_min_code = min_code; + input->utf8_part_decoded_char = decoded; + input->utf8_part_decoded_rest_len = 2; + break; + } + if ((*src & 0xC0) == 0x80) { + decoded = (decoded << 6) | (*src++ & 0x3F); + } else { + goto invalid_char; + } + goto one_more; + } else if ((*src & 0xF8) == 0xF0) { + min_code = 0x10000; + decoded = *src++ & 0x07; +three_more: + if (src == end) { + input->utf8_part_decoded_min_code = min_code; + input->utf8_part_decoded_char = decoded; + input->utf8_part_decoded_rest_len = 3; + break; + } + if ((*src & 0xC0) == 0x80) { + decoded = (decoded << 6) | (*src++ & 0x3F); + } else { + goto invalid_char; + } + goto two_more; + } else { +invalid_char: + input_error(0, 0, "invalid byte sequence in input"); +realign: + do { + ++src; + if (src == end) { + input->utf8_part_decoded_rest_len = 4; + break; + } + } while ((*src & 0xC0) == 0x80 || (*src & 0xF8) == 0xF8); + continue; + } + *dst++ = decoded; + } + + /* we're done when we could read more than 1 char */ + if (buffer != dst) + return dst - buffer; + } +} + +static size_t decode_windows_1252(input_t *input, utf32 *buffer, + size_t buffer_size) +{ + unsigned char read_buf[buffer_size]; + size_t const s = read_block(input, read_buf, sizeof(read_buf)); + + unsigned char const *src = read_buf; + unsigned char const *end = read_buf + s; + utf32 *dst = buffer; + while (src != end) { + utf32 tc = *src++; + switch (tc) { + case 0x80: tc = 0x20AC; break; // € + case 0x82: tc = 0x201A; break; // ‚ + case 0x83: tc = 0x0192; break; // ƒ + case 0x84: tc = 0x201E; break; // „ + case 0x85: tc = 0x2026; break; // … + case 0x86: tc = 0x2020; break; // † + case 0x87: tc = 0x2021; break; // ‡ + case 0x88: tc = 0x02C6; break; // ˆ + case 0x89: tc = 0x2030; break; // ‰ + case 0x8A: tc = 0x0160; break; // Å  + case 0x8B: tc = 0x2039; break; // ‹ + case 0x8C: tc = 0x0152; break; // Œ + case 0x8E: tc = 0x017D; break; // Ž + case 0x91: tc = 0x2018; break; // ‘ + case 0x92: tc = 0x2019; break; // ’ + case 0x93: tc = 0x201C; break; // “ + case 0x94: tc = 0x201D; break; // ” + case 0x95: tc = 0x2022; break; // • + case 0x96: tc = 0x2013; break; // – + case 0x97: tc = 0x2014; break; // — + case 0x98: tc = 0x02DC; break; // ˜ + case 0x99: tc = 0x2122; break; // ™ + case 0x9A: tc = 0x0161; break; // Å¡ + case 0x9B: tc = 0x203A; break; // › + case 0x9C: tc = 0x0153; break; // œ + case 0x9E: tc = 0x017E; break; // ž + case 0x9F: tc = 0x0178; break; // Ÿ + } + *dst++ = tc; + } + + return s; +} + +typedef struct named_decoder_t { + char const *name; + decode_func decoder; +} named_decoder_t; + +static named_decoder_t const decoders[] = { + { "CP819", decode_iso_8859_1 }, // official alias + { "IBM819", decode_iso_8859_1 }, // official alias + { "ISO-8859-1", decode_iso_8859_1 }, // official alias + { "ISO-8859-15", decode_iso_8859_15 }, // official name + { "ISO8859-1", decode_iso_8859_1 }, + { "ISO8859-15", decode_iso_8859_15 }, + { "ISO_8859-1", decode_iso_8859_1 }, // official alias + { "ISO_8859-15", decode_iso_8859_15 }, // official alias + { "ISO_8859-1:1987", decode_iso_8859_1 }, // official name + { "Latin-9", decode_iso_8859_15 }, // official alias + { "UTF-8", decode_utf8 }, // official name + { "csISOLatin1", decode_iso_8859_1 }, // official alias + { "cp1252", decode_windows_1252 }, + { "iso-ir-100", decode_iso_8859_1 }, // official alias + { "l1", decode_iso_8859_1 }, // official alias + { "latin1", decode_iso_8859_1 }, // official alias + { "windows-1252", decode_windows_1252 }, // official name + + { NULL, NULL } +}; + +/** strcasecmp is not part of C99 so we need our own implementation here */ +static int my_strcasecmp(const char *s1, const char *s2) +{ + for ( ; *s1 != 0; ++s1, ++s2) { + if (tolower(*s1) != tolower(*s2)) + break; + } + return (unsigned char)*s1 - (unsigned char)*s2; +} + +static void choose_decoder(input_t *result, const char *encoding) +{ + if (encoding == NULL) { + result->decode = decode_utf8; + } else { + for (named_decoder_t const *i = decoders; i->name != NULL; ++i) { + if (my_strcasecmp(encoding, i->name) != 0) + continue; + result->decode = i->decoder; + break; + } + if (result->decode == NULL) { + fprintf(stderr, "error: input encoding \"%s\" not supported\n", + encoding); + result->decode = decode_utf8; + } + } +} + +input_t *input_from_stream(FILE *file, const char *encoding) +{ + input_t *result = XMALLOCZ(input_t); + result->kind = INPUT_FILE; + result->in.file = file; + + choose_decoder(result, encoding); + + return result; +} + +input_t *input_from_string(const char *string, const char *encoding) +{ + input_t *result = XMALLOCZ(input_t); + result->kind = INPUT_STRING; + result->in.string = string; + + choose_decoder(result, encoding); + + return result; +} + +size_t decode(input_t *input, utf32 *buffer, size_t buffer_size) +{ + return input->decode(input, buffer, buffer_size); +} + +void input_free(input_t *input) +{ + xfree(input); +} diff --git a/input.h b/input.h new file mode 100644 index 0000000..053a5b9 --- /dev/null +++ b/input.h @@ -0,0 +1,23 @@ +#ifndef INPUT_H +#define INPUT_H + +#include <stdio.h> +#include "unicode.h" + +typedef struct input_t input_t; + +input_t *input_from_stream(FILE *stream, const char *encoding); +input_t *input_from_string(const char *string, const char *encoding); + +/** Type for a function being called on an input (or encoding) errors. */ +typedef void (*input_error_callback_func)(unsigned delta_lines, + unsigned delta_cols, + const char *message); + +void set_input_error_callback(input_error_callback_func func); + +size_t decode(input_t *input, utf32 *buffer, size_t buffer_size); + +void input_free(input_t *input); + +#endif diff --git a/lexer.c b/lexer.c index 87896c8..2b0ac5a 100644 --- a/lexer.c +++ b/lexer.c @@ -1,692 +1,701 @@ #include <config.h> #include "lexer.h" +#include "input.h" +#include "unicode.h" #include "symbol_table.h" #include "adt/error.h" #include "adt/strset.h" #include "adt/array.h" #include <stdbool.h> #include <assert.h> #include <errno.h> #include <string.h> #include <ctype.h> -#define MAX_PUTBACK 1 +#define MAX_PUTBACK 16 // 1 would be enough, 16 gives a nicer alignment #define MAX_INDENT 256 +#define C_EOF ((utf32)EOF) enum TOKEN_START_TYPE { START_UNKNOWN = 0, START_IDENT, START_NUMBER, START_SINGLE_CHARACTER_OPERATOR, START_OPERATOR, START_STRING_LITERAL, START_CHARACTER_CONSTANT, START_BACKSLASH, START_NEWLINE, }; -static int tables_init = 0; -static char char_type[256]; -static char ident_char[256]; +static bool tables_init = false; +static unsigned char char_type[256]; +static unsigned char ident_char[256]; -static int c; +static utf32 c; source_position_t source_position; -static FILE *input; -static char buf[1024 + MAX_PUTBACK]; -static const char *bufend; -static const char *bufpos; +static input_t *input; +static utf32 input_buf[1024 + MAX_PUTBACK]; +static utf32 *bufend; +static utf32 *bufpos; static strset_t stringset; -static int at_line_begin; +static bool at_line_begin; static unsigned not_returned_dedents; static unsigned newline_after_dedents; static unsigned indent_levels[MAX_INDENT]; static unsigned indent_levels_len; -static char last_line_indent[MAX_INDENT]; +static utf32 last_line_indent[MAX_INDENT]; static unsigned last_line_indent_len; static void init_tables(void) { memset(char_type, 0, sizeof(char_type)); memset(ident_char, 0, sizeof(ident_char)); for (int c = 0; c < 256; ++c) { if (isalnum(c)) { char_type[c] = START_IDENT; ident_char[c] = 1; } } char_type['_'] = START_IDENT; ident_char['_'] = 1; for (int c = '0'; c <= '9'; ++c) { ident_char[c] = 1; char_type[c] = START_NUMBER; } char_type['"'] = START_STRING_LITERAL; char_type['\''] = START_CHARACTER_CONSTANT; static const int single_char_ops[] = { '(', ')', '[', ']', '{', '}', ',', ';', ':', '*' }; for (size_t i = 0; i < sizeof(single_char_ops)/sizeof(single_char_ops[0]); ++i) { int c = single_char_ops[i]; char_type[c] = START_SINGLE_CHARACTER_OPERATOR; } static const int ops[] = { '+', '-', '/', '=', '<', '>', '.', '^', '!', '?', '&', '%', '~', '|', '\\', '$' }; for (size_t i = 0; i < sizeof(ops)/sizeof(ops[0]); ++i) { int c = ops[i]; char_type[c] = START_OPERATOR; } char_type['\n'] = START_NEWLINE; char_type['\\'] = START_BACKSLASH; - tables_init = 1; + tables_init = true; } static inline int is_ident_char(int c) { return ident_char[c]; } static void error_prefix_at(const char *input_name, unsigned linenr) { fprintf(stderr, "%s:%d: Error: ", input_name, linenr); } static void error_prefix(void) { error_prefix_at(source_position.input_name, source_position.linenr); } static void parse_error(const char *msg) { error_prefix(); fprintf(stderr, "%s\n", msg); } static inline void next_char(void) { - bufpos++; if (bufpos >= bufend) { - size_t s = fread(buf + MAX_PUTBACK, 1, sizeof(buf) - MAX_PUTBACK, - input); - if (s == 0) { + size_t n = decode(input, input_buf+MAX_PUTBACK, + sizeof(input_buf)-MAX_PUTBACK); + if (n == 0) { c = EOF; return; } - bufpos = buf + MAX_PUTBACK; - bufend = buf + MAX_PUTBACK + s; + bufpos = input_buf + MAX_PUTBACK; + bufend = bufpos + n; } - c = *(bufpos); + c = *(bufpos++); } -static inline void put_back(int c) +static inline void put_back(const utf32 pc) { - char *p = (char*) bufpos - 1; - bufpos--; - assert(p >= buf); - *p = c; + *(--bufpos - input_buf + input_buf) = pc; } static void parse_symbol(token_t *token) { symbol_t *symbol; char *string; do { obstack_1grow(&symbol_obstack, c); next_char(); } while (is_ident_char(c)); obstack_1grow(&symbol_obstack, '\0'); string = obstack_finish(&symbol_obstack); symbol = symbol_table_insert(string); if (symbol->ID > 0) { token->type = symbol->ID; } else { token->type = T_IDENTIFIER; } token->v.symbol = symbol; if (symbol->string != string) { obstack_free(&symbol_obstack, string); } } static void parse_number_bin(token_t *token) { assert(c == 'b' || c == 'B'); next_char(); if (c != '0' && c != '1') { parse_error("premature end of binary number literal"); token->type = T_ERROR; return; } int value = 0; for (;;) { switch (c) { case '0': value = 2 * value; break; case '1': value = 2 * value + 1; break; default: token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number_hex(token_t *token) { assert(c == 'x' || c == 'X'); next_char(); if (!isdigit(c) && !('A' <= c && c <= 'F') && !('a' <= c && c <= 'f')) { parse_error("premature end of hex number literal"); token->type = T_ERROR; return; } int value = 0; for (;;) { if (isdigit(c)) { value = 16 * value + c - '0'; } else if ('A' <= c && c <= 'F') { value = 16 * value + c - 'A' + 10; } else if ('a' <= c && c <= 'f') { value = 16 * value + c - 'a' + 10; } else { token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number_oct(token_t *token) { assert(c == 'o' || c == 'O'); next_char(); int value = 0; for (;;) { if ('0' <= c && c <= '7') { value = 8 * value + c - '0'; } else { token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number_dec(token_t *token, int first_char) { int value = 0; if (first_char > 0) { assert(first_char >= '0' && first_char <= '9'); value = first_char - '0'; } for (;;) { if (isdigit(c)) { value = 10 * value + c - '0'; } else { token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number(token_t *token) { // TODO check for overflow // TODO check for various invalid inputs sequences if (c == '0') { next_char(); switch (c) { case 'b': case 'B': parse_number_bin(token); break; case 'X': case 'x': parse_number_hex(token); break; case 'o': case 'O': parse_number_oct(token); break; default: parse_number_dec(token, '0'); } } else { parse_number_dec(token, 0); } } static int parse_escape_sequence(void) { assert(c == '\\'); next_char(); switch (c) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case '\\': return '\\'; case '"': return '"'; case '\'': return'\''; case '?': return '\?'; case 'x': /* TODO parse hex number ... */ parse_error("hex escape sequences not implemented yet"); return 0; case 'o': /* TODO parse octal number ... */ parse_error("octal escape sequences not implemented yet"); return 0; case EOF: parse_error("reached end of file while parsing escape sequence"); return EOF; default: parse_error("unknown escape sequence\n"); return 0; } } static void parse_string_literal(token_t *token) { unsigned start_linenr = source_position.linenr; char *string; const char *result; assert(c == '"'); next_char(); while (c != '\"') { if (c == '\\') { c = parse_escape_sequence(); } else if (c == '\n') { source_position.linenr++; } - if (c == EOF) { + if (c == C_EOF) { error_prefix_at(source_position.input_name, start_linenr); fprintf(stderr, "string has no end\n"); token->type = T_ERROR; return; } - obstack_1grow(&symbol_obstack, c); + obstack_grow_symbol(&symbol_obstack, c); next_char(); } next_char(); /* add finishing 0 to the string */ obstack_1grow(&symbol_obstack, '\0'); string = obstack_finish(&symbol_obstack); /* check if there is already a copy of the string */ result = strset_insert(&stringset, string); if (result != string) { obstack_free(&symbol_obstack, string); } token->type = T_STRING_LITERAL; token->v.string = result; } static void skip_multiline_comment(void) { unsigned start_linenr = source_position.linenr; unsigned level = 1; while (true) { switch (c) { case '*': next_char(); if (c == '/') { next_char(); level--; if (level == 0) return; } break; case '/': next_char(); if (c == '*') { next_char(); level++; } break; case EOF: error_prefix_at(source_position.input_name, start_linenr); fprintf(stderr, "comment has no end\n"); return; case '\n': next_char(); source_position.linenr++; break; default: next_char(); break; } } } static void skip_line_comment(void) { - while (c != '\n' && c != EOF) { + while (c != '\n' && c != C_EOF) { next_char(); } } static void parse_operator(token_t *token, int firstchar) { if (firstchar == '/') { if (c == '*') { next_char(); skip_multiline_comment(); return lexer_next_token(token); } else if (c == '/') { next_char(); skip_line_comment(); return lexer_next_token(token); } } obstack_1grow(&symbol_obstack, firstchar); while (char_type[c] == START_OPERATOR) { obstack_1grow(&symbol_obstack, c); next_char(); } obstack_1grow(&symbol_obstack, '\0'); char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); int ID = symbol->ID; if (ID > 0) { token->type = ID; } else { error_prefix(); fprintf(stderr, "unknown operator %s found\n", string); token->type = T_ERROR; } token->v.symbol = symbol; if (symbol->string != string) { obstack_free(&symbol_obstack, string); } } static void parse_indent(token_t *token) { if (not_returned_dedents > 0) { token->type = T_DEDENT; not_returned_dedents--; if (not_returned_dedents == 0 && !newline_after_dedents) - at_line_begin = 0; + at_line_begin = false; return; } if (newline_after_dedents) { token->type = T_NEWLINE; - at_line_begin = 0; + at_line_begin = false; newline_after_dedents = 0; return; } int skipped_line = 0; - char indent[MAX_INDENT]; + utf32 indent[MAX_INDENT]; unsigned indent_len; start_indent_parsing: indent_len = 0; while (c == ' ' || c == '\t') { indent[indent_len] = c; indent_len++; if (indent_len > MAX_INDENT) { panic("Indentation bigger than MAX_INDENT not supported"); } next_char(); } /* skip empty lines */ while (c == '/') { next_char(); if (c == '*') { next_char(); skip_multiline_comment(); } else if (c == '/') { next_char(); skip_line_comment(); } else { put_back(c); } } if (c == '\n') { next_char(); source_position.linenr++; skipped_line = 1; goto start_indent_parsing; } - at_line_begin = 0; + at_line_begin = false; unsigned i; for (i = 0; i < indent_len && i < last_line_indent_len; ++i) { if (indent[i] != last_line_indent[i]) { parse_error("space/tab usage for indentation different from " "previous line"); token->type = T_ERROR; return; } } if (last_line_indent_len < indent_len) { /* more indentation */ memcpy(& last_line_indent[i], & indent[i], indent_len - i); last_line_indent_len = indent_len; newline_after_dedents = 0; indent_levels[indent_levels_len] = indent_len; indent_levels_len++; token->type = T_INDENT; return; } else if (last_line_indent_len > indent_len) { /* less indentation */ unsigned lower_level; unsigned dedents = 0; do { dedents++; indent_levels_len--; lower_level = indent_levels[indent_levels_len - 1]; } while (lower_level > indent_len); if (lower_level < indent_len) { parse_error("returning to invalid indentation level"); token->type = T_ERROR; return; } assert(dedents >= 1); not_returned_dedents = dedents - 1; if (skipped_line) { newline_after_dedents = 1; - at_line_begin = 1; + at_line_begin = true; } else { newline_after_dedents = 0; if (not_returned_dedents > 0) { - at_line_begin = 1; + at_line_begin = true; } } last_line_indent_len = indent_len; token->type = T_DEDENT; return; } lexer_next_token(token); return; } void lexer_next_token(token_t *token) { int firstchar; if (at_line_begin) { parse_indent(token); return; } else { /* skip whitespaces */ while (c == ' ' || c == '\t') { next_char(); } } - if (c < 0 || c >= 256) { + if (c == C_EOF) { /* if we're indented at end of file, then emit a newline, dedent, ... * sequence of tokens */ if (indent_levels_len > 1) { not_returned_dedents = indent_levels_len - 1; - at_line_begin = 1; + at_line_begin = true; indent_levels_len = 1; token->type = T_NEWLINE; return; } token->type = T_EOF; return; } int type = char_type[c]; switch (type) { case START_SINGLE_CHARACTER_OPERATOR: token->type = c; next_char(); break; case START_OPERATOR: firstchar = c; next_char(); parse_operator(token, firstchar); break; case START_IDENT: parse_symbol(token); break; case START_NUMBER: parse_number(token); break; case START_STRING_LITERAL: parse_string_literal(token); break; case START_CHARACTER_CONSTANT: next_char(); if (c == '\\') { token->type = T_INTEGER; token->v.intvalue = parse_escape_sequence(); next_char(); } else { if (c == '\n') { parse_error("newline while parsing character constant"); source_position.linenr++; } token->type = T_INTEGER; token->v.intvalue = c; next_char(); } { int err_displayed = 0; - while (c != '\'' && c != EOF) { + while (c != '\'' && c != C_EOF) { if (!err_displayed) { parse_error("multibyte character constant"); err_displayed = 1; } token->type = T_ERROR; next_char(); } } next_char(); break; case START_NEWLINE: next_char(); token->type = T_NEWLINE; source_position.linenr++; - at_line_begin = 1; + at_line_begin = true; break; case START_BACKSLASH: next_char(); if (c == '\n') { next_char(); source_position.linenr++; } else { parse_operator(token, '\\'); return; } lexer_next_token(token); return; default: error_prefix(); fprintf(stderr, "unknown character '%c' found\n", c); token->type = T_ERROR; next_char(); break; } } -void lexer_init(FILE *stream, const char *input_name) +static void input_error(unsigned delta_lines, unsigned delta_cols, + const char *message) { - input = stream; + source_position.linenr += delta_lines; + (void) delta_cols; + parse_error(message); +} + +void lexer_init(input_t *new_input, const char *input_name) +{ + input = new_input; bufpos = NULL; bufend = NULL; source_position.linenr = 1; source_position.input_name = input_name; - at_line_begin = 1; + at_line_begin = true; indent_levels[0] = 0; indent_levels_len = 1; last_line_indent_len = 0; strset_init(&stringset); not_returned_dedents = 0; newline_after_dedents = 0; + set_input_error_callback(input_error); + if (!tables_init) { init_tables(); } next_char(); } void lexer_destroy(void) { } static __attribute__((unused)) void dbg_pos(const source_position_t source_position) { fprintf(stdout, "%s:%d\n", source_position.input_name, source_position.linenr); fflush(stdout); } diff --git a/lexer.h b/lexer.h index 507fc82..8d4ead7 100644 --- a/lexer.h +++ b/lexer.h @@ -1,19 +1,20 @@ #ifndef LEXER_H #define LEXER_H #include "symbol_table_t.h" #include "token_t.h" +#include "input.h" typedef struct source_position_t source_position_t; struct source_position_t { const char *input_name; unsigned linenr; }; extern source_position_t source_position; -void lexer_init(FILE *stream, const char *input_name); +void lexer_init(input_t *input, const char *input_name); void lexer_destroy(void); void lexer_next_token(token_t *token); #endif diff --git a/parser.c b/parser.c index 800e32f..4f530b5 100644 --- a/parser.c +++ b/parser.c @@ -1828,570 +1828,572 @@ static attribute_t *parse_attribute(void) } if (parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while (token.type == '$') { attribute_t *attribute = parse_attribute(); if (attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_struct(void) { eat(T_struct); entity_t *declaration = allocate_entity(ENTITY_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); type->compound.symbol = declaration->base.symbol; if (token.type == '<') { next_token(); type->compound.type_parameters = parse_type_parameters(&type->compound.context); expect('>', end_error); } type->compound.attributes = parse_attributes(); declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } add_entity(declaration); end_error: ; } static void parse_union(void) { eat(T_union); entity_t *declaration = allocate_entity(ENTITY_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); type_t *type = allocate_type(TYPE_COMPOUND_UNION); type->compound.symbol = declaration->base.symbol; type->compound.attributes = parse_attributes(); declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } end_error: add_entity(declaration); } static concept_function_t *parse_concept_function(void) { expect(T_func, end_error); entity_t *declaration = allocate_entity(ENTITY_CONCEPT_FUNCTION); type_t *type = allocate_type(TYPE_FUNCTION); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept function", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_parameter_declarations(&type->function, &declaration->concept_function.parameters); if (token.type == ':') { next_token(); type->function.result_type = parse_type(); } else { type->function.result_type = type_void; } expect(T_NEWLINE, end_error); declaration->concept_function.type = &type->function; add_entity(declaration); return &declaration->concept_function; end_error: return NULL; } static void parse_concept(void) { eat(T_concept); entity_t *declaration = allocate_entity(ENTITY_CONCEPT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); context_t *context = &declaration->concept.context; add_anchor_token('>'); declaration->concept.type_parameters = parse_type_parameters(context); rem_anchor_token('>'); expect('>', end_error); } expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_function_t *last_function = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_function_t *function = parse_concept_function(); function->concept = &declaration->concept; if (last_function != NULL) { last_function->next = function; } else { declaration->concept.functions = function; } last_function = function; } next_token(); end_of_parse_concept: add_entity(declaration); return; end_error: ; } static concept_function_instance_t *parse_concept_function_instance(void) { concept_function_instance_t *function_instance = allocate_ast_zero(sizeof(function_instance[0])); expect(T_func, end_error); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept function " "instance", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } function_instance->source_position = source_position; function_instance->symbol = token.v.symbol; next_token(); parse_function(&function_instance->function); return function_instance; end_error: return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect('>', end_error); } instance->type_arguments = parse_type_arguments(); expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_function_instance_t *last_function = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if (token.type == T_NEWLINE) { next_token(); continue; } concept_function_instance_t *function = parse_concept_function_instance(); if (function == NULL) continue; if (last_function != NULL) { last_function->next = function; } else { instance->function_instances = function; } last_function = function; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; return; end_error: ; } static void skip_declaration(void) { next_token(); } static void parse_import(void) { eat(T_import); if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing import directive", T_STRING_LITERAL, 0); eat_until_anchor(); return; } symbol_t *modulename = symbol_table_insert(token.v.string); next_token(); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing import directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } import_t *import = allocate_ast_zero(sizeof(import[0])); import->module = modulename; import->symbol = token.v.symbol; import->source_position = source_position; import->next = current_context->imports; current_context->imports = import; next_token(); if (token.type != ',') break; eat(','); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_export(void) { eat(T_export); while (true) { if (token.type == T_NEWLINE) { break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if (token.type != ',') { break; } next_token(); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_module(void) { eat(T_module); /* a simple URL string without a protocol */ if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing module", T_STRING_LITERAL, 0); return; } symbol_t *new_module_name = symbol_table_insert(token.v.string); next_token(); if (current_module_name != NULL && current_module_name != new_module_name) { parser_print_error_prefix(); fprintf(stderr, "new module name '%s' overrides old name '%s'\n", new_module_name->string, current_module_name->string); } current_module_name = new_module_name; expect(T_NEWLINE, end_error); end_error: ; } void parse_declaration(void) { if (token.type == T_EOF) return; if (token.type == T_ERROR) { /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parse = NULL; if (token.type < ARR_LEN(declaration_parsers)) parse = declaration_parsers[token.type]; if (parse == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_anchor(); return; } parse(); } static void register_declaration_parsers(void) { register_declaration_parser(parse_function_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); register_declaration_parser(parse_import, T_import); register_declaration_parser(parse_module, T_module); register_declaration_parser(skip_declaration, T_NEWLINE); } static module_t *get_module(symbol_t *name) { if (name == NULL) { name = symbol_table_insert(""); } /* search for an existing module */ module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } if (module == NULL) { module = allocate_ast_zero(sizeof(module[0])); module->name = name; module->next = modules; modules = module; } return module; } static void append_context(context_t *dest, const context_t *source) { entity_t *last = dest->entities; if (last != NULL) { while (last->base.next != NULL) { last = last->base.next; } last->base.next = source->entities; } else { dest->entities = source->entities; } concept_instance_t *last_concept_instance = dest->concept_instances; if (last_concept_instance != NULL) { while (last_concept_instance->next != NULL) { last_concept_instance = last_concept_instance->next; } last_concept_instance->next = source->concept_instances; } else { dest->concept_instances = source->concept_instances; } export_t *last_export = dest->exports; if (last_export != NULL) { while (last_export->next != NULL) { last_export = last_export->next; } last_export->next = source->exports; } else { dest->exports = source->exports; } import_t *last_import = dest->imports; if (last_import != NULL) { while (last_import->next != NULL) { last_import = last_import->next; } last_import->next = source->imports; } else { dest->imports = source->imports; } } bool parse_file(FILE *in, const char *input_name) { memset(token_anchor_set, 0, sizeof(token_anchor_set)); /* get the lexer running */ - lexer_init(in, input_name); + input_t *input = input_from_stream(in, NULL); + lexer_init(input, input_name); next_token(); context_t file_context; memset(&file_context, 0, sizeof(file_context)); assert(current_context == NULL); current_context = &file_context; current_module_name = NULL; add_anchor_token(T_EOF); while (token.type != T_EOF) { parse_declaration(); } rem_anchor_token(T_EOF); assert(current_context == &file_context); current_context = NULL; /* append stuff to module */ module_t *module = get_module(current_module_name); append_context(&module->context, &file_context); /* check that we have matching rem_anchor_token calls for each add */ #ifndef NDEBUG for (int i = 0; i < T_LAST_TOKEN; ++i) { if (token_anchor_set[i] > 0) { panic("leaked token"); } } #endif lexer_destroy(); + input_free(input); return !error; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); }
MatzeB/fluffy
02e107b0daffadb746797af6858e2eccf4897dc7
adapt tests to latest firm testsuite
diff --git a/test/expected_output/array.fluffy.output b/test/array.fluffy.ref similarity index 100% rename from test/expected_output/array.fluffy.output rename to test/array.fluffy.ref diff --git a/test/expected_output/bools.fluffy.output b/test/bools.fluffy.ref similarity index 100% rename from test/expected_output/bools.fluffy.output rename to test/bools.fluffy.ref diff --git a/test/expected_output/callbacks.fluffy.output b/test/callbacks.fluffy.ref similarity index 100% rename from test/expected_output/callbacks.fluffy.output rename to test/callbacks.fluffy.ref diff --git a/test/expected_output/error1.fluffy.output b/test/error1.fluffy.ref similarity index 100% rename from test/expected_output/error1.fluffy.output rename to test/error1.fluffy.ref diff --git a/test/expected_output/evil.fluffy.output b/test/evil.fluffy.ref similarity index 100% rename from test/expected_output/evil.fluffy.output rename to test/evil.fluffy.ref diff --git a/test/expected_output/fib.fluffy.output b/test/fib.fluffy.ref similarity index 100% rename from test/expected_output/fib.fluffy.output rename to test/fib.fluffy.ref diff --git a/test/expected_output/incdec.fluffy.output b/test/incdec.fluffy.ref similarity index 100% rename from test/expected_output/incdec.fluffy.output rename to test/incdec.fluffy.ref diff --git a/test/expected_output/inference.fluffy.output b/test/inference.fluffy.ref similarity index 100% rename from test/expected_output/inference.fluffy.output rename to test/inference.fluffy.ref diff --git a/test/expected_output/pointerarith.fluffy.output b/test/pointerarith.fluffy.ref similarity index 100% rename from test/expected_output/pointerarith.fluffy.output rename to test/pointerarith.fluffy.ref diff --git a/test/expected_output/polyinstance.fluffy.output b/test/polyinstance.fluffy.ref similarity index 100% rename from test/expected_output/polyinstance.fluffy.output rename to test/polyinstance.fluffy.ref diff --git a/test/expected_output/polymorphic.fluffy.output b/test/polymorphic.fluffy.ref similarity index 100% rename from test/expected_output/polymorphic.fluffy.output rename to test/polymorphic.fluffy.ref diff --git a/test/expected_output/polystruct.fluffy.output b/test/polystruct.fluffy.ref similarity index 100% rename from test/expected_output/polystruct.fluffy.output rename to test/polystruct.fluffy.ref diff --git a/test/quicktest.sh b/test/quicktest.sh deleted file mode 100755 index b540339..0000000 --- a/test/quicktest.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash - -TEMPOUT="/tmp/fluffytest.txt" -for i in *.fluffy; do - echo -n "$i..." - ../fluffy $i - ./a.out >& "$TEMPOUT" || echo "(return status != 0)" - if ! diff "$TEMPOUT" "expected_output/$i.output" > /dev/null; then - echo "FAIL" - else - echo "" - fi -done - -for i in shouldfail/*.fluffy; do - echo -n "$i..." - ../fluffy $i >& /dev/null && echo -n "COMPILED (this is bad)" - echo "" -done -rm -f a.out diff --git a/test/reportplugin.py b/test/reportplugin.py new file mode 100644 index 0000000..83dfb9e --- /dev/null +++ b/test/reportplugin.py @@ -0,0 +1,58 @@ +# New testclass +class TestFluffy(Test): + def __init__(self, filename, environment): + Test.__init__(self, filename, environment) + def _init_flags(self): + Test._init_flags(self) + environment = self.environment + environment.cflags = "-O3" + environment.ldflags = "" + def compile(self): + environment = self.environment + cmd = "%(compiler)s %(cflags)s %(filename)s %(ldflags)s -o %(executable)s" % environment.__dict__ + self.compile_command = cmd + self.compiling = "" + try: + self.compile_out, self.compile_err, self.compile_retcode = my_execute(cmd, timeout=60) + except SigKill, e: + self.error_msg = "compiler: %s" % e.name + return False + c = self.parse_compiler_output() + if not c: return c + return True + def check_compiler_errors(self): + if self.compile_retcode != 0: + self.error_msg = "compilation not ok (returncode %d)" % self.compile_retcode + self.long_error_msg = "\n".join((self.compile_command, self.compiling)) + return False + return True + +class FluffyShouldFail(TestFluffy): + def __init__(self, filename, environment): + TestFluffy.__init__(self, filename, environment) + + def check_compiler_errors(self): + if len(self.errors) == 0: + self.error_msg = "compiler missed error" + return False + return True + def check_execution(self): + return True # nothing to execute + +test_factories += [ + ( lambda name: name.endswith(".fluffy") and "should_fail" in name, FluffyShouldFail ), + ( lambda name: name.endswith(".fluffy"), TestFluffy ), +] +_EXTENSIONS.append("fluffy") + +# Configurations +def setup_fluffy(option, opt_str, value, parser): + global _ARCH_DIRS + _ARCH_DIRS = [] + global _DEFAULT_DIRS + _DEFAULT_DIRS = [ "fluffy", "fluffy/should_fail" ] + config = parser.values + config.compiler = "fluffy" + config.expect_url = "fluffy/fail_expectations" + +configurations["fluffy"] = setup_fluffy diff --git a/test/shouldfail/cast1.fluffy b/test/should_fail/cast1.fluffy similarity index 100% rename from test/shouldfail/cast1.fluffy rename to test/should_fail/cast1.fluffy diff --git a/test/shouldfail/cast2.fluffy b/test/should_fail/cast2.fluffy similarity index 100% rename from test/shouldfail/cast2.fluffy rename to test/should_fail/cast2.fluffy diff --git a/test/shouldfail/cast3.fluffy b/test/should_fail/cast3.fluffy similarity index 100% rename from test/shouldfail/cast3.fluffy rename to test/should_fail/cast3.fluffy diff --git a/test/shouldfail/cast4.fluffy b/test/should_fail/cast4.fluffy similarity index 100% rename from test/shouldfail/cast4.fluffy rename to test/should_fail/cast4.fluffy diff --git a/test/shouldfail/error2.fluffy b/test/should_fail/error2.fluffy similarity index 100% rename from test/shouldfail/error2.fluffy rename to test/should_fail/error2.fluffy diff --git a/test/shouldfail/syntax1.fluffy b/test/should_fail/syntax1.fluffy similarity index 100% rename from test/shouldfail/syntax1.fluffy rename to test/should_fail/syntax1.fluffy diff --git a/test/shouldfail/syntax2.fluffy b/test/should_fail/syntax2.fluffy similarity index 100% rename from test/shouldfail/syntax2.fluffy rename to test/should_fail/syntax2.fluffy diff --git a/test/expected_output/simple.fluffy.output b/test/simple.fluffy.ref similarity index 100% rename from test/expected_output/simple.fluffy.output rename to test/simple.fluffy.ref diff --git a/test/expected_output/struct.fluffy.output b/test/struct.fluffy.ref similarity index 100% rename from test/expected_output/struct.fluffy.output rename to test/struct.fluffy.ref diff --git a/test/expected_output/typealias.fluffy.output b/test/typealias.fluffy.ref similarity index 100% rename from test/expected_output/typealias.fluffy.output rename to test/typealias.fluffy.ref diff --git a/test/expected_output/typeclass.fluffy.output b/test/typeclass.fluffy.ref similarity index 100% rename from test/expected_output/typeclass.fluffy.output rename to test/typeclass.fluffy.ref diff --git a/test/expected_output/typeclass2.fluffy.output b/test/typeclass2.fluffy.ref similarity index 100% rename from test/expected_output/typeclass2.fluffy.output rename to test/typeclass2.fluffy.ref diff --git a/test/expected_output/typeof.fluffy.output b/test/typeof.fluffy.ref similarity index 100% rename from test/expected_output/typeof.fluffy.output rename to test/typeof.fluffy.ref
MatzeB/fluffy
7b3f9281670854cb93255b6b5ff0b8e5c2ef66c2
adapt to latest libfirm
diff --git a/Makefile b/Makefile index 3be9022..512ee56 100644 --- a/Makefile +++ b/Makefile @@ -1,72 +1,71 @@ -include config.mak GOAL = fluffy FIRM_CFLAGS ?= `pkg-config --cflags libfirm` FIRM_LIBS ?= `pkg-config --libs libfirm` CPPFLAGS = -I. CPPFLAGS += $(FIRM_CFLAGS) -DFIRM_BACKEND CFLAGS += -Wall -W -Wstrict-prototypes -Wmissing-prototypes -Werror -std=c99 CFLAGS += -O0 -g3 -m32 LFLAGS += $(FIRM_LIBS) -ldl SOURCES := \ adt/strset.c \ adt/obstack.c \ adt/obstack_printf.c \ ast.c \ type.c \ parser.c \ ast2firm.c \ lexer.c \ main.c \ mangle.c \ match_type.c \ plugins.c \ semantic.c \ symbol_table.c \ token.c \ type_hash.c \ - driver/firm_cmdline.c \ driver/firm_opt.c \ driver/firm_machine.c \ driver/firm_timing.c OBJECTS = $(SOURCES:%.c=build/%.o) Q = @ .PHONY : all clean dirs all: $(GOAL) ifeq ($(findstring $(MAKECMDGOALS), clean depend),) -include .depend endif .depend: $(SOURCES) @echo "===> DEPEND" @rm -f $@ && touch $@ && makedepend -p "$@ build/" -Y -f $@ -- $(CPPFLAGS) -- $(SOURCES) 2> /dev/null && rm [email protected] $(GOAL): $(OBJECTS) | build/driver build/adt @echo "===> LD $@" $(Q)$(CC) -m32 -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) build/adt: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/driver: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/%.o: %.c | build/adt build/driver @echo '===> CC $<' $(Q)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ clean: @echo '===> CLEAN' $(Q)rm -rf build $(GOAL) .depend diff --git a/adt/util.h b/adt/util.h index 61c3c7d..54dfc83 100644 --- a/adt/util.h +++ b/adt/util.h @@ -1,55 +1,57 @@ /* * This file is part of cparser. * Copyright (C) 2007-2009 Matthias Braun <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ /** * @file * @date 16.03.2007 * @brief Various utility functions that wrap compiler specific extensions * @author Matthias Braun * @version $Id$ */ #ifndef _FIRM_UTIL_H_ #define _FIRM_UTIL_H_ /** * Asserts that the constant expression x is not zero at compiletime. name has * to be a unique identifier. * * @note This uses the fact, that double case labels are not allowed. */ #define COMPILETIME_ASSERT(x, name) \ static __attribute__((unused)) void compiletime_assert_##name (int h) { \ switch(h) { case 0: case (x): {} } \ } /** * Indicates to the compiler that the value of x is very likely 1 * @note Only use this in speed critical code and when you are sure x is often 1 */ #define LIKELY(x) __builtin_expect((x), 1) /** * Indicates to the compiler that it's very likely that x is 0 * @note Only use this in speed critical code and when you are sure x is often 0 */ #define UNLIKELY(x) __builtin_expect((x), 0) #define lengthof(x) (sizeof(x) / sizeof(*(x))) +#define endof(x) ((x) + lengthof(x)) + #endif diff --git a/ast2firm.c b/ast2firm.c index 249bbfd..2dfec27 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -468,1392 +468,1402 @@ static ir_type *get_type_for_type_variable(type2firm_env_t *env, abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->base.firm_type != NULL) { assert(type->base.firm_type != INVALID_TYPE); return type->base.firm_type; } ir_type *firm_type = NULL; switch (type->kind) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, &type->atomic); break; case TYPE_FUNCTION: firm_type = get_function_type(env, &type->function); break; case TYPE_POINTER: firm_type = get_pointer_type(env, &type->pointer); break; case TYPE_ARRAY: firm_type = get_array_type(env, &type->array); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_ANY */ firm_type = new_type_primitive(mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, &type->compound); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, &type->compound); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, &type->reference); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, &type->bind_typevariables); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->base.firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static ir_mode *get_arithmetic_mode(type_t *type) { if (type->kind == TYPE_ATOMIC && type->atomic.akind == ATOMIC_TYPE_BOOL) { return mode_b; } /* TODO: does not work for typealiases, typevariables, etc. */ return get_ir_mode(type); } static instantiate_function_t *queue_function_instantiation( function_t *function, ir_entity *entity) { instantiate_function_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->function = function; instantiate->entity = entity; pdeq_putr(instantiate_functions, instantiate); return instantiate; } static int is_polymorphic_function(const function_t *function) { return function->type_parameters != NULL; } static ir_entity* get_concept_function_instance_entity( concept_function_instance_t *function_instance) { function_t *function = & function_instance->function; if (function->e.entity != NULL) return function->e.entity; function_type_t *function_type = function->type; concept_function_t *concept_function = function_instance->concept_function; concept_t *concept = concept_function->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_function->base.symbol); concept_instance_t *instance = function_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, ir_visibility_local); function->e.entity = entity; return entity; } static ir_entity* get_function_entity(function_t *function, symbol_t *symbol) { function_type_t *function_type = function->type; int is_polymorphic = is_polymorphic_function(function); if (!is_polymorphic && function->e.entity != NULL) { return function->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = function->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && function->e.entities != NULL) { int len = ARR_LEN(function->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = function->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (function->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } if (!is_polymorphic) { function->e.entity = entity; } else { if (function->e.entities == NULL) function->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, function->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *create_symconst(dbg_info *dbgi, ir_entity *entity) { assert(entity != NULL); union symconst_symbol sym; sym.entity_p = entity; return new_d_SymConst(dbgi, mode_P, sym, symconst_addr_ent); } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(1, byte_ir_type); ir_entity *entity = new_entity(global_type, unique_ident("str"), type); add_entity_linkage(entity, IR_LINKAGE_CONSTANT); set_entity_allocation(entity, allocation_static); set_entity_visibility(entity, ir_visibility_private); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; const size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); ir_tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } ir_initializer_t *initializer = create_initializer_compound(slen); for (size_t i = 0; i < slen; ++i) { ir_tarval *tv = new_tarval_from_long(string[i], mode); ir_initializer_t *val = create_initializer_tarval(tv); set_initializer_compound_value(initializer, i, val); } set_entity_initializer(entity, initializer); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return create_symconst(dbgi, entity); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); ir_tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); ir_tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P); return add; } static ir_entity *create_variable_entity(variable_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); if (variable->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = create_symconst(dbgi, entity); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; return get_value(variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { entity_t *entity = reference->entity; switch (entity->kind) { case ENTITY_VARIABLE: return variable_addr(&entity->variable); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_FUNCTION: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; entity_t *entity = ref->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = &entity->variable; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); - ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M); + ir_node *mem = new_Proj(result, mode_M, pn_CopyB_M); set_store(mem); } else { if (get_irn_mode(value) == mode_b) { value = new_Conv(value, get_atomic_mode(ATOMIC_TYPE_BOOL)); } result = new_d_Store(dbgi, store, addr, value, cons_none); - ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); + ir_node *mem = new_Proj(result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static ir_relation binexpr_kind_to_relation(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return ir_relation_equal; case EXPR_BINARY_NOTEQUAL: return ir_relation_less_greater; case EXPR_BINARY_LESS: return ir_relation_less; case EXPR_BINARY_LESSEQUAL: return ir_relation_less_equal; case EXPR_BINARY_GREATER: return ir_relation_greater; case EXPR_BINARY_GREATEREQUAL: return ir_relation_greater_equal; default: break; } panic("unknown relation"); } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); - ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); - ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); + ir_node *true_proj = new_Proj(cond, mode_X, pn_Cond_true); + ir_node *false_proj = new_Proj(cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); - ir_node *store = get_store(); + ir_node *store = new_Pin(new_NoMem()); ir_node *node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); - ir_node *new_store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); - ir_node *res = new_d_Proj(dbgi, node, mode, pn_Div_res); - set_store(new_store); - return res; + return new_Proj(node, mode, pn_Div_res); } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); - ir_node *store = get_store(); + ir_node *store = new_Pin(new_NoMem()); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); - - store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); - set_store(store); - return new_d_Proj(dbgi, node, mode, pn_Mod_res); + return new_Proj(node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ ir_relation relation = binexpr_kind_to_relation(kind); ir_node *cmp = new_d_Cmp(dbgi, left, right, relation); return cmp; } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); - ir_mode *mode = get_ir_mode(to_type); - dbg_info *dbgi = get_dbg_info(&cast->base.source_position); - assert(node != NULL); - return new_d_Conv(dbgi, node, mode); + if (to_type == type_void) { + return NULL; + } else { + ir_mode *mode = get_ir_mode(to_type); + dbg_info *dbgi = get_dbg_info(&cast->base.source_position); + return new_d_Conv(dbgi, node, mode); + } } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); - ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); - ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); + ir_node *mem = new_Proj(load, mode_M, pn_Load_M); + ir_node *val = new_Proj(load, mode, pn_Load_res); set_store(mem); ir_mode *result_mode = get_arithmetic_mode(type); if (result_mode != mode) val = new_Conv(val, result_mode); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->kind == TYPE_COMPOUND_STRUCT || entry_type->kind == TYPE_COMPOUND_UNION || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(function_entity_t *function_entity, type_argument_t *type_arguments) { assert(function_entity->base.kind == ENTITY_FUNCTION); function_t *function = &function_entity->function; symbol_t *symbol = function_entity->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(function->type_parameters, type_arguments); ir_entity *entity = get_function_entity(function, symbol); const char *name = get_entity_name(entity); if (function_entity->base.exported && get_entity_visibility(entity) != ir_visibility_external) { set_entity_visibility(entity, ir_visibility_default); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_functions, name) != NULL) { return entity; } instantiate_function_t *instantiate = queue_function_instantiation(function, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_functions, name); return entity; } static ir_node *function_reference_to_firm(function_entity_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(function, type_arguments); ir_node *symconst = create_symconst(dbgi, entity); return symconst; } static ir_node *concept_function_reference_to_firm(concept_function_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = function->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at function '%s' from '%s'\n", function->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_function_instance_t *function_instance = get_function_from_concept_instance(instance, function); if (function_instance == NULL) { fprintf(stderr, "panic: no function '%s' in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_function_instance_entity(function_instance); ir_node *symconst = create_symconst(dbgi, entity); pop_type_variable_bindings(old_top); return symconst; } static ir_node *function_parameter_reference_to_firm(function_parameter_t *parameter) { - return get_value(parameter->value_number, NULL); + ir_mode *mode = get_ir_mode(parameter->type); + return get_value(parameter->value_number, mode); } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); ir_tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } +static ir_node *create_conv(dbg_info *dbgi, ir_node *op, ir_mode *dest_mode) +{ + ir_mode *src_mode = get_irn_mode(op); + if (src_mode == dest_mode) + return op; + if (dest_mode == mode_b) { + ir_tarval *tv_zero = get_mode_null(src_mode); + ir_node *zero = new_Const(tv_zero); + return new_d_Cmp(dbgi, op, zero, ir_relation_less_greater); + } + return new_d_Conv(dbgi, op, dest_mode); +} + static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *function = call->function; ir_node *callee = expression_to_firm(function); assert(function->base.type->kind == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) function->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->kind == TYPE_FUNCTION); function_type_t *function_type = (function_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (function_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (size_t i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_type *irtype = get_ir_type(expression->base.type); ir_node *arg_node = expression_to_firm(expression); ir_mode *mode = get_type_mode(irtype); if (mode != NULL && get_irn_mode(arg_node) != mode) { arg_node = new_Conv(arg_node, mode); } in[n] = arg_node; if (new_method_type != NULL) { set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); - ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M); + ir_node *mem = new_Proj(node, mode_M, pn_Call_M); set_store(mem); type_t *result_type = function_type->result_type; ir_node *result = NULL; if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); - ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); - result = new_d_Proj(dbgi, resproj, mode, 0); + ir_node *resproj = new_Proj(node, mode_T, pn_Call_T_result); + result = new_Proj(resproj, mode, 0); ir_mode *result_mode = get_arithmetic_mode(result_type); - if (result_mode != mode) { - result = new_Conv(result, result_mode); - } + result = create_conv(dbgi, result, result_mode); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { function_t *function = &expression->function; ir_entity *entity = function->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_function_entity(function, symbol); } queue_function_instantiation(function, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { entity_t *entity = reference->entity; type_argument_t *type_arguments = reference->type_arguments; const source_position_t *source_position = &reference->base.source_position; switch (entity->kind) { case ENTITY_FUNCTION: return function_reference_to_firm(&entity->function, type_arguments, source_position); case ENTITY_CONCEPT_FUNCTION: return concept_function_reference_to_firm( &entity->concept_function, type_arguments, source_position); case ENTITY_FUNCTION_PARAMETER: return function_parameter_reference_to_firm(&entity->parameter); case ENTITY_CONSTANT: return constant_reference_to_firm(&entity->constant); case ENTITY_VARIABLE: return variable_to_firm(&entity->variable, source_position); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_LABEL: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); expression_t *value = statement->value; ir_node *ret; if (value != NULL) { ir_node *retval = expression_to_firm(value); ir_mode *mode = get_ir_mode(value->base.type); if (get_irn_mode(retval) != mode) { retval = new_d_Conv(dbgi, retval, mode); } ir_node *in[1] = { retval }; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); - ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); - ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); + ir_node *true_proj = new_Proj(cond, mode_X, pn_Cond_true); + ir_node *false_proj = new_Proj(cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_t *label = &label_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_function(function_t *function, ir_entity *entity, type_argument_t *type_arguments) { if (function->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_function(function)) { assert(type_arguments != NULL); push_type_variable_bindings(function->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, function->n_local_vars); + set_current_ir_graph(irg); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(function->n_local_vars * sizeof(value_numbers[0])); /* create initial values for variables */ ir_node *args = get_irg_args(irg); int parameter_num = 0; for (function_parameter_t *parameter = function->parameters; parameter != NULL; parameter = parameter->next, ++parameter_num) { ir_mode *mode = get_ir_mode(parameter->type); ir_node *proj = new_r_Proj(args, mode, parameter_num); set_r_value(irg, parameter->value_number, proj); } context2firm(&function->context); current_ir_graph = irg; ir_node *firstblock = get_cur_block(); - if (function->statement) + if (function->statement != NULL) statement_to_firm(function->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_verify(irg, VERIFY_ENFORCE_SSA); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_function_instance_t *function_instance = instance->function_instances; for ( ; function_instance != NULL; function_instance = function_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ function_t *function = &function_instance->function; /* make sure the function entity is set */ ir_entity *entity = get_concept_function_instance_entity(function_instance); /* we can emit it like a normal function */ queue_function_instantiation(function, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: if (!is_polymorphic_function(&entity->function.function)) { assure_instance(&entity->function, NULL); } break; case ENTITY_VARIABLE: create_variable_entity(&entity->variable); break; case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: break; case ENTITY_INVALID: case ENTITY_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_functions); instantiate_functions = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_functions)) { instantiate_function_t *instantiate_function = pdeq_getl(instantiate_functions); assert(typevar_binding_stack_top() == 0); create_function(instantiate_function->function, instantiate_function->entity, instantiate_function->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_functions); obstack_free(&obst, NULL); strset_destroy(&instantiated_functions); } diff --git a/main.c b/main.c index a82040b..d219237 100644 --- a/main.c +++ b/main.c @@ -1,312 +1,418 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> +#include <unistd.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" -#include "driver/firm_cmdline.h" #include "driver/firm_machine.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" #include "mangle.h" #include "adt/error.h" #include "adt/strutil.h" #define LINKER "gcc -m32" -#define TMPDIR "/tmp/" + +typedef struct file_list_entry_t file_list_entry_t; +struct file_list_entry_t { + const char *name; /**< filename or NULL for stdin */ + file_list_entry_t *next; +}; + +static file_list_entry_t *temp_files; static machine_triple_t *target_machine; static bool dump_graphs; static bool dump_asts; static bool verbose; static bool had_parse_errors; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; static void initialize_firm(void) { firm_early_init(); } static void get_output_name(char *buf, size_t buflen, const char *inputname, const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; for (const char *c = inputname; *c != 0; ++c) { if (*c == '.') last_dot = i; ++i; } if (last_dot == 0xffffffff) last_dot = i; if (last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if (extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } static void dump_ast(const context_t *context, const char *name, const char *ext) { if (!dump_asts) return; char filename[4096]; get_output_name(filename, sizeof(filename), name, ext); FILE* out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { print_ast(out, context); } fclose(out); } static void do_parse_file(FILE *in, const char *input_name) { bool result = parse_file(in, input_name); if (!result) { fprintf(stderr, "syntax errors found...\n"); had_parse_errors = true; return; } } static void do_check_semantic(void) { bool result = check_semantic(); if (!result) { fprintf(stderr, "Semantic errors found\n"); exit(1); } const module_t *module = modules; for ( ; module != NULL; module = module->next) { dump_ast(&module->context, module->name->string, "-semantic.txt"); } } -static void link(const char *in, const char *out) +static void do_link(const char *in, const char *out) { char buf[4096]; if (out == NULL) { out = "a.out"; } - int res = snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); + int res = snprintf(buf, sizeof(buf), "%s -x assembler %s -o %s", LINKER, in, out); if (res < 0 || res >= (int) sizeof(buf)) { panic("Couldn't construct linker commandline (too long?)"); } if (verbose) { puts(buf); } int err = system(buf); if (err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } static void setup_target(void) { const char *os = target_machine->operating_system; if (strstr(os, "linux") != NULL || strstr(os, "bsd") != NULL || streq(os, "solaris")) { set_add_underscore_prefix(false); } else if (streq(os, "darwin") || strstr(os, "mingw") || strstr(os, "win32")) { set_add_underscore_prefix(true); } else { panic("Unsupported operating system "); } } +static const char *try_dir(const char *dir) +{ + if (dir == NULL) + return dir; + if (access(dir, R_OK | W_OK | X_OK) == 0) + return dir; + return NULL; +} + +static const char *get_tempdir(void) +{ + static const char *tmpdir = NULL; + + if (tmpdir != NULL) + return tmpdir; + + if (tmpdir == NULL) + tmpdir = try_dir(getenv("TMPDIR")); + if (tmpdir == NULL) + tmpdir = try_dir(getenv("TMP")); + if (tmpdir == NULL) + tmpdir = try_dir(getenv("TEMP")); + +#ifdef P_tmpdir + if (tmpdir == NULL) + tmpdir = try_dir(P_tmpdir); +#endif + + if (tmpdir == NULL) + tmpdir = try_dir("/var/tmp"); + if (tmpdir == NULL) + tmpdir = try_dir("/usr/tmp"); + if (tmpdir == NULL) + tmpdir = try_dir("/tmp"); + + if (tmpdir == NULL) + tmpdir = "."; + + return tmpdir; +} + + + +/** + * an own version of tmpnam, which: writes in a buffer, emits no warnings + * during linking (like glibc/gnu ld do for tmpnam)... + */ +static FILE *make_temp_file(char *buffer, size_t buflen, const char *prefix) +{ + const char *tempdir = get_tempdir(); + + snprintf(buffer, buflen, "%s/%sXXXXXX", tempdir, prefix); + + int fd = mkstemp(buffer); + if (fd == -1) { + fprintf(stderr, "could not create temporary file: %s\n", + strerror(errno)); + exit(EXIT_FAILURE); + } + FILE *out = fdopen(fd, "w"); + if (out == NULL) { + fprintf(stderr, "could not create temporary file FILE*\n"); + exit(EXIT_FAILURE); + } + + file_list_entry_t *entry = xmalloc(sizeof(*entry)); + memset(entry, 0, sizeof(*entry)); + + size_t name_len = strlen(buffer) + 1; + char *name = malloc(name_len); + memcpy(name, buffer, name_len); + entry->name = name; + + entry->next = temp_files; + temp_files = entry; + + return out; +} + +static void free_temp_files(void) +{ + file_list_entry_t *entry = temp_files; + file_list_entry_t *next; + for ( ; entry != NULL; entry = next) { + next = entry->next; + + unlink(entry->name); + free((char*) entry->name); + free(entry); + } + temp_files = NULL; +} + int main(int argc, const char **argv) { int opt_level = 2; init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); init_mangle(); /* early options parsing */ for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') continue; const char *option = &arg[1]; if (option[0] == 'O') { sscanf(&option[1], "%d", &opt_level); } } const char *target = getenv("TARGET"); if (target != NULL) target_machine = firm_parse_machine_triple(target); if (target_machine == NULL) target_machine = firm_get_host_machine(); choose_optimization_pack(opt_level); setup_firm_for_machine(target_machine); setup_target(); const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (strcmp(arg, "-o") == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; } else if (strstart(arg, "-O")) { /* already processed in first pass */ } else if (strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if (strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if (strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if (strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; } else if (strcmp(arg, "-S") == 0) { mode = Compile; } else if (strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if (strcmp(arg, "-v") == 0) { verbose = 1; } else if (strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if (bearg[0] == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if (!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if (strcmp(bearg, "help") == 0) { return 1; } } else if (arg[0] == '-') { fprintf(stderr, "Invalid option '%s'\n", arg); return 1; } else { const char *filename = argv[i]; FILE *in; if (strcmp(filename, "-") == 0) { in = stdin; /* nitpicking: is there a way so we can't have a normal file * with the same name? probably not... */ filename = "<stdin>"; } else { in = fopen(filename, "r"); if (in == NULL) { fprintf(stderr, "Couldn't open file '%s' for reading: %s\n", filename, strerror(errno)); exit(1); } } do_parse_file(in, filename); parsed++; if (in != stdin) { fclose(in); } } } if (parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } if (had_parse_errors) { return 1; } gen_firm_init(); do_check_semantic(); ast2firm(modules); const char *asmname; + char temp[1024]; if (mode == Compile) { asmname = outname; } else { - asmname = TMPDIR "fluffy.s"; + FILE *tempf = make_temp_file(temp, sizeof(temp), "ccs"); + fclose(tempf); + asmname = temp; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } gen_firm_finish(asm_out, asmname); fclose(asm_out); if (mode == CompileAndLink) { - link(asmname, outname); + do_link(asmname, outname); } + //free_temp_files(); + (void)free_temp_files; + exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; } diff --git a/mangle.c b/mangle.c index a0d9755..be01154 100644 --- a/mangle.c +++ b/mangle.c @@ -1,234 +1,233 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" #include "type_t.h" #include "adt/error.h" #include <libfirm/firm.h> -#include "driver/firm_cmdline.h" static struct obstack obst; static bool add_underscore_prefix; static void mangle_string(const char *str) { size_t len = strlen(str); obstack_grow(&obst, str, len); } static void mangle_len_string(const char *string) { size_t len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); } static void mangle_atomic_type(const atomic_type_t *type) { char c; switch (type->akind) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(&obst, c); } void set_add_underscore_prefix(bool new_add_underscore_prefix) { add_underscore_prefix = new_add_underscore_prefix; } static void mangle_type_variables(type_variable_t *type_variables) { type_variable_t *type_variable = type_variables; for ( ; type_variable != NULL; type_variable = type_variable->next) { /* is this a good char? */ obstack_1grow(&obst, 'T'); mangle_type(type_variable->current_type); } } static void mangle_compound_type(const compound_type_t *type) { mangle_len_string(type->symbol->string); mangle_type_variables(type->type_parameters); } static void mangle_pointer_type(const pointer_type_t *type) { obstack_1grow(&obst, 'P'); mangle_type(type->points_to); } static void mangle_array_type(const array_type_t *type) { obstack_1grow(&obst, 'A'); mangle_type(type->element_type); int size = fold_constant_to_int(type->size_expression); obstack_printf(&obst, "%lu", size); } static void mangle_function_type(const function_type_t *type) { obstack_1grow(&obst, 'F'); mangle_type(type->result_type); function_parameter_type_t *parameter_type = type->parameter_types; while (parameter_type != NULL) { mangle_type(parameter_type->type); } obstack_1grow(&obst, 'E'); } static void mangle_reference_type_variable(const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if (current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(current_type); } static void mangle_bind_typevariables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); mangle_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void mangle_type(const type_t *type) { switch (type->kind) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(&obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type((const atomic_type_t*) type); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; mangle_type(typeof_type->expression->base.type); return; } case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type((const compound_type_t*) type); return; case TYPE_FUNCTION: mangle_function_type((const function_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: mangle_bind_typevariables((const bind_typevariables_type_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable((const type_reference_t*) type); return; case TYPE_ERROR: panic("trying to mangle error type"); } panic("Unknown type mangled"); } void mangle_symbol_simple(symbol_t *symbol) { mangle_string(symbol->string); } void mangle_symbol(symbol_t *symbol) { mangle_len_string(symbol->string); } void mangle_concept_name(symbol_t *symbol) { obstack_grow(&obst, "tcv", 3); mangle_len_string(symbol->string); } void start_mangle(void) { if (add_underscore_prefix) { obstack_1grow(&obst, '_'); } } ident *finish_mangle(void) { size_t size = obstack_object_size(&obst); char *str = obstack_finish(&obst); ident *id = new_id_from_chars(str, size); obstack_free(&obst, str); return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/plugins/api.fluffy b/plugins/api.fluffy index 4e720b5..706e790 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,484 +1,483 @@ module "fluffy.org/compiler/pluginapi" export SourcePosition, Symbol, Token, Type, Attribute, CompoundEntry, \ CompoundType, TypeConstraint, Entity, Export, Context, \ TypeVariable, Constant, Statement, Expression, IntConst, \ BinaryExpression, BlockStatement, ExpressionStatement, \ LabelStatement, GotoStatement, IfStatement, Concept, \ ConceptFunction, ConceptInstance, Lexer, \ STATEMENT_INAVLID, STATEMENT_ERROR, STATEMENT_BLOCK, \ STATEMENT_RETURN, STATEMENT_DECLARATION, STATEMENT_IF, \ STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, \ EXPR_BINARY_ADD, EXPR_BINARY_ASSIGN, \ register_new_token, register_statement, register_expression, \ register_declaration, register_attribute, register_statement_parser, \ register_attribute_parser, register_expression_parser, \ register_expression_infix_parser, register_declaration_parser, \ print_token, lexer_next_token, add_entity, parse_sub_expression, \ parse_expression, parse_statement, check_expression, \ register_statement_lowerer, register_expression_lowerer, \ make_atomic_type, make_pointer_type, symbol_table_insert, \ parse_type, print_error_prefix, print_warning_prefix, \ check_statement, source_position, api_init, expect, \ context_append, block_append, allocate, allocate_zero, AllocateOnAst, \ token, next_token, \ T_IDENTIFIER, T_INDENT, T_NEWLINE, T_EOF, ATOMIC_TYPE_INT, \ T_DEDENT import "fluffy.org/stdlib" stderr, fputs, abort, assert, memset struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct FunctionParameterType: type : Type* next : FunctionParameterType* struct TypeConstraint: concept_symbol : Symbol* conceptt : Concept* next : TypeConstraint* struct FunctionType: base : Type result_type : Type* parameter_types : FunctionParameterType* variable_arguments : bool struct TypeArgument: type : Type* next : TypeArgument* struct Entity: kind : unsigned int symbol : Symbol* source_position : SourcePosition next : Entity* exported : bool refs : int struct Export: symbol : Symbol* next : Export* source_position : SourcePosition struct Import: modulename : Symbol* symbol : Symbol* next : Import* source_position : SourcePosition struct Context: entities : Entity* concept_instances : ConceptInstance* exports : Export* imports : Import* struct TypeVariable: base : Entity constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct FunctionParameter: base : Entity next : FunctionParameter* type : Type* num : int struct Constant: base : Entity type : Type* expression : Expression* struct Function: type : FunctionType* type_parameters : TypeVariable* parameters : FunctionParameter* is_extern : bool context : Context statement : Statement* /* Missing here: union { ir_entity*entity, ir_entity ** entities; } */ dummy : void* n_local_vars : unsigned int struct FunctionEntity: base : Entity function : Function struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: kind : unsigned int type : Type* source_position : SourcePosition lowered : byte struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression - type : int left : Expression* right : Expression* struct BlockStatement: base : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: base : Statement expression : Expression* struct Label: base : Entity block : IrNode* next : Label* struct LabelStatement: base : Statement label : Label struct GotoStatement: base : Statement label_symbol : Symbol* label : Label* struct IfStatement: base : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct Concept: base : Entity type_parameters : TypeVariable* functions : ConceptFunction* instances : ConceptInstance context : Context struct ConceptFunction: base : Entity type : FunctionType* parameters : FunctionParameter* conceptt : Concept* next : ConceptFunction* struct ConceptFunctionInstance: function : Function symbol : Symbol* source_position : SourcePosition next : ConceptFunctionInstance* concept_function : ConceptFunction* concept_instances : ConceptInstance* struct ConceptInstance: concept_symbol : Symbol* source_position : SourcePosition conceptt : Concept* type_arguments : TypeArgument* function_instances : ConceptFunctionInstance* next : ConceptInstance* next_in_concept : ConceptInstance* context : Context type_parameters : TypeVariable* struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 const STATEMENT_ERROR = 1 const STATEMENT_BLOCK = 2 const STATEMENT_RETURN = 3 const STATEMENT_DECLARATION = 4 const STATEMENT_IF = 5 const STATEMENT_EXPRESSION = 6 const STATEMENT_GOTO = 7 const STATEMENT_LABEL = 8 const TYPE_INVALID = 0 const TYPE_ERROR = 1 const TYPE_VOID = 2 const TYPE_ATOMIC = 3 const TYPE_COMPOUND_STRUCT = 4 const TYPE_COMPOUND_UNION = 5 const TYPE_FUNCTION = 6 const TYPE_POINTER = 7 const TYPE_ARRAY = 8 const TYPE_TYPEOF = 9 const TYPE_REFERENCE = 10 const TYPE_REFERENCE_TYPE_VARIABLE = 11 const TYPE_BIND_TYPEVARIABLES = 12 const ENTITY_INVALID = 0 const ENTITY_ERROR = 1 const ENTITY_FUNCTION = 2 const ENTITY_FUNCTION_PARAMETER = 3 const ENTITY_TYPE_VARIABLE = 4 const ENTITY_CONCEPT_FUNCTION = 5 const ENTITY_CONCEPT = 6 const ENTITY_VARIABLE = 7 const ENTITY_CONSTANT = 8 const ENTITY_TYPEALIAS = 9 const ENTITY_LABEL = 10 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const ATOMIC_TYPE_LONGLONG = 10 const ATOMIC_TYPE_ULONGLONG = 11 const ATOMIC_TYPE_FLOAT = 12 const ATOMIC_TYPE_DOUBLE = 13 const EXPR_INVALID = 0 const EXPR_ERROR = 1 const EXPR_INT_CONST = 2 const EXPR_FLOAT_CONST = 3 const EXPR_BOOL_CONST = 4 const EXPR_STRING_CONST = 5 const EXPR_NULL_POINTER = 6 const EXPR_REFERENCE = 7 const EXPR_CALL = 8 const EXPR_SELECT = 9 const EXPR_ARRAY_ACCESS = 10 const EXPR_SIZEOF = 11 const EXPR_FUNC = 12 const EXPR_UNARY_NEGATE = 13 const EXPR_UNARY_NOT = 14 const EXPR_UNARY_BITWISE_NOT = 15 const EXPR_UNARY_DEREFERENCE = 16 const EXPR_UNARY_TAKE_ADDRESS = 17 const EXPR_UNARY_CAST = 18 const EXPR_UNARY_INCREMENT = 19 const EXPR_UNARY_DECREMENT = 20 const EXPR_BINARY_ASSIGN = 21 const EXPR_BINARY_ADD = 22 const EXPR_BINARY_SUB = 23 const EXPR_BINARY_MUL = 24 const EXPR_BINARY_DIV = 25 const EXPR_BINARY_MOD = 26 const EXPR_BINARY_EQUAL = 27 const EXPR_BINARY_NOTEQUAL = 28 const EXPR_BINARY_LESS = 29 const EXPR_BINARY_LESSEQUAL = 30 const EXPR_BINARY_GREATER = 31 const EXPR_BINARY_GREATEREQUAL = 32 const EXPR_BINARY_LAZY_AND = 33 const EXPR_BINARY_LAZY_OR = 34 const EXPR_BINARY_AND = 35 const EXPR_BINARY_OR = 36 const EXPR_BINARY_XOR = 37 const EXPR_BINARY_SHIFTLEFT = 38 const EXPR_BINARY_SHIFTRIGHT = 39 const T_EOF = 4 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* typealias ParseExpressionFunction = func () : Expression* typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_entity(entity : Entity*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_prefix(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.base.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.base.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.base.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.base.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.base.type = STATEMENT_LABEL res.label.base.kind = ENTITY_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.base.kind = ENTITY_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() res.expression.kind = EXPR_INT_CONST return res func api_init(): func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func context_append(context : Context*, entity : Entity*): entity.next = context.entities context.entities = entity func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label diff --git a/plugins/plugin_enum.fluffy b/plugins/plugin_enum.fluffy index 5242f60..e9c1939 100644 --- a/plugins/plugin_enum.fluffy +++ b/plugins/plugin_enum.fluffy @@ -1,64 +1,64 @@ import "fluffy.org/stdlib" assert import "fluffy.org/compiler/pluginapi" token, next_token, Type, \ - register_new_token, make_atomic_type, expect, Constant, allocate, \ - BinaryExpression, Expression, IntConst, parse_expression, add_declaration, \ + register_new_token, make_atomic_type, expect, Entity, Constant, allocate, \ + BinaryExpression, Expression, IntConst, parse_expression, add_entity, \ register_declaration_parser, ATOMIC_TYPE_INT, T_IDENTIFIER, T_INDENT, \ - T_DEDENT, BINEXPR_ADD, T_NEWLINE, T_EOF, \ - source_position, Declaration + T_DEDENT, EXPR_BINARY_ADD, T_NEWLINE, T_EOF, \ + source_position var token_enum : int var type_int : Type* func parse_enum(): assert(token.type == token_enum) next_token() expect(T_IDENTIFIER) expect(':') expect(T_NEWLINE) if token.type /= T_INDENT: return next_token() var idx = 0 var last_expression = cast<Expression* > null while token.type /= T_DEDENT && token.type /= T_EOF: assert(token.type == T_IDENTIFIER) - var constant = allocate<$Constant>() - constant.declaration.symbol = token.v.symbol - constant.declaration.source_position = source_position - constant.type = type_int + var constant = allocate<$Constant>() + constant.base.symbol = token.v.symbol + constant.base.source_position = source_position + constant.type = type_int next_token() if token.type == '=': next_token() var expression = parse_expression() last_expression = expression idx = 0 constant.expression = expression else: if last_expression /= null: var expression = allocate<$BinaryExpression>() var intconst = allocate<$IntConst>() intconst.value = idx - expression.type = BINEXPR_ADD + expression.expression.kind = EXPR_BINARY_ADD expression.left = last_expression expression.right = cast<Expression* > intconst constant.expression = cast<Expression* > expression else: var expression = allocate<$IntConst>() expression.value = idx constant.expression = cast<Expression* > expression - add_declaration(cast<Declaration* > constant) + add_entity(cast<Entity* > constant) expect(T_NEWLINE) idx = idx + 1 next_token() func init_plugin(): token_enum = register_new_token("enum") type_int = make_atomic_type(ATOMIC_TYPE_INT) register_declaration_parser(parse_enum, token_enum) export init_plugin
MatzeB/fluffy
ff9b4ae888eb78b2e9b3d20411d89262eb5ecbf4
mac Makefile stuff
diff --git a/Makefile b/Makefile index 9c20e8b..3be9022 100644 --- a/Makefile +++ b/Makefile @@ -1,72 +1,72 @@ -include config.mak GOAL = fluffy FIRM_CFLAGS ?= `pkg-config --cflags libfirm` FIRM_LIBS ?= `pkg-config --libs libfirm` CPPFLAGS = -I. CPPFLAGS += $(FIRM_CFLAGS) -DFIRM_BACKEND CFLAGS += -Wall -W -Wstrict-prototypes -Wmissing-prototypes -Werror -std=c99 -CFLAGS += -O0 -g3 +CFLAGS += -O0 -g3 -m32 LFLAGS += $(FIRM_LIBS) -ldl SOURCES := \ adt/strset.c \ adt/obstack.c \ adt/obstack_printf.c \ ast.c \ type.c \ parser.c \ ast2firm.c \ lexer.c \ main.c \ mangle.c \ match_type.c \ plugins.c \ semantic.c \ symbol_table.c \ token.c \ type_hash.c \ driver/firm_cmdline.c \ driver/firm_opt.c \ driver/firm_machine.c \ driver/firm_timing.c OBJECTS = $(SOURCES:%.c=build/%.o) Q = @ .PHONY : all clean dirs all: $(GOAL) ifeq ($(findstring $(MAKECMDGOALS), clean depend),) -include .depend endif .depend: $(SOURCES) @echo "===> DEPEND" @rm -f $@ && touch $@ && makedepend -p "$@ build/" -Y -f $@ -- $(CPPFLAGS) -- $(SOURCES) 2> /dev/null && rm [email protected] $(GOAL): $(OBJECTS) | build/driver build/adt @echo "===> LD $@" - $(Q)$(CC) -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) + $(Q)$(CC) -m32 -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) build/adt: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/driver: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/%.o: %.c | build/adt build/driver @echo '===> CC $<' $(Q)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ clean: @echo '===> CLEAN' $(Q)rm -rf build $(GOAL) .depend
MatzeB/fluffy
e76430e0759d06d5d6ba1385af69da8f039d624e
adapt to latest libfirm
diff --git a/ast2firm.c b/ast2firm.c index c85399a..249bbfd 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1837 +1,1859 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_t **value_numbers = NULL; static label_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_function_t instantiate_function_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; -static type_t *type_bool = NULL; struct instantiate_function_t { function_t *function; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_functions; static pdeq *instantiate_functions = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const variable_t *variable = value_numbers[pos]; print_warning_prefix(variable->base.source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", variable->base.symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { } static void init_ir_types(void) { - type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); - atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.base.kind = TYPE_ATOMIC; byte_type.akind = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(ir_type_void); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } -static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) +static ir_mode *get_atomic_mode(const atomic_type_kind_t atomic_kind) { - switch (atomic_type->akind) { + switch (atomic_kind) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; - case ATOMIC_TYPE_BOOL: return mode_b; + case ATOMIC_TYPE_BOOL: return mode_Bu; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch (type->akind) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_BOOL: return 1; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch (type->kind) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_FUNCTION: /* just a pointer to the function */ return get_mode_size_bytes(mode_P); case TYPE_POINTER: return get_mode_size_bytes(mode_P); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const function_type_t *function_type) { int count = 0; function_parameter_type_t *param_type = function_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; - ir_mode *mode = get_atomic_mode(type); + ir_mode *mode = get_atomic_mode(type->akind); ir_type *irtype = new_type_primitive(mode); return irtype; } static ir_type *get_function_type(type2firm_env_t *env, const function_type_t *function_type) { type_t *result_type = function_type->result_type; int n_parameters = count_parameters(function_type); int n_results = result_type->kind == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(n_parameters, n_results); if (result_type->kind != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } function_parameter_type_t *param_type = function_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (function_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(ir_type_void); type->base.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_node *expression_to_firm(expression_t *expression); static ir_tarval *fold_constant_to_tarval(expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } ir_tarval* tv = get_Const_tarval(cnst); return tv; } long fold_constant_to_int(expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; ir_tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } - ir_type *ir_type = new_type_struct(id); + ir_type *type_ir = new_type_struct(id); - type->base.firm_type = ir_type; + type->base.firm_type = type_ir; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { - ident *ident = new_id_from_str(entry->symbol->string); - ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); + ident *ident = new_id_from_str(entry->symbol->string); + ir_type *entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; - ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); + ir_entity *entity = new_entity(type_ir, ident, entry_ir_type); set_entity_offset(entity, offset); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; - set_type_alignment_bytes(ir_type, align_all); - set_type_size_bytes(ir_type, offset); - set_type_state(ir_type, layout_fixed); + set_type_alignment_bytes(type_ir, align_all); + set_type_size_bytes(type_ir, offset); + set_type_state(type_ir, layout_fixed); - return ir_type; + return type_ir; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } - ir_type *ir_type = new_type_union(id); + ir_type *type_ir = new_type_union(id); - type->base.firm_type = ir_type; + type->base.firm_type = type_ir; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { - ident *ident = new_id_from_str(entry->symbol->string); - ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); + ident *ident = new_id_from_str(entry->symbol->string); + ir_type *entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); - ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); + ir_entity *entity = new_entity(type_ir, ident, entry_ir_type); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } - set_type_alignment_bytes(ir_type, align_all); - set_type_size_bytes(ir_type, size); - set_type_state(ir_type, layout_fixed); + set_type_alignment_bytes(type_ir, align_all); + set_type_size_bytes(type_ir, size); + set_type_state(type_ir, layout_fixed); - return ir_type; + return type_ir; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->base.kind == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->base.firm_type != NULL) { assert(type->base.firm_type != INVALID_TYPE); return type->base.firm_type; } ir_type *firm_type = NULL; switch (type->kind) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, &type->atomic); break; case TYPE_FUNCTION: firm_type = get_function_type(env, &type->function); break; case TYPE_POINTER: firm_type = get_pointer_type(env, &type->pointer); break; case TYPE_ARRAY: firm_type = get_array_type(env, &type->array); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_ANY */ firm_type = new_type_primitive(mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, &type->compound); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, &type->compound); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, &type->reference); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, &type->bind_typevariables); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->base.firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } -static inline -ir_mode *get_ir_mode(type_t *type) +static ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } +static ir_mode *get_arithmetic_mode(type_t *type) +{ + if (type->kind == TYPE_ATOMIC && type->atomic.akind == ATOMIC_TYPE_BOOL) { + return mode_b; + } + /* TODO: does not work for typealiases, typevariables, etc. */ + return get_ir_mode(type); +} + static instantiate_function_t *queue_function_instantiation( function_t *function, ir_entity *entity) { instantiate_function_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->function = function; instantiate->entity = entity; pdeq_putr(instantiate_functions, instantiate); return instantiate; } static int is_polymorphic_function(const function_t *function) { return function->type_parameters != NULL; } static ir_entity* get_concept_function_instance_entity( concept_function_instance_t *function_instance) { function_t *function = & function_instance->function; if (function->e.entity != NULL) return function->e.entity; function_type_t *function_type = function->type; concept_function_t *concept_function = function_instance->concept_function; concept_t *concept = concept_function->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_function->base.symbol); concept_instance_t *instance = function_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, ir_visibility_local); function->e.entity = entity; return entity; } static ir_entity* get_function_entity(function_t *function, symbol_t *symbol) { function_type_t *function_type = function->type; int is_polymorphic = is_polymorphic_function(function); if (!is_polymorphic && function->e.entity != NULL) { return function->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = function->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && function->e.entities != NULL) { int len = ARR_LEN(function->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = function->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (function->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } if (!is_polymorphic) { function->e.entity = entity; } else { if (function->e.entities == NULL) function->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, function->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *create_symconst(dbg_info *dbgi, ir_entity *entity) { assert(entity != NULL); union symconst_symbol sym; sym.entity_p = entity; return new_d_SymConst(dbgi, mode_P, sym, symconst_addr_ent); } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(1, byte_ir_type); ir_entity *entity = new_entity(global_type, unique_ident("str"), type); add_entity_linkage(entity, IR_LINKAGE_CONSTANT); set_entity_allocation(entity, allocation_static); set_entity_visibility(entity, ir_visibility_private); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; const size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); ir_tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } ir_initializer_t *initializer = create_initializer_compound(slen); for (size_t i = 0; i < slen; ++i) { ir_tarval *tv = new_tarval_from_long(string[i], mode); ir_initializer_t *val = create_initializer_tarval(tv); set_initializer_compound_value(initializer, i, val); } set_entity_initializer(entity, initializer); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return create_symconst(dbgi, entity); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); ir_tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); ir_tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P); return add; } static ir_entity *create_variable_entity(variable_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); if (variable->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = create_symconst(dbgi, entity); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; return get_value(variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { entity_t *entity = reference->entity; switch (entity->kind) { case ENTITY_VARIABLE: return variable_addr(&entity->variable); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_FUNCTION: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; entity_t *entity = ref->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = &entity->variable; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M); set_store(mem); } else { + if (get_irn_mode(value) == mode_b) { + value = new_Conv(value, get_atomic_mode(ATOMIC_TYPE_BOOL)); + } result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static ir_relation binexpr_kind_to_relation(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return ir_relation_equal; case EXPR_BINARY_NOTEQUAL: return ir_relation_less_greater; case EXPR_BINARY_LESS: return ir_relation_less; case EXPR_BINARY_LESSEQUAL: return ir_relation_less_equal; case EXPR_BINARY_GREATER: return ir_relation_greater; case EXPR_BINARY_GREATEREQUAL: return ir_relation_greater_equal; default: break; } panic("unknown relation"); } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); - dbg_info *dbgi - = get_dbg_info(&binary_expression->base.source_position); - - ir_node *val1 = expression_to_firm(binary_expression->left); + dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); + ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); - if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); ir_node *new_store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); ir_node *res = new_d_Proj(dbgi, node, mode, pn_Div_res); set_store(new_store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ ir_relation relation = binexpr_kind_to_relation(kind); ir_node *cmp = new_d_Cmp(dbgi, left, right, relation); return cmp; } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); + ir_mode *result_mode = get_arithmetic_mode(type); + if (result_mode != mode) + val = new_Conv(val, result_mode); + return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->kind == TYPE_COMPOUND_STRUCT || entry_type->kind == TYPE_COMPOUND_UNION || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(function_entity_t *function_entity, type_argument_t *type_arguments) { assert(function_entity->base.kind == ENTITY_FUNCTION); function_t *function = &function_entity->function; symbol_t *symbol = function_entity->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(function->type_parameters, type_arguments); ir_entity *entity = get_function_entity(function, symbol); const char *name = get_entity_name(entity); if (function_entity->base.exported && get_entity_visibility(entity) != ir_visibility_external) { set_entity_visibility(entity, ir_visibility_default); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_functions, name) != NULL) { return entity; } instantiate_function_t *instantiate = queue_function_instantiation(function, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_functions, name); return entity; } static ir_node *function_reference_to_firm(function_entity_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(function, type_arguments); ir_node *symconst = create_symconst(dbgi, entity); return symconst; } static ir_node *concept_function_reference_to_firm(concept_function_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = function->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at function '%s' from '%s'\n", function->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_function_instance_t *function_instance = get_function_from_concept_instance(instance, function); if (function_instance == NULL) { fprintf(stderr, "panic: no function '%s' in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_function_instance_entity(function_instance); ir_node *symconst = create_symconst(dbgi, entity); pop_type_variable_bindings(old_top); return symconst; } static ir_node *function_parameter_reference_to_firm(function_parameter_t *parameter) { return get_value(parameter->value_number, NULL); } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); ir_tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *function = call->function; ir_node *callee = expression_to_firm(function); assert(function->base.type->kind == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) function->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->kind == TYPE_FUNCTION); function_type_t *function_type = (function_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (function_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (size_t i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; + ir_type *irtype = get_ir_type(expression->base.type); ir_node *arg_node = expression_to_firm(expression); - + ir_mode *mode = get_type_mode(irtype); + if (mode != NULL && get_irn_mode(arg_node) != mode) { + arg_node = new_Conv(arg_node, mode); + } in[n] = arg_node; if (new_method_type != NULL) { - ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M); set_store(mem); type_t *result_type = function_type->result_type; ir_node *result = NULL; if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); + + ir_mode *result_mode = get_arithmetic_mode(result_type); + if (result_mode != mode) { + result = new_Conv(result, result_mode); + } } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { function_t *function = &expression->function; ir_entity *entity = function->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_function_entity(function, symbol); } queue_function_instantiation(function, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { entity_t *entity = reference->entity; type_argument_t *type_arguments = reference->type_arguments; const source_position_t *source_position = &reference->base.source_position; switch (entity->kind) { case ENTITY_FUNCTION: return function_reference_to_firm(&entity->function, type_arguments, source_position); case ENTITY_CONCEPT_FUNCTION: return concept_function_reference_to_firm( &entity->concept_function, type_arguments, source_position); case ENTITY_FUNCTION_PARAMETER: return function_parameter_reference_to_firm(&entity->parameter); case ENTITY_CONSTANT: return constant_reference_to_firm(&entity->constant); case ENTITY_VARIABLE: return variable_to_firm(&entity->variable, source_position); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_LABEL: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { - dbg_info *dbgi = get_dbg_info(&statement->base.source_position); - ir_node *ret; - if (statement->value != NULL) { - ir_node *retval = expression_to_firm(statement->value); - ir_node *in[1]; + dbg_info *dbgi = get_dbg_info(&statement->base.source_position); + expression_t *value = statement->value; + ir_node *ret; + if (value != NULL) { + ir_node *retval = expression_to_firm(value); + ir_mode *mode = get_ir_mode(value->base.type); + + if (get_irn_mode(retval) != mode) { + retval = new_d_Conv(dbgi, retval, mode); + } - in[0] = retval; + ir_node *in[1] = { retval }; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_t *label = &label_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_function(function_t *function, ir_entity *entity, type_argument_t *type_arguments) { if (function->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_function(function)) { assert(type_arguments != NULL); push_type_variable_bindings(function->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, function->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(function->n_local_vars * sizeof(value_numbers[0])); /* create initial values for variables */ ir_node *args = get_irg_args(irg); int parameter_num = 0; for (function_parameter_t *parameter = function->parameters; parameter != NULL; parameter = parameter->next, ++parameter_num) { ir_mode *mode = get_ir_mode(parameter->type); ir_node *proj = new_r_Proj(args, mode, parameter_num); - set_value(parameter->value_number, proj); + set_r_value(irg, parameter->value_number, proj); } context2firm(&function->context); current_ir_graph = irg; ir_node *firstblock = get_cur_block(); if (function->statement) statement_to_firm(function->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_verify(irg, VERIFY_ENFORCE_SSA); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_function_instance_t *function_instance = instance->function_instances; for ( ; function_instance != NULL; function_instance = function_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ function_t *function = &function_instance->function; /* make sure the function entity is set */ ir_entity *entity = get_concept_function_instance_entity(function_instance); /* we can emit it like a normal function */ queue_function_instantiation(function, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: if (!is_polymorphic_function(&entity->function.function)) { assure_instance(&entity->function, NULL); } break; case ENTITY_VARIABLE: create_variable_entity(&entity->variable); break; case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: break; case ENTITY_INVALID: case ENTITY_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_functions); instantiate_functions = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_functions)) { instantiate_function_t *instantiate_function = pdeq_getl(instantiate_functions); assert(typevar_binding_stack_top() == 0); create_function(instantiate_function->function, instantiate_function->entity, instantiate_function->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_functions); obstack_free(&obst, NULL); strset_destroy(&instantiated_functions); } diff --git a/ast_t.h b/ast_t.h index 77d5de0..1483636 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,502 +1,502 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; -typedef enum declaration_kind_t { +typedef enum entity_kind_t { ENTITY_INVALID, ENTITY_ERROR, ENTITY_FUNCTION, ENTITY_FUNCTION_PARAMETER, ENTITY_TYPE_VARIABLE, ENTITY_CONCEPT_FUNCTION, ENTITY_CONCEPT, ENTITY_VARIABLE, ENTITY_CONSTANT, ENTITY_TYPEALIAS, ENTITY_LABEL, ENTITY_LAST = ENTITY_LABEL, } entity_kind_t; /** * a named entity is something which can be referenced by its name * (a symbol) */ typedef struct entity_base_t { entity_kind_t kind; symbol_t *symbol; source_position_t source_position; entity_t *next; - bool exported : 1; + bool exported; int refs; /**< temporarily used by semantic phase */ } entity_base_t; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; struct import_t { symbol_t *module; symbol_t *symbol; import_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { entity_t *entities; concept_instance_t *concept_instances; export_t *exports; import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { entity_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct function_parameter_t { entity_base_t base; function_parameter_t *next; type_t *type; int value_number; }; struct function_t { function_type_t *type; type_variable_t *type_parameters; function_parameter_t *parameters; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; unsigned n_local_vars; }; struct function_entity_t { entity_base_t base; function_t function; }; struct variable_t { entity_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; ir_entity *entity; int value_number; }; struct label_t { entity_base_t base; ir_node *block; label_t *next; }; struct constant_t { entity_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { entity_base_t base; type_t *type; }; struct concept_function_t { entity_base_t base; function_type_t *type; function_parameter_t *parameters; concept_t *concept; concept_function_t *next; }; struct concept_t { entity_base_t base; type_variable_t *type_parameters; concept_function_t *functions; concept_instance_t *instances; context_t context; }; union entity_t { entity_kind_t kind; entity_base_t base; type_variable_t type_variable; variable_t variable; function_entity_t function; function_parameter_t parameter; constant_t constant; label_t label; typealias_t typealias; concept_t concept; concept_function_t concept_function; }; struct module_t { symbol_t *name; context_t context; module_t *next; bool processing : 1; bool processed : 1; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; function_t function; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; entity_t *entity; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *function; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; entity_t *entity; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST = STATEMENT_LABEL } statement_kind_t; struct statement_base_t { statement_kind_t kind; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_base_t base; expression_t *value; }; struct block_statement_t { statement_base_t base; statement_t *statements; source_position_t end_position; context_t context; }; struct declaration_statement_t { statement_base_t base; variable_t entity; }; struct if_statement_t { statement_base_t base; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_base_t base; symbol_t *label_symbol; label_t *label; }; struct label_statement_t { statement_base_t base; label_t label; }; struct expression_statement_t { statement_base_t base; expression_t *expression; }; union statement_t { statement_kind_t kind; statement_base_t base; return_statement_t returns; block_statement_t block; declaration_statement_t declaration; goto_statement_t gotos; label_statement_t label; expression_statement_t expression; if_statement_t ifs; }; struct concept_function_instance_t { function_t function; symbol_t *symbol; source_position_t source_position; concept_function_instance_t *next; concept_function_t *concept_function; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_function_instance_t *function_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_entity_kind_name(entity_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_entity(void); expression_t *allocate_expression(expression_kind_t kind); entity_t *allocate_entity(entity_kind_t kind); #endif
MatzeB/fluffy
404bdd77b9814a40b48ff45d4f3ddf111d61ebc3
redo paramter handling
diff --git a/ast2firm.c b/ast2firm.c index 784c916..c85399a 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -807,1026 +807,1031 @@ static ir_node *array_access_expression_addr(const array_access_expression_t* ac ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P); return add; } static ir_entity *create_variable_entity(variable_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); if (variable->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = create_symconst(dbgi, entity); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; return get_value(variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { entity_t *entity = reference->entity; switch (entity->kind) { case ENTITY_VARIABLE: return variable_addr(&entity->variable); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_FUNCTION: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; entity_t *entity = ref->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = &entity->variable; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static ir_relation binexpr_kind_to_relation(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return ir_relation_equal; case EXPR_BINARY_NOTEQUAL: return ir_relation_less_greater; case EXPR_BINARY_LESS: return ir_relation_less; case EXPR_BINARY_LESSEQUAL: return ir_relation_less_equal; case EXPR_BINARY_GREATER: return ir_relation_greater; case EXPR_BINARY_GREATEREQUAL: return ir_relation_greater_equal; default: break; } panic("unknown relation"); } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); ir_node *new_store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); ir_node *res = new_d_Proj(dbgi, node, mode, pn_Div_res); set_store(new_store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ ir_relation relation = binexpr_kind_to_relation(kind); ir_node *cmp = new_d_Cmp(dbgi, left, right, relation); return cmp; } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->kind == TYPE_COMPOUND_STRUCT || entry_type->kind == TYPE_COMPOUND_UNION || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(function_entity_t *function_entity, type_argument_t *type_arguments) { assert(function_entity->base.kind == ENTITY_FUNCTION); function_t *function = &function_entity->function; symbol_t *symbol = function_entity->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(function->type_parameters, type_arguments); ir_entity *entity = get_function_entity(function, symbol); const char *name = get_entity_name(entity); if (function_entity->base.exported && get_entity_visibility(entity) != ir_visibility_external) { set_entity_visibility(entity, ir_visibility_default); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_functions, name) != NULL) { return entity; } instantiate_function_t *instantiate = queue_function_instantiation(function, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_functions, name); return entity; } static ir_node *function_reference_to_firm(function_entity_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(function, type_arguments); ir_node *symconst = create_symconst(dbgi, entity); return symconst; } static ir_node *concept_function_reference_to_firm(concept_function_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = function->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at function '%s' from '%s'\n", function->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_function_instance_t *function_instance = get_function_from_concept_instance(instance, function); if (function_instance == NULL) { fprintf(stderr, "panic: no function '%s' in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_function_instance_entity(function_instance); ir_node *symconst = create_symconst(dbgi, entity); pop_type_variable_bindings(old_top); return symconst; } static ir_node *function_parameter_reference_to_firm(function_parameter_t *parameter) { - ir_node *args = get_irg_args(current_ir_graph); - ir_mode *mode = get_ir_mode(parameter->type); - long pn = parameter->num; - ir_node *proj = new_r_Proj(args, mode, pn); - - return proj; + return get_value(parameter->value_number, NULL); } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); ir_tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *function = call->function; ir_node *callee = expression_to_firm(function); assert(function->base.type->kind == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) function->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->kind == TYPE_FUNCTION); function_type_t *function_type = (function_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (function_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (size_t i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M); set_store(mem); type_t *result_type = function_type->result_type; ir_node *result = NULL; if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { function_t *function = &expression->function; ir_entity *entity = function->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_function_entity(function, symbol); } queue_function_instantiation(function, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { entity_t *entity = reference->entity; type_argument_t *type_arguments = reference->type_arguments; const source_position_t *source_position = &reference->base.source_position; switch (entity->kind) { case ENTITY_FUNCTION: return function_reference_to_firm(&entity->function, type_arguments, source_position); case ENTITY_CONCEPT_FUNCTION: return concept_function_reference_to_firm( &entity->concept_function, type_arguments, source_position); case ENTITY_FUNCTION_PARAMETER: return function_parameter_reference_to_firm(&entity->parameter); case ENTITY_CONSTANT: return constant_reference_to_firm(&entity->constant); case ENTITY_VARIABLE: return variable_to_firm(&entity->variable, source_position); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_LABEL: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *ret; if (statement->value != NULL) { ir_node *retval = expression_to_firm(statement->value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_t *label = &label_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_function(function_t *function, ir_entity *entity, type_argument_t *type_arguments) { if (function->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_function(function)) { assert(type_arguments != NULL); push_type_variable_bindings(function->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, function->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(function->n_local_vars * sizeof(value_numbers[0])); + /* create initial values for variables */ + ir_node *args = get_irg_args(irg); + int parameter_num = 0; + for (function_parameter_t *parameter = function->parameters; + parameter != NULL; parameter = parameter->next, ++parameter_num) { + ir_mode *mode = get_ir_mode(parameter->type); + ir_node *proj = new_r_Proj(args, mode, parameter_num); + set_value(parameter->value_number, proj); + } + context2firm(&function->context); current_ir_graph = irg; ir_node *firstblock = get_cur_block(); if (function->statement) statement_to_firm(function->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_verify(irg, VERIFY_ENFORCE_SSA); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_function_instance_t *function_instance = instance->function_instances; for ( ; function_instance != NULL; function_instance = function_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ function_t *function = &function_instance->function; /* make sure the function entity is set */ ir_entity *entity = get_concept_function_instance_entity(function_instance); /* we can emit it like a normal function */ queue_function_instantiation(function, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: if (!is_polymorphic_function(&entity->function.function)) { assure_instance(&entity->function, NULL); } break; case ENTITY_VARIABLE: create_variable_entity(&entity->variable); break; case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: break; case ENTITY_INVALID: case ENTITY_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_functions); instantiate_functions = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_functions)) { instantiate_function_t *instantiate_function = pdeq_getl(instantiate_functions); assert(typevar_binding_stack_top() == 0); create_function(instantiate_function->function, instantiate_function->entity, instantiate_function->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_functions); obstack_free(&obst, NULL); strset_destroy(&instantiated_functions); } diff --git a/ast_t.h b/ast_t.h index 3c0c1b0..77d5de0 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,502 +1,502 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum declaration_kind_t { ENTITY_INVALID, ENTITY_ERROR, ENTITY_FUNCTION, ENTITY_FUNCTION_PARAMETER, ENTITY_TYPE_VARIABLE, ENTITY_CONCEPT_FUNCTION, ENTITY_CONCEPT, ENTITY_VARIABLE, ENTITY_CONSTANT, ENTITY_TYPEALIAS, ENTITY_LABEL, ENTITY_LAST = ENTITY_LABEL, } entity_kind_t; /** * a named entity is something which can be referenced by its name * (a symbol) */ typedef struct entity_base_t { entity_kind_t kind; symbol_t *symbol; source_position_t source_position; entity_t *next; bool exported : 1; int refs; /**< temporarily used by semantic phase */ } entity_base_t; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; struct import_t { symbol_t *module; symbol_t *symbol; import_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { entity_t *entities; concept_instance_t *concept_instances; export_t *exports; import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { entity_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct function_parameter_t { entity_base_t base; function_parameter_t *next; type_t *type; - int num; + int value_number; }; struct function_t { - function_type_t *type; - type_variable_t *type_parameters; + function_type_t *type; + type_variable_t *type_parameters; function_parameter_t *parameters; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; unsigned n_local_vars; }; struct function_entity_t { entity_base_t base; function_t function; }; struct variable_t { entity_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; ir_entity *entity; int value_number; }; struct label_t { entity_base_t base; ir_node *block; label_t *next; }; struct constant_t { entity_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { entity_base_t base; type_t *type; }; struct concept_function_t { entity_base_t base; function_type_t *type; function_parameter_t *parameters; concept_t *concept; concept_function_t *next; }; struct concept_t { entity_base_t base; type_variable_t *type_parameters; concept_function_t *functions; concept_instance_t *instances; context_t context; }; union entity_t { entity_kind_t kind; entity_base_t base; type_variable_t type_variable; variable_t variable; function_entity_t function; function_parameter_t parameter; constant_t constant; label_t label; typealias_t typealias; concept_t concept; concept_function_t concept_function; }; struct module_t { symbol_t *name; context_t context; module_t *next; bool processing : 1; bool processed : 1; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; function_t function; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; entity_t *entity; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *function; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; entity_t *entity; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST = STATEMENT_LABEL } statement_kind_t; struct statement_base_t { statement_kind_t kind; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_base_t base; expression_t *value; }; struct block_statement_t { statement_base_t base; statement_t *statements; source_position_t end_position; context_t context; }; struct declaration_statement_t { statement_base_t base; variable_t entity; }; struct if_statement_t { statement_base_t base; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_base_t base; symbol_t *label_symbol; label_t *label; }; struct label_statement_t { statement_base_t base; label_t label; }; struct expression_statement_t { statement_base_t base; expression_t *expression; }; union statement_t { statement_kind_t kind; statement_base_t base; return_statement_t returns; block_statement_t block; declaration_statement_t declaration; goto_statement_t gotos; label_statement_t label; expression_statement_t expression; if_statement_t ifs; }; struct concept_function_instance_t { function_t function; symbol_t *symbol; source_position_t source_position; concept_function_instance_t *next; concept_function_t *concept_function; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_function_instance_t *function_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_entity_kind_name(entity_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_entity(void); expression_t *allocate_expression(expression_kind_t kind); entity_t *allocate_entity(entity_kind_t kind); #endif diff --git a/semantic.c b/semantic.c index 4d5ff74..fc33cb1 100644 --- a/semantic.c +++ b/semantic.c @@ -1584,1005 +1584,1002 @@ static void check_not_expression(unary_expression_t *expression) expression->base.type = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static entity_t *find_entity(const context_t *context, symbol_t *symbol) { entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { if (entity->base.symbol == symbol) break; } return entity; } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->base.type; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->kind == TYPE_COMPOUND_STRUCT || datatype->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) datatype; } else { if (datatype->kind != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->kind == TYPE_COMPOUND_STRUCT || points_to->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ entity_t *entity = find_entity(&compound_type->context, symbol); if (entity != NULL) { type_t *type = check_reference(entity, select->base.source_position); select->base.type = type; select->entity = entity; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; if (type == NULL || (type->kind != TYPE_POINTER && type->kind != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->kind == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { function_t *function = & expression->function; resolve_function_types(function); check_function(function, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) function->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { function_t *function = current_function; type_t *function_result_type = function->type->result_type; statement->value = check_expression(statement->value); expression_t *return_value = statement->value; last_statement_was_return = true; if (return_value != NULL) { if (function_result_type == type_void && return_value->base.type != type_void) { error_at(statement->base.source_position, "return with value in void function\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != function_result_type) { return_value = make_cast(return_value, function_result_type, statement->base.source_position, false); statement->value = return_value; } } else { if (function_result_type != type_void) { error_at(statement->base.source_position, "missing return value in non-void function\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->base.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { environment_push(entity, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->base.next; statement = check_statement(statement); assert(statement->base.next == next || statement->base.next == NULL); statement->base.next = next; if (last != NULL) { last->base.next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(declaration_statement_t *statement) { function_t *function = current_function; variable_t *variable = &statement->entity; assert(function != NULL); variable->value_number = function->n_local_vars; function->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ variable->base.refs = 0; if (variable->type != NULL) { variable->type = normalize_type(variable->type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->base.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->base.source_position, "unresolved anonymous goto\n"); return; } entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (entity->kind != ENTITY_LABEL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_entity_kind_name(entity->kind)); return; } label_t *label = &entity->label; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->kind < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->kind]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->kind) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement(&statement->block); break; case STATEMENT_RETURN: check_return_statement(&statement->returns); break; case STATEMENT_GOTO: check_goto_statement(&statement->gotos); break; case STATEMENT_LABEL: check_label_statement(&statement->label); break; case STATEMENT_IF: check_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: check_variable_declaration(&statement->declaration); break; case STATEMENT_EXPRESSION: check_expression_statement(&statement->expression); break; default: panic("Unknown statement found"); break; } return statement; } static void check_function(function_t *function, symbol_t *symbol, const source_position_t source_position) { if (function->is_extern) return; int old_top = environment_top(); push_context(&function->context); function_t *last_function = current_function; current_function = function; /* set function parameter numbers */ function_parameter_t *parameter = function->parameters; - int n = 0; - while (parameter != NULL) { - parameter->num = n; - n++; - parameter = parameter->next; + for ( ; parameter != NULL; parameter = parameter->next) { + parameter->value_number = function->n_local_vars++; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (function->statement != NULL) { function->statement = check_statement(function->statement); } if (!last_statement_was_return) { type_t *result_type = function->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_function = last_function; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (entity->kind != ENTITY_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_entity_kind_name(entity->kind)); return; } constraint->concept = &entity->concept; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_function_types(function_t *function) { int old_top = environment_top(); /* push type variables */ push_context(&function->context); resolve_type_variable_constraints(function->type_parameters); /* normalize parameter types */ function_parameter_t *parameter = function->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } function->type = (function_type_t*) normalize_type((type_t*)function->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_function_instance_t *function_instance = instance->function_instances; while (function_instance != NULL) { function_t *function = &function_instance->function; resolve_function_types(function); check_function(function, function_instance->symbol, function_instance->source_position); function_instance = function_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { entity_t *entity = (entity_t*) type_parameter; environment_push(entity, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize function types */ concept_function_t *concept_function = concept->functions; for (; concept_function!=NULL; concept_function = concept_function->next) { type_t *normalized_type = normalize_type((type_t*) concept_function->type); assert(normalized_type->kind == TYPE_FUNCTION); concept_function->type = (function_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (entity->kind != ENTITY_CONCEPT) { print_error_prefix(entity->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_entity_kind_name(entity->kind)); return; } concept_t *concept = &entity->concept; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { entity_t *entity = (entity_t*) type_parameter; environment_push(entity, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link functions and normalize their types */ size_t n_concept_functions = 0; concept_function_t *function = concept->functions; for ( ; function != NULL; function = function->next) { ++n_concept_functions; } bool have_function[n_concept_functions]; memset(&have_function, 0, sizeof(have_function)); concept_function_instance_t *function_instance = instance->function_instances; for (; function_instance != NULL; function_instance = function_instance->next) { /* find corresponding concept function */ int n = 0; for (function = concept->functions; function != NULL; function = function->next, ++n) { if (function->base.symbol == function_instance->symbol) break; } if (function == NULL) { print_warning_prefix(function_instance->source_position); fprintf(stderr, "concept '%s' does not declare a function '%s'\n", concept->base.symbol->string, function->base.symbol->string); } else { function_instance->concept_function = function; function_instance->concept_instance = instance; if (have_function[n]) { print_error_prefix(function_instance->source_position); fprintf(stderr, "multiple implementations of function '%s' found in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); } have_function[n] = true; } function_t *ifunction = & function_instance->function; if (ifunction->type_parameters != NULL) { print_error_prefix(function_instance->source_position); fprintf(stderr, "instance function '%s' must not have type parameters\n", function_instance->symbol->string); } ifunction->type = (function_type_t*) normalize_type((type_t*) ifunction->type); } size_t n = 0; for (function = concept->functions; function != NULL; function = function->next, ++n) { if (!have_function[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "function '%s'\n", concept->base.symbol->string, function->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; entity_t *entity = symbol->entity; if (entity == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } entity->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_VARIABLE: entity->variable.type = normalize_type(entity->variable.type); break; case ENTITY_FUNCTION: resolve_function_types(&entity->function.function); break; case ENTITY_TYPEALIAS: { type_t *type = normalize_type(entity->typealias.type); if (type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } entity->typealias.type = type; break; } case ENTITY_CONCEPT: resolve_concept_types(&entity->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in functions */ entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: { check_function(&entity->function.function, entity->base.symbol, entity->base.source_position); break; } case ENTITY_CONSTANT: check_constant(&entity->constant); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; entity_t *entity; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); entity = create_error_entity(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); entity = create_error_entity(symbol); } else { check_module(ref_module); entity = find_entity(&ref_module->context, symbol); if (entity == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); entity = create_error_entity(symbol); } else { ref_context = &ref_module->context; } } } if (!entity->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->entity == entity) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(entity, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); }
MatzeB/fluffy
32327c526f483fa59c1e5973ccf9d3a331542b81
reformating/simplification
diff --git a/ast2firm.c b/ast2firm.c index 7eb6172..784c916 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1846 +1,1832 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_t **value_numbers = NULL; static label_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_function_t instantiate_function_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_function_t { function_t *function; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_functions; static pdeq *instantiate_functions = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const variable_t *variable = value_numbers[pos]; print_warning_prefix(variable->base.source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", variable->base.symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { } static void init_ir_types(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.base.kind = TYPE_ATOMIC; byte_type.akind = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(ir_type_void); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { switch (atomic_type->akind) { - case ATOMIC_TYPE_BYTE: - return mode_Bs; - case ATOMIC_TYPE_UBYTE: - return mode_Bu; - case ATOMIC_TYPE_SHORT: - return mode_Hs; - case ATOMIC_TYPE_USHORT: - return mode_Hu; - case ATOMIC_TYPE_INT: - return mode_Is; - case ATOMIC_TYPE_UINT: - return mode_Iu; - case ATOMIC_TYPE_LONG: - return mode_Ls; - case ATOMIC_TYPE_ULONG: - return mode_Lu; - case ATOMIC_TYPE_LONGLONG: - return mode_LLs; - case ATOMIC_TYPE_ULONGLONG: - return mode_LLu; - case ATOMIC_TYPE_FLOAT: - return mode_F; - case ATOMIC_TYPE_DOUBLE: - return mode_D; - case ATOMIC_TYPE_BOOL: - return mode_b; - case ATOMIC_TYPE_INVALID: - break; + case ATOMIC_TYPE_BYTE: return mode_Bs; + case ATOMIC_TYPE_UBYTE: return mode_Bu; + case ATOMIC_TYPE_SHORT: return mode_Hs; + case ATOMIC_TYPE_USHORT: return mode_Hu; + case ATOMIC_TYPE_INT: return mode_Is; + case ATOMIC_TYPE_UINT: return mode_Iu; + case ATOMIC_TYPE_LONG: return mode_Ls; + case ATOMIC_TYPE_ULONG: return mode_Lu; + case ATOMIC_TYPE_LONGLONG: return mode_LLs; + case ATOMIC_TYPE_ULONGLONG: return mode_LLu; + case ATOMIC_TYPE_FLOAT: return mode_F; + case ATOMIC_TYPE_DOUBLE: return mode_D; + case ATOMIC_TYPE_BOOL: return mode_b; + case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch (type->akind) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: + case ATOMIC_TYPE_BOOL: return 1; - case ATOMIC_TYPE_BOOL: + case ATOMIC_TYPE_SHORT: + case ATOMIC_TYPE_USHORT: + return 2; + case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; - case ATOMIC_TYPE_SHORT: - case ATOMIC_TYPE_USHORT: - return 2; - case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch (type->kind) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_FUNCTION: /* just a pointer to the function */ - return get_mode_size_bytes(mode_P_code); + return get_mode_size_bytes(mode_P); case TYPE_POINTER: - return get_mode_size_bytes(mode_P_data); + return get_mode_size_bytes(mode_P); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const function_type_t *function_type) { int count = 0; function_parameter_type_t *param_type = function_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ir_type *irtype = new_type_primitive(mode); return irtype; } static ir_type *get_function_type(type2firm_env_t *env, const function_type_t *function_type) { type_t *result_type = function_type->result_type; int n_parameters = count_parameters(function_type); int n_results = result_type->kind == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(n_parameters, n_results); if (result_type->kind != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } function_parameter_type_t *param_type = function_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (function_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(ir_type_void); type->base.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_node *expression_to_firm(expression_t *expression); static ir_tarval *fold_constant_to_tarval(expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } ir_tarval* tv = get_Const_tarval(cnst); return tv; } long fold_constant_to_int(expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; ir_tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->base.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->base.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->base.kind == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->base.firm_type != NULL) { assert(type->base.firm_type != INVALID_TYPE); return type->base.firm_type; } ir_type *firm_type = NULL; switch (type->kind) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, &type->atomic); break; case TYPE_FUNCTION: firm_type = get_function_type(env, &type->function); break; case TYPE_POINTER: firm_type = get_pointer_type(env, &type->pointer); break; case TYPE_ARRAY: firm_type = get_array_type(env, &type->array); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_ANY */ firm_type = new_type_primitive(mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, &type->compound); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, &type->compound); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, &type->reference); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, &type->bind_typevariables); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->base.firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_function_t *queue_function_instantiation( function_t *function, ir_entity *entity) { instantiate_function_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->function = function; instantiate->entity = entity; pdeq_putr(instantiate_functions, instantiate); return instantiate; } static int is_polymorphic_function(const function_t *function) { return function->type_parameters != NULL; } static ir_entity* get_concept_function_instance_entity( concept_function_instance_t *function_instance) { function_t *function = & function_instance->function; if (function->e.entity != NULL) return function->e.entity; function_type_t *function_type = function->type; concept_function_t *concept_function = function_instance->concept_function; concept_t *concept = concept_function->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_function->base.symbol); concept_instance_t *instance = function_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, ir_visibility_local); function->e.entity = entity; return entity; } static ir_entity* get_function_entity(function_t *function, symbol_t *symbol) { function_type_t *function_type = function->type; int is_polymorphic = is_polymorphic_function(function); if (!is_polymorphic && function->e.entity != NULL) { return function->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = function->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && function->e.entities != NULL) { int len = ARR_LEN(function->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = function->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (function->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } if (!is_polymorphic) { function->e.entity = entity; } else { if (function->e.entities == NULL) function->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, function->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); ir_tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *create_symconst(dbg_info *dbgi, ir_entity *entity) { assert(entity != NULL); union symconst_symbol sym; sym.entity_p = entity; return new_d_SymConst(dbgi, mode_P, sym, symconst_addr_ent); } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(1, byte_ir_type); ir_entity *entity = new_entity(global_type, unique_ident("str"), type); add_entity_linkage(entity, IR_LINKAGE_CONSTANT); set_entity_allocation(entity, allocation_static); set_entity_visibility(entity, ir_visibility_private); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; const size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); ir_tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } ir_initializer_t *initializer = create_initializer_compound(slen); for (size_t i = 0; i < slen; ++i) { ir_tarval *tv = new_tarval_from_long(string[i], mode); ir_initializer_t *val = create_initializer_tarval(tv); set_initializer_compound_value(initializer, i, val); } set_entity_initializer(entity, initializer); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return create_symconst(dbgi, entity); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); ir_tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); ir_tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); - ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); + ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P); return add; } static ir_entity *create_variable_entity(variable_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); if (variable->is_extern) { set_entity_visibility(entity, ir_visibility_external); } else { set_entity_visibility(entity, ir_visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = create_symconst(dbgi, entity); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; return get_value(variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { entity_t *entity = reference->entity; switch (entity->kind) { case ENTITY_VARIABLE: return variable_addr(&entity->variable); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_FUNCTION: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; entity_t *entity = ref->entity; if (entity->kind == ENTITY_VARIABLE) { variable_t *variable = &entity->variable; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static ir_relation binexpr_kind_to_relation(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return ir_relation_equal; case EXPR_BINARY_NOTEQUAL: return ir_relation_less_greater; case EXPR_BINARY_LESS: return ir_relation_less; case EXPR_BINARY_LESSEQUAL: return ir_relation_less_equal; case EXPR_BINARY_GREATER: return ir_relation_greater; case EXPR_BINARY_GREATEREQUAL: return ir_relation_greater_equal; default: break; } panic("unknown relation"); } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); ir_node *new_store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); ir_node *res = new_d_Proj(dbgi, node, mode, pn_Div_res); set_store(new_store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ ir_relation relation = binexpr_kind_to_relation(kind); ir_node *cmp = new_d_Cmp(dbgi, left, right, relation); return cmp; } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->kind == TYPE_COMPOUND_STRUCT || entry_type->kind == TYPE_COMPOUND_UNION || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(function_entity_t *function_entity, type_argument_t *type_arguments) { assert(function_entity->base.kind == ENTITY_FUNCTION); function_t *function = &function_entity->function; symbol_t *symbol = function_entity->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(function->type_parameters, type_arguments); ir_entity *entity = get_function_entity(function, symbol); const char *name = get_entity_name(entity); if (function_entity->base.exported && get_entity_visibility(entity) != ir_visibility_external) { set_entity_visibility(entity, ir_visibility_default); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_functions, name) != NULL) { return entity; } instantiate_function_t *instantiate = queue_function_instantiation(function, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_functions, name); return entity; } static ir_node *function_reference_to_firm(function_entity_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(function, type_arguments); ir_node *symconst = create_symconst(dbgi, entity); return symconst; } static ir_node *concept_function_reference_to_firm(concept_function_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = function->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at function '%s' from '%s'\n", function->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_function_instance_t *function_instance = get_function_from_concept_instance(instance, function); if (function_instance == NULL) { fprintf(stderr, "panic: no function '%s' in instance of concept '%s'\n", function->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_function_instance_entity(function_instance); ir_node *symconst = create_symconst(dbgi, entity); pop_type_variable_bindings(old_top); return symconst; } static ir_node *function_parameter_reference_to_firm(function_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); long pn = parameter->num; ir_node *proj = new_r_Proj(args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); ir_tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *function = call->function; ir_node *callee = expression_to_firm(function); assert(function->base.type->kind == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) function->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->kind == TYPE_FUNCTION); function_type_t *function_type = (function_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (function_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (size_t i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M); set_store(mem); type_t *result_type = function_type->result_type; ir_node *result = NULL; if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { function_t *function = &expression->function; ir_entity *entity = function->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_function_entity(function, symbol); } queue_function_instantiation(function, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { entity_t *entity = reference->entity; type_argument_t *type_arguments = reference->type_arguments; const source_position_t *source_position = &reference->base.source_position; switch (entity->kind) { case ENTITY_FUNCTION: return function_reference_to_firm(&entity->function, type_arguments, source_position); case ENTITY_CONCEPT_FUNCTION: return concept_function_reference_to_firm( &entity->concept_function, type_arguments, source_position); case ENTITY_FUNCTION_PARAMETER: return function_parameter_reference_to_firm(&entity->parameter); case ENTITY_CONSTANT: return constant_reference_to_firm(&entity->constant); case ENTITY_VARIABLE: return variable_to_firm(&entity->variable, source_position); case ENTITY_INVALID: case ENTITY_ERROR: case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_LABEL: case ENTITY_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *ret; if (statement->value != NULL) { ir_node *retval = expression_to_firm(statement->value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_t *label = &label_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_function(function_t *function, ir_entity *entity, type_argument_t *type_arguments) { if (function->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_function(function)) { assert(type_arguments != NULL); push_type_variable_bindings(function->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, function->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(function->n_local_vars * sizeof(value_numbers[0])); context2firm(&function->context); current_ir_graph = irg; ir_node *firstblock = get_cur_block(); if (function->statement) statement_to_firm(function->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_verify(irg, VERIFY_ENFORCE_SSA); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_function_instance_t *function_instance = instance->function_instances; - for ( ; function_instance != NULL; function_instance = function_instance->next) { + for ( ; function_instance != NULL; + function_instance = function_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ - function_t *function = & function_instance->function; + function_t *function = &function_instance->function; /* make sure the function entity is set */ ir_entity *entity = get_concept_function_instance_entity(function_instance); /* we can emit it like a normal function */ queue_function_instantiation(function, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ entity_t *entity = context->entities; for ( ; entity != NULL; entity = entity->base.next) { switch (entity->kind) { case ENTITY_FUNCTION: if (!is_polymorphic_function(&entity->function.function)) { assure_instance(&entity->function, NULL); } break; case ENTITY_VARIABLE: create_variable_entity(&entity->variable); break; case ENTITY_TYPEALIAS: case ENTITY_CONCEPT: case ENTITY_CONSTANT: case ENTITY_LABEL: case ENTITY_FUNCTION_PARAMETER: case ENTITY_CONCEPT_FUNCTION: case ENTITY_TYPE_VARIABLE: break; case ENTITY_INVALID: case ENTITY_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_functions); instantiate_functions = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_functions)) { instantiate_function_t *instantiate_function = pdeq_getl(instantiate_functions); assert(typevar_binding_stack_top() == 0); create_function(instantiate_function->function, instantiate_function->entity, instantiate_function->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_functions); obstack_free(&obst, NULL); strset_destroy(&instantiated_functions); } -
MatzeB/fluffy
e71b3389423150deb40b6d4a5a665e6c5405a0ab
avoid endless loop for compound type parsing errors
diff --git a/parser.c b/parser.c index f730f44..800e32f 100644 --- a/parser.c +++ b/parser.c @@ -34,1024 +34,1026 @@ static context_t *current_context; static int error = 0; token_t token; module_t *modules; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_entity_struct_size(entity_kind_t kind) { static const size_t sizes[] = { [ENTITY_ERROR] = sizeof(entity_base_t), [ENTITY_FUNCTION] = sizeof(function_entity_t), [ENTITY_FUNCTION_PARAMETER] = sizeof(function_parameter_t), [ENTITY_VARIABLE] = sizeof(variable_t), [ENTITY_CONSTANT] = sizeof(constant_t), [ENTITY_TYPE_VARIABLE] = sizeof(type_variable_t), [ENTITY_TYPEALIAS] = sizeof(typealias_t), [ENTITY_CONCEPT] = sizeof(concept_t), [ENTITY_CONCEPT_FUNCTION] = sizeof(concept_function_t), [ENTITY_LABEL] = sizeof(label_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } entity_t *allocate_entity(entity_kind_t kind) { size_t size = get_entity_struct_size(kind); entity_t *entity = allocate_ast_zero(size); entity->kind = kind; return entity; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { [EXPR_ERROR] = sizeof(expression_base_t), [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } static size_t get_statement_struct_size(statement_kind_t kind) { static const size_t sizes[] = { [STATEMENT_ERROR] = sizeof(statement_base_t), [STATEMENT_BLOCK] = sizeof(block_statement_t), [STATEMENT_RETURN] = sizeof(return_statement_t), [STATEMENT_DECLARATION] = sizeof(declaration_statement_t), [STATEMENT_IF] = sizeof(if_statement_t), [STATEMENT_EXPRESSION] = sizeof(expression_statement_t), [STATEMENT_GOTO] = sizeof(goto_statement_t), [STATEMENT_LABEL] = sizeof(label_statement_t), }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; }; static statement_t *allocate_statement(statement_kind_t kind) { size_t size = get_statement_struct_size(kind); statement_t *statement = allocate_ast_zero(size); statement->kind = kind; return statement; } static size_t get_type_struct_size(type_kind_t kind) { static const size_t sizes[] = { [TYPE_ERROR] = sizeof(type_base_t), [TYPE_VOID] = sizeof(type_base_t), [TYPE_ATOMIC] = sizeof(atomic_type_t), [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t), [TYPE_COMPOUND_UNION] = sizeof(compound_type_t), [TYPE_FUNCTION] = sizeof(function_type_t), [TYPE_POINTER] = sizeof(pointer_type_t), [TYPE_ARRAY] = sizeof(array_type_t), [TYPE_TYPEOF] = sizeof(typeof_type_t), [TYPE_REFERENCE] = sizeof(type_reference_t), [TYPE_REFERENCE_TYPE_VARIABLE] = sizeof(type_reference_t), [TYPE_BIND_TYPEVARIABLES] = sizeof(bind_typevariables_type_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } type_t *allocate_type(type_kind_t kind) { size_t size = get_type_struct_size(kind); type_t *type = obstack_alloc(type_obst, size); memset(type, 0, size); type->kind = kind; return type; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(token_type_t token_type) { assert(token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(token_type_t token_type) { assert(token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(token_type_t type) { token_type_t end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_function(function_t *function); static statement_t *parse_block(void); static void parse_parameter_declarations(function_type_t *function_type, function_parameter_t **parameters); static atomic_type_kind_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_kind_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_kind_t akind; switch (token.type) { case T_unsigned: next_token(); akind = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: akind = parse_signed_atomic_type(); break; } type_t *type = allocate_type(TYPE_ATOMIC); type->atomic.akind = akind; type_t *result = typehash_insert(type); if (result != type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { type_t *type = allocate_type(TYPE_TYPEOF); eat(T_typeof); expect('(', end_error); add_anchor_token(')'); type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_t *type = allocate_type(TYPE_REFERENCE); type->reference.symbol = token.v.symbol; type->reference.source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return type; } static type_t *create_error_type(void) { return allocate_type(TYPE_ERROR); } static type_t *parse_function_type(void) { eat(T_func); type_t *type = allocate_type(TYPE_FUNCTION); parse_parameter_declarations(&type->function, NULL); expect(':', end_error); type->function.result_type = parse_type(); return type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); + eat_until_matching_token(T_NEWLINE); + next_token(); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); type_t *type = allocate_type(TYPE_COMPOUND_UNION); type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return type; } static type_t *parse_struct_type(void) { eat(T_struct); type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return type; } static type_t *make_pointer_type_no_hash(type_t *points_to) { type_t *type = allocate_type(TYPE_POINTER); type->pointer.points_to = points_to; return type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_function_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); expression_t *size = parse_expression(); rem_anchor_token(']'); expect(']', end_error); type_t *array_type = allocate_type(TYPE_ARRAY); array_type->array.element_type = type; array_type->array.size_expression = size; type = array_type; break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); parse_function(&expression->func.function); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); type_t *type = allocate_type(TYPE_TYPEOF); add_anchor_token(')'); type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); expression->sizeofe.type = type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(token_type_t token_type) { unsigned len = (unsigned) ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, token_type_t token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, token_type_t token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { expression_t *expression = allocate_expression(EXPR_CALL); expression->call.function = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \
MatzeB/fluffy
6ea4842e77ad733995b1f352874aeda828948e4d
remove unused entity definition
diff --git a/ast_t.h b/ast_t.h index a42e87e..a762c35 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,516 +1,508 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_FUNCTION, DECLARATION_FUNCTION_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_FUNCTION, DECLARATION_LABEL, DECLARATION_LAST = DECLARATION_LABEL } declaration_kind_t; -typedef enum { - ENTITY_FUNCTION, - ENTITY_FUNCTION_PARAMETER, - ENTITY_EXPRESSION, - ENTITY_LABEL, - ENTITY_CONCEPT, -} entity_kind_t; - /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; int refs; /**< temporarily used by semantic phase */ bool exported : 1; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; struct import_t { symbol_t *module; symbol_t *symbol; import_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct function_t { function_type_t *type; type_variable_t *type_parameters; function_parameter_t *parameters; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct function_declaration_t { declaration_base_t base; function_t function; }; struct iterator_declaration_t { declaration_base_t base; function_t function; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_function_t { declaration_base_t base; function_type_t *type; function_parameter_t *parameters; concept_t *concept; concept_function_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_function_t *functions; concept_instance_t *instances; context_t context; }; struct module_t { symbol_t *name; context_t context; module_t *next; bool processing : 1; bool processed : 1; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; function_declaration_t function; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_function_t concept_function; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; function_t function; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *function; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST = STATEMENT_LABEL } statement_kind_t; struct statement_base_t { statement_kind_t kind; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_base_t base; expression_t *value; }; struct block_statement_t { statement_base_t base; statement_t *statements; source_position_t end_position; context_t context; }; struct declaration_statement_t { statement_base_t base; variable_declaration_t declaration; }; struct if_statement_t { statement_base_t base; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_base_t base; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_base_t base; label_declaration_t declaration; }; struct expression_statement_t { statement_base_t base; expression_t *expression; }; union statement_t { statement_kind_t kind; statement_base_t base; return_statement_t returns; block_statement_t block; declaration_statement_t declaration; goto_statement_t gotos; label_statement_t label; expression_statement_t expression; if_statement_t ifs; }; struct function_parameter_t { declaration_t declaration; function_parameter_t *next; type_t *type; int num; }; struct concept_function_instance_t { function_t function; symbol_t *symbol; source_position_t source_position; concept_function_instance_t *next; concept_function_t *concept_function; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_function_instance_t *function_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); expression_t *allocate_expression(expression_kind_t kind); declaration_t *allocate_declaration(declaration_kind_t kind); #endif
MatzeB/fluffy
058d7ded720c2c3d31e9ecc22ebd66c35aed78bd
rename method to function
diff --git a/ast.c b/ast.c index 922d0b8..a4f2f8d 100644 --- a/ast.c +++ b/ast.c @@ -1,766 +1,767 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for (const char *c = string_const->value; *c != 0; ++c) { switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { - print_expression(call->method); + print_expression(call->function); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->base.symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch (unexpr->base.kind) { case EXPR_UNARY_CAST: fprintf(out, "cast<"); print_type(unexpr->base.type); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->base.kind); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch (binexpr->base.kind) { case EXPR_BINARY_ASSIGN: fprintf(out, "<-"); break; case EXPR_BINARY_ADD: fprintf(out, "+"); break; case EXPR_BINARY_SUB: fprintf(out, "-"); break; case EXPR_BINARY_MUL: fprintf(out, "*"); break; case EXPR_BINARY_DIV: fprintf(out, "/"); break; case EXPR_BINARY_NOTEQUAL: fprintf(out, "/="); break; case EXPR_BINARY_EQUAL: fprintf(out, "="); break; case EXPR_BINARY_LESS: fprintf(out, "<"); break; case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; case EXPR_BINARY_GREATER: fprintf(out, ">"); break; case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->base.kind); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->kind) { case EXPR_ERROR: fprintf(out, "*error expression*"); break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_FUNC: /* TODO */ fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { indent++; print_statement(statement); indent--; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->value != NULL) print_expression(statement->value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->base.symbol->string); } static void print_declaration_statement(const declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch (statement->kind) { case STATEMENT_BLOCK: print_block_statement(&statement->block); break; case STATEMENT_RETURN: print_return_statement(&statement->returns); break; case STATEMENT_EXPRESSION: print_expression_statement(&statement->expression); break; case STATEMENT_LABEL: print_label_statement(&statement->label); break; case STATEMENT_GOTO: print_goto_statement(&statement->gotos); break; case STATEMENT_IF: print_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: print_declaration_statement(&statement->declaration); break; case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } -static void print_method_parameters(const method_parameter_t *parameters, - const function_type_t *function_type) +static void print_function_parameters(const function_parameter_t *parameters, + const function_type_t *function_type) { fprintf(out, "("); - int first = 1; - const method_parameter_t *parameter = parameters; + int first = 1; + const function_parameter_t *parameter = parameters; const function_parameter_type_t *parameter_type = function_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } -static void print_method(const method_declaration_t *method_declaration) +static void print_function(const function_declaration_t *function_declaration) { - const method_t *method = &method_declaration->method; - function_type_t *type = method->type; + const function_t *function = &function_declaration->function; + function_type_t *type = function->type; fprintf(out, "func "); - if (method->is_extern) { + if (function->is_extern) { fprintf(out, "extern "); } - fprintf(out, " %s", method_declaration->base.symbol->string); + fprintf(out, " %s", function_declaration->base.symbol->string); - print_type_parameters(method->type_parameters); + print_type_parameters(function->type_parameters); - print_method_parameters(method->parameters, type); + print_function_parameters(function->parameters, type); fprintf(out, " : "); print_type(type->result_type); - if (method->statement != NULL) { + if (function->statement != NULL) { fprintf(out, ":\n"); - print_statement(method->statement); + print_statement(function->statement); } else { fprintf(out, "\n"); } } -static void print_concept_method(const concept_method_t *method) +static void print_concept_function(const concept_function_t *function) { fprintf(out, "\tfunc "); - fprintf(out, "%s", method->base.symbol->string); - print_method_parameters(method->parameters, method->type); + fprintf(out, "%s", function->base.symbol->string); + print_function_parameters(function->parameters, function->type); fprintf(out, " : "); - print_type(method->type->result_type); + print_type(function->type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); - concept_method_t *method = concept->methods; - while (method != NULL) { - print_concept_method(method); + concept_function_t *function = concept->functions; + while (function != NULL) { + print_concept_function(function); - method = method->next; + function = function->next; } } -static void print_concept_method_instance( - concept_method_instance_t *method_instance) +static void print_concept_function_instance( + concept_function_instance_t *function_instance) { fprintf(out, "\tfunc "); - const method_t *method = &method_instance->method; - if (method_instance->concept_method != NULL) { - concept_method_t *method = method_instance->concept_method; - fprintf(out, "%s", method->base.symbol->string); + const function_t *function = &function_instance->function; + if (function_instance->concept_function != NULL) { + concept_function_t *function = function_instance->concept_function; + fprintf(out, "%s", function->base.symbol->string); } else { - fprintf(out, "?%s", method_instance->symbol->string); + fprintf(out, "?%s", function_instance->symbol->string); } - print_method_parameters(method->parameters, method->type); + print_function_parameters(function->parameters, function->type); fprintf(out, " : "); - print_type(method_instance->method.type->result_type); + print_type(function_instance->function.type->result_type); - if (method->statement != NULL) { + if (function->statement != NULL) { fprintf(out, ":\n"); - print_statement(method->statement); + print_statement(function->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); - concept_method_instance_t *method_instance = instance->method_instances; - while (method_instance != NULL) { - print_concept_method_instance(method_instance); + concept_function_instance_t *function_instance + = instance->function_instances; + while (function_instance != NULL) { + print_concept_function_instance(function_instance); - method_instance = method_instance->next; + function_instance = function_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch (declaration->kind) { - case DECLARATION_METHOD: - print_method((const method_declaration_t*) declaration); + case DECLARATION_FUNCTION: + print_function(&declaration->function); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: - case DECLARATION_CONCEPT_METHOD: - case DECLARATION_METHOD_PARAMETER: + case DECLARATION_CONCEPT_FUNCTION: + case DECLARATION_FUNCTION_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type '%s'\n", get_declaration_kind_name(declaration->kind)); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: fprintf(out, "invalid declaration (%s)\n", get_declaration_kind_name(declaration->kind)); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { print_declaration(declaration); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } void print_ast(FILE *new_out, const context_t *context) { indent = 0; out = new_out; print_context(context); assert(indent == 0); out = NULL; } const char *get_declaration_kind_name(declaration_kind_t type) { switch (type) { - case DECLARATION_ERROR: return "parse error"; - case DECLARATION_INVALID: return "invalid reference"; - case DECLARATION_VARIABLE: return "variable"; - case DECLARATION_CONSTANT: return "constant"; - case DECLARATION_METHOD_PARAMETER: return "method parameter"; - case DECLARATION_METHOD: return "method"; - case DECLARATION_ITERATOR: return "iterator"; - case DECLARATION_CONCEPT: return "concept"; - case DECLARATION_TYPEALIAS: return "type alias"; - case DECLARATION_TYPE_VARIABLE: return "type variable"; - case DECLARATION_LABEL: return "label"; - case DECLARATION_CONCEPT_METHOD: return "concept method"; + case DECLARATION_ERROR: return "parse error"; + case DECLARATION_INVALID: return "invalid reference"; + case DECLARATION_VARIABLE: return "variable"; + case DECLARATION_CONSTANT: return "constant"; + case DECLARATION_FUNCTION_PARAMETER: return "function parameter"; + case DECLARATION_FUNCTION: return "function"; + case DECLARATION_ITERATOR: return "iterator"; + case DECLARATION_CONCEPT: return "concept"; + case DECLARATION_TYPEALIAS: return "type alias"; + case DECLARATION_TYPE_VARIABLE: return "type variable"; + case DECLARATION_LABEL: return "label"; + case DECLARATION_CONCEPT_FUNCTION: return "concept function"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } bool is_linktime_constant(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: /* TODO */ return false; case EXPR_ARRAY_ACCESS: /* TODO */ return false; case EXPR_UNARY_DEREFERENCE: return is_constant_expression(expression->unary.value); default: return false; } } bool is_constant_expression(const expression_t *expression) { switch (expression->kind) { case EXPR_INT_CONST: case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_NULL_POINTER: case EXPR_SIZEOF: return true; case EXPR_STRING_CONST: case EXPR_FUNC: case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: case EXPR_UNARY_DEREFERENCE: case EXPR_BINARY_ASSIGN: case EXPR_SELECT: case EXPR_ARRAY_ACCESS: return false; case EXPR_UNARY_TAKE_ADDRESS: return is_linktime_constant(expression->unary.value); case EXPR_REFERENCE: { declaration_t *declaration = expression->reference.declaration; if (declaration->kind == DECLARATION_CONSTANT) return true; return false; } case EXPR_CALL: /* TODO: we might introduce pure/side effect free calls */ return false; case EXPR_UNARY_CAST: case EXPR_UNARY_NEGATE: case EXPR_UNARY_NOT: case EXPR_UNARY_BITWISE_NOT: return is_constant_expression(expression->unary.value); case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: case EXPR_BINARY_MUL: case EXPR_BINARY_DIV: case EXPR_BINARY_MOD: case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: /* not that lazy and/or are not constant if their value is clear after * evaluating the left side. This is because we can't (always) evaluate the * left hand side until the ast2firm phase, and therefore can't determine * constness */ case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: return is_constant_expression(expression->binary.left) && is_constant_expression(expression->binary.right); case EXPR_ERROR: return true; case EXPR_INVALID: break; } panic("invalid expression in is_constant_expression"); } diff --git a/ast.h b/ast.h index b325387..10b71cc 100644 --- a/ast.h +++ b/ast.h @@ -1,80 +1,80 @@ #ifndef AST_H #define AST_H #include <stdbool.h> #include <stdio.h> typedef struct attribute_t attribute_t; typedef union declaration_t declaration_t; typedef union expression_t expression_t; typedef union statement_t statement_t; typedef struct context_t context_t; typedef struct export_t export_t; typedef struct import_t import_t; typedef struct declaration_base_t declaration_base_t; typedef struct expression_base_t expression_base_t; typedef struct int_const_t int_const_t; typedef struct float_const_t float_const_t; typedef struct string_const_t string_const_t; typedef struct bool_const_t bool_const_t; typedef struct cast_expression_t cast_expression_t; typedef struct reference_expression_t reference_expression_t; typedef struct call_argument_t call_argument_t; typedef struct call_expression_t call_expression_t; typedef struct binary_expression_t binary_expression_t; typedef struct unary_expression_t unary_expression_t; typedef struct select_expression_t select_expression_t; typedef struct array_access_expression_t array_access_expression_t; typedef struct sizeof_expression_t sizeof_expression_t; typedef struct func_expression_t func_expression_t; typedef struct statement_base_t statement_base_t; typedef struct block_statement_t block_statement_t; typedef struct return_statement_t return_statement_t; typedef struct if_statement_t if_statement_t; typedef struct variable_declaration_t variable_declaration_t; typedef struct declaration_statement_t declaration_statement_t; typedef struct expression_statement_t expression_statement_t; typedef struct goto_statement_t goto_statement_t; typedef struct label_declaration_t label_declaration_t; typedef struct label_statement_t label_statement_t; typedef struct module_t module_t; -typedef struct method_parameter_t method_parameter_t; -typedef struct method_t method_t; -typedef struct method_declaration_t method_declaration_t; +typedef struct function_parameter_t function_parameter_t; +typedef struct function_t function_t; +typedef struct function_declaration_t function_declaration_t; typedef struct iterator_declaration_t iterator_declaration_t; typedef struct constant_t constant_t; typedef struct global_variable_t global_variable_t; typedef struct typealias_t typealias_t; typedef struct concept_instance_t concept_instance_t; -typedef struct concept_method_instance_t - concept_method_instance_t; +typedef struct concept_function_instance_t + concept_function_instance_t; typedef struct concept_t concept_t; -typedef struct concept_method_t concept_method_t; +typedef struct concept_function_t concept_function_t; void init_ast_module(void); void exit_ast_module(void); void print_ast(FILE *out, const context_t *context); void print_expression(const expression_t *expression); void *allocate_ast(size_t size); /** * Returns true if a given expression is a compile time * constant. */ bool is_constant_expression(const expression_t *expression); /** * An object with a fixed but at compiletime unknown adress which will be known * at link/load time. */ bool is_linktime_constant(const expression_t *expression); long fold_constant_to_int(expression_t *expression); bool fold_constant_to_bool(expression_t *expression); #endif diff --git a/ast2firm.c b/ast2firm.c index 1439be1..3d9f055 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1896 +1,1897 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; -typedef struct instantiate_method_t instantiate_method_t; +typedef struct instantiate_function_t instantiate_function_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; -struct instantiate_method_t { - method_t *method; - ir_entity *entity; - type_argument_t *type_arguments; +struct instantiate_function_t { + function_t *function; + ir_entity *entity; + type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; -static strset_t instantiated_methods; -static pdeq *instantiate_methods = NULL; +static strset_t instantiated_functions; +static pdeq *instantiate_functions = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = (const declaration_t*) &value_numbers[pos]; print_warning_prefix(declaration->base.source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->base.symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { } static void init_ir_types(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.base.kind = TYPE_ATOMIC; byte_type.akind = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch (type->akind) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch (type->kind) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_FUNCTION: - /* just a pointer to the method */ + /* just a pointer to the function */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const function_type_t *function_type) { int count = 0; function_parameter_type_t *param_type = function_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_function_type(type2firm_env_t *env, const function_type_t *function_type) { type_t *result_type = function_type->result_type; ident *id = unique_ident("functiontype"); int n_parameters = count_parameters(function_type); int n_results = result_type->kind == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if (result_type->kind != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } function_parameter_type_t *param_type = function_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (function_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->base.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_node *expression_to_firm(expression_t *expression); static tarval *fold_constant_to_tarval(expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } tarval* tv = get_Const_tarval(cnst); return tv; } long fold_constant_to_int(expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->base.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->base.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->base.kind == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->base.firm_type != NULL) { assert(type->base.firm_type != INVALID_TYPE); return type->base.firm_type; } ir_type *firm_type = NULL; switch (type->kind) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, &type->atomic); break; case TYPE_FUNCTION: firm_type = get_function_type(env, &type->function); break; case TYPE_POINTER: firm_type = get_pointer_type(env, &type->pointer); break; case TYPE_ARRAY: firm_type = get_array_type(env, &type->array); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, &type->compound); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, &type->compound); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, &type->reference); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, &type->bind_typevariables); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->base.firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } -static instantiate_method_t *queue_method_instantiation(method_t *method, - ir_entity *entity) +static instantiate_function_t *queue_function_instantiation( + function_t *function, ir_entity *entity) { - instantiate_method_t *instantiate + instantiate_function_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); - instantiate->method = method; - instantiate->entity = entity; - pdeq_putr(instantiate_methods, instantiate); + instantiate->function = function; + instantiate->entity = entity; + pdeq_putr(instantiate_functions, instantiate); return instantiate; } -static int is_polymorphic_method(const method_t *method) +static int is_polymorphic_function(const function_t *function) { - return method->type_parameters != NULL; + return function->type_parameters != NULL; } -static ir_entity* get_concept_method_instance_entity( - concept_method_instance_t *method_instance) +static ir_entity* get_concept_function_instance_entity( + concept_function_instance_t *function_instance) { - method_t *method = & method_instance->method; - if (method->e.entity != NULL) - return method->e.entity; + function_t *function = & function_instance->function; + if (function->e.entity != NULL) + return function->e.entity; - function_type_t *function_type = method->type; + function_type_t *function_type = function->type; - concept_method_t *concept_method = method_instance->concept_method; - concept_t *concept = concept_method->concept; + concept_function_t *concept_function = function_instance->concept_function; + concept_t *concept = concept_function->concept; start_mangle(); mangle_concept_name(concept->base.symbol); - mangle_symbol(concept_method->base.symbol); + mangle_symbol(concept_function->base.symbol); - concept_instance_t *instance = method_instance->concept_instance; + concept_instance_t *instance = function_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); - method->e.entity = entity; + function->e.entity = entity; return entity; } -static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) +static ir_entity* get_function_entity(function_t *function, symbol_t *symbol) { - function_type_t *function_type = method->type; - int is_polymorphic = is_polymorphic_method(method); + function_type_t *function_type = function->type; + int is_polymorphic = is_polymorphic_function(function); - if (!is_polymorphic && method->e.entity != NULL) { - return method->e.entity; + if (!is_polymorphic && function->e.entity != NULL) { + return function->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { - type_variable_t *type_variable = method->type_parameters; + type_variable_t *type_variable = function->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ - if (is_polymorphic && method->e.entities != NULL) { - int len = ARR_LEN(method->e.entities); + if (is_polymorphic && function->e.entities != NULL) { + int len = ARR_LEN(function->e.entities); for (int i = 0; i < len; ++i) { - ir_entity *entity = method->e.entities[i]; + ir_entity *entity = function->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); - if (method->is_extern) { + if (function->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { - method->e.entity = entity; + function->e.entity = entity; } else { - if (method->e.entities == NULL) - method->e.entities = NEW_ARR_F(ir_entity*, 0); - ARR_APP1(ir_entity*, method->e.entities, entity); + if (function->e.entities == NULL) + function->e.entities = NEW_ARR_F(ir_entity*, 0); + ARR_APP1(ir_entity*, function->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch (declaration->kind) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: - case DECLARATION_METHOD: - case DECLARATION_METHOD_PARAMETER: + case DECLARATION_FUNCTION: + case DECLARATION_FUNCTION_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: - case DECLARATION_CONCEPT_METHOD: + case DECLARATION_CONCEPT_FUNCTION: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static long binexpr_kind_to_cmp_pn(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; case EXPR_BINARY_LESS: return pn_Cmp_Lt; case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; case EXPR_BINARY_GREATER: return pn_Cmp_Gt; case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ long compare_pn = binexpr_kind_to_cmp_pn(kind); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->kind == TYPE_COMPOUND_STRUCT || entry_type->kind == TYPE_COMPOUND_UNION || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(declaration_t *declaration, type_argument_t *type_arguments) { - assert(declaration->kind == DECLARATION_METHOD); - method_t *method = &declaration->method.method; + assert(declaration->kind == DECLARATION_FUNCTION); + function_t *function = &declaration->function.function; symbol_t *symbol = declaration->base.symbol; int old_top = typevar_binding_stack_top(); - push_type_variable_bindings(method->type_parameters, type_arguments); + push_type_variable_bindings(function->type_parameters, type_arguments); - ir_entity *entity = get_method_entity(method, symbol); + ir_entity *entity = get_function_entity(function, symbol); const char *name = get_entity_name(entity); if (declaration->base.exported && get_entity_visibility(entity) != visibility_external_allocated) { set_entity_visibility(entity, visibility_external_visible); } pop_type_variable_bindings(old_top); - if (strset_find(&instantiated_methods, name) != NULL) { + if (strset_find(&instantiated_functions, name) != NULL) { return entity; } - instantiate_method_t *instantiate - = queue_method_instantiation(method, entity); + instantiate_function_t *instantiate + = queue_function_instantiation(function, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } - strset_insert(&instantiated_methods, name); + strset_insert(&instantiated_functions, name); return entity; } -static ir_node *method_reference_to_firm(declaration_t *declaration, - type_argument_t *type_arguments, - const source_position_t *source_position) +static ir_node *function_reference_to_firm(declaration_t *declaration, + type_argument_t *type_arguments, + const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(declaration, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } -static ir_node *concept_method_reference_to_firm(concept_method_t *method, +static ir_node *concept_function_reference_to_firm(concept_function_t *function, type_argument_t *type_arguments, const source_position_t *source_position) { - concept_t *concept = method->concept; + concept_t *concept = function->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { - fprintf(stderr, "while looking at method '%s' from '%s'\n", - method->base.symbol->string, + fprintf(stderr, "while looking at function '%s' from '%s'\n", + function->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } - concept_method_instance_t *method_instance - = get_method_from_concept_instance(instance, method); - if (method_instance == NULL) { - fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", - method->base.symbol->string, + concept_function_instance_t *function_instance + = get_function_from_concept_instance(instance, function); + if (function_instance == NULL) { + fprintf(stderr, "panic: no function '%s' in instance of concept '%s'\n", + function->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); - ir_entity *entity = get_concept_method_instance_entity(method_instance); + ir_entity *entity = get_concept_function_instance_entity(function_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } -static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) +static ir_node *function_parameter_reference_to_firm(function_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { - expression_t *method = call->method; - ir_node *callee = expression_to_firm(method); + expression_t *function = call->function; + ir_node *callee = expression_to_firm(function); - assert(method->base.type->kind == TYPE_POINTER); - pointer_type_t *pointer_type = (pointer_type_t*) method->base.type; + assert(function->base.type->kind == TYPE_POINTER); + pointer_type_t *pointer_type = (pointer_type_t*) function->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->kind == TYPE_FUNCTION); function_type_t *function_type = (function_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) function_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (function_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = function_type->result_type; ir_node *result = NULL; if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { - method_t *method = & expression->method; - ir_entity *entity = method->e.entity; + function_t *function = &expression->function; + ir_entity *entity = function->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); - entity = get_method_entity(method, symbol); + entity = get_function_entity(function, symbol); } - queue_method_instantiation(method, entity); + queue_function_instantiation(function, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { - method_declaration_t *method_declaration; + function_declaration_t *function_declaration; switch (declaration->kind) { - case DECLARATION_METHOD: - method_declaration = (method_declaration_t*) declaration; - return method_reference_to_firm(declaration, type_arguments, - source_position); + case DECLARATION_FUNCTION: + function_declaration = (function_declaration_t*) declaration; + return function_reference_to_firm(declaration, type_arguments, + source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; - case DECLARATION_CONCEPT_METHOD: - return concept_method_reference_to_firm( - (concept_method_t*) declaration, type_arguments, + case DECLARATION_CONCEPT_FUNCTION: + return concept_function_reference_to_firm( + (concept_function_t*) declaration, type_arguments, source_position); - case DECLARATION_METHOD_PARAMETER: - return method_parameter_reference_to_firm( - (method_parameter_t*) declaration); + case DECLARATION_FUNCTION_PARAMETER: + return function_parameter_reference_to_firm( + (function_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->base.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *ret; if (statement->value != NULL) { ir_node *retval = expression_to_firm(statement->value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } -static void create_method(method_t *method, ir_entity *entity, - type_argument_t *type_arguments) +static void create_function(function_t *function, ir_entity *entity, + type_argument_t *type_arguments) { - if (method->is_extern) + if (function->is_extern) return; int old_top = typevar_binding_stack_top(); - if (is_polymorphic_method(method)) { + if (is_polymorphic_function(function)) { assert(type_arguments != NULL); - push_type_variable_bindings(method->type_parameters, type_arguments); + push_type_variable_bindings(function->type_parameters, type_arguments); } - ir_graph *irg = new_ir_graph(entity, method->n_local_vars); + ir_graph *irg = new_ir_graph(entity, function->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); - value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); + value_numbers = xmalloc(function->n_local_vars * sizeof(value_numbers[0])); - context2firm(&method->context); + context2firm(&function->context); ir_node *firstblock = get_cur_block(); - if (method->statement) - statement_to_firm(method->statement); + if (function->statement) + statement_to_firm(function->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; - concept_method_instance_t *method_instance = instance->method_instances; - for ( ; method_instance != NULL; method_instance = method_instance->next) { + concept_function_instance_t *function_instance = instance->function_instances; + for ( ; function_instance != NULL; function_instance = function_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ - method_t *method = & method_instance->method; - /* make sure the method entity is set */ - ir_entity *entity = get_concept_method_instance_entity(method_instance); - /* we can emit it like a normal method */ - queue_method_instantiation(method, entity); + function_t *function = & function_instance->function; + /* make sure the function entity is set */ + ir_entity *entity + = get_concept_function_instance_entity(function_instance); + /* we can emit it like a normal function */ + queue_function_instantiation(function, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { - case DECLARATION_METHOD: - if (!is_polymorphic_method(&declaration->method.method)) { + case DECLARATION_FUNCTION: + if (!is_polymorphic_function(&declaration->function.function)) { assure_instance(declaration, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: - case DECLARATION_METHOD_PARAMETER: - case DECLARATION_CONCEPT_METHOD: + case DECLARATION_FUNCTION_PARAMETER: + case DECLARATION_CONCEPT_FUNCTION: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); - strset_init(&instantiated_methods); - instantiate_methods = new_pdeq(); + strset_init(&instantiated_functions); + instantiate_functions = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ - while (!pdeq_empty(instantiate_methods)) { - instantiate_method_t *instantiate_method - = pdeq_getl(instantiate_methods); + while (!pdeq_empty(instantiate_functions)) { + instantiate_function_t *instantiate_function + = pdeq_getl(instantiate_functions); assert(typevar_binding_stack_top() == 0); - create_method(instantiate_method->method, - instantiate_method->entity, - instantiate_method->type_arguments); + create_function(instantiate_function->function, + instantiate_function->entity, + instantiate_function->type_arguments); } assert(typevar_binding_stack_top() == 0); - del_pdeq(instantiate_methods); + del_pdeq(instantiate_functions); obstack_free(&obst, NULL); - strset_destroy(&instantiated_methods); + strset_destroy(&instantiated_functions); } diff --git a/ast_t.h b/ast_t.h index f73f4c7..a42e87e 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,516 +1,516 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, - DECLARATION_METHOD, - DECLARATION_METHOD_PARAMETER, + DECLARATION_FUNCTION, + DECLARATION_FUNCTION_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, - DECLARATION_CONCEPT_METHOD, + DECLARATION_CONCEPT_FUNCTION, DECLARATION_LABEL, DECLARATION_LAST = DECLARATION_LABEL } declaration_kind_t; typedef enum { ENTITY_FUNCTION, ENTITY_FUNCTION_PARAMETER, ENTITY_EXPRESSION, ENTITY_LABEL, ENTITY_CONCEPT, } entity_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; int refs; /**< temporarily used by semantic phase */ bool exported : 1; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; struct import_t { symbol_t *module; symbol_t *symbol; import_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; -struct method_t { - function_type_t *type; - type_variable_t *type_parameters; - method_parameter_t *parameters; - bool is_extern; +struct function_t { + function_type_t *type; + type_variable_t *type_parameters; + function_parameter_t *parameters; + bool is_extern; - context_t context; - statement_t *statement; + context_t context; + statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; -struct method_declaration_t { +struct function_declaration_t { declaration_base_t base; - method_t method; + function_t function; }; struct iterator_declaration_t { declaration_base_t base; - method_t method; + function_t function; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; -struct concept_method_t { - declaration_base_t base; - function_type_t *type; - method_parameter_t *parameters; - concept_t *concept; +struct concept_function_t { + declaration_base_t base; + function_type_t *type; + function_parameter_t *parameters; + concept_t *concept; - concept_method_t *next; + concept_function_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; - concept_method_t *methods; + concept_function_t *functions; concept_instance_t *instances; context_t context; }; struct module_t { symbol_t *name; context_t context; module_t *next; bool processing : 1; bool processed : 1; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; - method_declaration_t method; + function_declaration_t function; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; - concept_method_t concept_method; + concept_function_t concept_function; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; - method_t method; + function_t function; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; - expression_t *method; + expression_t *function; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST = STATEMENT_LABEL } statement_kind_t; struct statement_base_t { statement_kind_t kind; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_base_t base; expression_t *value; }; struct block_statement_t { statement_base_t base; statement_t *statements; source_position_t end_position; context_t context; }; struct declaration_statement_t { statement_base_t base; variable_declaration_t declaration; }; struct if_statement_t { statement_base_t base; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_base_t base; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_base_t base; label_declaration_t declaration; }; struct expression_statement_t { statement_base_t base; expression_t *expression; }; union statement_t { statement_kind_t kind; statement_base_t base; return_statement_t returns; block_statement_t block; declaration_statement_t declaration; goto_statement_t gotos; label_statement_t label; expression_statement_t expression; if_statement_t ifs; }; -struct method_parameter_t { - declaration_t declaration; - method_parameter_t *next; - type_t *type; - int num; +struct function_parameter_t { + declaration_t declaration; + function_parameter_t *next; + type_t *type; + int num; }; -struct concept_method_instance_t { - method_t method; - symbol_t *symbol; - source_position_t source_position; - concept_method_instance_t *next; +struct concept_function_instance_t { + function_t function; + symbol_t *symbol; + source_position_t source_position; + concept_function_instance_t *next; - concept_method_t *concept_method; - concept_instance_t *concept_instance; + concept_function_t *concept_function; + concept_instance_t *concept_instance; }; struct concept_instance_t { - symbol_t *concept_symbol; - source_position_t source_position; - concept_t *concept; - type_argument_t *type_arguments; - concept_method_instance_t *method_instances; - concept_instance_t *next; - concept_instance_t *next_in_concept; - context_t context; - type_variable_t *type_parameters; + symbol_t *concept_symbol; + source_position_t source_position; + concept_t *concept; + type_argument_t *type_arguments; + concept_function_instance_t *function_instances; + concept_instance_t *next; + concept_instance_t *next_in_concept; + context_t context; + type_variable_t *type_parameters; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); expression_t *allocate_expression(expression_kind_t kind); declaration_t *allocate_declaration(declaration_kind_t kind); #endif diff --git a/parser.c b/parser.c index cd3a0c8..4af1dda 100644 --- a/parser.c +++ b/parser.c @@ -1,2414 +1,2414 @@ #include <config.h> #include "token_t.h" #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers; static parse_statement_function *statement_parsers; static parse_declaration_function *declaration_parsers; static parse_attribute_function *attribute_parsers; static unsigned char token_anchor_set[T_LAST_TOKEN]; static symbol_t *current_module_name; static context_t *current_context; static int error = 0; token_t token; module_t *modules; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_declaration_struct_size(declaration_kind_t kind) { static const size_t sizes[] = { - [DECLARATION_ERROR] = sizeof(declaration_base_t), - [DECLARATION_METHOD] = sizeof(method_declaration_t), - [DECLARATION_METHOD_PARAMETER] = sizeof(method_parameter_t), - [DECLARATION_ITERATOR] = sizeof(iterator_declaration_t), - [DECLARATION_VARIABLE] = sizeof(variable_declaration_t), - [DECLARATION_CONSTANT] = sizeof(constant_t), - [DECLARATION_TYPE_VARIABLE] = sizeof(type_variable_t), - [DECLARATION_TYPEALIAS] = sizeof(typealias_t), - [DECLARATION_CONCEPT] = sizeof(concept_t), - [DECLARATION_CONCEPT_METHOD] = sizeof(concept_method_t), - [DECLARATION_LABEL] = sizeof(label_declaration_t) + [DECLARATION_ERROR] = sizeof(declaration_base_t), + [DECLARATION_FUNCTION] = sizeof(function_declaration_t), + [DECLARATION_FUNCTION_PARAMETER] = sizeof(function_parameter_t), + [DECLARATION_ITERATOR] = sizeof(iterator_declaration_t), + [DECLARATION_VARIABLE] = sizeof(variable_declaration_t), + [DECLARATION_CONSTANT] = sizeof(constant_t), + [DECLARATION_TYPE_VARIABLE] = sizeof(type_variable_t), + [DECLARATION_TYPEALIAS] = sizeof(typealias_t), + [DECLARATION_CONCEPT] = sizeof(concept_t), + [DECLARATION_CONCEPT_FUNCTION] = sizeof(concept_function_t), + [DECLARATION_LABEL] = sizeof(label_declaration_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } declaration_t *allocate_declaration(declaration_kind_t kind) { size_t size = get_declaration_struct_size(kind); declaration_t *declaration = allocate_ast_zero(size); declaration->kind = kind; return declaration; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { [EXPR_ERROR] = sizeof(expression_base_t), [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } static size_t get_statement_struct_size(statement_kind_t kind) { static const size_t sizes[] = { [STATEMENT_ERROR] = sizeof(statement_base_t), [STATEMENT_BLOCK] = sizeof(block_statement_t), [STATEMENT_RETURN] = sizeof(return_statement_t), [STATEMENT_DECLARATION] = sizeof(declaration_statement_t), [STATEMENT_IF] = sizeof(if_statement_t), [STATEMENT_EXPRESSION] = sizeof(expression_statement_t), [STATEMENT_GOTO] = sizeof(goto_statement_t), [STATEMENT_LABEL] = sizeof(label_statement_t), }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; }; static statement_t *allocate_statement(statement_kind_t kind) { size_t size = get_statement_struct_size(kind); statement_t *statement = allocate_ast_zero(size); statement->kind = kind; return statement; } static size_t get_type_struct_size(type_kind_t kind) { static const size_t sizes[] = { [TYPE_ERROR] = sizeof(type_base_t), [TYPE_VOID] = sizeof(type_base_t), [TYPE_ATOMIC] = sizeof(atomic_type_t), [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t), [TYPE_COMPOUND_UNION] = sizeof(compound_type_t), [TYPE_FUNCTION] = sizeof(function_type_t), [TYPE_POINTER] = sizeof(pointer_type_t), [TYPE_ARRAY] = sizeof(array_type_t), [TYPE_TYPEOF] = sizeof(typeof_type_t), [TYPE_REFERENCE] = sizeof(type_reference_t), [TYPE_REFERENCE_TYPE_VARIABLE] = sizeof(type_reference_t), [TYPE_BIND_TYPEVARIABLES] = sizeof(bind_typevariables_type_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } type_t *allocate_type(type_kind_t kind) { size_t size = get_type_struct_size(kind); type_t *type = obstack_alloc(type_obst, size); memset(type, 0, size); type->kind = kind; return type; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) -static void parse_method(method_t *method); +static void parse_function(function_t *function); static statement_t *parse_block(void); static void parse_parameter_declarations(function_type_t *function_type, - method_parameter_t **parameters); + function_parameter_t **parameters); static atomic_type_kind_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_kind_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_kind_t akind; switch (token.type) { case T_unsigned: next_token(); akind = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: akind = parse_signed_atomic_type(); break; } type_t *type = allocate_type(TYPE_ATOMIC); type->atomic.akind = akind; type_t *result = typehash_insert(type); if (result != type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { type_t *type = allocate_type(TYPE_TYPEOF); eat(T_typeof); expect('(', end_error); add_anchor_token(')'); type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_t *type = allocate_type(TYPE_REFERENCE); type->reference.symbol = token.v.symbol; type->reference.source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return type; } static type_t *create_error_type(void) { return allocate_type(TYPE_ERROR); } static type_t *parse_function_type(void) { eat(T_func); type_t *type = allocate_type(TYPE_FUNCTION); parse_parameter_declarations(&type->function, NULL); expect(':', end_error); type->function.result_type = parse_type(); return type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); type_t *type = allocate_type(TYPE_COMPOUND_UNION); type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return type; } static type_t *parse_struct_type(void) { eat(T_struct); type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return type; } static type_t *make_pointer_type_no_hash(type_t *points_to) { type_t *type = allocate_type(TYPE_POINTER); type->pointer.points_to = points_to; return type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_function_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); expression_t *size = parse_expression(); rem_anchor_token(']'); expect(']', end_error); type_t *array_type = allocate_type(TYPE_ARRAY); array_type->array.element_type = type; array_type->array.size_expression = size; type = array_type; break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); - parse_method(&expression->func.method); + parse_function(&expression->func.function); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); type_t *type = allocate_type(TYPE_TYPEOF); add_anchor_token(')'); type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); expression->sizeofe.type = type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { - expression_t *expression = allocate_expression(EXPR_CALL); - expression->call.method = left; + expression_t *expression = allocate_expression(EXPR_CALL); + expression->call.function = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \ return expression; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); register_expression_parser(parse_EXPR_UNARY_NOT, '!'); register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->base.source_position = start; while (true) { if (token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->base.source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { eat(T_return); statement_t *return_statement = allocate_statement(STATEMENT_RETURN); if (token.type != T_NEWLINE) { return_statement->returns.value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return return_statement; } static statement_t *create_error_statement(void) { return allocate_statement(STATEMENT_ERROR); } static statement_t *parse_goto_statement(void) { eat(T_goto); statement_t *goto_statement = allocate_statement(STATEMENT_GOTO); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->gotos.label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); statement_t *label = allocate_statement(STATEMENT_LABEL); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->label.declaration.base.kind = DECLARATION_LABEL; label->label.declaration.base.source_position = source_position; label->label.declaration.base.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->label.declaration); expect(T_NEWLINE, end_error); return label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if (token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if (token.type != T_INDENT) { /* create an empty block */ statement_t *block = allocate_statement(STATEMENT_BLOCK); return block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if (token.type == T_else) { next_token(); if (token.type == ':') next_token(); false_statement = parse_sub_block(); } statement_t *if_statement = allocate_statement(STATEMENT_IF); if_statement->ifs.condition = condition; if_statement->ifs.true_statement = true_statement; if_statement->ifs.false_statement = false_statement; return if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = symbol; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.source_position = source_position; assign->binary.left = expression; assign->binary.right = parse_expression(); statement_t *expr_statement = allocate_statement(STATEMENT_EXPRESSION); expr_statement->expression.expression = assign; return expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } statement_t *statement = allocate_statement(STATEMENT_DECLARATION); declaration_t *declaration = (declaration_t*) &statement->declaration.declaration; declaration->base.kind = DECLARATION_VARIABLE; declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &statement->declaration.declaration; if (token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if (last_statement != NULL) { last_statement->base.next = statement; } else { first_statement = statement; } last_statement = statement; /* do we have an assignment expression? */ if (token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->base.symbol); last_statement->base.next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if (token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { statement_t *statement = allocate_statement(STATEMENT_EXPRESSION); statement->expression.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: return statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if (token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; parse_statement_function parser = NULL; if (token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; add_anchor_token(T_NEWLINE); if (parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if (token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if (declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } rem_anchor_token(T_NEWLINE); if (statement == NULL) return NULL; statement->base.source_position = start; statement_t *next = statement->base.next; while (next != NULL) { next->base.source_position = start; next = next->base.next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); statement_t *block_statement = allocate_statement(STATEMENT_BLOCK); context_t *last_context = current_context; current_context = &block_statement->block.context; add_anchor_token(T_DEDENT); statement_t *last_statement = NULL; while (token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if (statement == NULL) continue; if (last_statement != NULL) { last_statement->base.next = statement; } else { block_statement->block.statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while (last_statement->base.next != NULL) last_statement = last_statement->base.next; } assert(current_context == &block_statement->block.context); current_context = last_context; block_statement->block.end_position = source_position; rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: return block_statement; } static void parse_parameter_declarations(function_type_t *function_type, - method_parameter_t **parameters) + function_parameter_t **parameters) { assert(function_type != NULL); function_parameter_type_t *last_type = NULL; - method_parameter_t *last_param = NULL; + function_parameter_t *last_param = NULL; if (parameters != NULL) *parameters = NULL; expect('(', end_error2); if (token.type == ')') { next_token(); return; } add_anchor_token(')'); add_anchor_token(','); while (true) { if (token.type == T_DOTDOTDOT) { function_type->variable_arguments = 1; next_token(); if (token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); goto end_error; } break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); function_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if (last_type != NULL) { last_type->next = param_type; } else { function_type->parameter_types = param_type; } last_type = param_type; if (parameters != NULL) { - method_parameter_t *method_param - = allocate_ast_zero(sizeof(method_param[0])); - method_param->declaration.base.kind - = DECLARATION_METHOD_PARAMETER; - method_param->declaration.base.symbol = symbol; - method_param->declaration.base.source_position = source_position; - method_param->type = param_type->type; + function_parameter_t *function_param + = allocate_ast_zero(sizeof(function_param[0])); + function_param->declaration.base.kind + = DECLARATION_FUNCTION_PARAMETER; + function_param->declaration.base.symbol = symbol; + function_param->declaration.base.source_position = source_position; + function_param->type = param_type->type; if (last_param != NULL) { - last_param->next = method_param; + last_param->next = function_param; } else { - *parameters = method_param; + *parameters = function_param; } - last_param = method_param; + last_param = function_param; } if (token.type != ',') break; next_token(); } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error2); return; end_error: rem_anchor_token(','); rem_anchor_token(')'); end_error2: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while (token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if (last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static declaration_t *parse_type_parameter(void) { declaration_t *declaration = allocate_declaration(DECLARATION_TYPE_VARIABLE); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->type_variable.constraints = parse_type_constraints(); } return declaration; } static type_variable_t *parse_type_parameters(context_t *context) { declaration_t *first_variable = NULL; declaration_t *last_variable = NULL; while (true) { declaration_t *type_variable = parse_type_parameter(); if (last_variable != NULL) { last_variable->type_variable.next = &type_variable->type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if (context != NULL) { type_variable->base.next = context->declarations; context->declarations = type_variable; } if (token.type != ',') break; next_token(); } return &first_variable->type_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->base.source_position.input_name != NULL); assert(current_context != NULL); declaration->base.next = current_context->declarations; current_context->declarations = declaration; } -static void parse_method(method_t *method) +static void parse_function(function_t *function) { type_t *type = allocate_type(TYPE_FUNCTION); context_t *last_context = current_context; - current_context = &method->context; + current_context = &function->context; if (token.type == '<') { next_token(); add_anchor_token('>'); - method->type_parameters = parse_type_parameters(current_context); + function->type_parameters = parse_type_parameters(current_context); rem_anchor_token('>'); expect('>', end_error); } - parse_parameter_declarations(&type->function, &method->parameters); - method->type = &type->function; + parse_parameter_declarations(&type->function, &function->parameters); + function->type = &type->function; /* add parameters to context */ - method_parameter_t *parameter = method->parameters; + function_parameter_t *parameter = function->parameters; for ( ; parameter != NULL; parameter = parameter->next) { declaration_t *declaration = (declaration_t*) parameter; declaration->base.next = current_context->declarations; current_context->declarations = declaration; } type->function.result_type = type_void; if (token.type == ':') { next_token(); if (token.type == T_NEWLINE) { - method->statement = parse_sub_block(); - goto method_parser_end; + function->statement = parse_sub_block(); + goto function_parser_end; } type->function.result_type = parse_type(); if (token.type == ':') { next_token(); - method->statement = parse_sub_block(); - goto method_parser_end; + function->statement = parse_sub_block(); + goto function_parser_end; } } expect(T_NEWLINE, end_error); -method_parser_end: - assert(current_context == &method->context); +function_parser_end: + assert(current_context == &function->context); current_context = last_context; end_error: ; } -static void parse_method_declaration(void) +static void parse_function_declaration(void) { eat(T_func); - declaration_t *declaration = allocate_declaration(DECLARATION_METHOD); + declaration_t *declaration = allocate_declaration(DECLARATION_FUNCTION); if (token.type == T_extern) { - declaration->method.method.is_extern = true; + declaration->function.function.is_extern = true; next_token(); } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); - parse_method(&declaration->method.method); + parse_function(&declaration->function.function); add_declaration(declaration); } static void parse_global_variable(void) { eat(T_var); declaration_t *declaration = allocate_declaration(DECLARATION_VARIABLE); declaration->variable.is_global = true; if (token.type == T_extern) { next_token(); declaration->variable.is_extern = true; } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); declaration->variable.type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_declaration(declaration); } static void parse_constant(void) { eat(T_const); declaration_t *declaration = allocate_declaration(DECLARATION_CONSTANT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->constant.type = parse_type(); } expect('=', end_error); declaration->constant.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static void parse_typealias(void) { eat(T_typealias); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); expect('=', end_error); declaration->typealias.type = parse_type(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if (token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if (token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if (parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if (parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while (token.type == '$') { attribute_t *attribute = parse_attribute(); if (attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_struct(void) { eat(T_struct); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); type->compound.symbol = declaration->base.symbol; if (token.type == '<') { next_token(); type->compound.type_parameters = parse_type_parameters(&type->compound.context); expect('>', end_error); } type->compound.attributes = parse_attributes(); declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration(declaration); end_error: ; } static void parse_union(void) { eat(T_union); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); type_t *type = allocate_type(TYPE_COMPOUND_UNION); type->compound.symbol = declaration->base.symbol; type->compound.attributes = parse_attributes(); declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } end_error: add_declaration(declaration); } -static concept_method_t *parse_concept_method(void) +static concept_function_t *parse_concept_function(void) { expect(T_func, end_error); declaration_t *declaration - = allocate_declaration(DECLARATION_CONCEPT_METHOD); + = allocate_declaration(DECLARATION_CONCEPT_FUNCTION); type_t *type = allocate_type(TYPE_FUNCTION); if (token.type != T_IDENTIFIER) { - parse_error_expected("Problem while parsing concept method", + parse_error_expected("Problem while parsing concept function", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_parameter_declarations(&type->function, - &declaration->concept_method.parameters); + &declaration->concept_function.parameters); if (token.type == ':') { next_token(); type->function.result_type = parse_type(); } else { type->function.result_type = type_void; } expect(T_NEWLINE, end_error); - declaration->concept_method.type = &type->function; + declaration->concept_function.type = &type->function; add_declaration(declaration); - return &declaration->concept_method; + return &declaration->concept_function; end_error: return NULL; } static void parse_concept(void) { eat(T_concept); declaration_t *declaration = allocate_declaration(DECLARATION_CONCEPT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); context_t *context = &declaration->concept.context; add_anchor_token('>'); declaration->concept.type_parameters = parse_type_parameters(context); rem_anchor_token('>'); expect('>', end_error); } expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); - concept_method_t *last_method = NULL; + concept_function_t *last_function = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } - concept_method_t *method = parse_concept_method(); - method->concept = &declaration->concept; + concept_function_t *function = parse_concept_function(); + function->concept = &declaration->concept; - if (last_method != NULL) { - last_method->next = method; + if (last_function != NULL) { + last_function->next = function; } else { - declaration->concept.methods = method; + declaration->concept.functions = function; } - last_method = method; + last_function = function; } next_token(); end_of_parse_concept: add_declaration(declaration); return; end_error: ; } -static concept_method_instance_t *parse_concept_method_instance(void) +static concept_function_instance_t *parse_concept_function_instance(void) { - concept_method_instance_t *method_instance - = allocate_ast_zero(sizeof(method_instance[0])); + concept_function_instance_t *function_instance + = allocate_ast_zero(sizeof(function_instance[0])); expect(T_func, end_error); if (token.type != T_IDENTIFIER) { - parse_error_expected("Problem while parsing concept method " + parse_error_expected("Problem while parsing concept function " "instance", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } - method_instance->source_position = source_position; - method_instance->symbol = token.v.symbol; + function_instance->source_position = source_position; + function_instance->symbol = token.v.symbol; next_token(); - parse_method(& method_instance->method); - return method_instance; + parse_function(&function_instance->function); + return function_instance; end_error: return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect('>', end_error); } instance->type_arguments = parse_type_arguments(); expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); - concept_method_instance_t *last_method = NULL; + concept_function_instance_t *last_function = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if (token.type == T_NEWLINE) { next_token(); continue; } - concept_method_instance_t *method = parse_concept_method_instance(); - if (method == NULL) + concept_function_instance_t *function = parse_concept_function_instance(); + if (function == NULL) continue; - if (last_method != NULL) { - last_method->next = method; + if (last_function != NULL) { + last_function->next = function; } else { - instance->method_instances = method; + instance->function_instances = function; } - last_method = method; + last_function = function; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; return; end_error: ; } static void skip_declaration(void) { next_token(); } static void parse_import(void) { eat(T_import); if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing import directive", T_STRING_LITERAL, 0); eat_until_anchor(); return; } symbol_t *modulename = symbol_table_insert(token.v.string); next_token(); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing import directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } import_t *import = allocate_ast_zero(sizeof(import[0])); import->module = modulename; import->symbol = token.v.symbol; import->source_position = source_position; import->next = current_context->imports; current_context->imports = import; next_token(); if (token.type != ',') break; eat(','); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_export(void) { eat(T_export); while (true) { if (token.type == T_NEWLINE) { break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if (token.type != ',') { break; } next_token(); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_module(void) { eat(T_module); /* a simple URL string without a protocol */ if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing module", T_STRING_LITERAL, 0); return; } symbol_t *new_module_name = symbol_table_insert(token.v.string); next_token(); if (current_module_name != NULL && current_module_name != new_module_name) { parser_print_error_prefix(); fprintf(stderr, "new module name '%s' overrides old name '%s'\n", new_module_name->string, current_module_name->string); } current_module_name = new_module_name; expect(T_NEWLINE, end_error); end_error: ; } void parse_declaration(void) { if (token.type < 0) { if (token.type == T_EOF) return; /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parse = NULL; if (token.type < ARR_LEN(declaration_parsers)) parse = declaration_parsers[token.type]; if (parse == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_anchor(); return; } parse(); } static void register_declaration_parsers(void) { - register_declaration_parser(parse_method_declaration, T_func); - register_declaration_parser(parse_global_variable, T_var); - register_declaration_parser(parse_constant, T_const); - register_declaration_parser(parse_struct, T_struct); - register_declaration_parser(parse_union, T_union); - register_declaration_parser(parse_typealias, T_typealias); - register_declaration_parser(parse_concept, T_concept); - register_declaration_parser(parse_concept_instance, T_instance); - register_declaration_parser(parse_export, T_export); - register_declaration_parser(parse_import, T_import); - register_declaration_parser(parse_module, T_module); - register_declaration_parser(skip_declaration, T_NEWLINE); + register_declaration_parser(parse_function_declaration, T_func); + register_declaration_parser(parse_global_variable, T_var); + register_declaration_parser(parse_constant, T_const); + register_declaration_parser(parse_struct, T_struct); + register_declaration_parser(parse_union, T_union); + register_declaration_parser(parse_typealias, T_typealias); + register_declaration_parser(parse_concept, T_concept); + register_declaration_parser(parse_concept_instance, T_instance); + register_declaration_parser(parse_export, T_export); + register_declaration_parser(parse_import, T_import); + register_declaration_parser(parse_module, T_module); + register_declaration_parser(skip_declaration, T_NEWLINE); } static module_t *get_module(symbol_t *name) { if (name == NULL) { name = symbol_table_insert(""); } /* search for an existing module */ module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } if (module == NULL) { module = allocate_ast_zero(sizeof(module[0])); module->name = name; module->next = modules; modules = module; } return module; } static void append_context(context_t *dest, const context_t *source) { declaration_t *last = dest->declarations; if (last != NULL) { while (last->base.next != NULL) { last = last->base.next; } last->base.next = source->declarations; } else { dest->declarations = source->declarations; } concept_instance_t *last_concept_instance = dest->concept_instances; if (last_concept_instance != NULL) { while (last_concept_instance->next != NULL) { last_concept_instance = last_concept_instance->next; } last_concept_instance->next = source->concept_instances; } else { dest->concept_instances = source->concept_instances; } export_t *last_export = dest->exports; if (last_export != NULL) { while (last_export->next != NULL) { last_export = last_export->next; } last_export->next = source->exports; } else { dest->exports = source->exports; } import_t *last_import = dest->imports; if (last_import != NULL) { while (last_import->next != NULL) { last_import = last_import->next; } last_import->next = source->imports; } else { dest->imports = source->imports; } } bool parse_file(FILE *in, const char *input_name) { memset(token_anchor_set, 0, sizeof(token_anchor_set)); /* get the lexer running */ lexer_init(in, input_name); next_token(); context_t file_context; memset(&file_context, 0, sizeof(file_context)); assert(current_context == NULL); current_context = &file_context; current_module_name = NULL; add_anchor_token(T_EOF); while (token.type != T_EOF) { parse_declaration(); } rem_anchor_token(T_EOF); assert(current_context == &file_context); current_context = NULL; /* append stuff to module */ module_t *module = get_module(current_module_name); append_context(&module->context, &file_context); /* check that we have matching rem_anchor_token calls for each add */ #ifndef NDEBUG for (int i = 0; i < T_LAST_TOKEN; ++i) { if (token_anchor_set[i] > 0) { panic("leaked token"); } } #endif lexer_destroy(); return !error; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); } diff --git a/semantic.c b/semantic.c index 73823ef..38f6437 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2606 +1,2613 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; -static method_t *current_method = NULL; -bool last_statement_was_return = false; +static function_t *current_function = NULL; +bool last_statement_was_return = false; static void check_and_push_context(context_t *context); -static void check_method(method_t *method, symbol_t *symbol, - const source_position_t source_position); +static void check_function(function_t *function, symbol_t *symbol, + const source_position_t source_position); -static void resolve_function_types(method_t *method); +static void resolve_function_types(function_t *function); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->base.refs == 0 && !declaration->base.exported) { switch (declaration->kind) { - /* only warn for methods/variables at the moment, we don't + /* only warn for functions/variables at the moment, we don't count refs on types yet */ - case DECLARATION_METHOD: + case DECLARATION_FUNCTION: case DECLARATION_VARIABLE: print_warning_prefix(declaration->base.source_position); fprintf(stderr, "%s '%s' was declared but never read\n", get_declaration_kind_name(declaration->kind), symbol->string); default: break; } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return type_invalid; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->base.kind = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return type_invalid; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->base.kind = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); type->size_expression = check_expression(type->size_expression); return typehash_insert((type_t*) type); } static type_t *normalize_function_type(function_type_t *function_type) { function_type->result_type = normalize_type(function_type->result_type); function_parameter_type_t *parameter = function_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) function_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->kind == TYPE_COMPOUND_STRUCT || polymorphic_type->kind == TYPE_COMPOUND_UNION); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_FUNCTION: return normalize_function_type((function_type_t*) type); case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; - method_declaration_t *method; - method_parameter_t *method_parameter; + function_declaration_t *function; + function_parameter_t *function_parameter; constant_t *constant; - concept_method_t *concept_method; + concept_function_t *concept_function; type_t *type; declaration->base.refs++; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; type = variable->type; if (type == NULL) return NULL; if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_BIND_TYPEVARIABLES || type->kind == TYPE_ARRAY) { variable->needs_entity = 1; } return type; - case DECLARATION_METHOD: - method = (method_declaration_t*) declaration; - return make_pointer_type((type_t*) method->method.type); + case DECLARATION_FUNCTION: + function = (function_declaration_t*) declaration; + return make_pointer_type((type_t*) function->function.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; - case DECLARATION_METHOD_PARAMETER: - method_parameter = (method_parameter_t*) declaration; - assert(method_parameter->type != NULL); - return method_parameter->type; - case DECLARATION_CONCEPT_METHOD: - concept_method = (concept_method_t*) declaration; - return make_pointer_type((type_t*) concept_method->type); + case DECLARATION_FUNCTION_PARAMETER: + function_parameter = (function_parameter_t*) declaration; + assert(function_parameter->type != NULL); + return function_parameter->type; + case DECLARATION_CONCEPT_FUNCTION: + concept_function = (concept_function_t*) declaration; + return make_pointer_type((type_t*) concept_function->type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); } panic("reference to unknown declaration type encountered"); } static declaration_t *create_error_declarataion(symbol_t *symbol) { declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); declaration->base.symbol = symbol; declaration->base.exported = true; return declaration; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); declaration = create_error_declarataion(symbol); } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->base.source_position); ref->base.type = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->base.refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) - * ("can't implicitely cast for argument 2 of method call...") + * ("can't implicitely cast for argument 2 of function call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->kind == TYPE_POINTER) { if (dest_type->kind == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->kind == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->kind == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->kind == TYPE_ATOMIC) { if (dest_type->kind != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = &from_type->atomic; atomic_type_kind_t from_akind = from_type_atomic->akind; atomic_type_t *dest_type_atomic = &dest_type->atomic; atomic_type_kind_t dest_akind = dest_type_atomic->akind; switch (from_akind) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_BYTE) || (dest_akind == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_USHORT) || (dest_akind == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_UINT) || (dest_akind == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_ULONG) || (dest_akind == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_ULONGLONG) || (dest_akind == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_akind == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_akind == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; type_t *righttype = right->base.type; if (lefttype->kind != TYPE_POINTER && righttype->kind != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ if (lefttype->kind == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } if (lefttype->kind == TYPE_POINTER && righttype->kind == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } -concept_method_instance_t *get_method_from_concept_instance( - concept_instance_t *instance, concept_method_t *method) +concept_function_instance_t *get_function_from_concept_instance( + concept_instance_t *instance, concept_function_t *function) { - concept_method_instance_t *method_instance = instance->method_instances; - while (method_instance != NULL) { - if (method_instance->concept_method == method) { - return method_instance; + concept_function_instance_t *function_instance + = instance->function_instances; + while (function_instance != NULL) { + if (function_instance->concept_function == function) { + return function_instance; } - method_instance = method_instance->next; + function_instance = function_instance->next; } return NULL; } -static void resolve_concept_method_instance(reference_expression_t *reference) +static void resolve_concept_function_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; - assert(declaration->kind == DECLARATION_CONCEPT_METHOD); + assert(declaration->kind == DECLARATION_CONCEPT_FUNCTION); - concept_method_t *concept_method = (concept_method_t*) declaration; - concept_t *concept = concept_method->concept; + concept_function_t *concept_function = (concept_function_t*) declaration; + concept_t *concept = concept_function->concept; /* test whether 1 of the type variables points to another type variable. - * this can happen when concept methods are invoked inside polymorphic - * methods. We can't resolve the method right now, but we have to check + * this can happen when concept functions are invoked inside polymorphic + * functions. We can't resolve the function right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " - "concept '%s' when using method '%s'.\n", + "concept '%s' when using function '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, - concept_method->base.symbol->string); + concept_function->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->base.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 - concept_method_instance_t *method_instance - = get_method_from_concept_instance(instance, concept_method); - if (method_instance == NULL) { + concept_function_instance_t *function_instance + = get_function_from_concept_instance(instance, concept_function); + if (function_instance == NULL) { print_error_prefix(reference->base.source_position); - fprintf(stderr, "no instance of method '%s' found in concept " - "instance?\n", concept_method->declaration.symbol->string); + fprintf(stderr, "no instance of function '%s' found in concept " + "instance?\n", concept_function->declaration.symbol->string); panic("panic"); } - type_t *type = (type_t*) method_instance->method.type; + type_t *type = (type_t*) function_instance->function.type; type_t *pointer_type = make_pointer_type(type); reference->base.type = pointer_type; - reference->declaration = (declaration_t*) &method_instance->method; + reference->declaration = (declaration_t*) &function_instance->function; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->base.symbol->string, concept->base.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " - "method doesn't match type constraints:\n", + "function doesn't match type constraints:\n", type_var->base.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->base.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); switch (type->kind) { case TYPE_ATOMIC: atomic_type = &type->atomic; switch (atomic_type->akind) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_FUNCTION: print_error_prefix(source_position); fprintf(stderr, "function type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return error_type; case TYPE_ERROR: return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { - call->method = check_expression(call->method); - expression_t *method = call->method; - type_t *type = method->base.type; + call->function = check_expression(call->function); + expression_t *function = call->function; + type_t *type = function->base.type; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if (type == NULL) return; - /* determine method type */ + /* determine function type */ if (type->kind != TYPE_POINTER) { print_error_prefix(call->base.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if (type->kind != TYPE_FUNCTION) { print_error_prefix(call->base.source_position); - fprintf(stderr, "trying to call a non-method value of type"); + fprintf(stderr, "trying to call a non-function value of type"); print_type(type); fprintf(stderr, "\n"); return; } function_type_t *function_type = (function_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; - if (method->kind == EXPR_REFERENCE) { + if (function->kind == EXPR_REFERENCE) { reference_expression_t *reference - = (reference_expression_t*) method; + = (reference_expression_t*) function; declaration_t *declaration = reference->declaration; - if (declaration->kind == DECLARATION_CONCEPT_METHOD) { - concept_method_t *concept_method = (concept_method_t*) declaration; - concept_t *concept = concept_method->concept; + if (declaration->kind == DECLARATION_CONCEPT_FUNCTION) { + concept_function_t *concept_function + = (concept_function_t*) declaration; + concept_t *concept = concept_function->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; - } else if (declaration->kind == DECLARATION_METHOD) { - method_declaration_t *method_declaration - = (method_declaration_t*) declaration; + } else if (declaration->kind == DECLARATION_FUNCTION) { + function_declaration_t *function_declaration + = (function_declaration_t*) declaration; - type_variables = method_declaration->method.type_parameters; + type_variables = function_declaration->function.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if (type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while (type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if (type_argument != NULL || type_var != NULL) { - error_at(method->base.source_position, - "wrong number of type arguments on method reference"); + error_at(function->base.source_position, + "wrong number of type arguments on function reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; function_parameter_type_t *param_type = function_type->parameter_types; int i = 0; while (argument != NULL) { if (param_type == NULL && !function_type->variable_arguments) { error_at(call->base.source_position, - "too much arguments for method call\n"); + "too much arguments for function call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->base.type; if (param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->base.source_position); } /* match type of argument against type variables */ if (type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->base.source_position, true); } else if (expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->base.source_position, lenient); if (new_expression == NULL) { print_error_prefix(expression->base.source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->base.type); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if (param_type != NULL) param_type = param_type->next; ++i; } if (param_type != NULL) { error_at(call->base.source_position, - "too few arguments for method call\n"); + "too few arguments for function call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while (type_var != NULL) { if (type_var->current_type == NULL) { print_error_prefix(call->base.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->base.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->base.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = function_type->result_type; if (type_variables != NULL) { - reference_expression_t *ref = (reference_expression_t*) method; + reference_expression_t *ref = (reference_expression_t*) function; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); - if (declaration->kind == DECLARATION_CONCEPT_METHOD) { - /* we might be able to resolve the concept_method_instance now */ - resolve_concept_method_instance(ref); + if (declaration->kind == DECLARATION_CONCEPT_FUNCTION) { + /* we might be able to resolve the concept_function_instance now */ + resolve_concept_function_instance(ref); - concept_method_t *concept_method = (concept_method_t*) declaration; - concept_t *concept = concept_method->concept; - type_parameters = concept->type_parameters; + concept_function_t *concept_function + = (concept_function_t*) declaration; + concept_t *concept = concept_function->concept; + type_parameters = concept->type_parameters; } else { /* check type constraints */ - assert(declaration->kind == DECLARATION_METHOD); + assert(declaration->kind == DECLARATION_FUNCTION); check_type_constraints(type_variables, call->base.source_position); - method_declaration_t *method_declaration - = (method_declaration_t*) declaration; - type_parameters = method_declaration->method.type_parameters; + function_declaration_t *function_declaration + = (function_declaration_t*) declaration; + type_parameters = function_declaration->function.type_parameters; } /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->base.type = create_concrete_type(ref->base.type); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->base.type = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->base.type == NULL) { panic("Cast expression needs a datatype!"); } cast->base.type = normalize_type(cast->base.type); cast->value = check_expression(cast->value); if (cast->value->base.type == type_void) { error_at(cast->base.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->base.type == NULL) { error_at(dereference->base.source_position, "can't derefence expression with unknown datatype\n"); return; } if (value->base.type->kind != TYPE_POINTER) { error_at(dereference->base.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->base.type; type_t *dereferenced_type = pointer_type->points_to; dereference->base.type = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->base.source_position, "can only take address of l-values\n"); return; } if (value->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->base.type = result_type; } static bool is_arithmetic_type(type_t *type) { if (type->kind != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static expression_t *lower_incdec_expression(expression_t *expression_) { unary_expression_t *expression = (unary_expression_t*) expression_; expression_t *value = check_expression(expression->value); type_t *type = value->base.type; expression_kind_t kind = expression->base.kind; if (!is_type_numeric(type) && type->kind != TYPE_POINTER) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression needs an lvalue\n", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->kind == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->akind == ATOMIC_TYPE_FLOAT || atomic_type->akind == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { constant = allocate_expression(EXPR_INT_CONST); constant->base.type = type; constant->int_const.value = 1; } else { constant = allocate_expression(EXPR_FLOAT_CONST); constant->base.type = type; constant->float_const.value = 1.0; } expression_t *add = allocate_expression(kind == EXPR_UNARY_INCREMENT ? EXPR_BINARY_ADD : EXPR_BINARY_SUB); add->base.type = type; add->binary.left = value; add->binary.right = constant; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.type = type; assign->binary.left = value; assign->binary.right = add; return assign; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type != type_bool) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->base.type; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->kind == TYPE_COMPOUND_STRUCT || datatype->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) datatype; } else { if (datatype->kind != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->kind == TYPE_COMPOUND_STRUCT || points_to->kind == TYPE_COMPOUND_UNION) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->base.source_position); select->base.type = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; if (type == NULL || (type->kind != TYPE_POINTER && type->kind != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->kind == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { - method_t *method = & expression->method; - resolve_function_types(method); - check_method(method, NULL, expression->base.source_position); + function_t *function = & expression->function; + resolve_function_types(function); + check_function(function, NULL, expression->base.source_position); - expression->base.type = make_pointer_type((type_t*) method->type); + expression->base.type = make_pointer_type((type_t*) function->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { - method_t *method = current_method; - type_t *method_result_type = method->type->result_type; + function_t *function = current_function; + type_t *function_result_type = function->type->result_type; statement->value = check_expression(statement->value); expression_t *return_value = statement->value; last_statement_was_return = true; if (return_value != NULL) { - if (method_result_type == type_void + if (function_result_type == type_void && return_value->base.type != type_void) { error_at(statement->base.source_position, - "return with value in void method\n"); + "return with value in void function\n"); return; } /* do we need a cast ?*/ - if (return_value->base.type != method_result_type) { + if (return_value->base.type != function_result_type) { return_value - = make_cast(return_value, method_result_type, + = make_cast(return_value, function_result_type, statement->base.source_position, false); statement->value = return_value; } } else { - if (method_result_type != type_void) { + if (function_result_type != type_void) { error_at(statement->base.source_position, - "missing return value in non-void method\n"); + "missing return value in non-void function\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->base.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->base.next; statement = check_statement(statement); assert(statement->base.next == next || statement->base.next == NULL); statement->base.next = next; if (last != NULL) { last->base.next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(declaration_statement_t *statement) { - method_t *method = current_method; - assert(method != NULL); + function_t *function = current_function; + assert(function != NULL); - statement->declaration.value_number = method->n_local_vars; - method->n_local_vars++; + statement->declaration.value_number = function->n_local_vars; + function->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.base.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->base.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->base.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->kind < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->kind]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->kind) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement(&statement->block); break; case STATEMENT_RETURN: check_return_statement(&statement->returns); break; case STATEMENT_GOTO: check_goto_statement(&statement->gotos); break; case STATEMENT_LABEL: check_label_statement(&statement->label); break; case STATEMENT_IF: check_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: check_variable_declaration(&statement->declaration); break; case STATEMENT_EXPRESSION: check_expression_statement(&statement->expression); break; default: panic("Unknown statement found"); break; } return statement; } -static void check_method(method_t *method, symbol_t *symbol, - const source_position_t source_position) +static void check_function(function_t *function, symbol_t *symbol, + const source_position_t source_position) { - if (method->is_extern) + if (function->is_extern) return; int old_top = environment_top(); - push_context(&method->context); + push_context(&function->context); - method_t *last_method = current_method; - current_method = method; + function_t *last_function = current_function; + current_function = function; - /* set method parameter numbers */ - method_parameter_t *parameter = method->parameters; + /* set function parameter numbers */ + function_parameter_t *parameter = function->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; - if (method->statement != NULL) { - method->statement = check_statement(method->statement); + if (function->statement != NULL) { + function->statement = check_statement(function->statement); } if (!last_statement_was_return) { - type_t *result_type = method->type->result_type; + type_t *result_type = function->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } - current_method = last_method; + current_function = last_function; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } -static void resolve_function_types(method_t *method) +static void resolve_function_types(function_t *function) { int old_top = environment_top(); /* push type variables */ - push_context(&method->context); - resolve_type_variable_constraints(method->type_parameters); + push_context(&function->context); + resolve_type_variable_constraints(function->type_parameters); /* normalize parameter types */ - method_parameter_t *parameter = method->parameters; + function_parameter_t *parameter = function->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } - method->type = (function_type_t*) normalize_type((type_t*) method->type); + function->type = (function_type_t*) normalize_type((type_t*)function->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { - concept_method_instance_t *method_instance = instance->method_instances; - while (method_instance != NULL) { - method_t *method = &method_instance->method; - resolve_function_types(method); - check_method(method, method_instance->symbol, - method_instance->source_position); + concept_function_instance_t *function_instance + = instance->function_instances; + while (function_instance != NULL) { + function_t *function = &function_instance->function; + resolve_function_types(function); + check_function(function, function_instance->symbol, + function_instance->source_position); - method_instance = method_instance->next; + function_instance = function_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); - /* normalize method types */ - concept_method_t *concept_method = concept->methods; - for ( ; concept_method != NULL; concept_method = concept_method->next) { + /* normalize function types */ + concept_function_t *concept_function = concept->functions; + for (; concept_function!=NULL; concept_function = concept_function->next) { type_t *normalized_type - = normalize_type((type_t*) concept_method->type); + = normalize_type((type_t*) concept_function->type); assert(normalized_type->kind == TYPE_FUNCTION); - concept_method->type = (function_type_t*) normalized_type; + concept_function->type = (function_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } - /* link methods and normalize their types */ - size_t n_concept_methods = 0; - concept_method_t *method; - for (method = concept->methods; method != NULL; method = method->next) { - ++n_concept_methods; + /* link functions and normalize their types */ + size_t n_concept_functions = 0; + concept_function_t *function = concept->functions; + for ( ; function != NULL; function = function->next) { + ++n_concept_functions; } - bool have_method[n_concept_methods]; - memset(&have_method, 0, sizeof(have_method)); + bool have_function[n_concept_functions]; + memset(&have_function, 0, sizeof(have_function)); - concept_method_instance_t *method_instance; - for (method_instance = instance->method_instances; method_instance != NULL; - method_instance = method_instance->next) { + concept_function_instance_t *function_instance + = instance->function_instances; + for (; function_instance != NULL; + function_instance = function_instance->next) { - /* find corresponding concept method */ + /* find corresponding concept function */ int n = 0; - for (method = concept->methods; method != NULL; - method = method->next, ++n) { - if (method->base.symbol == method_instance->symbol) + for (function = concept->functions; function != NULL; + function = function->next, ++n) { + if (function->base.symbol == function_instance->symbol) break; } - if (method == NULL) { - print_warning_prefix(method_instance->source_position); - fprintf(stderr, "concept '%s' does not declare a method '%s'\n", + if (function == NULL) { + print_warning_prefix(function_instance->source_position); + fprintf(stderr, "concept '%s' does not declare a function '%s'\n", concept->base.symbol->string, - method->base.symbol->string); + function->base.symbol->string); } else { - method_instance->concept_method = method; - method_instance->concept_instance = instance; - if (have_method[n]) { - print_error_prefix(method_instance->source_position); - fprintf(stderr, "multiple implementations of method '%s' found " - "in instance of concept '%s'\n", - method->base.symbol->string, + function_instance->concept_function = function; + function_instance->concept_instance = instance; + if (have_function[n]) { + print_error_prefix(function_instance->source_position); + fprintf(stderr, + "multiple implementations of function '%s' found in instance of concept '%s'\n", + function->base.symbol->string, concept->base.symbol->string); } - have_method[n] = true; + have_function[n] = true; } - method_t *imethod = & method_instance->method; + function_t *ifunction = & function_instance->function; - if (imethod->type_parameters != NULL) { - print_error_prefix(method_instance->source_position); - fprintf(stderr, "instance method '%s' must not have type parameters\n", - method_instance->symbol->string); + if (ifunction->type_parameters != NULL) { + print_error_prefix(function_instance->source_position); + fprintf(stderr, + "instance function '%s' must not have type parameters\n", + function_instance->symbol->string); } - imethod->type - = (function_type_t*) normalize_type((type_t*) imethod->type); + ifunction->type + = (function_type_t*) normalize_type((type_t*) ifunction->type); } size_t n = 0; - for (method = concept->methods; method != NULL; - method = method->next, ++n) { - if (!have_method[n]) { + for (function = concept->functions; function != NULL; + function = function->next, ++n) { + if (!have_function[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " - "method '%s'\n", concept->base.symbol->string, - method->base.symbol->string); + "function '%s'\n", concept->base.symbol->string, + function->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } declaration->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; - case DECLARATION_METHOD: - resolve_function_types(&declaration->method.method); + case DECLARATION_FUNCTION: + resolve_function_types(&declaration->function.function); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->kind == TYPE_COMPOUND_UNION || type->kind == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } - /* check semantics in methods */ + /* check semantics in functions */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { - case DECLARATION_METHOD: { - check_method(&declaration->method.method, declaration->base.symbol, - declaration->base.source_position); + case DECLARATION_FUNCTION: { + check_function(&declaration->function.function, + declaration->base.symbol, + declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } static declaration_t *find_declaration(const context_t *context, symbol_t *symbol) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } return declaration; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; declaration_t *declaration; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); declaration = create_error_declarataion(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); declaration = create_error_declarataion(symbol); } else { check_module(ref_module); declaration = find_declaration(&ref_module->context, symbol); if (declaration == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); declaration = create_error_declarataion(symbol); } else { ref_context = &ref_module->context; } } } if (!declaration->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->declaration == declaration) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(declaration, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/semantic.h b/semantic.h index 8c5c5b0..292049b 100644 --- a/semantic.h +++ b/semantic.h @@ -1,18 +1,18 @@ #ifndef SEMANTIC_H #define SEMANTIC_H #include "ast.h" /* check static semantic of a bunch of files and organize them into modules * if semantic is fine */ bool check_semantic(void); concept_instance_t *find_concept_instance(concept_t *concept); -concept_method_instance_t *get_method_from_concept_instance( - concept_instance_t *instance, concept_method_t *method); +concept_function_instance_t *get_function_from_concept_instance( + concept_instance_t *instance, concept_function_t *function); void init_semantic_module(void); void exit_semantic_module(void); #endif
MatzeB/fluffy
35a979817093ec09ac360e3e08d5a519da631eef
docu cleanup, moving around
diff --git a/DESIGN b/DESIGN deleted file mode 100644 index b6e9f62..0000000 --- a/DESIGN +++ /dev/null @@ -1,31 +0,0 @@ -- Input: utf-8 -- python like indentation to form blocks, but force user to either use spaces or tabs to indent - -- Only 1 hierarchic namespace (so 1 name specifies alway the same thing, - independent of the context; Different things might be defined in the - hierarchy) - - -To-Design: - -Namespacing: - - How to handle modules, imports, exports, libraries? - - Should we have file-local things? - == Modules == - Each file belongs to exactly 1 module. If there's no module specified then - stuff will go to the anonymous "main" module. - - Modules are specified by the module command. - Modulenames are a URL without the protocol part or optionally protocol - "fluffymodule://" - - All files of a module have to be compiled together. - - A recommendataion for naming is using internet urls: - module fluffy.org/stdlib - - (Practical question 1: should we allow all possible strings? Or just - stuff which is allowed in filenames?) - - - Think about a 2nd model where all files in a directory form a module - with a separate module description file in the directory... diff --git a/docs/design.txt b/docs/design.txt new file mode 100644 index 0000000..ecdf604 --- /dev/null +++ b/docs/design.txt @@ -0,0 +1,70 @@ + Design Scratchpad + +Input Files: + - UTF-8 should be the default to avoid most encoding troubles. + (Maybe add explicit way to override this for exceptional cases) + - File Extension? .fluffy for now + - Think about a recommded standard for file naming/hierarchy. Similar to + javas directory hierarchy equals package hierarchy, filename==classname + thing. Build tools and IDEs can then work with this standard and make + it considerably easier to setup new projects/build foreign ones. + (Basing this on pure filesystem hierarchy also avoids new configuration + or buildfile specification that noone wants to deal with) + +Layout: + - Default mode is python like. Only difference is that we explicitely + differentiate between tab and space indentation. Mixing these gives an + error, to avoid the typical problems when editing python source and + not having your editor set to tab=8 spaces. + (Example: if a line is indented with 2 spaces, then the next line + may be indented with 0 or 1 space, or 2 spaces + any number of spaces + and tabs. What is not allowed it having a tab(+space) or space+tab + indentation in that next line) + +Contexts: + - What is a context? A Name+A Context gives a semantic meaning to a language + construct. + - Try to avoid having multiple "namespaces" depending only on the usage. + (= Types, Variables should be in the same namespace so you cannot have a + type and a variable with the same name in the same namespace nesting + level) + +Concepts/Instances: + - Concept functions should go to the default namespace (do we want an + additional mode where they are availble under a special name only?) + - Determining the concept instance from the calling type is very usefull + - But we probably also want named concept instances. We would then need + a way to call these explicitely and/or bind them to the current context. + (Which brings us back to the question what is a context?) + - Shouldn't we rather call it implementation instead of instance? + +Coroutine Support: + - To avoid complications with a 2nd stack in the coroutine datastructure, + yield is only allowed at the coroutine itself (you can't call a function + which yields) + - A coroutine supports producing (typed) values with each yield + - A coroutine needs a way to signal the end of a coroutine vs. a yield. + In the coroutine code this would be yield vs. return. + How would one go about this when using the coroutine? + +Namespacing: + - How to handle modules, imports, exports, libraries? + - Is there a concept of file-local? module-local? global? + == Modules == + Each file belongs to exactly 1 module. If there's no module specified then + stuff will go to the anonymous "main" module. + + Modules are specified by the module command. + Modulenames are a URL without the protocol part or optionally protocol + "fluffymodule://" + + All files of a module have to be compiled together. + + A recommendataion for naming is using internet urls: + module fluffy.org/stdlib + + (Practical question 1: should we allow all possible strings? Or just + stuff which is allowed in filenames?) + + - Think about a 2nd model where all files in a directory form a module + with a separate module description file in the directory... diff --git a/docs/manifest.txt b/docs/manifest.txt new file mode 100644 index 0000000..cc7e099 --- /dev/null +++ b/docs/manifest.txt @@ -0,0 +1,66 @@ +#Goal# + - Enable programmers to write efficient code, our first target is being + an alternative to C/C++. Which means playing nice in the unix/mac/windows + world and their exising C libraries. + - lean and modern: Don't introduce complicated constructs to keep (backward) + compatible with other stuff. + - Play nice with others: Enable and support bridges to the rest of the world + (but remember the "be modern" rule) + +#Programming World# + - Projects are driven by multiple developers. They have a compositional + nature where each developer is responsible for his part. + This project division can happen at multiple levels. Horizontally + or vertically (heh what does this really mean... I guess mostly that there + should be multiple dimensions that allow extending/composing a program) + - At the places where developers interact communication starts. We should + have strong possibilities to document, hint and specify public information + (making it easy to keep it in sync with the real stuff is also important + to keep the information usefull). This is the most important part to + avoid errors. A way to specify invariants is also helpfull. Maybe also + a way to specify "smells" for possible wrong usage, where an invariant + would be too strong. + - Some code becomes a commodity (logging, file system access, + container classes, http protocol, xml parsing, ...). + Provide way to easily specify, locate and use implementations of these + codes to start a process where such code is maintained and developed + in an open source fashion so everybody benefits (Look at how nice linux + package managers work for open source software). + +#Productivity# + - Make it hard to produce accidental errors by: + * Enable the compiler to warn/check static invariants where possible. + This needs more discussion to what extend the type system should be + employed here. In what way we allow people to annotate their libraries + to hint at correct library usage. + (Bad example: C/printf fails if format string doesn't match the + arguments. Without the compiler being able to tell most of the times. + Another C example: Catching too small buffers in strncat, snprintf) + * Disallow some standard notations (but make sure there are easy + workarounds to do the same with a bit more typing maybe). Example: + if a = b: should be disallowed because its a common type for + if a == b: as a workaround we should allow if (a = b): + * Limit implicit effects. Make things explicit where possible + try to be short, as much typing is painfull. Just don't use the + shorter syntax if it introduces too much implicit stuff. + (A really bad example here is pearl with all its $', $`, etc. + variables getting defined implicitely, variable assignment is + an important semantic thing and should never happen without an + explicit syntax). + +#Language Implementation# + - Keep the language simple. We want to stimulate 3rd parties to provide + tools and support for our language: IDEs, ports to new architectures, + competing compiler implementations, refactoring tools, build tools, + editors. Some ways we try to achieve this: + * Make the language fit into the SLL(k) category so parsers are + easy to write. (Helps refactoring tools) + * Try hard to put stuff into libraries instead of the core language + (only generic support for libraries needed in 3rd party tools) + * Have a simple core language and a way to transform complicated + language constructs ("syntactic sugar") into this core language + (helps program analysis, comprehension tools) + Take care to identify things for the core language, and stuff for + libraries + + diff --git a/docs/vision.txt b/docs/vision.txt new file mode 100644 index 0000000..3272608 --- /dev/null +++ b/docs/vision.txt @@ -0,0 +1,44 @@ +- Try to preserve the things C did well +- Be compatible with C play nice in the linux/unix/macos world + - make it easy to create wrappers for C libraries + - provide lots of prepared wrappers +- If the programmer wants maximum speed, give him maximum speed +- If the programmer wants control over resources, give it to him +- Make it hard to fall into common pitfalls +- Don't make it impossible to do things because of this +- Always offer a fast way if the prohibiting errors costs speed +- Make it simple to pickup other projects (build, dependencies, ...) +- Simple things should be simple +- Keep the language simple, move stuff into the library where possible +- Have example programs ready when deciding what to add to the language +- When adding stuff to the language try to make it generic +- But don't make the constructs verbose +- While not unnecessarily abreviating +- Avoid implicit effects +- Macros and Language extensions are nice to have +- Unless they prohibit language tools (refactoring, etc.) +- Side effects are pragmatic +- Pure code is pragmatic if the programmer wants it that way +- A good and comprehensive standard library is important +- When adding stuff to the standard library prefer it in this order: + - simple + generic + - usefull + - efficient +- There are several usefull programming paradigms: + Algorithmic: + - pure functions, functions as first-class objects + - map/reduce stuff + - matching list manipulation + Reusable Code: + - Generic Programming (type-classes) + - Object Oriented Programming (mixins) + - Module/Library System + Efficient Code: + - pointers + - arbitrary side-effects + - "atomic" operations + Safe Code: + - Garbage Collection? + - Array Bound Checks? + - Type Qualifiers? + - Custom restricted Types diff --git a/test/wip/coroutine.fluffy b/test/wip/coroutine.fluffy new file mode 100644 index 0000000..12f8e06 --- /dev/null +++ b/test/wip/coroutine.fluffy @@ -0,0 +1,4 @@ +// 2 actors... + +coroutine actor1(): + diff --git a/test/wip/newsyntax.fluffy b/test/wip/newsyntax.fluffy new file mode 100644 index 0000000..c47a410 --- /dev/null +++ b/test/wip/newsyntax.fluffy @@ -0,0 +1,4 @@ +c = 5 +foo = func(a : int, b : float) : int: + // ... +
MatzeB/fluffy
0398a10d671bfe79bf46fa4f8299800c7d7eeb22
refactoring: transform type_t to a union
diff --git a/TODO b/TODO index 4edfb98..7cad6bc 100644 --- a/TODO +++ b/TODO @@ -1,26 +1,25 @@ This does not describe the goals and visions but short term things that should not be forgotten. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime - forbid same variable names in nested blocks (really?) - change firm to pass on debug info on unitialized_variable callback - introduce const type qualifier Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Add an alloca operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) Refactorings (mindless but often labor intensive tasks): -- make unions for type_t (see cparser), rename type->type to type->kind - keep typerefs as long as possible (start the skip_typeref madness similar to cparser) diff --git a/ast2firm.c b/ast2firm.c index 5dd7842..11b2c89 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1955 +1,1955 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_method_t instantiate_method_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_method_t { method_t *method; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_methods; static pdeq *instantiate_methods = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = (const declaration_t*) &value_numbers[pos]; print_warning_prefix(declaration->base.source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->base.symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { } static void init_ir_types(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); - byte_type.type.type = TYPE_ATOMIC; - byte_type.atype = ATOMIC_TYPE_BYTE; + byte_type.base.kind = TYPE_ATOMIC; + byte_type.akind = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { - switch (atomic_type->atype) { + switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { - switch (type->atype) { + switch (type->akind) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { - ir_type *irtype = get_ir_type(&type->type); + ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { - ir_type *irtype = get_ir_type(&type->type); + ir_type *irtype = get_ir_type((type_t*) type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { - switch (type->type) { + switch (type->kind) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); - int n_results = result_type->type == TYPE_VOID ? 0 : 1; + int n_results = result_type->kind == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); - if (result_type->type != TYPE_VOID) { + if (result_type->kind != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); - type->type.firm_type = ir_type; + type->base.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_node *expression_to_firm(expression_t *expression); static tarval *fold_constant_to_tarval(expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } tarval* tv = get_Const_tarval(cnst); return tv; } long fold_constant_to_int(expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); - type->type.firm_type = ir_type; + type->base.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); - type->type.firm_type = ir_type; + type->base.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); - type->type.firm_type = class_ir_type; + type->base.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->kind == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->kind != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = declaration->base.symbol; ident *ident = new_id_from_str(symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { - assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); + assert(ref->base.kind == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); - if (type->firm_type != NULL) { - assert(type->firm_type != INVALID_TYPE); - return type->firm_type; + if (type->base.firm_type != NULL) { + assert(type->base.firm_type != INVALID_TYPE); + return type->base.firm_type; } ir_type *firm_type = NULL; - switch (type->type) { + switch (type->kind) { case TYPE_ATOMIC: - firm_type = get_atomic_type(env, (atomic_type_t*) type); + firm_type = get_atomic_type(env, &type->atomic); break; case TYPE_METHOD: - firm_type = get_method_type(env, (method_type_t*) type); + firm_type = get_method_type(env, &type->method); break; case TYPE_POINTER: - firm_type = get_pointer_type(env, (pointer_type_t*) type); + firm_type = get_pointer_type(env, &type->pointer); break; case TYPE_ARRAY: - firm_type = get_array_type(env, (array_type_t*) type); + firm_type = get_array_type(env, &type->array); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: - firm_type = get_struct_type(env, (compound_type_t*) type); + firm_type = get_struct_type(env, &type->compound); break; case TYPE_COMPOUND_UNION: - firm_type = get_union_type(env, (compound_type_t*) type); + firm_type = get_union_type(env, &type->compound); break; case TYPE_COMPOUND_CLASS: - firm_type = get_class_type(env, (compound_type_t*) type); + firm_type = get_class_type(env, &type->compound); break; case TYPE_REFERENCE_TYPE_VARIABLE: - firm_type = get_type_for_type_variable(env, (type_reference_t*) type); + firm_type = get_type_for_type_variable(env, &type->reference); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, - (bind_typevariables_type_t*) type); + &type->bind_typevariables); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { - type->firm_type = firm_type; + type->base.firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_method->base.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; - if (type->type == TYPE_COMPOUND_STRUCT - || type->type == TYPE_COMPOUND_UNION - || type->type == TYPE_COMPOUND_CLASS - || type->type == TYPE_BIND_TYPEVARIABLES - || type->type == TYPE_ARRAY) { + if (type->kind == TYPE_COMPOUND_STRUCT + || type->kind == TYPE_COMPOUND_UNION + || type->kind == TYPE_COMPOUND_CLASS + || type->kind == TYPE_BIND_TYPEVARIABLES + || type->kind == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch (declaration->kind) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; - if (type->type == TYPE_COMPOUND_STRUCT - || type->type == TYPE_COMPOUND_UNION) { + if (type->kind == TYPE_COMPOUND_STRUCT + || type->kind == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static long binexpr_kind_to_cmp_pn(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; case EXPR_BINARY_LESS: return pn_Cmp_Lt; case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; case EXPR_BINARY_GREATER: return pn_Cmp_Gt; case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ long compare_pn = binexpr_kind_to_cmp_pn(kind); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; - if (entry_type->type == TYPE_COMPOUND_STRUCT - || entry_type->type == TYPE_COMPOUND_UNION - || entry_type->type == TYPE_ARRAY) + if (entry_type->kind == TYPE_COMPOUND_STRUCT + || entry_type->kind == TYPE_COMPOUND_UNION + || entry_type->kind == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(declaration_t *declaration, type_argument_t *type_arguments) { assert(declaration->kind == DECLARATION_METHOD); method_t *method = &declaration->method.method; symbol_t *symbol = declaration->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); if (declaration->base.exported && get_entity_visibility(entity) != visibility_external_allocated) { set_entity_visibility(entity, visibility_external_visible); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(declaration, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); - assert(method->base.type->type == TYPE_POINTER); + assert(method->base.type->kind == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->base.type; type_t *points_to = pointer_type->points_to; - assert(points_to->type == TYPE_METHOD); + assert(points_to->kind == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; - if (result_type->type != TYPE_VOID) { + if (result_type->kind != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(declaration, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->base.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *ret; if (statement->value != NULL) { ir_node *retval = expression_to_firm(statement->value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->base.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->kind) { case STATEMENT_BLOCK: block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: if_statement_to_firm(&statement->ifs); return; case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: if (!is_polymorphic_method(&declaration->method.method)) { assure_instance(declaration, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/mangle.c b/mangle.c index a601659..b11d654 100644 --- a/mangle.c +++ b/mangle.c @@ -1,230 +1,230 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" #include "type_t.h" #include "adt/error.h" #include <libfirm/firm.h> #include "driver/firm_cmdline.h" static struct obstack obst; static void mangle_string(const char *str) { size_t len = strlen(str); obstack_grow(&obst, str, len); } static void mangle_len_string(const char *string) { size_t len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); } static void mangle_atomic_type(const atomic_type_t *type) { char c; - switch (type->atype) { + switch (type->akind) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(&obst, c); } static void mangle_type_variables(type_variable_t *type_variables) { type_variable_t *type_variable = type_variables; for ( ; type_variable != NULL; type_variable = type_variable->next) { /* is this a good char? */ obstack_1grow(&obst, 'T'); mangle_type(type_variable->current_type); } } static void mangle_compound_type(const compound_type_t *type) { mangle_len_string(type->symbol->string); mangle_type_variables(type->type_parameters); } static void mangle_pointer_type(const pointer_type_t *type) { obstack_1grow(&obst, 'P'); mangle_type(type->points_to); } static void mangle_array_type(const array_type_t *type) { obstack_1grow(&obst, 'A'); mangle_type(type->element_type); int size = fold_constant_to_int(type->size_expression); obstack_printf(&obst, "%lu", size); } static void mangle_method_type(const method_type_t *type) { obstack_1grow(&obst, 'F'); mangle_type(type->result_type); method_parameter_type_t *parameter_type = type->parameter_types; while (parameter_type != NULL) { mangle_type(parameter_type->type); } obstack_1grow(&obst, 'E'); } static void mangle_reference_type_variable(const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if (current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(current_type); } static void mangle_bind_typevariables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); mangle_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void mangle_type(const type_t *type) { - switch (type->type) { + switch (type->kind) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(&obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type((const atomic_type_t*) type); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; mangle_type(typeof_type->expression->base.type); return; } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: mangle_method_type((const method_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: mangle_bind_typevariables((const bind_typevariables_type_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable((const type_reference_t*) type); return; case TYPE_ERROR: panic("trying to mangle error type"); } panic("Unknown type mangled"); } void mangle_symbol_simple(symbol_t *symbol) { mangle_string(symbol->string); } void mangle_symbol(symbol_t *symbol) { mangle_len_string(symbol->string); } void mangle_concept_name(symbol_t *symbol) { obstack_grow(&obst, "tcv", 3); mangle_len_string(symbol->string); } void start_mangle(void) { if (firm_opt.os_support == OS_SUPPORT_MACHO || firm_opt.os_support == OS_SUPPORT_MINGW) { obstack_1grow(&obst, '_'); } } ident *finish_mangle(void) { size_t size = obstack_object_size(&obst); char *str = obstack_finish(&obst); ident *id = new_id_from_chars(str, size); obstack_free(&obst, str); return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/match_type.c b/match_type.c index 52f77be..eb5d4cb 100644 --- a/match_type.c +++ b/match_type.c @@ -1,234 +1,234 @@ #include <config.h> #include "match_type.h" #include <assert.h> #include "type_t.h" #include "ast_t.h" #include "semantic_t.h" #include "type_hash.h" #include "adt/error.h" static inline void match_error(type_t *variant, type_t *concrete, const source_position_t source_position) { print_error_prefix(source_position); fprintf(stderr, "can't match variant type "); print_type(variant); fprintf(stderr, " against "); print_type(concrete); fprintf(stderr, "\n"); } static bool matched_type_variable(type_variable_t *type_variable, type_t *type, const source_position_t source_position, bool report_errors) { type_t *current_type = type_variable->current_type; if (current_type != NULL && current_type != type) { if (report_errors) { print_error_prefix(source_position); fprintf(stderr, "ambiguous matches found for type variable '%s': ", type_variable->base.symbol->string); print_type(current_type); fprintf(stderr, ", "); print_type(type); fprintf(stderr, "\n"); } /* are both types normalized? */ assert(typehash_contains(current_type)); assert(typehash_contains(type)); return false; } type_variable->current_type = type; return true; } static bool match_compound_type(compound_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_variable_t *type_parameters = variant_type->type_parameters; if (type_parameters == NULL) { if (concrete_type != (type_t*) variant_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } return true; } - if (concrete_type->type != TYPE_BIND_TYPEVARIABLES) { + if (concrete_type->kind != TYPE_BIND_TYPEVARIABLES) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if (polymorphic_type != variant_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = bind_typevariables->type_arguments; bool result = true; while (type_parameter != NULL) { assert(type_argument != NULL); if (!matched_type_variable(type_parameter, type_argument->type, source_position, true)) result = false; type_parameter = type_parameter->next; type_argument = type_argument->next; } return result; } static bool match_bind_typevariables(bind_typevariables_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { - if (concrete_type->type != TYPE_BIND_TYPEVARIABLES) { + if (concrete_type->kind != TYPE_BIND_TYPEVARIABLES) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if (polymorphic_type != variant_type->polymorphic_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_argument_t *argument1 = variant_type->type_arguments; type_argument_t *argument2 = bind_typevariables->type_arguments; bool result = true; while (argument1 != NULL) { assert(argument2 != NULL); if (!match_variant_to_concrete_type(argument1->type, argument2->type, source_position, report_errors)) result = false; argument1 = argument1->next; argument2 = argument2->next; } assert(argument2 == NULL); return result; } bool match_variant_to_concrete_type(type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_reference_t *type_ref; type_variable_t *type_var; pointer_type_t *pointer_type_1; pointer_type_t *pointer_type_2; method_type_t *method_type_1; method_type_t *method_type_2; assert(type_valid(variant_type)); assert(type_valid(concrete_type)); variant_type = skip_typeref(variant_type); concrete_type = skip_typeref(concrete_type); - switch (variant_type->type) { + switch (variant_type->kind) { case TYPE_REFERENCE_TYPE_VARIABLE: type_ref = (type_reference_t*) variant_type; type_var = type_ref->type_variable; return matched_type_variable(type_var, concrete_type, source_position, report_errors); case TYPE_VOID: case TYPE_ATOMIC: if (concrete_type != variant_type) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return true; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return match_compound_type((compound_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_POINTER: - if (concrete_type->type != TYPE_POINTER) { + if (concrete_type->kind != TYPE_POINTER) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } pointer_type_1 = (pointer_type_t*) variant_type; pointer_type_2 = (pointer_type_t*) concrete_type; return match_variant_to_concrete_type(pointer_type_1->points_to, pointer_type_2->points_to, source_position, report_errors); case TYPE_METHOD: - if (concrete_type->type != TYPE_METHOD) { + if (concrete_type->kind != TYPE_METHOD) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } method_type_1 = (method_type_t*) variant_type; method_type_2 = (method_type_t*) concrete_type; bool result = match_variant_to_concrete_type(method_type_1->result_type, method_type_2->result_type, source_position, report_errors); method_parameter_type_t *param1 = method_type_1->parameter_types; method_parameter_type_t *param2 = method_type_2->parameter_types; while (param1 != NULL && param2 != NULL) { if (!match_variant_to_concrete_type(param1->type, param2->type, source_position, report_errors)) result = false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return result; case TYPE_BIND_TYPEVARIABLES: return match_bind_typevariables( (bind_typevariables_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_ARRAY: panic("TODO"); case TYPE_ERROR: return false; case TYPE_TYPEOF: case TYPE_REFERENCE: panic("type reference not resolved in match variant to concrete type"); case TYPE_INVALID: panic("invalid type in match variant to concrete type"); } panic("unknown type in match variant to concrete type"); } diff --git a/parser.c b/parser.c index 96f3589..f7b9489 100644 --- a/parser.c +++ b/parser.c @@ -1,2462 +1,2460 @@ #include <config.h> #include "token_t.h" #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers; static parse_statement_function *statement_parsers; static parse_declaration_function *declaration_parsers; static parse_attribute_function *attribute_parsers; static unsigned char token_anchor_set[T_LAST_TOKEN]; static symbol_t *current_module_name; static context_t *current_context; static int error = 0; token_t token; module_t *modules; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_declaration_struct_size(declaration_kind_t kind) { static const size_t sizes[] = { [DECLARATION_ERROR] = sizeof(declaration_base_t), [DECLARATION_METHOD] = sizeof(method_declaration_t), [DECLARATION_METHOD_PARAMETER] = sizeof(method_parameter_t), [DECLARATION_ITERATOR] = sizeof(iterator_declaration_t), [DECLARATION_VARIABLE] = sizeof(variable_declaration_t), [DECLARATION_CONSTANT] = sizeof(constant_t), [DECLARATION_TYPE_VARIABLE] = sizeof(type_variable_t), [DECLARATION_TYPEALIAS] = sizeof(typealias_t), [DECLARATION_CONCEPT] = sizeof(concept_t), [DECLARATION_CONCEPT_METHOD] = sizeof(concept_method_t), [DECLARATION_LABEL] = sizeof(label_declaration_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } declaration_t *allocate_declaration(declaration_kind_t kind) { size_t size = get_declaration_struct_size(kind); declaration_t *declaration = allocate_ast_zero(size); declaration->kind = kind; return declaration; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { [EXPR_ERROR] = sizeof(expression_base_t), [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } static size_t get_statement_struct_size(statement_kind_t kind) { static const size_t sizes[] = { [STATEMENT_ERROR] = sizeof(statement_base_t), [STATEMENT_BLOCK] = sizeof(block_statement_t), [STATEMENT_RETURN] = sizeof(return_statement_t), [STATEMENT_DECLARATION] = sizeof(declaration_statement_t), [STATEMENT_IF] = sizeof(if_statement_t), [STATEMENT_EXPRESSION] = sizeof(expression_statement_t), [STATEMENT_GOTO] = sizeof(goto_statement_t), [STATEMENT_LABEL] = sizeof(label_statement_t), }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; }; static statement_t *allocate_statement(statement_kind_t kind) { size_t size = get_statement_struct_size(kind); statement_t *statement = allocate_ast_zero(size); statement->kind = kind; return statement; } -static inline void *allocate_type_zero(size_t size) +static size_t get_type_struct_size(type_kind_t kind) { - void *res = obstack_alloc(type_obst, size); - memset(res, 0, size); - return res; + static const size_t sizes[] = { + [TYPE_ERROR] = sizeof(type_base_t), + [TYPE_VOID] = sizeof(type_base_t), + [TYPE_ATOMIC] = sizeof(atomic_type_t), + [TYPE_COMPOUND_CLASS] = sizeof(compound_type_t), + [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t), + [TYPE_COMPOUND_UNION] = sizeof(compound_type_t), + [TYPE_METHOD] = sizeof(method_type_t), + [TYPE_POINTER] = sizeof(pointer_type_t), + [TYPE_ARRAY] = sizeof(array_type_t), + [TYPE_TYPEOF] = sizeof(typeof_type_t), + [TYPE_REFERENCE] = sizeof(type_reference_t), + [TYPE_REFERENCE_TYPE_VARIABLE] = sizeof(type_reference_t), + [TYPE_BIND_TYPEVARIABLES] = sizeof(bind_typevariables_type_t) + }; + assert(kind < sizeof(sizes)/sizeof(sizes[0])); + assert(sizes[kind] != 0); + return sizes[kind]; +} + +type_t *allocate_type(type_kind_t kind) +{ + size_t size = get_type_struct_size(kind); + type_t *type = obstack_alloc(type_obst, size); + memset(type, 0, size); + type->kind = kind; + return type; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters); -static atomic_type_type_t parse_unsigned_atomic_type(void) +static atomic_type_kind_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } -static atomic_type_type_t parse_signed_atomic_type(void) +static atomic_type_kind_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { - atomic_type_type_t atype; + atomic_type_kind_t akind; switch (token.type) { case T_unsigned: next_token(); - atype = parse_unsigned_atomic_type(); + akind = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: - atype = parse_signed_atomic_type(); + akind = parse_signed_atomic_type(); break; } - atomic_type_t *type = allocate_type_zero(sizeof(type[0])); - type->type.type = TYPE_ATOMIC; - type->atype = atype; + type_t *type = allocate_type(TYPE_ATOMIC); + type->atomic.akind = akind; - type_t *result = typehash_insert((type_t*) type); - if (result != (type_t*) type) { + type_t *result = typehash_insert(type); + if (result != type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { - typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); - typeof_type->type.type = TYPE_TYPEOF; + type_t *type = allocate_type(TYPE_TYPEOF); eat(T_typeof); expect('(', end_error); add_anchor_token(')'); - typeof_type->expression = parse_expression(); + type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: - return (type_t*) typeof_type; + return type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); - type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); - - type_ref->type.type = TYPE_REFERENCE; - type_ref->symbol = token.v.symbol; - type_ref->source_position = source_position; + type_t *type = allocate_type(TYPE_REFERENCE); + type->reference.symbol = token.v.symbol; + type->reference.source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); - type_ref->type_arguments = parse_type_arguments(); + type->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: - return (type_t*) type_ref; + return type; } static type_t *create_error_type(void) { - type_t *error_type = allocate_type_zero(sizeof(error_type[0])); - error_type->type = TYPE_ERROR; - return error_type; + return allocate_type(TYPE_ERROR); } static type_t *parse_method_type(void) { eat(T_func); - method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); - method_type->type.type = TYPE_METHOD; + type_t *type = allocate_type(TYPE_METHOD); - parse_parameter_declarations(method_type, NULL); + parse_parameter_declarations(&type->method, NULL); expect(':', end_error); - method_type->result_type = parse_type(); + type->method.result_type = parse_type(); - return (type_t*) method_type; + return type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); - compound_type_t *compound_type - = allocate_ast_zero(sizeof(compound_type[0])); - compound_type->type.type = TYPE_COMPOUND_UNION; - compound_type->attributes = parse_attributes(); + type_t *type = allocate_type(TYPE_COMPOUND_UNION); + type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); - compound_type->entries = parse_compound_entries(); + type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: - return (type_t*) compound_type; + return type; } static type_t *parse_struct_type(void) { eat(T_struct); - compound_type_t *compound_type - = allocate_ast_zero(sizeof(compound_type[0])); - compound_type->type.type = TYPE_COMPOUND_STRUCT; - compound_type->attributes = parse_attributes(); + type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); + type->compound.attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); - add_anchor_token(T_DEDENT); - compound_type->entries = parse_compound_entries(); + add_anchor_token(T_DEDENT); + type->compound.entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: - return (type_t*) compound_type; + return type; } -static type_t *make_pointer_type_no_hash(type_t *type) +static type_t *make_pointer_type_no_hash(type_t *points_to) { - pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); - - pointer_type->type.type = TYPE_POINTER; - pointer_type->points_to = type; + type_t *type = allocate_type(TYPE_POINTER); + type->pointer.points_to = points_to; - return (type_t*) pointer_type; + return type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); expression_t *size = parse_expression(); rem_anchor_token(']'); expect(']', end_error); - array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); - - array_type->type.type = TYPE_ARRAY; - array_type->element_type = type; - array_type->size_expression = size; - - type = (type_t*) array_type; + type_t *array_type = allocate_type(TYPE_ARRAY); + array_type->array.element_type = type; + array_type->array.size_expression = size; + type = array_type; break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); parse_method(&expression->func.method); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); - typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); - typeof_type->type.type = TYPE_TYPEOF; + type_t *type = allocate_type(TYPE_TYPEOF); add_anchor_token(')'); - typeof_type->expression = parse_expression(); + type->typeof.expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); - expression->sizeofe.type = (type_t*) typeof_type; + expression->sizeofe.type = type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { expression_t *expression = allocate_expression(EXPR_CALL); expression->call.method = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \ return expression; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); register_expression_parser(parse_EXPR_UNARY_NOT, '!'); register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->base.source_position = start; while (true) { if (token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->base.source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { eat(T_return); statement_t *return_statement = allocate_statement(STATEMENT_RETURN); if (token.type != T_NEWLINE) { return_statement->returns.value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return return_statement; } static statement_t *create_error_statement(void) { return allocate_statement(STATEMENT_ERROR); } static statement_t *parse_goto_statement(void) { eat(T_goto); statement_t *goto_statement = allocate_statement(STATEMENT_GOTO); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->gotos.label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); statement_t *label = allocate_statement(STATEMENT_LABEL); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->label.declaration.base.kind = DECLARATION_LABEL; label->label.declaration.base.source_position = source_position; label->label.declaration.base.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->label.declaration); expect(T_NEWLINE, end_error); return label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if (token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if (token.type != T_INDENT) { /* create an empty block */ statement_t *block = allocate_statement(STATEMENT_BLOCK); return block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if (token.type == T_else) { next_token(); if (token.type == ':') next_token(); false_statement = parse_sub_block(); } statement_t *if_statement = allocate_statement(STATEMENT_IF); if_statement->ifs.condition = condition; if_statement->ifs.true_statement = true_statement; if_statement->ifs.false_statement = false_statement; return if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = symbol; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.source_position = source_position; assign->binary.left = expression; assign->binary.right = parse_expression(); statement_t *expr_statement = allocate_statement(STATEMENT_EXPRESSION); expr_statement->expression.expression = assign; return expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } statement_t *statement = allocate_statement(STATEMENT_DECLARATION); declaration_t *declaration = (declaration_t*) &statement->declaration.declaration; declaration->base.kind = DECLARATION_VARIABLE; declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &statement->declaration.declaration; if (token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if (last_statement != NULL) { last_statement->base.next = statement; } else { first_statement = statement; } last_statement = statement; /* do we have an assignment expression? */ if (token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->base.symbol); last_statement->base.next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if (token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { statement_t *statement = allocate_statement(STATEMENT_EXPRESSION); statement->expression.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: return statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if (token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; parse_statement_function parser = NULL; if (token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; add_anchor_token(T_NEWLINE); if (parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if (token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if (declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } rem_anchor_token(T_NEWLINE); if (statement == NULL) return NULL; statement->base.source_position = start; statement_t *next = statement->base.next; while (next != NULL) { next->base.source_position = start; next = next->base.next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); statement_t *block_statement = allocate_statement(STATEMENT_BLOCK); context_t *last_context = current_context; current_context = &block_statement->block.context; add_anchor_token(T_DEDENT); statement_t *last_statement = NULL; while (token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if (statement == NULL) continue; if (last_statement != NULL) { last_statement->base.next = statement; } else { block_statement->block.statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while (last_statement->base.next != NULL) last_statement = last_statement->base.next; } assert(current_context == &block_statement->block.context); current_context = last_context; block_statement->block.end_position = source_position; rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: return block_statement; } static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if (parameters != NULL) *parameters = NULL; expect('(', end_error2); if (token.type == ')') { next_token(); return; } add_anchor_token(')'); add_anchor_token(','); while (true) { if (token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if (token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); goto end_error; } break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if (last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if (parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.base.kind = DECLARATION_METHOD_PARAMETER; method_param->declaration.base.symbol = symbol; method_param->declaration.base.source_position = source_position; method_param->type = param_type->type; if (last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if (token.type != ',') break; next_token(); } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error2); return; end_error: rem_anchor_token(','); rem_anchor_token(')'); end_error2: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while (token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if (last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static declaration_t *parse_type_parameter(void) { declaration_t *declaration = allocate_declaration(DECLARATION_TYPE_VARIABLE); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->type_variable.constraints = parse_type_constraints(); } return declaration; } static type_variable_t *parse_type_parameters(context_t *context) { declaration_t *first_variable = NULL; declaration_t *last_variable = NULL; while (true) { declaration_t *type_variable = parse_type_parameter(); if (last_variable != NULL) { last_variable->type_variable.next = &type_variable->type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if (context != NULL) { type_variable->base.next = context->declarations; context->declarations = type_variable; } if (token.type != ',') break; next_token(); } return &first_variable->type_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->base.source_position.input_name != NULL); assert(current_context != NULL); declaration->base.next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { - method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); - method_type->type.type = TYPE_METHOD; + type_t *type = allocate_type(TYPE_METHOD); context_t *last_context = current_context; current_context = &method->context; if (token.type == '<') { next_token(); add_anchor_token('>'); method->type_parameters = parse_type_parameters(current_context); rem_anchor_token('>'); expect('>', end_error); } - parse_parameter_declarations(method_type, &method->parameters); - method->type = method_type; + parse_parameter_declarations(&type->method, &method->parameters); + method->type = &type->method; /* add parameters to context */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { declaration_t *declaration = (declaration_t*) parameter; declaration->base.next = current_context->declarations; current_context->declarations = declaration; } - method_type->result_type = type_void; + type->method.result_type = type_void; if (token.type == ':') { next_token(); if (token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } - method_type->result_type = parse_type(); + type->method.result_type = parse_type(); if (token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } expect(T_NEWLINE, end_error); method_parser_end: assert(current_context == &method->context); current_context = last_context; end_error: ; } static void parse_method_declaration(void) { eat(T_func); declaration_t *declaration = allocate_declaration(DECLARATION_METHOD); if (token.type == T_extern) { declaration->method.method.is_extern = true; next_token(); } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_method(&declaration->method.method); add_declaration(declaration); } static void parse_global_variable(void) { eat(T_var); declaration_t *declaration = allocate_declaration(DECLARATION_VARIABLE); declaration->variable.is_global = true; if (token.type == T_extern) { next_token(); declaration->variable.is_extern = true; } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); declaration->variable.type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_declaration(declaration); } static void parse_constant(void) { eat(T_const); declaration_t *declaration = allocate_declaration(DECLARATION_CONSTANT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->constant.type = parse_type(); } expect('=', end_error); declaration->constant.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static void parse_typealias(void) { eat(T_typealias); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); expect('=', end_error); declaration->typealias.type = parse_type(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if (token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if (token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if (parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if (parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while (token.type == '$') { attribute_t *attribute = parse_attribute(); if (attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_class(void) { eat(T_class); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing class", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); - compound_type_t *compound_type - = allocate_ast_zero(sizeof(compound_type[0])); - compound_type->type.type = TYPE_COMPOUND_CLASS; - compound_type->symbol = declaration->base.symbol; - compound_type->attributes = parse_attributes(); + type_t *type = allocate_type(TYPE_COMPOUND_CLASS); + type->compound.symbol = declaration->base.symbol; + type->compound.attributes = parse_attributes(); - declaration->typealias.type = (type_t*) compound_type; + declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); context_t *last_context = current_context; - current_context = &compound_type->context; + current_context = &type->compound.context; while (token.type != T_EOF && token.type != T_DEDENT) { parse_declaration(); } next_token(); - assert(current_context == &compound_type->context); + assert(current_context == &type->compound.context); current_context = last_context; } end_error: add_declaration(declaration); } static void parse_struct(void) { eat(T_struct); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); - compound_type_t *compound_type - = allocate_ast_zero(sizeof(compound_type[0])); - compound_type->type.type = TYPE_COMPOUND_STRUCT; - compound_type->symbol = declaration->base.symbol; + type_t *type = allocate_type(TYPE_COMPOUND_STRUCT); + type->compound.symbol = declaration->base.symbol; if (token.type == '<') { next_token(); - compound_type->type_parameters - = parse_type_parameters(&compound_type->context); + type->compound.type_parameters + = parse_type_parameters(&type->compound.context); expect('>', end_error); } - compound_type->attributes = parse_attributes(); + type->compound.attributes = parse_attributes(); - declaration->typealias.type = (type_t*) compound_type; + declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); - compound_type->entries = parse_compound_entries(); + type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration(declaration); end_error: ; } static void parse_union(void) { eat(T_union); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); - compound_type_t *compound_type - = allocate_ast_zero(sizeof(compound_type[0])); - compound_type->type.type = TYPE_COMPOUND_UNION; - compound_type->symbol = declaration->base.symbol; - compound_type->attributes = parse_attributes(); + type_t *type = allocate_type(TYPE_COMPOUND_UNION); + type->compound.symbol = declaration->base.symbol; + type->compound.attributes = parse_attributes(); - declaration->typealias.type = (type_t*) compound_type; + declaration->typealias.type = type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); - compound_type->entries = parse_compound_entries(); + type->compound.entries = parse_compound_entries(); eat(T_DEDENT); } end_error: add_declaration(declaration); } static concept_method_t *parse_concept_method(void) { expect(T_func, end_error); declaration_t *declaration = allocate_declaration(DECLARATION_CONCEPT_METHOD); - method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); - memset(method_type, 0, sizeof(method_type[0])); - method_type->type.type = TYPE_METHOD; + type_t *type = allocate_type(TYPE_METHOD); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); - parse_parameter_declarations(method_type, + parse_parameter_declarations(&type->method, &declaration->concept_method.parameters); if (token.type == ':') { next_token(); - method_type->result_type = parse_type(); + type->method.result_type = parse_type(); } else { - method_type->result_type = type_void; + type->method.result_type = type_void; } expect(T_NEWLINE, end_error); - declaration->concept_method.method_type = method_type; + declaration->concept_method.method_type = &type->method; add_declaration(declaration); return &declaration->concept_method; end_error: return NULL; } static void parse_concept(void) { eat(T_concept); declaration_t *declaration = allocate_declaration(DECLARATION_CONCEPT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); context_t *context = &declaration->concept.context; add_anchor_token('>'); declaration->concept.type_parameters = parse_type_parameters(context); rem_anchor_token('>'); expect('>', end_error); } expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_method_t *last_method = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_method_t *method = parse_concept_method(); method->concept = &declaration->concept; if (last_method != NULL) { last_method->next = method; } else { declaration->concept.methods = method; } last_method = method; } next_token(); end_of_parse_concept: add_declaration(declaration); return; end_error: ; } static concept_method_instance_t *parse_concept_method_instance(void) { concept_method_instance_t *method_instance = allocate_ast_zero(sizeof(method_instance[0])); expect(T_func, end_error); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method " "instance", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } method_instance->source_position = source_position; method_instance->symbol = token.v.symbol; next_token(); parse_method(& method_instance->method); return method_instance; end_error: return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect('>', end_error); } instance->type_arguments = parse_type_arguments(); expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_method_instance_t *last_method = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if (token.type == T_NEWLINE) { next_token(); continue; } concept_method_instance_t *method = parse_concept_method_instance(); if (method == NULL) continue; if (last_method != NULL) { last_method->next = method; } else { instance->method_instances = method; } last_method = method; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; return; end_error: ; } static void skip_declaration(void) { next_token(); } static void parse_import(void) { eat(T_import); if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing import directive", T_STRING_LITERAL, 0); eat_until_anchor(); return; } symbol_t *modulename = symbol_table_insert(token.v.string); next_token(); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing import directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } import_t *import = allocate_ast_zero(sizeof(import[0])); import->module = modulename; import->symbol = token.v.symbol; import->source_position = source_position; import->next = current_context->imports; current_context->imports = import; next_token(); if (token.type != ',') break; eat(','); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_export(void) { eat(T_export); while (true) { if (token.type == T_NEWLINE) { break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if (token.type != ',') { break; } next_token(); } expect(T_NEWLINE, end_error); end_error: ; } static void parse_module(void) { eat(T_module); /* a simple URL string without a protocol */ if (token.type != T_STRING_LITERAL) { parse_error_expected("problem while parsing module", T_STRING_LITERAL, 0); return; } symbol_t *new_module_name = symbol_table_insert(token.v.string); next_token(); if (current_module_name != NULL && current_module_name != new_module_name) { parser_print_error_prefix(); fprintf(stderr, "new module name '%s' overrides old name '%s'\n", new_module_name->string, current_module_name->string); } current_module_name = new_module_name; expect(T_NEWLINE, end_error); end_error: ; } void parse_declaration(void) { if (token.type < 0) { if (token.type == T_EOF) return; /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parse = NULL; if (token.type < ARR_LEN(declaration_parsers)) parse = declaration_parsers[token.type]; if (parse == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_anchor(); return; } parse(); } static void register_declaration_parsers(void) { register_declaration_parser(parse_method_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_class, T_class); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); register_declaration_parser(parse_import, T_import); register_declaration_parser(parse_module, T_module); register_declaration_parser(skip_declaration, T_NEWLINE); } static module_t *get_module(symbol_t *name) { if (name == NULL) { name = symbol_table_insert(""); } /* search for an existing module */ module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } if (module == NULL) { module = allocate_ast_zero(sizeof(module[0])); module->name = name; module->next = modules; modules = module; } return module; } static void append_context(context_t *dest, const context_t *source) { declaration_t *last = dest->declarations; if (last != NULL) { while (last->base.next != NULL) { last = last->base.next; } last->base.next = source->declarations; } else { dest->declarations = source->declarations; } concept_instance_t *last_concept_instance = dest->concept_instances; if (last_concept_instance != NULL) { while (last_concept_instance->next != NULL) { last_concept_instance = last_concept_instance->next; } last_concept_instance->next = source->concept_instances; } else { dest->concept_instances = source->concept_instances; } export_t *last_export = dest->exports; if (last_export != NULL) { while (last_export->next != NULL) { last_export = last_export->next; } last_export->next = source->exports; } else { dest->exports = source->exports; } import_t *last_import = dest->imports; if (last_import != NULL) { while (last_import->next != NULL) { last_import = last_import->next; } last_import->next = source->imports; } else { dest->imports = source->imports; } } bool parse_file(FILE *in, const char *input_name) { memset(token_anchor_set, 0, sizeof(token_anchor_set)); /* get the lexer running */ lexer_init(in, input_name); next_token(); context_t file_context; memset(&file_context, 0, sizeof(file_context)); assert(current_context == NULL); current_context = &file_context; current_module_name = NULL; add_anchor_token(T_EOF); while (token.type != T_EOF) { parse_declaration(); } rem_anchor_token(T_EOF); assert(current_context == &file_context); current_context = NULL; /* append stuff to module */ module_t *module = get_module(current_module_name); append_context(&module->context, &file_context); /* check that we have matching rem_anchor_token calls for each add */ #ifndef NDEBUG for (int i = 0; i < T_LAST_TOKEN; ++i) { if (token_anchor_set[i] > 0) { panic("leaked token"); } } #endif lexer_destroy(); return !error; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); } diff --git a/semantic.c b/semantic.c index db72af0..01d2dc8 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2614 +1,2614 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->base.refs == 0 && !declaration->base.exported) { switch (declaration->kind) { /* only warn for methods/variables at the moment, we don't count refs on types yet */ case DECLARATION_METHOD: case DECLARATION_VARIABLE: print_warning_prefix(declaration->base.source_position); fprintf(stderr, "%s '%s' was declared but never read\n", get_declaration_kind_name(declaration->kind), symbol->string); default: break; } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return type_invalid; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } - type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; + type_ref->base.kind = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return type_invalid; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; - if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION - || type->type == TYPE_COMPOUND_CLASS) { + if (type->kind == TYPE_COMPOUND_STRUCT || type->kind == TYPE_COMPOUND_UNION + || type->kind == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); - bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; + bind_typevariables->base.kind = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); type->size_expression = check_expression(type->size_expression); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; - if (type->type == TYPE_COMPOUND_STRUCT - || type->type == TYPE_COMPOUND_UNION - || type->type == TYPE_COMPOUND_CLASS) { + if (type->kind == TYPE_COMPOUND_STRUCT + || type->kind == TYPE_COMPOUND_UNION + || type->kind == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); - assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || - polymorphic_type->type == TYPE_COMPOUND_UNION || - polymorphic_type->type == TYPE_COMPOUND_CLASS); + assert(polymorphic_type->kind == TYPE_COMPOUND_STRUCT || + polymorphic_type->kind == TYPE_COMPOUND_UNION || + polymorphic_type->kind == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; - switch (type->type) { + switch (type->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; declaration->base.refs++; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; type = variable->type; if (type == NULL) return NULL; - if (type->type == TYPE_COMPOUND_STRUCT - || type->type == TYPE_COMPOUND_UNION - || type->type == TYPE_COMPOUND_CLASS - || type->type == TYPE_BIND_TYPEVARIABLES - || type->type == TYPE_ARRAY) { + if (type->kind == TYPE_COMPOUND_STRUCT + || type->kind == TYPE_COMPOUND_UNION + || type->kind == TYPE_COMPOUND_CLASS + || type->kind == TYPE_BIND_TYPEVARIABLES + || type->kind == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); } panic("reference to unknown declaration type encountered"); } static declaration_t *create_error_declarataion(symbol_t *symbol) { declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); declaration->base.symbol = symbol; declaration->base.exported = true; return declaration; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); declaration = create_error_declarataion(symbol); } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->base.source_position); ref->base.type = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->base.refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; - if (from_type->type == TYPE_POINTER) { - if (dest_type->type == TYPE_POINTER) { + if (from_type->kind == TYPE_POINTER) { + if (dest_type->kind == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } - } else if (from_type->type == TYPE_ARRAY) { + } else if (from_type->kind == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; - if (dest_type->type == TYPE_POINTER) { + if (dest_type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } - } else if (dest_type->type == TYPE_POINTER) { + } else if (dest_type->kind == TYPE_POINTER) { implicit_cast_allowed = false; - } else if (from_type->type == TYPE_ATOMIC) { - if (dest_type->type != TYPE_ATOMIC) { + } else if (from_type->kind == TYPE_ATOMIC) { + if (dest_type->kind != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { - atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; - atomic_type_type_t from_atype = from_type_atomic->atype; - atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; - atomic_type_type_t dest_atype = dest_type_atomic->atype; + atomic_type_t *from_type_atomic = &from_type->atomic; + atomic_type_kind_t from_akind = from_type_atomic->akind; + atomic_type_t *dest_type_atomic = &dest_type->atomic; + atomic_type_kind_t dest_akind = dest_type_atomic->akind; - switch (from_atype) { + switch (from_akind) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_BYTE) || - (dest_atype == ATOMIC_TYPE_UBYTE); + (dest_akind == ATOMIC_TYPE_BYTE) || + (dest_akind == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_USHORT) || - (dest_atype == ATOMIC_TYPE_SHORT); + (dest_akind == ATOMIC_TYPE_USHORT) || + (dest_akind == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_UINT) || - (dest_atype == ATOMIC_TYPE_INT); + (dest_akind == ATOMIC_TYPE_UINT) || + (dest_akind == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_ULONG) || - (dest_atype == ATOMIC_TYPE_LONG); + (dest_akind == ATOMIC_TYPE_ULONG) || + (dest_akind == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_ULONGLONG) || - (dest_atype == ATOMIC_TYPE_LONGLONG); + (dest_akind == ATOMIC_TYPE_ULONGLONG) || + (dest_akind == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_SHORT); + (dest_akind == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_INT); + (dest_akind == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_LONG); + (dest_akind == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= - (dest_atype == ATOMIC_TYPE_LONGLONG); + (dest_akind == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: - implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); + implicit_cast_allowed = (dest_akind == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; type_t *righttype = right->base.type; - if (lefttype->type != TYPE_POINTER && righttype->type != TYPE_POINTER) + if (lefttype->kind != TYPE_POINTER && righttype->kind != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ - if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { + if (lefttype->kind == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } - if (lefttype->type == TYPE_POINTER && righttype->type == TYPE_POINTER) { + if (lefttype->kind == TYPE_POINTER && righttype->kind == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; - if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { + if (current_type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->base.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if (method_instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->base.type = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; - if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { + if (current_type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->base.symbol->string, concept->base.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->base.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->base.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); - switch (type->type) { + switch (type->kind) { case TYPE_ATOMIC: - atomic_type = (atomic_type_t*) type; - switch (atomic_type->atype) { + atomic_type = &type->atomic; + switch (atomic_type->akind) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return error_type; case TYPE_ERROR: return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->base.type; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if (type == NULL) return; /* determine method type */ - if (type->type != TYPE_POINTER) { + if (type->kind != TYPE_POINTER) { print_error_prefix(call->base.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; - if (type->type != TYPE_METHOD) { + if (type->kind != TYPE_METHOD) { print_error_prefix(call->base.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if (method->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if (declaration->kind == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if (type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while (type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if (type_argument != NULL || type_var != NULL) { error_at(method->base.source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while (argument != NULL) { if (param_type == NULL && !method_type->variable_arguments) { error_at(call->base.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->base.type; if (param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->base.source_position); } /* match type of argument against type variables */ if (type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->base.source_position, true); } else if (expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->base.source_position, lenient); if (new_expression == NULL) { print_error_prefix(expression->base.source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->base.type); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if (param_type != NULL) param_type = param_type->next; ++i; } if (param_type != NULL) { error_at(call->base.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while (type_var != NULL) { if (type_var->current_type == NULL) { print_error_prefix(call->base.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->base.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->base.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if (type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if (declaration->kind == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->kind == DECLARATION_METHOD); check_type_constraints(type_variables, call->base.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->base.type = create_concrete_type(ref->base.type); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->base.type = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->base.type == NULL) { panic("Cast expression needs a datatype!"); } cast->base.type = normalize_type(cast->base.type); cast->value = check_expression(cast->value); if (cast->value->base.type == type_void) { error_at(cast->base.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->base.type == NULL) { error_at(dereference->base.source_position, "can't derefence expression with unknown datatype\n"); return; } - if (value->base.type->type != TYPE_POINTER) { + if (value->base.type->kind != TYPE_POINTER) { error_at(dereference->base.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->base.type; type_t *dereferenced_type = pointer_type->points_to; dereference->base.type = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->base.source_position, "can only take address of l-values\n"); return; } if (value->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->base.type = result_type; } static bool is_arithmetic_type(type_t *type) { - if (type->type != TYPE_ATOMIC) + if (type->kind != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; - switch (atomic_type->atype) { + switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static expression_t *lower_incdec_expression(expression_t *expression_) { unary_expression_t *expression = (unary_expression_t*) expression_; expression_t *value = check_expression(expression->value); type_t *type = value->base.type; expression_kind_t kind = expression->base.kind; - if (!is_type_numeric(type) && type->type != TYPE_POINTER) { + if (!is_type_numeric(type) && type->kind != TYPE_POINTER) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression needs an lvalue\n", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; - if (type->type == TYPE_ATOMIC) { + if (type->kind == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; - if (atomic_type->atype == ATOMIC_TYPE_FLOAT || - atomic_type->atype == ATOMIC_TYPE_DOUBLE) { + if (atomic_type->akind == ATOMIC_TYPE_FLOAT || + atomic_type->akind == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { constant = allocate_expression(EXPR_INT_CONST); constant->base.type = type; constant->int_const.value = 1; } else { constant = allocate_expression(EXPR_FLOAT_CONST); constant->base.type = type; constant->float_const.value = 1.0; } expression_t *add = allocate_expression(kind == EXPR_UNARY_INCREMENT ? EXPR_BINARY_ADD : EXPR_BINARY_SUB); add->base.type = type; add->binary.left = value; add->binary.right = constant; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.type = type; assign->binary.left = value; assign->binary.right = add; return assign; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type != type_bool) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->base.type; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; - if (datatype->type == TYPE_BIND_TYPEVARIABLES) { + if (datatype->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; - } else if (datatype->type == TYPE_COMPOUND_STRUCT - || datatype->type == TYPE_COMPOUND_UNION - || datatype->type == TYPE_COMPOUND_CLASS) { + } else if (datatype->kind == TYPE_COMPOUND_STRUCT + || datatype->kind == TYPE_COMPOUND_UNION + || datatype->kind == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { - if (datatype->type != TYPE_POINTER) { + if (datatype->kind != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; - if (points_to->type == TYPE_BIND_TYPEVARIABLES) { + if (points_to->kind == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; - } else if (points_to->type == TYPE_COMPOUND_STRUCT - || points_to->type == TYPE_COMPOUND_UNION - || points_to->type == TYPE_COMPOUND_CLASS) { + } else if (points_to->kind == TYPE_COMPOUND_STRUCT + || points_to->kind == TYPE_COMPOUND_UNION + || points_to->kind == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->base.source_position); select->base.type = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; if (type == NULL || - (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { + (type->kind != TYPE_POINTER && type->kind != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; - if (type->type == TYPE_POINTER) { + if (type->kind == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { - assert(type->type == TYPE_ARRAY); + assert(type->kind == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->value = check_expression(statement->value); expression_t *return_value = statement->value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->base.type != type_void) { error_at(statement->base.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->base.source_position, false); statement->value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->base.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->base.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->base.next; statement = check_statement(statement); assert(statement->base.next == next || statement->base.next == NULL); statement->base.next = next; if (last != NULL) { last->base.next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.base.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->base.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->base.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->kind < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->kind]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->kind) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement(&statement->block); break; case STATEMENT_RETURN: check_return_statement(&statement->returns); break; case STATEMENT_GOTO: check_goto_statement(&statement->gotos); break; case STATEMENT_LABEL: check_label_statement(&statement->label); break; case STATEMENT_IF: check_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: check_variable_declaration(&statement->declaration); break; case STATEMENT_EXPRESSION: check_expression_statement(&statement->expression); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); - assert(normalized_type->type == TYPE_METHOD); + assert(normalized_type->kind == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } declaration->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); - if (type->type == TYPE_COMPOUND_UNION - || type->type == TYPE_COMPOUND_STRUCT) { + if (type->kind == TYPE_COMPOUND_UNION + || type->kind == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } static declaration_t *find_declaration(const context_t *context, symbol_t *symbol) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } return declaration; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; declaration_t *declaration; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); declaration = create_error_declarataion(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); declaration = create_error_declarataion(symbol); } else { check_module(ref_module); declaration = find_declaration(&ref_module->context, symbol); if (declaration == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); declaration = create_error_declarataion(symbol); } else { ref_context = &ref_module->context; } } } if (!declaration->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->declaration == declaration) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(declaration, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/type.c b/type.c index 81fe746..cd6b1d2 100644 --- a/type.c +++ b/type.c @@ -1,589 +1,575 @@ #include <config.h> #include "type_t.h" #include "ast_t.h" #include "type_hash.h" #include "adt/error.h" #include "adt/array.h" //#define DEBUG_TYPEVAR_BINDING typedef struct typevar_binding_t typevar_binding_t; struct typevar_binding_t { type_variable_t *type_variable; type_t *old_current_type; }; static typevar_binding_t *typevar_binding_stack = NULL; static struct obstack _type_obst; struct obstack *type_obst = &_type_obst; -static type_t type_void_ = { TYPE_VOID, NULL }; -static type_t type_invalid_ = { TYPE_INVALID, NULL }; -type_t *type_void = &type_void_; -type_t *type_invalid = &type_invalid_; +static type_base_t type_void_ = { TYPE_VOID, NULL }; +static type_base_t type_invalid_ = { TYPE_INVALID, NULL }; +type_t *type_void = (type_t*) &type_void_; +type_t *type_invalid = (type_t*) &type_invalid_; static FILE* out; void init_type_module() { obstack_init(type_obst); typevar_binding_stack = NEW_ARR_F(typevar_binding_t, 0); out = stderr; } void exit_type_module() { DEL_ARR_F(typevar_binding_stack); obstack_free(type_obst, NULL); } static void print_atomic_type(const atomic_type_t *type) { - switch (type->atype) { + switch (type->akind) { case ATOMIC_TYPE_INVALID: fputs("INVALIDATOMIC", out); break; case ATOMIC_TYPE_BOOL: fputs("bool", out); break; case ATOMIC_TYPE_BYTE: fputs("byte", out); break; case ATOMIC_TYPE_UBYTE: fputs("unsigned byte", out); break; case ATOMIC_TYPE_INT: fputs("int", out); break; case ATOMIC_TYPE_UINT: fputs("unsigned int", out); break; case ATOMIC_TYPE_SHORT: fputs("short", out); break; case ATOMIC_TYPE_USHORT: fputs("unsigned short", out); break; case ATOMIC_TYPE_LONG: fputs("long", out); break; case ATOMIC_TYPE_ULONG: fputs("unsigned long", out); break; case ATOMIC_TYPE_LONGLONG: fputs("long long", out); break; case ATOMIC_TYPE_ULONGLONG: fputs("unsigned long long", out); break; case ATOMIC_TYPE_FLOAT: fputs("float", out); break; case ATOMIC_TYPE_DOUBLE: fputs("double", out); break; default: fputs("UNKNOWNATOMIC", out); break; } } static void print_method_type(const method_type_t *type) { fputs("<", out); fputs("func(", out); method_parameter_type_t *param_type = type->parameter_types; int first = 1; while (param_type != NULL) { if (first) { first = 0; } else { fputs(", ", out); } print_type(param_type->type); param_type = param_type->next; } fputs(")", out); - if (type->result_type != NULL && type->result_type->type != TYPE_VOID) { + if (type->result_type != NULL && type->result_type->kind != TYPE_VOID) { fputs(" : ", out); print_type(type->result_type); } fputs(">", out); } static void print_pointer_type(const pointer_type_t *type) { print_type(type->points_to); fputs("*", out); } static void print_array_type(const array_type_t *type) { print_type(type->element_type); fputs("[", out); print_expression(type->size_expression); fputs("]", out); } static void print_type_reference(const type_reference_t *type) { fprintf(out, "<?%s>", type->symbol->string); } static void print_type_variable(const type_variable_t *type_variable) { if (type_variable->current_type != NULL) { print_type(type_variable->current_type); return; } fprintf(out, "%s:", type_variable->base.symbol->string); type_constraint_t *constraint = type_variable->constraints; int first = 1; while (constraint != NULL) { if (first) { first = 0; } else { fprintf(out, ", "); } fprintf(out, "%s", constraint->concept_symbol->string); constraint = constraint->next; } } static void print_type_reference_variable(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; print_type_variable(type_variable); } static void print_compound_type(const compound_type_t *type) { fprintf(out, "%s", type->symbol->string); type_variable_t *type_parameter = type->type_parameters; if (type_parameter != NULL) { fprintf(out, "<"); while (type_parameter != NULL) { if (type_parameter != type->type_parameters) { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } fprintf(out, ">"); } } static void print_bind_type_variables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); print_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void print_type(const type_t *type) { if (type == NULL) { fputs("nil type", out); return; } - switch (type->type) { + switch (type->kind) { case TYPE_INVALID: fputs("invalid", out); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; fputs("typeof(", out); print_expression(typeof_type->expression); fputs(")", out); return; } case TYPE_ERROR: fputs("error", out); return; case TYPE_VOID: fputs("void", out); return; case TYPE_ATOMIC: print_atomic_type((const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: print_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: print_method_type((const method_type_t*) type); return; case TYPE_POINTER: print_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: print_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: print_type_reference((const type_reference_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: print_type_reference_variable((const type_reference_t*) type); return; case TYPE_BIND_TYPEVARIABLES: print_bind_type_variables((const bind_typevariables_type_t*) type); return; } fputs("unknown", out); } int type_valid(const type_t *type) { - switch (type->type) { + switch (type->kind) { case TYPE_INVALID: case TYPE_REFERENCE: return 0; default: return 1; } } int is_type_int(const type_t *type) { - if (type->type != TYPE_ATOMIC) + if (type->kind != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; - switch (atomic_type->atype) { + switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return 1; default: return 0; } } int is_type_numeric(const type_t *type) { - if (type->type != TYPE_ATOMIC) + if (type->kind != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; - switch (atomic_type->atype) { + switch (atomic_type->akind) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return 1; default: return 0; } } -type_t* make_atomic_type(atomic_type_type_t atype) +type_t* make_atomic_type(atomic_type_kind_t akind) { - atomic_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); - memset(type, 0, sizeof(type[0])); - type->type.type = TYPE_ATOMIC; - type->atype = atype; + type_t *type = allocate_type(TYPE_ATOMIC); + type->atomic.akind = akind; - type_t *normalized_type = typehash_insert((type_t*) type); - if (normalized_type != (type_t*) type) { + type_t *normalized_type = typehash_insert(type); + if (normalized_type != type) { obstack_free(type_obst, type); } return normalized_type; } type_t* make_pointer_type(type_t *points_to) { - pointer_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); - memset(type, 0, sizeof(type[0])); - type->type.type = TYPE_POINTER; - type->points_to = points_to; + type_t *type = allocate_type(TYPE_POINTER); + type->pointer.points_to = points_to; - type_t *normalized_type = typehash_insert((type_t*) type); - if (normalized_type != (type_t*) type) { + type_t *normalized_type = typehash_insert(type); + if (normalized_type != type) { obstack_free(type_obst, type); } return normalized_type; } static type_t *create_concrete_compound_type(compound_type_t *type) { /* TODO: handle structs with typevars */ return (type_t*) type; } static type_t *create_concrete_method_type(method_type_t *type) { int need_new_type = 0; - method_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); - memset(new_type, 0, sizeof(new_type[0])); - new_type->type.type = TYPE_METHOD; + type_t *new_type = allocate_type(TYPE_METHOD); type_t *result_type = create_concrete_type(type->result_type); if (result_type != type->result_type) need_new_type = 1; - new_type->result_type = result_type; + new_type->method.result_type = result_type; method_parameter_type_t *parameter_type = type->parameter_types; method_parameter_type_t *last_parameter_type = NULL; while (parameter_type != NULL) { type_t *param_type = parameter_type->type; type_t *new_param_type = create_concrete_type(param_type); if (new_param_type != param_type) need_new_type = 1; method_parameter_type_t *new_parameter_type = obstack_alloc(type_obst, sizeof(new_parameter_type[0])); memset(new_parameter_type, 0, sizeof(new_parameter_type[0])); new_parameter_type->type = new_param_type; if (last_parameter_type != NULL) { last_parameter_type->next = new_parameter_type; } else { - new_type->parameter_types = new_parameter_type; + new_type->method.parameter_types = new_parameter_type; } last_parameter_type = new_parameter_type; parameter_type = parameter_type->next; } if (!need_new_type) { obstack_free(type_obst, new_type); - new_type = type; + new_type = (type_t*) type; } - return (type_t*) new_type; + return new_type; } static type_t *create_concrete_pointer_type(pointer_type_t *type) { type_t *points_to = create_concrete_type(type->points_to); if (points_to == type->points_to) return (type_t*) type; - pointer_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); - memset(new_type, 0, sizeof(new_type[0])); - new_type->type.type = TYPE_POINTER; - new_type->points_to = points_to; + type_t *new_type = allocate_type(TYPE_POINTER); + new_type->pointer.points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) new_type); - if (normalized_type != (type_t*) new_type) { + if (normalized_type != new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_type_variable_reference_type(type_reference_t *type) { type_variable_t *type_variable = type->type_variable; type_t *current_type = type_variable->current_type; if (current_type != NULL) return current_type; return (type_t*) type; } static type_t *create_concrete_array_type(array_type_t *type) { type_t *element_type = create_concrete_type(type->element_type); if (element_type == type->element_type) return (type_t*) type; - array_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); - memset(new_type, 0, sizeof(new_type[0])); - - new_type->type.type = TYPE_ARRAY; - new_type->element_type = element_type; - new_type->size_expression = type->size_expression; + type_t *new_type = allocate_type(TYPE_ARRAY); + new_type->array.element_type = element_type; + new_type->array.size_expression = type->size_expression; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_typevar_binding_type(bind_typevariables_type_t *type) { int changed = 0; type_argument_t *new_arguments; type_argument_t *last_argument = NULL; type_argument_t *type_argument = type->type_arguments; while (type_argument != NULL) { type_t *type = type_argument->type; type_t *new_type = create_concrete_type(type); if (new_type != type) { changed = 1; } type_argument_t *new_argument = obstack_alloc(type_obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = new_type; if (last_argument != NULL) { last_argument->next = new_argument; } else { new_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } if (!changed) { assert(new_arguments != NULL); obstack_free(type_obst, new_arguments); return (type_t*) type; } - bind_typevariables_type_t *new_type - = obstack_alloc(type_obst, sizeof(new_type[0])); - memset(new_type, 0, sizeof(new_type[0])); - new_type->type.type = TYPE_BIND_TYPEVARIABLES; - new_type->polymorphic_type = type->polymorphic_type; - new_type->type_arguments = new_arguments; + type_t *new_type = allocate_type(TYPE_BIND_TYPEVARIABLES); + new_type->bind_typevariables.polymorphic_type = type->polymorphic_type; + new_type->bind_typevariables.type_arguments = new_arguments; - type_t *normalized_type = typehash_insert((type_t*) new_type); - if (normalized_type != (type_t*) new_type) { + type_t *normalized_type = typehash_insert(new_type); + if (normalized_type != new_type) { obstack_free(type_obst, new_type); } return normalized_type; } type_t *create_concrete_type(type_t *type) { - switch (type->type) { + switch (type->kind) { case TYPE_INVALID: return type_invalid; case TYPE_VOID: return type_void; case TYPE_ERROR: case TYPE_ATOMIC: return type; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return create_concrete_compound_type((compound_type_t*) type); case TYPE_METHOD: return create_concrete_method_type((method_type_t*) type); case TYPE_POINTER: return create_concrete_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return create_concrete_array_type((array_type_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return create_concrete_type_variable_reference_type( (type_reference_t*) type); case TYPE_BIND_TYPEVARIABLES: return create_concrete_typevar_binding_type( (bind_typevariables_type_t*) type); case TYPE_TYPEOF: panic("TODO: concrete type for typeof()"); case TYPE_REFERENCE: panic("trying to normalize unresolved type reference"); break; } return type; } int typevar_binding_stack_top() { return ARR_LEN(typevar_binding_stack); } void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments) { type_variable_t *type_parameter; type_argument_t *type_argument; if (type_parameters == NULL || type_arguments == NULL) return; /* we have to take care that all rebinding happens atomically, so we first * create the structures on the binding stack and misuse the * old_current_type value to temporarily save the new! current_type. * We can then walk the list and set the new types */ type_parameter = type_parameters; type_argument = type_arguments; int old_top = typevar_binding_stack_top(); int top = ARR_LEN(typevar_binding_stack) + 1; while (type_parameter != NULL) { type_t *type = type_argument->type; - while (type->type == TYPE_REFERENCE_TYPE_VARIABLE) { + while (type->kind == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) type; type_variable_t *var = ref->type_variable; if (var->current_type == NULL) { break; } type = var->current_type; } top = ARR_LEN(typevar_binding_stack) + 1; ARR_RESIZE(typevar_binding_t, typevar_binding_stack, top); typevar_binding_t *binding = & typevar_binding_stack[top-1]; binding->type_variable = type_parameter; binding->old_current_type = type; type_parameter = type_parameter->next; type_argument = type_argument->next; } assert(type_parameter == NULL && type_argument == NULL); for (int i = old_top+1; i <= top; ++i) { typevar_binding_t *binding = & typevar_binding_stack[i-1]; type_variable_t *type_variable = binding->type_variable; type_t *new_type = binding->old_current_type; binding->old_current_type = type_variable->current_type; type_variable->current_type = new_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "binding '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, type_variable->current_type); fprintf(stderr, "\n"); #endif } } void pop_type_variable_bindings(int new_top) { int top = ARR_LEN(typevar_binding_stack) - 1; for (int i = top; i >= new_top; --i) { typevar_binding_t *binding = & typevar_binding_stack[i]; type_variable_t *type_variable = binding->type_variable; type_variable->current_type = binding->old_current_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "reset binding of '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, binding->old_current_type); fprintf(stderr, "\n"); #endif } ARR_SHRINKLEN(typevar_binding_stack, new_top); } type_t *skip_typeref(type_t *type) { - if (type->type == TYPE_TYPEOF) { - typeof_type_t *typeof_type = (typeof_type_t*) type; + if (type->kind == TYPE_TYPEOF) { + typeof_type_t *typeof_type = &type->typeof; return skip_typeref(typeof_type->expression->base.type); } return type; } diff --git a/type.h b/type.h index c7954f8..556b2ca 100644 --- a/type.h +++ b/type.h @@ -1,64 +1,66 @@ #ifndef TYPE_H #define TYPE_H #include <stdio.h> -typedef struct type_t type_t; +typedef union type_t type_t; +typedef struct type_base_t type_base_t; typedef struct atomic_type_t atomic_type_t; typedef struct type_reference_t type_reference_t; typedef struct compound_entry_t compound_entry_t; typedef struct compound_type_t compound_type_t; typedef struct type_constraint_t type_constraint_t; typedef struct type_variable_t type_variable_t; typedef struct type_argument_t type_argument_t; typedef struct bind_typevariables_type_t bind_typevariables_type_t; typedef struct method_parameter_type_t method_parameter_type_t; typedef struct method_type_t method_type_t; typedef struct pointer_type_t pointer_type_t; typedef struct array_type_t array_type_t; typedef struct typeof_type_t typeof_type_t; +typedef struct iterator_type_t iterator_type_t; extern type_t *type_void; extern type_t *type_invalid; void init_type_module(void); void exit_type_module(void); /** * prints a human readable form of @p type to a stream */ void print_type(const type_t *type); /** * returns 1 if type contains integer numbers */ int is_type_int(const type_t *type); /** * returns 1 if type contains numbers (float or int) */ int is_type_numeric(const type_t *type); /** * returns 1 if the type is valid. A type is valid if it contains no unresolved * references anymore and is not of TYPE_INVALID. */ int type_valid(const type_t *type); /** * returns a normalized copy of a type with type variables replaced by their * current type. The given type (and all its hierarchy) is not modified. */ type_t *create_concrete_type(type_t *type); type_t *skip_typeref(type_t *type); int typevar_binding_stack_top(void); void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments); void pop_type_variable_bindings(int new_top); #endif diff --git a/type_hash.c b/type_hash.c index 20bdd51..268a2ab 100644 --- a/type_hash.c +++ b/type_hash.c @@ -1,290 +1,288 @@ #include <config.h> #include <stdbool.h> #include "type_hash.h" #include "adt/error.h" #include "type_t.h" #include <assert.h> #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #include "adt/hashset.h" #undef ValueType #undef HashSetIterator #undef HashSet typedef struct type_hash_iterator_t type_hash_iterator_t; typedef struct type_hash_t type_hash_t; static unsigned hash_ptr(const void *ptr) { unsigned ptr_int = ((const char*) ptr - (const char*) NULL); return ptr_int >> 3; } static unsigned hash_atomic_type(const atomic_type_t *type) { unsigned some_prime = 27644437; - return type->atype * some_prime; + return type->akind * some_prime; } static unsigned hash_pointer_type(const pointer_type_t *type) { return hash_ptr(type->points_to); } static unsigned hash_array_type(const array_type_t *type) { return hash_ptr(type->element_type) ^ hash_ptr(type->size_expression); } static unsigned hash_compound_type(const compound_type_t *type) { unsigned result = hash_ptr(type->symbol); return result; } static unsigned hash_type(const type_t *type); static unsigned hash_method_type(const method_type_t *type) { unsigned result = hash_ptr(type->result_type); method_parameter_type_t *parameter = type->parameter_types; while (parameter != NULL) { result ^= hash_ptr(parameter->type); parameter = parameter->next; } if (type->variable_arguments) result = ~result; return result; } static unsigned hash_type_reference_type_variable(const type_reference_t *type) { return hash_ptr(type->type_variable); } static unsigned hash_bind_typevariables_type_t(const bind_typevariables_type_t *type) { unsigned hash = hash_compound_type(type->polymorphic_type); type_argument_t *argument = type->type_arguments; while (argument != NULL) { hash ^= hash_type(argument->type); argument = argument->next; } return hash; } static unsigned hash_type(const type_t *type) { - switch (type->type) { + switch (type->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: panic("internalizing void or invalid types not possible"); case TYPE_REFERENCE_TYPE_VARIABLE: - return hash_type_reference_type_variable( - (const type_reference_t*) type); + return hash_type_reference_type_variable(&type->reference); case TYPE_ATOMIC: - return hash_atomic_type((const atomic_type_t*) type); + return hash_atomic_type(&type->atomic); case TYPE_TYPEOF: { - const typeof_type_t *typeof_type = (const typeof_type_t*) type; - return hash_ptr(typeof_type->expression); + return hash_ptr(type->typeof.expression); } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return hash_compound_type((const compound_type_t*) type); case TYPE_METHOD: return hash_method_type((const method_type_t*) type); case TYPE_POINTER: return hash_pointer_type((const pointer_type_t*) type); case TYPE_ARRAY: return hash_array_type((const array_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return hash_bind_typevariables_type_t( (const bind_typevariables_type_t*) type); } abort(); } static bool atomic_types_equal(const atomic_type_t *type1, const atomic_type_t *type2) { - return type1->atype == type2->atype; + return type1->akind == type2->akind; } static bool compound_types_equal(const compound_type_t *type1, const compound_type_t *type2) { if (type1->symbol != type2->symbol) return false; /* TODO: check type parameters? */ return true; } static bool method_types_equal(const method_type_t *type1, const method_type_t *type2) { if (type1->result_type != type2->result_type) return false; if (type1->variable_arguments != type2->variable_arguments) return false; method_parameter_type_t *param1 = type1->parameter_types; method_parameter_type_t *param2 = type2->parameter_types; while (param1 != NULL && param2 != NULL) { if (param1->type != param2->type) return false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) return false; return true; } static bool pointer_types_equal(const pointer_type_t *type1, const pointer_type_t *type2) { return type1->points_to == type2->points_to; } static bool array_types_equal(const array_type_t *type1, const array_type_t *type2) { return type1->element_type == type2->element_type && type1->size_expression == type2->size_expression; } static bool type_references_type_variable_equal(const type_reference_t *type1, const type_reference_t *type2) { return type1->type_variable == type2->type_variable; } static bool bind_typevariables_type_equal(const bind_typevariables_type_t*type1, const bind_typevariables_type_t*type2) { if (type1->polymorphic_type != type2->polymorphic_type) return false; type_argument_t *argument1 = type1->type_arguments; type_argument_t *argument2 = type2->type_arguments; while (argument1 != NULL) { if (argument2 == NULL) return false; if (argument1->type != argument2->type) return false; argument1 = argument1->next; argument2 = argument2->next; } if (argument2 != NULL) return false; return true; } static bool types_equal(const type_t *type1, const type_t *type2) { if (type1 == type2) return true; - if (type1->type != type2->type) + if (type1->kind != type2->kind) return false; - switch (type1->type) { + switch (type1->kind) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: return false; case TYPE_TYPEOF: { const typeof_type_t *typeof_type1 = (const typeof_type_t*) type1; const typeof_type_t *typeof_type2 = (const typeof_type_t*) type2; return typeof_type1->expression == typeof_type2->expression; } case TYPE_REFERENCE_TYPE_VARIABLE: return type_references_type_variable_equal( (const type_reference_t*) type1, (const type_reference_t*) type2); case TYPE_ATOMIC: return atomic_types_equal((const atomic_type_t*) type1, (const atomic_type_t*) type2); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return compound_types_equal((const compound_type_t*) type1, (const compound_type_t*) type2); case TYPE_METHOD: return method_types_equal((const method_type_t*) type1, (const method_type_t*) type2); case TYPE_POINTER: return pointer_types_equal((const pointer_type_t*) type1, (const pointer_type_t*) type2); case TYPE_ARRAY: return array_types_equal((const array_type_t*) type1, (const array_type_t*) type2); case TYPE_BIND_TYPEVARIABLES: return bind_typevariables_type_equal( (const bind_typevariables_type_t*) type1, (const bind_typevariables_type_t*) type2); } panic("invalid type encountered"); } #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #define NullValue NULL #define DeletedValue ((type_t*)-1) #define Hash(this, key) hash_type(key) #define KeysEqual(this,key1,key2) types_equal(key1, key2) #define SetRangeEmpty(ptr,size) memset(ptr, 0, (size) * sizeof(*(ptr))) #define hashset_init _typehash_init #define hashset_init_size _typehash_init_size #define hashset_destroy _typehash_destroy #define hashset_insert _typehash_insert #define hashset_remove typehash_remove #define hashset_find typehash_find #define hashset_size typehash_size #define hashset_iterator_init typehash_iterator_init #define hashset_iterator_next typehash_iterator_next #define hashset_remove_iterator typehash_remove_iterator #define SCALAR_RETURN #include "adt/hashset.c" static type_hash_t typehash; void init_typehash(void) { _typehash_init(&typehash); } void exit_typehash(void) { _typehash_destroy(&typehash); } type_t *typehash_insert(type_t *type) { return _typehash_insert(&typehash, type); } int typehash_contains(type_t *type) { return typehash_find(&typehash, type) != NULL; } diff --git a/type_t.h b/type_t.h index afd24d8..09d2113 100644 --- a/type_t.h +++ b/type_t.h @@ -1,149 +1,166 @@ #ifndef TYPE_T_H #define TYPE_T_H #include <stdbool.h> #include "type.h" #include "symbol.h" #include "lexer.h" #include "ast.h" #include "ast_t.h" #include "adt/obst.h" #include <libfirm/typerep.h> struct obstack *type_obst; typedef enum { TYPE_INVALID, TYPE_ERROR, TYPE_VOID, TYPE_ATOMIC, TYPE_COMPOUND_CLASS, TYPE_COMPOUND_STRUCT, TYPE_COMPOUND_UNION, TYPE_METHOD, TYPE_POINTER, TYPE_ARRAY, TYPE_TYPEOF, TYPE_REFERENCE, TYPE_REFERENCE_TYPE_VARIABLE, - TYPE_BIND_TYPEVARIABLES -} type_type_t; + TYPE_BIND_TYPEVARIABLES, + TYPE_LAST = TYPE_BIND_TYPEVARIABLES +} type_kind_t; typedef enum { ATOMIC_TYPE_INVALID, ATOMIC_TYPE_BOOL, ATOMIC_TYPE_BYTE, ATOMIC_TYPE_UBYTE, ATOMIC_TYPE_SHORT, ATOMIC_TYPE_USHORT, ATOMIC_TYPE_INT, ATOMIC_TYPE_UINT, ATOMIC_TYPE_LONG, ATOMIC_TYPE_ULONG, ATOMIC_TYPE_LONGLONG, ATOMIC_TYPE_ULONGLONG, ATOMIC_TYPE_FLOAT, ATOMIC_TYPE_DOUBLE, -} atomic_type_type_t; +} atomic_type_kind_t; -struct type_t { - type_type_t type; +struct type_base_t { + type_kind_t kind; ir_type *firm_type; }; struct atomic_type_t { - type_t type; - atomic_type_type_t atype; + type_base_t base; + atomic_type_kind_t akind; }; struct pointer_type_t { - type_t type; - type_t *points_to; + type_base_t base; + type_t *points_to; }; struct array_type_t { - type_t type; + type_base_t base; type_t *element_type; expression_t *size_expression; }; struct typeof_type_t { - type_t type; + type_base_t base; expression_t *expression; }; struct type_argument_t { type_t *type; type_argument_t *next; }; struct type_reference_t { - type_t type; + type_base_t base; symbol_t *symbol; source_position_t source_position; type_argument_t *type_arguments; type_variable_t *type_variable; }; struct bind_typevariables_type_t { - type_t type; + type_base_t base; type_argument_t *type_arguments; compound_type_t *polymorphic_type; }; struct method_parameter_type_t { type_t *type; method_parameter_type_t *next; }; struct type_constraint_t { symbol_t *concept_symbol; concept_t *concept; type_constraint_t *next; }; struct method_type_t { - type_t type; + type_base_t base; type_t *result_type; method_parameter_type_t *parameter_types; bool variable_arguments; }; struct iterator_type_t { - type_t type; + type_base_t base; type_t *element_type; method_parameter_type_t *parameter_types; }; struct compound_entry_t { type_t *type; symbol_t *symbol; compound_entry_t *next; attribute_t *attributes; source_position_t source_position; ir_entity *entity; }; struct compound_type_t { - type_t type; + type_base_t base; compound_entry_t *entries; symbol_t *symbol; attribute_t *attributes; type_variable_t *type_parameters; context_t context; source_position_t source_position; }; -type_t *make_atomic_type(atomic_type_type_t type); +union type_t +{ + type_kind_t kind; + type_base_t base; + atomic_type_t atomic; + pointer_type_t pointer; + array_type_t array; + typeof_type_t typeof; + type_reference_t reference; + bind_typevariables_type_t bind_typevariables; + method_type_t method; + iterator_type_t iterator; + compound_type_t compound; +}; + +type_t *allocate_type(type_kind_t kind); +type_t *make_atomic_type(atomic_type_kind_t type); type_t *make_pointer_type(type_t *type); static inline bool is_type_array(const type_t *type) { - return type->type == TYPE_ARRAY; + return type->kind == TYPE_ARRAY; } #endif
MatzeB/fluffy
3b0ed2750f4aa31ea3ca675684eb9b8654ad032c
avoid a few NULL pointer crashes
diff --git a/TODO b/TODO index 961a54a..4edfb98 100644 --- a/TODO +++ b/TODO @@ -1,28 +1,26 @@ This does not describe the goals and visions but short term things that should not be forgotten. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime -- forbid same variable names in nested blocks +- forbid same variable names in nested blocks (really?) - change firm to pass on debug info on unitialized_variable callback -- introduce constant expressions - introduce const type qualifier Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Add an alloca operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) Refactorings (mindless but often labor intensive tasks): -- make unions for type_t (see cparser) -- rename type to kind +- make unions for type_t (see cparser), rename type->type to type->kind - keep typerefs as long as possible (start the skip_typeref madness similar to cparser) diff --git a/semantic.c b/semantic.c index b74a890..db72af0 100644 --- a/semantic.c +++ b/semantic.c @@ -1,991 +1,999 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->base.refs == 0 && !declaration->base.exported) { switch (declaration->kind) { /* only warn for methods/variables at the moment, we don't count refs on types yet */ case DECLARATION_METHOD: case DECLARATION_VARIABLE: print_warning_prefix(declaration->base.source_position); fprintf(stderr, "%s '%s' was declared but never read\n", get_declaration_kind_name(declaration->kind), symbol->string); default: break; } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); - return NULL; + return type_invalid; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); - return NULL; + return type_invalid; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); type->size_expression = check_expression(type->size_expression); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; declaration->base.refs++; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); } panic("reference to unknown declaration type encountered"); } +static declaration_t *create_error_declarataion(symbol_t *symbol) +{ + declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); + declaration->base.symbol = symbol; + declaration->base.exported = true; + return declaration; +} + static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); - return; + declaration = create_error_declarataion(symbol); } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->base.source_position); ref->base.type = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->base.refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; type_t *righttype = right->base.type; if (lefttype->type != TYPE_POINTER && righttype->type != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } if (lefttype->type == TYPE_POINTER && righttype->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->base.source_position; @@ -1969,646 +1977,638 @@ static void check_variable_declaration(declaration_statement_t *statement) } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->base.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->base.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->base.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->kind < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->kind]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->kind) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement(&statement->block); break; case STATEMENT_RETURN: check_return_statement(&statement->returns); break; case STATEMENT_GOTO: check_goto_statement(&statement->gotos); break; case STATEMENT_LABEL: check_label_statement(&statement->label); break; case STATEMENT_IF: check_if_statement(&statement->ifs); break; case STATEMENT_DECLARATION: check_variable_declaration(&statement->declaration); break; case STATEMENT_EXPRESSION: check_expression_statement(&statement->expression); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } declaration->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } -static declaration_t *create_error_declarataion(symbol_t *symbol) -{ - declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); - declaration->base.symbol = symbol; - declaration->base.exported = true; - return declaration; -} - static declaration_t *find_declaration(const context_t *context, symbol_t *symbol) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } return declaration; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; declaration_t *declaration; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); declaration = create_error_declarataion(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); declaration = create_error_declarataion(symbol); } else { check_module(ref_module); declaration = find_declaration(&ref_module->context, symbol); if (declaration == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); declaration = create_error_declarataion(symbol); } else { ref_context = &ref_module->context; } } } if (!declaration->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->declaration == declaration) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(declaration, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); }
MatzeB/fluffy
2208f9e6ebb5a51960882c8f45f07bdf55605fab
transform statement_t to a union
diff --git a/ast.c b/ast.c index c4ee421..99eed0b 100644 --- a/ast.c +++ b/ast.c @@ -1,770 +1,766 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for (const char *c = string_const->value; *c != 0; ++c) { switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->base.symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch (unexpr->base.kind) { case EXPR_UNARY_CAST: fprintf(out, "cast<"); print_type(unexpr->base.type); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->base.kind); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch (binexpr->base.kind) { case EXPR_BINARY_ASSIGN: fprintf(out, "<-"); break; case EXPR_BINARY_ADD: fprintf(out, "+"); break; case EXPR_BINARY_SUB: fprintf(out, "-"); break; case EXPR_BINARY_MUL: fprintf(out, "*"); break; case EXPR_BINARY_DIV: fprintf(out, "/"); break; case EXPR_BINARY_NOTEQUAL: fprintf(out, "/="); break; case EXPR_BINARY_EQUAL: fprintf(out, "="); break; case EXPR_BINARY_LESS: fprintf(out, "<"); break; case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; case EXPR_BINARY_GREATER: fprintf(out, ">"); break; case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->base.kind); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->kind) { case EXPR_ERROR: fprintf(out, "*error expression*"); break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_FUNC: /* TODO */ fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; - while (statement != NULL) { + for ( ; statement != NULL; statement = statement->base.next) { indent++; print_statement(statement); indent--; - - statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); - if (statement->return_value != NULL) - print_expression(statement->return_value); + if (statement->value != NULL) + print_expression(statement->value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->base.symbol->string); } -static void print_variable_declaration_statement( - const variable_declaration_statement_t *statement) +static void print_declaration_statement(const declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); - switch (statement->type) { + switch (statement->kind) { case STATEMENT_BLOCK: - print_block_statement((const block_statement_t*) statement); + print_block_statement(&statement->block); break; case STATEMENT_RETURN: - print_return_statement((const return_statement_t*) statement); + print_return_statement(&statement->returns); break; case STATEMENT_EXPRESSION: - print_expression_statement((const expression_statement_t*) statement); + print_expression_statement(&statement->expression); break; case STATEMENT_LABEL: - print_label_statement((const label_statement_t*) statement); + print_label_statement(&statement->label); break; case STATEMENT_GOTO: - print_goto_statement((const goto_statement_t*) statement); + print_goto_statement(&statement->gotos); break; case STATEMENT_IF: - print_if_statement((const if_statement_t*) statement); + print_if_statement(&statement->ifs); break; - case STATEMENT_VARIABLE_DECLARATION: - print_variable_declaration_statement( - (const variable_declaration_statement_t*) statement); + case STATEMENT_DECLARATION: + print_declaration_statement(&statement->declaration); break; case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if (method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->base.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->base.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while (method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if (method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->base.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch (declaration->kind) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type '%s'\n", get_declaration_kind_name(declaration->kind)); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: fprintf(out, "invalid declaration (%s)\n", get_declaration_kind_name(declaration->kind)); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { print_declaration(declaration); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } void print_ast(FILE *new_out, const context_t *context) { indent = 0; out = new_out; print_context(context); assert(indent == 0); out = NULL; } const char *get_declaration_kind_name(declaration_kind_t type) { switch (type) { case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } bool is_linktime_constant(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: /* TODO */ return false; case EXPR_ARRAY_ACCESS: /* TODO */ return false; case EXPR_UNARY_DEREFERENCE: return is_constant_expression(expression->unary.value); default: return false; } } bool is_constant_expression(const expression_t *expression) { switch (expression->kind) { case EXPR_INT_CONST: case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_NULL_POINTER: case EXPR_SIZEOF: return true; case EXPR_STRING_CONST: case EXPR_FUNC: case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: case EXPR_UNARY_DEREFERENCE: case EXPR_BINARY_ASSIGN: case EXPR_SELECT: case EXPR_ARRAY_ACCESS: return false; case EXPR_UNARY_TAKE_ADDRESS: return is_linktime_constant(expression->unary.value); case EXPR_REFERENCE: { declaration_t *declaration = expression->reference.declaration; if (declaration->kind == DECLARATION_CONSTANT) return true; return false; } case EXPR_CALL: /* TODO: we might introduce pure/side effect free calls */ return false; case EXPR_UNARY_CAST: case EXPR_UNARY_NEGATE: case EXPR_UNARY_NOT: case EXPR_UNARY_BITWISE_NOT: return is_constant_expression(expression->unary.value); case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: case EXPR_BINARY_MUL: case EXPR_BINARY_DIV: case EXPR_BINARY_MOD: case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: /* not that lazy and/or are not constant if their value is clear after * evaluating the left side. This is because we can't (always) evaluate the * left hand side until the ast2firm phase, and therefore can't determine * constness */ case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: return is_constant_expression(expression->binary.left) && is_constant_expression(expression->binary.right); case EXPR_ERROR: return true; case EXPR_INVALID: break; } panic("invalid expression in is_constant_expression"); } diff --git a/ast.h b/ast.h index 512c0d1..b325387 100644 --- a/ast.h +++ b/ast.h @@ -1,79 +1,80 @@ #ifndef AST_H #define AST_H #include <stdbool.h> #include <stdio.h> typedef struct attribute_t attribute_t; typedef union declaration_t declaration_t; typedef union expression_t expression_t; +typedef union statement_t statement_t; + typedef struct context_t context_t; typedef struct export_t export_t; typedef struct import_t import_t; typedef struct declaration_base_t declaration_base_t; typedef struct expression_base_t expression_base_t; typedef struct int_const_t int_const_t; typedef struct float_const_t float_const_t; typedef struct string_const_t string_const_t; typedef struct bool_const_t bool_const_t; typedef struct cast_expression_t cast_expression_t; typedef struct reference_expression_t reference_expression_t; typedef struct call_argument_t call_argument_t; typedef struct call_expression_t call_expression_t; typedef struct binary_expression_t binary_expression_t; typedef struct unary_expression_t unary_expression_t; typedef struct select_expression_t select_expression_t; typedef struct array_access_expression_t array_access_expression_t; typedef struct sizeof_expression_t sizeof_expression_t; typedef struct func_expression_t func_expression_t; -typedef struct statement_t statement_t; +typedef struct statement_base_t statement_base_t; typedef struct block_statement_t block_statement_t; typedef struct return_statement_t return_statement_t; typedef struct if_statement_t if_statement_t; typedef struct variable_declaration_t variable_declaration_t; -typedef struct variable_declaration_statement_t - variable_declaration_statement_t; +typedef struct declaration_statement_t declaration_statement_t; typedef struct expression_statement_t expression_statement_t; typedef struct goto_statement_t goto_statement_t; typedef struct label_declaration_t label_declaration_t; typedef struct label_statement_t label_statement_t; typedef struct module_t module_t; typedef struct method_parameter_t method_parameter_t; typedef struct method_t method_t; typedef struct method_declaration_t method_declaration_t; typedef struct iterator_declaration_t iterator_declaration_t; typedef struct constant_t constant_t; typedef struct global_variable_t global_variable_t; typedef struct typealias_t typealias_t; typedef struct concept_instance_t concept_instance_t; typedef struct concept_method_instance_t concept_method_instance_t; typedef struct concept_t concept_t; typedef struct concept_method_t concept_method_t; void init_ast_module(void); void exit_ast_module(void); void print_ast(FILE *out, const context_t *context); void print_expression(const expression_t *expression); void *allocate_ast(size_t size); /** * Returns true if a given expression is a compile time * constant. */ bool is_constant_expression(const expression_t *expression); /** * An object with a fixed but at compiletime unknown adress which will be known * at link/load time. */ bool is_linktime_constant(const expression_t *expression); -long fold_constant_to_int(const expression_t *expression); -bool fold_constant_to_bool(const expression_t *expression); +long fold_constant_to_int(expression_t *expression); +bool fold_constant_to_bool(expression_t *expression); #endif diff --git a/ast2firm.c b/ast2firm.c index 7322ce5..5dd7842 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,865 +1,865 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_method_t instantiate_method_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_method_t { method_t *method; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_methods; static pdeq *instantiate_methods = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = (const declaration_t*) &value_numbers[pos]; print_warning_prefix(declaration->base.source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->base.symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { } static void init_ir_types(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.type.type = TYPE_ATOMIC; byte_type.atype = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch (type->atype) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch (type->type) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if (result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } -static ir_node *expression_to_firm(const expression_t *expression); +static ir_node *expression_to_firm(expression_t *expression); -static tarval *fold_constant_to_tarval(const expression_t *expression) +static tarval *fold_constant_to_tarval(expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } tarval* tv = get_Const_tarval(cnst); return tv; } -long fold_constant_to_int(const expression_t *expression) +long fold_constant_to_int(expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->kind == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->kind != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = declaration->base.symbol; ident *ident = new_id_from_str(symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch (type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_method->base.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; @@ -1073,892 +1073,883 @@ static ir_node *assign_expression_to_firm(const binary_expression_t *assign) return value; } static long binexpr_kind_to_cmp_pn(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; case EXPR_BINARY_LESS: return pn_Cmp_Lt; case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; case EXPR_BINARY_GREATER: return pn_Cmp_Gt; case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ long compare_pn = binexpr_kind_to_cmp_pn(kind); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(declaration_t *declaration, type_argument_t *type_arguments) { assert(declaration->kind == DECLARATION_METHOD); method_t *method = &declaration->method.method; symbol_t *symbol = declaration->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); if (declaration->base.exported && get_entity_visibility(entity) != visibility_external_allocated) { set_entity_visibility(entity, visibility_external_visible); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(declaration, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->base.type->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if (result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(declaration, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->base.source_position); } -static ir_node *expression_to_firm(const expression_t *expression) +static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: - return int_const_to_firm((const int_const_t*) expression); + return int_const_to_firm(&expression->int_const); case EXPR_FLOAT_CONST: - return float_const_to_firm((const float_const_t*) expression); + return float_const_to_firm(&expression->float_const); case EXPR_STRING_CONST: - return string_const_to_firm((const string_const_t*) expression); + return string_const_to_firm(&expression->string_const); case EXPR_BOOL_CONST: - return bool_const_to_firm((const bool_const_t*) expression); + return bool_const_to_firm(&expression->bool_const); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: - return reference_expression_to_firm( - (const reference_expression_t*) expression); + return reference_expression_to_firm(&expression->reference); EXPR_BINARY_CASES - return binary_expression_to_firm( - (const binary_expression_t*) expression); + return binary_expression_to_firm(&expression->binary); EXPR_UNARY_CASES - return unary_expression_to_firm( - (const unary_expression_t*) expression); + return unary_expression_to_firm(&expression->unary); case EXPR_SELECT: - return select_expression_to_firm( - (const select_expression_t*) expression); + return select_expression_to_firm(&expression->select); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: - return call_expression_to_firm((const call_expression_t*) expression); + return call_expression_to_firm(&expression->call); case EXPR_SIZEOF: - return sizeof_expression_to_firm( - (const sizeof_expression_t*) expression); + return sizeof_expression_to_firm(&expression->sizeofe); case EXPR_FUNC: - return func_expression_to_firm( - (func_expression_t*) expression); + return func_expression_to_firm(&expression->func); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } - - static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { - dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); + dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *ret; - if (statement->return_value != NULL) { - ir_node *retval = expression_to_firm(statement->return_value); + if (statement->value != NULL) { + ir_node *retval = expression_to_firm(statement->value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { - dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); + dbg_info *dbgi = get_dbg_info(&statement->base.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; - while (statement != NULL) { + for ( ; statement != NULL; statement = statement->base.next) { statement_to_firm(statement); - statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi - = get_dbg_info(&goto_statement->statement.source_position); + = get_dbg_info(&goto_statement->base.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { - if (statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { + if (statement->kind != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } - switch (statement->type) { + switch (statement->kind) { case STATEMENT_BLOCK: - block_statement_to_firm((block_statement_t*) statement); + block_statement_to_firm(&statement->block); return; case STATEMENT_RETURN: - return_statement_to_firm((return_statement_t*) statement); + return_statement_to_firm(&statement->returns); return; case STATEMENT_IF: - if_statement_to_firm((if_statement_t*) statement); + if_statement_to_firm(&statement->ifs); return; - case STATEMENT_VARIABLE_DECLARATION: + case STATEMENT_DECLARATION: /* nothing to do */ return; case STATEMENT_EXPRESSION: - expression_statement_to_firm((expression_statement_t*) statement); + expression_statement_to_firm(&statement->expression); return; case STATEMENT_LABEL: - label_statement_to_firm((label_statement_t*) statement); + label_statement_to_firm(&statement->label); return; case STATEMENT_GOTO: - goto_statement_to_firm((goto_statement_t*) statement); + goto_statement_to_firm(&statement->gotos); return; case STATEMENT_ERROR: case STATEMENT_INVALID: break; } panic("Invalid statement kind found"); } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: if (!is_polymorphic_method(&declaration->method.method)) { assure_instance(declaration, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index f702ce6..81fd1ea 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,496 +1,508 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST = DECLARATION_LABEL } declaration_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; int refs; /**< temporarily used by semantic phase */ bool exported : 1; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; struct import_t { symbol_t *module; symbol_t *symbol; import_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_base_t base; method_t method; }; struct iterator_declaration_t { declaration_base_t base; method_t method; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_method_t { declaration_base_t base; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct module_t { symbol_t *name; context_t context; module_t *next; bool processing : 1; bool processed : 1; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; method_declaration_t method; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_method_t concept_method; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; method_t method; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *method; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, - STATEMENT_VARIABLE_DECLARATION, + STATEMENT_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST = STATEMENT_LABEL -} statement_type_t; +} statement_kind_t; -struct statement_t { - statement_type_t type; +struct statement_base_t { + statement_kind_t kind; statement_t *next; source_position_t source_position; }; struct return_statement_t { - statement_t statement; - expression_t *return_value; + statement_base_t base; + expression_t *value; }; struct block_statement_t { - statement_t statement; + statement_base_t base; statement_t *statements; source_position_t end_position; context_t context; }; -struct variable_declaration_statement_t { - statement_t statement; +struct declaration_statement_t { + statement_base_t base; variable_declaration_t declaration; }; struct if_statement_t { - statement_t statement; - expression_t *condition; - statement_t *true_statement; - statement_t *false_statement; + statement_base_t base; + expression_t *condition; + statement_t *true_statement; + statement_t *false_statement; }; struct goto_statement_t { - statement_t statement; + statement_base_t base; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { - statement_t statement; + statement_base_t base; label_declaration_t declaration; }; struct expression_statement_t { - statement_t statement; - expression_t *expression; + statement_base_t base; + expression_t *expression; +}; + +union statement_t { + statement_kind_t kind; + statement_base_t base; + return_statement_t returns; + block_statement_t block; + declaration_statement_t declaration; + goto_statement_t gotos; + label_statement_t label; + expression_statement_t expression; + if_statement_t ifs; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); expression_t *allocate_expression(expression_kind_t kind); declaration_t *allocate_declaration(declaration_kind_t kind); #endif diff --git a/parser.c b/parser.c index eca5e7f..96f3589 100644 --- a/parser.c +++ b/parser.c @@ -1,621 +1,646 @@ #include <config.h> #include "token_t.h" #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers; static parse_statement_function *statement_parsers; static parse_declaration_function *declaration_parsers; static parse_attribute_function *attribute_parsers; static unsigned char token_anchor_set[T_LAST_TOKEN]; static symbol_t *current_module_name; static context_t *current_context; static int error = 0; token_t token; module_t *modules; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_declaration_struct_size(declaration_kind_t kind) { static const size_t sizes[] = { [DECLARATION_ERROR] = sizeof(declaration_base_t), [DECLARATION_METHOD] = sizeof(method_declaration_t), [DECLARATION_METHOD_PARAMETER] = sizeof(method_parameter_t), [DECLARATION_ITERATOR] = sizeof(iterator_declaration_t), [DECLARATION_VARIABLE] = sizeof(variable_declaration_t), [DECLARATION_CONSTANT] = sizeof(constant_t), [DECLARATION_TYPE_VARIABLE] = sizeof(type_variable_t), [DECLARATION_TYPEALIAS] = sizeof(typealias_t), [DECLARATION_CONCEPT] = sizeof(concept_t), [DECLARATION_CONCEPT_METHOD] = sizeof(concept_method_t), [DECLARATION_LABEL] = sizeof(label_declaration_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } declaration_t *allocate_declaration(declaration_kind_t kind) { size_t size = get_declaration_struct_size(kind); declaration_t *declaration = allocate_ast_zero(size); declaration->kind = kind; return declaration; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { [EXPR_ERROR] = sizeof(expression_base_t), [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } +static size_t get_statement_struct_size(statement_kind_t kind) +{ + static const size_t sizes[] = { + [STATEMENT_ERROR] = sizeof(statement_base_t), + [STATEMENT_BLOCK] = sizeof(block_statement_t), + [STATEMENT_RETURN] = sizeof(return_statement_t), + [STATEMENT_DECLARATION] = sizeof(declaration_statement_t), + [STATEMENT_IF] = sizeof(if_statement_t), + [STATEMENT_EXPRESSION] = sizeof(expression_statement_t), + [STATEMENT_GOTO] = sizeof(goto_statement_t), + [STATEMENT_LABEL] = sizeof(label_statement_t), + }; + assert(kind < sizeof(sizes)/sizeof(sizes[0])); + assert(sizes[kind] != 0); + return sizes[kind]; +}; + +static statement_t *allocate_statement(statement_kind_t kind) +{ + size_t size = get_statement_struct_size(kind); + statement_t *statement = allocate_ast_zero(size); + statement->kind = kind; + return statement; +} + static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch (token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if (result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *create_error_type(void) { type_t *error_type = allocate_type_zero(sizeof(error_type[0])); error_type->type = TYPE_ERROR; return error_type; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; parse_parameter_declarations(method_type, NULL); expect(':', end_error); method_type->result_type = parse_type(); return (type_t*) method_type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); @@ -647,1340 +672,1317 @@ type_t *parse_type(void) /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); expression_t *size = parse_expression(); rem_anchor_token(']'); expect(']', end_error); array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size_expression = size; type = (type_t*) array_type; break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); parse_method(&expression->func.method); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); expression->sizeofe.type = (type_t*) typeof_type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { expression_t *expression = allocate_expression(EXPR_CALL); expression->call.method = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \ return expression; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); register_expression_parser(parse_EXPR_UNARY_NOT, '!'); register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->base.source_position = start; while (true) { if (token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->base.source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { - return_statement_t *return_statement = - allocate_ast_zero(sizeof(return_statement[0])); - - return_statement->statement.type = STATEMENT_RETURN; - next_token(); + eat(T_return); + statement_t *return_statement = allocate_statement(STATEMENT_RETURN); if (token.type != T_NEWLINE) { - return_statement->return_value = parse_expression(); + return_statement->returns.value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: - return (statement_t*) return_statement; + return return_statement; } static statement_t *create_error_statement(void) { - statement_t *statement = allocate_ast_zero(sizeof(statement[0])); - statement->type = STATEMENT_ERROR; - return statement; + return allocate_statement(STATEMENT_ERROR); } static statement_t *parse_goto_statement(void) { eat(T_goto); - goto_statement_t *goto_statement - = allocate_ast_zero(sizeof(goto_statement[0])); - goto_statement->statement.type = STATEMENT_GOTO; - + statement_t *goto_statement = allocate_statement(STATEMENT_GOTO); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } - goto_statement->label_symbol = token.v.symbol; + goto_statement->gotos.label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); - return (statement_t*) goto_statement; + return goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); - label_statement_t *label = allocate_ast_zero(sizeof(label[0])); - label->statement.type = STATEMENT_LABEL; - + statement_t *label = allocate_statement(STATEMENT_LABEL); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } - label->declaration.base.kind = DECLARATION_LABEL; - label->declaration.base.source_position = source_position; - label->declaration.base.symbol = token.v.symbol; + label->label.declaration.base.kind = DECLARATION_LABEL; + label->label.declaration.base.source_position = source_position; + label->label.declaration.base.symbol = token.v.symbol; next_token(); - add_declaration((declaration_t*) &label->declaration); + add_declaration((declaration_t*) &label->label.declaration); expect(T_NEWLINE, end_error); - return (statement_t*) label; + return label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if (token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if (token.type != T_INDENT) { /* create an empty block */ - block_statement_t *block = allocate_ast_zero(sizeof(block[0])); - block->statement.type = STATEMENT_BLOCK; - return (statement_t*) block; + statement_t *block = allocate_statement(STATEMENT_BLOCK); + return block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if (token.type == T_else) { next_token(); if (token.type == ':') next_token(); false_statement = parse_sub_block(); } - if_statement_t *if_statement - = allocate_ast_zero(sizeof(if_statement[0])); - - if_statement->statement.type = STATEMENT_IF; - if_statement->condition = condition; - if_statement->true_statement = true_statement; - if_statement->false_statement = false_statement; + statement_t *if_statement = allocate_statement(STATEMENT_IF); + if_statement->ifs.condition = condition; + if_statement->ifs.true_statement = true_statement; + if_statement->ifs.false_statement = false_statement; - return (statement_t*) if_statement; + return if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = symbol; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.source_position = source_position; assign->binary.left = expression; assign->binary.right = parse_expression(); - expression_statement_t *expr_statement - = allocate_ast_zero(sizeof(expr_statement[0])); - expr_statement->statement.type = STATEMENT_EXPRESSION; - expr_statement->expression = assign; - - return (statement_t*) expr_statement; + statement_t *expr_statement = allocate_statement(STATEMENT_EXPRESSION); + expr_statement->expression.expression = assign; + return expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } - variable_declaration_statement_t *declaration_statement - = allocate_ast_zero(sizeof(declaration_statement[0])); - declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; + statement_t *statement = allocate_statement(STATEMENT_DECLARATION); declaration_t *declaration - = (declaration_t*) &declaration_statement->declaration; + = (declaration_t*) &statement->declaration.declaration; declaration->base.kind = DECLARATION_VARIABLE; declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration - = &declaration_statement->declaration; + = &statement->declaration.declaration; if (token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if (last_statement != NULL) { - last_statement->next = (statement_t*) declaration_statement; + last_statement->base.next = statement; } else { - first_statement = (statement_t*) declaration_statement; + first_statement = statement; } - last_statement = (statement_t*) declaration_statement; + last_statement = statement; /* do we have an assignment expression? */ if (token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->base.symbol); - last_statement->next = assign; - last_statement = assign; + last_statement->base.next = assign; + last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if (token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { - expression_statement_t *expression_statement - = allocate_ast_zero(sizeof(expression_statement[0])); - - expression_statement->statement.type = STATEMENT_EXPRESSION; - expression_statement->expression = parse_expression(); + statement_t *statement = allocate_statement(STATEMENT_EXPRESSION); + statement->expression.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: - return (statement_t*) expression_statement; + return statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if (token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; parse_statement_function parser = NULL; if (token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; add_anchor_token(T_NEWLINE); if (parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if (token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if (declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } rem_anchor_token(T_NEWLINE); if (statement == NULL) return NULL; - statement->source_position = start; - statement_t *next = statement->next; + statement->base.source_position = start; + statement_t *next = statement->base.next; while (next != NULL) { - next->source_position = start; - next = next->next; + next->base.source_position = start; + next = next->base.next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); - block_statement_t *block = allocate_ast_zero(sizeof(block[0])); - block->statement.type = STATEMENT_BLOCK; - + statement_t *block_statement = allocate_statement(STATEMENT_BLOCK); + context_t *last_context = current_context; - current_context = &block->context; + current_context = &block_statement->block.context; add_anchor_token(T_DEDENT); statement_t *last_statement = NULL; while (token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if (statement == NULL) continue; if (last_statement != NULL) { - last_statement->next = statement; + last_statement->base.next = statement; } else { - block->statements = statement; + block_statement->block.statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ - while (last_statement->next != NULL) - last_statement = last_statement->next; + while (last_statement->base.next != NULL) + last_statement = last_statement->base.next; } - assert(current_context == &block->context); + assert(current_context == &block_statement->block.context); current_context = last_context; - block->end_position = source_position; + block_statement->block.end_position = source_position; rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: - return (statement_t*) block; + return block_statement; } static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if (parameters != NULL) *parameters = NULL; expect('(', end_error2); if (token.type == ')') { next_token(); return; } add_anchor_token(')'); add_anchor_token(','); while (true) { if (token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if (token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); goto end_error; } break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if (last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if (parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.base.kind = DECLARATION_METHOD_PARAMETER; method_param->declaration.base.symbol = symbol; method_param->declaration.base.source_position = source_position; method_param->type = param_type->type; if (last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if (token.type != ',') break; next_token(); } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error2); return; end_error: rem_anchor_token(','); rem_anchor_token(')'); end_error2: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while (token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if (last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static declaration_t *parse_type_parameter(void) { declaration_t *declaration = allocate_declaration(DECLARATION_TYPE_VARIABLE); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->type_variable.constraints = parse_type_constraints(); } return declaration; } static type_variable_t *parse_type_parameters(context_t *context) { declaration_t *first_variable = NULL; declaration_t *last_variable = NULL; while (true) { declaration_t *type_variable = parse_type_parameter(); if (last_variable != NULL) { last_variable->type_variable.next = &type_variable->type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if (context != NULL) { type_variable->base.next = context->declarations; context->declarations = type_variable; } if (token.type != ',') break; next_token(); } return &first_variable->type_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->base.source_position.input_name != NULL); assert(current_context != NULL); declaration->base.next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if (token.type == '<') { next_token(); add_anchor_token('>'); method->type_parameters = parse_type_parameters(current_context); rem_anchor_token('>'); expect('>', end_error); } parse_parameter_declarations(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { declaration_t *declaration = (declaration_t*) parameter; declaration->base.next = current_context->declarations; current_context->declarations = declaration; } method_type->result_type = type_void; if (token.type == ':') { next_token(); if (token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } method_type->result_type = parse_type(); if (token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } expect(T_NEWLINE, end_error); method_parser_end: assert(current_context == &method->context); current_context = last_context; end_error: ; } static void parse_method_declaration(void) { eat(T_func); declaration_t *declaration = allocate_declaration(DECLARATION_METHOD); if (token.type == T_extern) { declaration->method.method.is_extern = true; next_token(); } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_method(&declaration->method.method); add_declaration(declaration); } static void parse_global_variable(void) { eat(T_var); declaration_t *declaration = allocate_declaration(DECLARATION_VARIABLE); declaration->variable.is_global = true; if (token.type == T_extern) { next_token(); declaration->variable.is_extern = true; } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); declaration->variable.type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_declaration(declaration); } static void parse_constant(void) { eat(T_const); declaration_t *declaration = allocate_declaration(DECLARATION_CONSTANT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->constant.type = parse_type(); } expect('=', end_error); declaration->constant.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static void parse_typealias(void) { eat(T_typealias); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); expect('=', end_error); declaration->typealias.type = parse_type(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if (token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if (token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if (parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if (parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while (token.type == '$') { attribute_t *attribute = parse_attribute(); if (attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_class(void) { eat(T_class); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing class", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_CLASS; compound_type->symbol = declaration->base.symbol; compound_type->attributes = parse_attributes(); declaration->typealias.type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); context_t *last_context = current_context; current_context = &compound_type->context; while (token.type != T_EOF && token.type != T_DEDENT) { parse_declaration(); } next_token(); assert(current_context == &compound_type->context); current_context = last_context; } end_error: add_declaration(declaration); } static void parse_struct(void) { eat(T_struct); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->symbol = declaration->base.symbol; if (token.type == '<') { next_token(); compound_type->type_parameters = parse_type_parameters(&compound_type->context); expect('>', end_error); } compound_type->attributes = parse_attributes(); declaration->typealias.type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration(declaration); end_error: ; } static void parse_union(void) { eat(T_union); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->symbol = declaration->base.symbol; compound_type->attributes = parse_attributes(); declaration->typealias.type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } diff --git a/semantic.c b/semantic.c index 60164f0..b74a890 100644 --- a/semantic.c +++ b/semantic.c @@ -1351,1246 +1351,1244 @@ static void check_call_expression(call_expression_t *call) /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->base.type = create_concrete_type(ref->base.type); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->base.type = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->base.type == NULL) { panic("Cast expression needs a datatype!"); } cast->base.type = normalize_type(cast->base.type); cast->value = check_expression(cast->value); if (cast->value->base.type == type_void) { error_at(cast->base.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->base.type == NULL) { error_at(dereference->base.source_position, "can't derefence expression with unknown datatype\n"); return; } if (value->base.type->type != TYPE_POINTER) { error_at(dereference->base.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->base.type; type_t *dereferenced_type = pointer_type->points_to; dereference->base.type = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->base.source_position, "can only take address of l-values\n"); return; } if (value->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->base.type = result_type; } static bool is_arithmetic_type(type_t *type) { if (type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static expression_t *lower_incdec_expression(expression_t *expression_) { unary_expression_t *expression = (unary_expression_t*) expression_; expression_t *value = check_expression(expression->value); type_t *type = value->base.type; expression_kind_t kind = expression->base.kind; if (!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression needs an lvalue\n", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { constant = allocate_expression(EXPR_INT_CONST); constant->base.type = type; constant->int_const.value = 1; } else { constant = allocate_expression(EXPR_FLOAT_CONST); constant->base.type = type; constant->float_const.value = 1.0; } expression_t *add = allocate_expression(kind == EXPR_UNARY_INCREMENT ? EXPR_BINARY_ADD : EXPR_BINARY_SUB); add->base.type = type; add->binary.left = value; add->binary.right = constant; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.type = type; assign->binary.left = value; assign->binary.right = add; return assign; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type != type_bool) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->base.type; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if (datatype->type != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->base.source_position); select->base.type = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; if (type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; - statement->return_value - = check_expression(statement->return_value); - expression_t *return_value = statement->return_value; + statement->value = check_expression(statement->value); + expression_t *return_value = statement->value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->base.type != type_void) { - error_at(statement->statement.source_position, + error_at(statement->base.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != method_result_type) { return_value = make_cast(return_value, method_result_type, - statement->statement.source_position, false); + statement->base.source_position, false); - statement->return_value = return_value; + statement->value = return_value; } } else { if (method_result_type != type_void) { - error_at(statement->statement.source_position, + error_at(statement->base.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { - error_at(statement->statement.source_position, + error_at(statement->base.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { - statement_t *next = statement->next; + statement_t *next = statement->base.next; statement = check_statement(statement); - assert(statement->next == next || statement->next == NULL); - statement->next = next; + assert(statement->base.next == next || statement->base.next == NULL); + statement->base.next = next; if (last != NULL) { - last->next = statement; + last->base.next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } -static void check_variable_declaration(variable_declaration_statement_t *statement) +static void check_variable_declaration(declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.base.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { - print_warning_prefix(statement->statement.source_position); + print_warning_prefix(statement->base.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { - print_warning_prefix(statement->statement.source_position); + print_warning_prefix(statement->base.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } - print_warning_prefix(statement->statement.source_position); + print_warning_prefix(statement->base.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { - error_at(goto_statement->statement.source_position, + error_at(goto_statement->base.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { - print_error_prefix(goto_statement->statement.source_position); + print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { - print_error_prefix(goto_statement->statement.source_position); + print_error_prefix(goto_statement->base.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ - if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { - lower_statement_function lowerer = statement_lowerers[statement->type]; + if ((int) statement->kind < (int) ARR_LEN(statement_lowerers)) { + lower_statement_function lowerer = statement_lowerers[statement->kind]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; - switch (statement->type) { + switch (statement->kind) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: - check_block_statement((block_statement_t*) statement); + check_block_statement(&statement->block); break; case STATEMENT_RETURN: - check_return_statement((return_statement_t*) statement); + check_return_statement(&statement->returns); break; case STATEMENT_GOTO: - check_goto_statement((goto_statement_t*) statement); + check_goto_statement(&statement->gotos); break; case STATEMENT_LABEL: - check_label_statement((label_statement_t*) statement); + check_label_statement(&statement->label); break; case STATEMENT_IF: - check_if_statement((if_statement_t*) statement); + check_if_statement(&statement->ifs); break; - case STATEMENT_VARIABLE_DECLARATION: - check_variable_declaration((variable_declaration_statement_t*) - statement); + case STATEMENT_DECLARATION: + check_variable_declaration(&statement->declaration); break; case STATEMENT_EXPRESSION: - check_expression_statement((expression_statement_t*) statement); + check_expression_statement(&statement->expression); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } declaration->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } static declaration_t *create_error_declarataion(symbol_t *symbol) { declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); declaration->base.symbol = symbol; declaration->base.exported = true; return declaration; } static declaration_t *find_declaration(const context_t *context, symbol_t *symbol) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } return declaration; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; declaration_t *declaration; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); declaration = create_error_declarataion(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); declaration = create_error_declarataion(symbol); } else { check_module(ref_module); declaration = find_declaration(&ref_module->context, symbol); if (declaration == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); declaration = create_error_declarataion(symbol); } else { ref_context = &ref_module->context; } } } if (!declaration->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->declaration == declaration) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(declaration, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL);
MatzeB/fluffy
5932d87e7da487a889ae26bb3c2e4fd499cad029
plugin update (not finished yet)
diff --git a/TODO b/TODO index 0665c7d..961a54a 100644 --- a/TODO +++ b/TODO @@ -1,27 +1,28 @@ This does not describe the goals and visions but short term things that should not be forgotten. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime - forbid same variable names in nested blocks - change firm to pass on debug info on unitialized_variable callback - introduce constant expressions +- introduce const type qualifier Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Add an alloca operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) Refactorings (mindless but often labor intensive tasks): - make unions for type_t (see cparser) - rename type to kind - keep typerefs as long as possible (start the skip_typeref madness similar to cparser) diff --git a/plugins/Makefile b/plugins/Makefile index 3fc1a90..63f029d 100644 --- a/plugins/Makefile +++ b/plugins/Makefile @@ -1,26 +1,26 @@ LFLAGS = SOURCES = $(wildcard plugin_*.fluffy) PLUGINS = $(addsuffix .dylib, $(basename $(SOURCES))) FLUFFY_FLAGS = -bomitfp=no -bdebuginfo=stabs DYNAMIC_LINK = -undefined dynamic_lookup .PHONY: all clean all: $(PLUGINS) %.dylib: %.o #gcc -shared $*.s $(LFLAGS) -o $*.so libtool -dynamic -o $@ $(DYNAMIC_LINK) $*.o %.o: %.s gcc -c $< -o $@ %.s: %.fluffy api.fluffy - ../fluffy --time $(FLUFFY_FLAGS) -S api.fluffy $*.fluffy -o $*.s + ../fluffy $(FLUFFY_FLAGS) -S api.fluffy $*.fluffy -o $*.s plugin_sql.s: plugin_while.dylib plugin_enum.s: plugin_while.dylib clean: rm -rf $(PLUGINS) diff --git a/plugins/api.fluffy b/plugins/api.fluffy index 2bd89be..11fed58 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,381 +1,392 @@ +module "fluffy.org/compiler/pluginapi" +export SourcePosition, Symbol, Token, Type, Attribute, CompoundEntry, \ + CompoundType, TypeConstraint, Declaration, Export, Context, \ + TypeVariable, Constant, Statement, Expression, IntConst, \ + BinaryExpression, BlockStatement, ExpressionStatement, \ + LabelStatement, GotoStatement, IfStatement, TypeClass, \ + TypeClassMethod, TypeClassInstance, Lexer, \ + STATEMENT_INAVLID, STATEMENT_ERROR, STATEMENT_BLOCK, \ + STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, \ + STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL + struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: kind : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: - type : unsigned int - datatype : Type* + kind : unsigned int + type : Type* source_position : SourcePosition lowered : byte struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 const STATEMENT_ERROR = 1 const STATEMENT_BLOCK = 2 const STATEMENT_RETURN = 3 const STATEMENT_VARIABLE_DECLARATION = 4 const STATEMENT_IF = 5 const STATEMENT_EXPRESSION = 6 const STATEMENT_GOTO = 7 const STATEMENT_LABEL = 8 const TYPE_INVALID = 0 const TYPE_ERROR = 1 const TYPE_VOID = 2 const TYPE_ATOMIC = 3 const TYPE_COMPOUND_CLASS = 4 const TYPE_COMPOUND_STRUCT = 5 const TYPE_COMPOUND_UNION = 6 const TYPE_METHOD = 7 const TYPE_POINTER = 8 const TYPE_ARRAY = 9 const TYPE_REFERENCE = 10 const TYPE_REFERENCE_TYPE_VARIABLE = 11 const TYPE_BIND_TYPEVARIABLES = 12 const DECLARATION_INVALID = 0 const DECLARATION_ERROR = 1 const DECLARATION_METHOD = 2 const DECLARATION_METHOD_PARAMETER = 3 const DECLARATION_ITERATOR = 4 const DECLARATION_VARIABLE = 5 const DECLARATION_CONSTANT = 6 const DECLARATION_TYPE_VARIABLE = 7 const DECLARATION_TYPEALIAS = 8 const DECLARATION_CONCEPT = 9 const DECLARATION_CONCEPT_METHOD = 10 const DECLARATION_LABEL = 11 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const EXPR_INVALID = 0 const EXPR_ERROR = 1 const EXPR_INT_CONST = 2 const EXPR_FLOAT_CONST = 3 const EXPR_BOOL_CONST = 4 const EXPR_STRING_CONST = 5 const EXPR_NULL_POINTER = 6 const EXPR_REFERENCE = 7 const EXPR_CALL = 8 const EXPR_UNARY = 9 const EXPR_BINARY = 10 const BINEXPR_INVALID = 0 const BINEXPR_ASSIGN = 1 const BINEXPR_ADD = 2 const T_EOF = 4 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* typealias ParseExpressionFunction = func () : Expression* typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.statement.type = STATEMENT_LABEL res.declaration.declaration.kind = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.declaration.kind = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() - res.expression.type = EXPR_BINARY + res.expression.kind = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() - res.expression.type = EXPR_INT_CONST + res.expression.kind = EXPR_INT_CONST return res func api_init(): stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): declaration.next = context.declarations context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label
MatzeB/fluffy
7496707e072ee0c3d48edfd56bcb411ad5f10e56
fix crash in error message
diff --git a/semantic.c b/semantic.c index 5c1d13b..60164f0 100644 --- a/semantic.c +++ b/semantic.c @@ -1748,869 +1748,869 @@ static void check_array_access_expression(array_access_expression_t *access) result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->base.type != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if (last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.base.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { - print_error_prefix(declaration->base.source_position); + print_error_prefix(instance->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } declaration->base.exported = true; found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } static module_t *find_module(symbol_t *name) { module_t *module = modules; for ( ; module != NULL; module = module->next) { if (module->name == name) break; } return module; } static declaration_t *create_error_declarataion(symbol_t *symbol) { declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); declaration->base.symbol = symbol; declaration->base.exported = true; return declaration; } static declaration_t *find_declaration(const context_t *context, symbol_t *symbol) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } return declaration; } static void check_module(module_t *module) { if (module->processed) return; assert(!module->processing); module->processing = true; int old_top = environment_top(); /* check imports */ import_t *import = module->context.imports; for( ; import != NULL; import = import->next) { const context_t *ref_context = NULL; declaration_t *declaration; symbol_t *symbol = import->symbol; symbol_t *modulename = import->module; module_t *ref_module = find_module(modulename); if (ref_module == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Referenced module \"%s\" does not exist\n", modulename->string); declaration = create_error_declarataion(symbol); } else { if (ref_module->processing) { print_error_prefix(import->source_position); fprintf(stderr, "Reference to module '%s' is recursive\n", modulename->string); declaration = create_error_declarataion(symbol); } else { check_module(ref_module); declaration = find_declaration(&ref_module->context, symbol); if (declaration == NULL) { print_error_prefix(import->source_position); fprintf(stderr, "Module '%s' does not declare '%s'\n", modulename->string, symbol->string); declaration = create_error_declarataion(symbol); } else { ref_context = &ref_module->context; } } } if (!declaration->base.exported) { print_error_prefix(import->source_position); fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", symbol->string, modulename->string); } if (symbol->declaration == declaration) { print_warning_prefix(import->source_position); fprintf(stderr, "'%s' imported twice\n", symbol->string); /* imported twice, ignore */ continue; } environment_push(declaration, ref_context); } check_and_push_context(&module->context); environment_pop_to(old_top); assert(module->processing); module->processing = false; assert(!module->processed); module->processed = true; } bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; module_t *module = modules; for ( ; module != NULL; module = module->next) { check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/test/shouldfail/error2.fluffy b/test/shouldfail/error2.fluffy new file mode 100644 index 0000000..8125029 --- /dev/null +++ b/test/shouldfail/error2.fluffy @@ -0,0 +1,2 @@ +instance NotThere int: + diff --git a/test/shouldfail/syntax2.fluffy b/test/shouldfail/syntax2.fluffy new file mode 100644 index 0000000..8df1a7f --- /dev/null +++ b/test/shouldfail/syntax2.fluffy @@ -0,0 +1,3 @@ +func main() : int: + return (0 * + 0)
MatzeB/fluffy
135a23fd1c4af829646a919b5976ee979eabe982
make meaning of _LAST enums consistent
diff --git a/ast.c b/ast.c index d7bcdbd..c4ee421 100644 --- a/ast.c +++ b/ast.c @@ -1,773 +1,770 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for (const char *c = string_const->value; *c != 0; ++c) { switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->base.symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch (unexpr->base.kind) { case EXPR_UNARY_CAST: fprintf(out, "cast<"); print_type(unexpr->base.type); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->base.kind); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch (binexpr->base.kind) { case EXPR_BINARY_ASSIGN: fprintf(out, "<-"); break; case EXPR_BINARY_ADD: fprintf(out, "+"); break; case EXPR_BINARY_SUB: fprintf(out, "-"); break; case EXPR_BINARY_MUL: fprintf(out, "*"); break; case EXPR_BINARY_DIV: fprintf(out, "/"); break; case EXPR_BINARY_NOTEQUAL: fprintf(out, "/="); break; case EXPR_BINARY_EQUAL: fprintf(out, "="); break; case EXPR_BINARY_LESS: fprintf(out, "<"); break; case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; case EXPR_BINARY_GREATER: fprintf(out, ">"); break; case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->base.kind); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->kind) { case EXPR_ERROR: fprintf(out, "*error expression*"); break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_FUNC: /* TODO */ fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while (statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->base.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch (statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; - case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if (method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->base.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->base.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while (method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if (method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->base.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch (declaration->kind) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type '%s'\n", get_declaration_kind_name(declaration->kind)); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: - case DECLARATION_LAST: fprintf(out, "invalid declaration (%s)\n", get_declaration_kind_name(declaration->kind)); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { print_declaration(declaration); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } void print_ast(FILE *new_out, const context_t *context) { indent = 0; out = new_out; print_context(context); assert(indent == 0); out = NULL; } const char *get_declaration_kind_name(declaration_kind_t type) { switch (type) { - case DECLARATION_LAST: case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } bool is_linktime_constant(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: /* TODO */ return false; case EXPR_ARRAY_ACCESS: /* TODO */ return false; case EXPR_UNARY_DEREFERENCE: return is_constant_expression(expression->unary.value); default: return false; } } bool is_constant_expression(const expression_t *expression) { switch (expression->kind) { case EXPR_INT_CONST: case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_NULL_POINTER: case EXPR_SIZEOF: return true; case EXPR_STRING_CONST: case EXPR_FUNC: case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: case EXPR_UNARY_DEREFERENCE: case EXPR_BINARY_ASSIGN: case EXPR_SELECT: case EXPR_ARRAY_ACCESS: return false; case EXPR_UNARY_TAKE_ADDRESS: return is_linktime_constant(expression->unary.value); case EXPR_REFERENCE: { declaration_t *declaration = expression->reference.declaration; if (declaration->kind == DECLARATION_CONSTANT) return true; return false; } case EXPR_CALL: /* TODO: we might introduce pure/side effect free calls */ return false; case EXPR_UNARY_CAST: case EXPR_UNARY_NEGATE: case EXPR_UNARY_NOT: case EXPR_UNARY_BITWISE_NOT: return is_constant_expression(expression->unary.value); case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: case EXPR_BINARY_MUL: case EXPR_BINARY_DIV: case EXPR_BINARY_MOD: case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: /* not that lazy and/or are not constant if their value is clear after * evaluating the left side. This is because we can't (always) evaluate the * left hand side until the ast2firm phase, and therefore can't determine * constness */ case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: return is_constant_expression(expression->binary.left) && is_constant_expression(expression->binary.right); case EXPR_ERROR: return true; case EXPR_INVALID: break; } panic("invalid expression in is_constant_expression"); } diff --git a/ast2firm.c b/ast2firm.c index 898d96d..7322ce5 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -476,1490 +476,1489 @@ static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->kind == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->kind != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = declaration->base.symbol; ident *ident = new_id_from_str(symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch (type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_method->base.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch (declaration->kind) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: - case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static long binexpr_kind_to_cmp_pn(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; case EXPR_BINARY_LESS: return pn_Cmp_Lt; case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; case EXPR_BINARY_GREATER: return pn_Cmp_Gt; case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ long compare_pn = binexpr_kind_to_cmp_pn(kind); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(declaration_t *declaration, type_argument_t *type_arguments) { assert(declaration->kind == DECLARATION_METHOD); method_t *method = &declaration->method.method; symbol_t *symbol = declaration->base.symbol; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); if (declaration->base.exported && get_entity_visibility(entity) != visibility_external_allocated) { set_entity_visibility(entity, visibility_external_visible); } pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(declaration, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->base.type->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if (result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(declaration, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); - case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->base.source_position); } static ir_node *expression_to_firm(const expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); EXPR_BINARY_CASES return binary_expression_to_firm( (const binary_expression_t*) expression); EXPR_UNARY_CASES return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if (statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while (statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ - break; + return; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); - break; + return; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); - break; + return; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); + return; + case STATEMENT_ERROR: + case STATEMENT_INVALID: break; - default: - abort(); } + panic("Invalid statement kind found"); } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: if (!is_polymorphic_method(&declaration->method.method)) { assure_instance(declaration, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; - case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } /** * Build a firm representation of the program */ void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); /* transform toplevel stuff */ const module_t *module = modules; for ( ; module != NULL; module = module->next) { context2firm(&module->context); } /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index 7c68f00..f702ce6 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,496 +1,496 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, - DECLARATION_LAST + DECLARATION_LAST = DECLARATION_LABEL } declaration_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; int refs; /**< temporarily used by semantic phase */ bool exported : 1; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; struct import_t { symbol_t *module; symbol_t *symbol; import_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_base_t base; method_t method; }; struct iterator_declaration_t { declaration_base_t base; method_t method; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_method_t { declaration_base_t base; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct module_t { symbol_t *name; context_t context; module_t *next; bool processing : 1; bool processed : 1; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; method_declaration_t method; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_method_t concept_method; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; method_t method; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *method; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, - STATEMENT_LAST + STATEMENT_LAST = STATEMENT_LABEL } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); expression_t *allocate_expression(expression_kind_t kind); declaration_t *allocate_declaration(declaration_kind_t kind); #endif diff --git a/main.c b/main.c index a12ee84..84c2b11 100644 --- a/main.c +++ b/main.c @@ -1,365 +1,373 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" #include "driver/firm_cmdline.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" #include "mangle.h" #include "adt/error.h" #ifdef _WIN32 #define LINKER "gcc.exe" #define TMPDIR "" #else #define LINKER "gcc" #define TMPDIR "/tmp/" #endif static bool dump_graphs; static bool dump_asts; static bool verbose; static bool had_parse_errors; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; static void initialize_firm(void) { firm_early_init(); dump_consts_local(1); dump_keepalive_edges(1); dbg_init(NULL, NULL, dbg_snprint); } static void get_output_name(char *buf, size_t buflen, const char *inputname, const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; for (const char *c = inputname; *c != 0; ++c) { if (*c == '.') last_dot = i; ++i; } if (last_dot == 0xffffffff) last_dot = i; if (last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if (extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } static void dump_ast(const context_t *context, const char *name, const char *ext) { if (!dump_asts) return; char filename[4096]; get_output_name(filename, sizeof(filename), name, ext); FILE* out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { print_ast(out, context); } fclose(out); } static void do_parse_file(FILE *in, const char *input_name) { bool result = parse_file(in, input_name); if (!result) { fprintf(stderr, "syntax errors found...\n"); had_parse_errors = true; return; } } static void do_check_semantic(void) { bool result = check_semantic(); if (!result) { fprintf(stderr, "Semantic errors found\n"); exit(1); } const module_t *module = modules; for ( ; module != NULL; module = module->next) { dump_ast(&module->context, module->name->string, "-semantic.txt"); } } static void link(const char *in, const char *out) { char buf[4096]; if (out == NULL) { out = "a.out"; } int res = snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); if (res < 0 || res >= (int) sizeof(buf)) { panic("Couldn't construct linker commandline (too long?)"); } if (verbose) { puts(buf); } int err = system(buf); if (err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } void lower_compound_params(void) { } static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } static void init_os_support(void) { /* OS option must be set to the backend */ switch (firm_opt.os_support) { case OS_SUPPORT_MINGW: set_be_option("ia32-gasmode=mingw"); break; case OS_SUPPORT_LINUX: set_be_option("ia32-gasmode=elf"); break; case OS_SUPPORT_MACHO: set_be_option("ia32-gasmode=macho"); set_be_option("ia32-stackalign=4"); set_be_option("pic"); break; } } static void set_option(const char *arg) { int res = firm_option(arg); (void) res; assert(res); } int main(int argc, const char **argv) { int opt_level; init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); init_mangle(); /* early options parsing */ for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') continue; const char *option = &arg[1]; if (option[0] == 'O') { sscanf(&option[1], "%d", &opt_level); } if (strcmp(arg, "-fwin32") == 0) { firm_opt.os_support = OS_SUPPORT_MINGW; } else if (strcmp(arg, "-fmac") == 0) { firm_opt.os_support = OS_SUPPORT_MACHO; } else if (strcmp(arg, "-flinux") == 0) { firm_opt.os_support = OS_SUPPORT_LINUX; } } /* set target/os specific stuff */ init_os_support(); /* set optimisations based on optimisation level */ switch(opt_level) { case 0: set_option("no-opt"); break; case 1: set_option("no-inline"); break; default: case 4: set_option("strict-aliasing"); /* use_builtins = true; */ /* fallthrough */ case 3: set_option("cond-eval"); set_option("if-conv"); /* fallthrough */ case 2: set_option("inline"); set_option("deconv"); set_be_option("omitfp"); break; } const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (strcmp(arg, "-o") == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; + } else if (arg[0] == 'O' + || strcmp(arg, "-fmac") == 0 + || strcmp(arg, "-fwin32") == 0 + || strcmp(arg, "-flinux") == 0) { + /* already processed in first pass */ } else if (strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if (strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if (strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if (strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; } else if (strcmp(arg, "-S") == 0) { mode = Compile; } else if (strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if (strcmp(arg, "-v") == 0) { verbose = 1; } else if (strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if (bearg[0] == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if (!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if (strcmp(bearg, "help") == 0) { return 1; } + } else if (arg[0] == '-') { + fprintf(stderr, "Invalid option '%s'\n", arg); + return 1; } else { const char *filename = argv[i]; FILE *in; if (strcmp(filename, "-") == 0) { in = stdin; /* nitpicking: is there a way so we can't have a normal file * with the same name? probably not... */ filename = "<stdin>"; } else { in = fopen(filename, "r"); if (in == NULL) { fprintf(stderr, "Couldn't open file '%s' for reading: %s\n", filename, strerror(errno)); exit(1); } } do_parse_file(in, filename); parsed++; if (in != stdin) { fclose(in); } } } if (parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } if (had_parse_errors) { return 1; } gen_firm_init(); do_check_semantic(); ast2firm(modules); const char *asmname; if (mode == Compile) { asmname = outname; } else { asmname = TMPDIR "fluffy.s"; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } set_ll_modes( mode_Ls, mode_Lu, mode_Is, mode_Iu); gen_firm_finish(asm_out, asmname, 1, true); fclose(asm_out); if (mode == CompileAndLink) { link(asmname, outname); } exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; } diff --git a/semantic.c b/semantic.c index 8e5749f..5c1d13b 100644 --- a/semantic.c +++ b/semantic.c @@ -1,978 +1,977 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->base.refs == 0 && !declaration->base.exported) { switch (declaration->kind) { /* only warn for methods/variables at the moment, we don't count refs on types yet */ case DECLARATION_METHOD: case DECLARATION_VARIABLE: print_warning_prefix(declaration->base.source_position); fprintf(stderr, "%s '%s' was declared but never read\n", get_declaration_kind_name(declaration->kind), symbol->string); default: break; } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); type->size_expression = check_expression(type->size_expression); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; declaration->base.refs++; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; - case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); } panic("reference to unknown declaration type encountered"); } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->base.source_position); ref->base.type = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->base.refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; type_t *righttype = right->base.type; if (lefttype->type != TYPE_POINTER && righttype->type != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } if (lefttype->type == TYPE_POINTER && righttype->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string);
MatzeB/fluffy
0d6098fb6b8dfbe5411f939020000dfdee06bd49
fix warnings
diff --git a/test/error1.fluffy b/test/error1.fluffy index 4b6fe19..a6d5d1d 100644 --- a/test/error1.fluffy +++ b/test/error1.fluffy @@ -1,10 +1,11 @@ // bool as compound element fails struct Foo: a : int b : bool var k : Foo* func main() : int: + cast<void> k return 0 export main diff --git a/test/evil.fluffy b/test/evil.fluffy index 89b4d0a..c6a4ccf 100644 --- a/test/evil.fluffy +++ b/test/evil.fluffy @@ -1,29 +1,28 @@ func extern printf(format : byte*, ...) : int -func extern malloc(size : unsigned int) : void* func extern puts(string : byte*) : int concept Print<T>: func print(object : T) instance Print int: func print(object : int): printf("%d\n", object) instance Print byte*: func print(object : byte*): puts(object) func swap<ST : Print, ST2 : Print>(obj1 : ST, obj2 : ST2, marker : int) : void: if marker <= 0: return print(obj1) print(obj2) swap(obj2, obj1, marker-1) func callit(): swap("blup", 42, 4) func main() : int: callit() return 0 export main diff --git a/test/polystruct.fluffy b/test/polystruct.fluffy index 56a206a..106ffc6 100644 --- a/test/polystruct.fluffy +++ b/test/polystruct.fluffy @@ -1,75 +1,74 @@ typealias String = byte* func extern malloc(size : unsigned int) : void* func extern printf(format : String, ...) : int func extern puts(val : String) -func extern strcmp(s1 : String, s2 : String) : int concept Printable<T>: func print(obj : T) instance Printable String: func print(obj : String): puts(obj) instance Printable int: func print(obj : int): printf("%d\n", obj) struct ListElement<T>: val : T next : ListElement<T>* struct List<T>: first : ListElement<T>* func AddToList<T>(list : List<T>*, element : ListElement<T>*): element.next = list.first list.first = element func AddMakeElement<T>(list : List<T>*, value : T): var element = cast<ListElement<T>*> malloc( sizeof<T> ) element.val = value AddToList(list, element) func PrintList<T : Printable>(list : List<T>*): var elem = list.first :beginloop if elem == null: return print(elem.val) elem = elem.next goto beginloop instance Printable List<int>*: func print(obj : List<int>*): PrintList(obj) instance Printable List<String>*: func print(obj : List<String>*): PrintList(obj) func main() : int: var l : List<String> l.first = null var e1 : ListElement<String> e1.val = "Hallo" var e2 : ListElement<String> e2.val = "Welt" AddToList(&l, &e1) AddToList(&l, &e2) print(&l) var l2 : List<int> l2.first = null AddMakeElement(&l2, 42) AddMakeElement(&l2, 13) print(&l2) var l3 : List<List<int>*> l3.first = null PrintList(&l3) return 0 export main diff --git a/test/typeclass.fluffy b/test/typeclass.fluffy index ec5d4f2..0dedae8 100644 --- a/test/typeclass.fluffy +++ b/test/typeclass.fluffy @@ -1,21 +1,20 @@ func extern printf(format : byte*, ...) : int -func extern malloc(size : unsigned int) : void* func extern puts(string : byte*) : int concept Print<T>: func print(object : T) instance Print int: func print(object : int): printf("%d\n", object) instance Print byte*: func print(object : byte*): puts(object) func main() : int: print("Eine fünf:") print(5) return 0 export main
MatzeB/fluffy
93dce96aa3ca1ac12ed6d5788aaf566b188e1090
adjustments for new modulesystem
diff --git a/stdlib/construct.fluffy b/stdlib/construct.fluffy index a6631ad..cecdcf4 100644 --- a/stdlib/construct.fluffy +++ b/stdlib/construct.fluffy @@ -1,15 +1,17 @@ +module "fluffy.org/stdlib" + concept Construct<T>: func construct(object : T*) func destruct(object : T*) func new<T : Construct>() : T*: var result = cast<T* > malloc(sizeof<T>) construct(result) return result func delete<T : Construct>(obj : T*): destruct(obj) free(obj) func allocate<T>() : T*: return cast<T*> malloc(sizeof<T>) diff --git a/stdlib/cstdio.fluffy b/stdlib/cstdio.fluffy index af7a489..fcfe12f 100644 --- a/stdlib/cstdio.fluffy +++ b/stdlib/cstdio.fluffy @@ -1,24 +1,35 @@ +module "fluffy.org/stdlib" +export FILE +export stdout, stderr, stdin, errno +export fputc, fputs, fopen, fclose, fflush, fread, fwrite +export ungetc, puts, putchar, printf, fprintf, sprintf, snprintf, EOF +export strerror + typealias FILE = void +/* TODO: these can be macros */ var extern stdout : FILE* var extern stderr : FILE* var extern stdin : FILE* +var extern errno : int func extern fputc(c : int, stream : FILE* ) : int func extern fputs(s : String, stream : FILE* ) : int func extern fopen(path : String, mode : String) : FILE* func extern fclose(stream : FILE* ) : int func extern fflush(stream : FILE* ) : int func extern fread(ptr : void*, size : size_t, nmemb : size_t, stream : FILE*) : size_t func extern fwrite(ptr : void*, size : size_t, nmemb : size_t, stream : FILE*) : size_t func extern ungetc(c : int, stream : FILE*) : int func extern puts(s : String) : int func extern putchar(c : int) : int func extern printf(format : String, ...) : int func extern fprintf(stream : FILE*, format : String, ...) : int func extern sprintf(str : String, format : String, ...) : int func extern snprintf(std : String, size : size_t, format : String, ...) : int +func extern strerror(errnum : int) : String + const EOF = -1 diff --git a/stdlib/cstdlib.fluffy b/stdlib/cstdlib.fluffy index 58f335a..09c3a08 100644 --- a/stdlib/cstdlib.fluffy +++ b/stdlib/cstdlib.fluffy @@ -1,24 +1,31 @@ +module "fluffy.org/stdlib" + +export calloc, malloc, realloc, free +export abort, atexit, exit +export getenc, system, abs, llabs, atof, atoi, atoll +export rand, srand, assert + func extern calloc(nmemb : size_t, size : size_t) : void* func extern malloc(size : size_t) : void* func extern realloc(ptr : void*, size : size_t) : void* func extern free(ptr : void*) func extern abort() func extern atexit(function : (func() : void)* ) func extern exit(status : int) func extern getenc(name : String) : String func extern system(string : String) : int func extern abs(j : int) : int func extern llabs(k : long) : long func extern atof(nptr : String) : double func extern atoi(nptr : String) : int func extern atoll(nptr : String) : long func extern rand() : int func extern srand(seed : unsigned int) func assert(condition : bool): if !condition: abort() diff --git a/stdlib/cstring.fluffy b/stdlib/cstring.fluffy index 7429539..e8bdce5 100644 --- a/stdlib/cstring.fluffy +++ b/stdlib/cstring.fluffy @@ -1,15 +1,17 @@ +module "fluffy.org/stdlib" + func extern memcpy(dest : void*, src : void*, size : size_t) : void* func extern memmove(dest : void*, src : void*, size : size_t) : void* func extern memcmp(s1 : void*, s2 : void*) : int func extern memset(s : void*, c : int, size : size_t) : void* func extern strcpy(dest : String, src : String) : String func extern strncpy(dest : String, src : String, n : size_t) : String func extern strcat(s1 : String, s2 : String) : String func extern strncat(s1 : String, s2 : String, n : size_t) : String func extern strcmp(s1 : String, s2 : String) : int func extern strncmp(s1 : String, s2 : String, n : size_t) : int func extern strlen(s : String) : size_t func extern strerror(errnum : int) : String diff --git a/stdlib/ctime.fluffy b/stdlib/ctime.fluffy index 1c723e0..a81833c 100644 --- a/stdlib/ctime.fluffy +++ b/stdlib/ctime.fluffy @@ -1,6 +1,8 @@ +module "fluffy.org/stdlib" + typealias time_t = int func extern time(timer : time_t*) : time_t func extern difftime(time1 : time_t, time0 : time_t) : double func extern ctime(timer : time_t*) : byte* diff --git a/stdlib/ctype.fluffy b/stdlib/ctype.fluffy index a8d7612..33dc3ad 100644 --- a/stdlib/ctype.fluffy +++ b/stdlib/ctype.fluffy @@ -1,16 +1,17 @@ +module "fluffy.org/stdlib" func extern isalpha(c : int) : int func extern isalnum(c : int) : int func extern isblank(c : int) : int func extern iscntrl(c : int) : int func extern isdigit(c : int) : int func extern isgraph(c : int) : int func extern islower(c : int) : int func extern isprint(c : int) : int func extern ispunct(c : int) : int func extern isspace(c : int) : int func extern isupper(c : int) : int func extern isxdigit(c : int) : int func extern tolower(c : int) : int func extern toupper(c : int) : int diff --git a/stdlib/ctypes.fluffy b/stdlib/ctypes.fluffy index eba75e8..623b0bc 100644 --- a/stdlib/ctypes.fluffy +++ b/stdlib/ctypes.fluffy @@ -1,3 +1,7 @@ +module "fluffy.org/stdlib" + +export size_t, String + typealias size_t = unsigned int typealias String = byte* diff --git a/stdlib/flexarray.fluffy b/stdlib/flexarray.fluffy index 2a58e2e..e8c74d8 100644 --- a/stdlib/flexarray.fluffy +++ b/stdlib/flexarray.fluffy @@ -1,38 +1,40 @@ +module "fluffy.org/stdlib" + struct FlexibleArray: buffer : byte* len : size_t size : size_t instance Construct FlexibleArray: func construct(array : FlexibleArray*): array.buffer = null array.len = 0 array.size = 0 func destruct(array : FlexibleArray*): free(array.buffer) func flexarray_resize(array : FlexibleArray*, new_len : size_t): if new_len > array.size: var new_size = array.size + 1 while new_size < new_len: new_size = new_size * 2 array.buffer = cast<byte* > realloc(array.buffer, new_size) array.size = new_size array.len = new_len func flexarray_append_char(array : FlexibleArray*, c : byte): flexarray_resize(array, array.len + 1) array.buffer[array.len - 1] = c func flexarray_append(array : FlexibleArray*, buffer : byte*, buffer_len : size_t): var old_len = array.len flexarray_resize(array, array.len + buffer_len) memcpy(array.buffer + cast<byte* > old_len, buffer, buffer_len) func flexarray_append_string(array : FlexibleArray*, string : String): var len = strlen(string) flexarray_append(array, string, len)
MatzeB/fluffy
0d2552ac05b0b8d9798614192e6889d33f4e8558
rewrote/extended support for modules
diff --git a/DESIGN b/DESIGN index e0c1862..b6e9f62 100644 --- a/DESIGN +++ b/DESIGN @@ -1,6 +1,31 @@ - Input: utf-8 - python like indentation to form blocks, but force user to either use spaces or tabs to indent - Only 1 hierarchic namespace (so 1 name specifies alway the same thing, independent of the context; Different things might be defined in the hierarchy) + + +To-Design: + +Namespacing: + - How to handle modules, imports, exports, libraries? + - Should we have file-local things? + == Modules == + Each file belongs to exactly 1 module. If there's no module specified then + stuff will go to the anonymous "main" module. + + Modules are specified by the module command. + Modulenames are a URL without the protocol part or optionally protocol + "fluffymodule://" + + All files of a module have to be compiled together. + + A recommendataion for naming is using internet urls: + module fluffy.org/stdlib + + (Practical question 1: should we allow all possible strings? Or just + stuff which is allowed in filenames?) + + - Think about a 2nd model where all files in a directory form a module + with a separate module description file in the directory... diff --git a/ast.c b/ast.c index 0bc56be..d7bcdbd 100644 --- a/ast.c +++ b/ast.c @@ -1,774 +1,773 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; -namespace_t *namespaces; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for (const char *c = string_const->value; *c != 0; ++c) { switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->base.symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch (unexpr->base.kind) { case EXPR_UNARY_CAST: fprintf(out, "cast<"); print_type(unexpr->base.type); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->base.kind); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch (binexpr->base.kind) { case EXPR_BINARY_ASSIGN: fprintf(out, "<-"); break; case EXPR_BINARY_ADD: fprintf(out, "+"); break; case EXPR_BINARY_SUB: fprintf(out, "-"); break; case EXPR_BINARY_MUL: fprintf(out, "*"); break; case EXPR_BINARY_DIV: fprintf(out, "/"); break; case EXPR_BINARY_NOTEQUAL: fprintf(out, "/="); break; case EXPR_BINARY_EQUAL: fprintf(out, "="); break; case EXPR_BINARY_LESS: fprintf(out, "<"); break; case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; case EXPR_BINARY_GREATER: fprintf(out, ">"); break; case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->base.kind); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->kind) { case EXPR_ERROR: fprintf(out, "*error expression*"); break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_FUNC: /* TODO */ fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while (statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->base.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch (statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if (method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->base.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->base.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while (method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if (method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->base.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch (declaration->kind) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type '%s'\n", get_declaration_kind_name(declaration->kind)); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: - fprintf(out, "invalid namespace declaration (%s)\n", + fprintf(out, "invalid declaration (%s)\n", get_declaration_kind_name(declaration->kind)); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { print_declaration(declaration); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } -void print_ast(FILE *new_out, const namespace_t *namespace) +void print_ast(FILE *new_out, const context_t *context) { indent = 0; out = new_out; - print_context(&namespace->context); + print_context(context); assert(indent == 0); out = NULL; } const char *get_declaration_kind_name(declaration_kind_t type) { switch (type) { case DECLARATION_LAST: case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } bool is_linktime_constant(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: /* TODO */ return false; case EXPR_ARRAY_ACCESS: /* TODO */ return false; case EXPR_UNARY_DEREFERENCE: return is_constant_expression(expression->unary.value); default: return false; } } bool is_constant_expression(const expression_t *expression) { switch (expression->kind) { case EXPR_INT_CONST: case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_NULL_POINTER: case EXPR_SIZEOF: return true; case EXPR_STRING_CONST: case EXPR_FUNC: case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: case EXPR_UNARY_DEREFERENCE: case EXPR_BINARY_ASSIGN: case EXPR_SELECT: case EXPR_ARRAY_ACCESS: return false; case EXPR_UNARY_TAKE_ADDRESS: return is_linktime_constant(expression->unary.value); case EXPR_REFERENCE: { declaration_t *declaration = expression->reference.declaration; if (declaration->kind == DECLARATION_CONSTANT) return true; return false; } case EXPR_CALL: /* TODO: we might introduce pure/side effect free calls */ return false; case EXPR_UNARY_CAST: case EXPR_UNARY_NEGATE: case EXPR_UNARY_NOT: case EXPR_UNARY_BITWISE_NOT: return is_constant_expression(expression->unary.value); case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: case EXPR_BINARY_MUL: case EXPR_BINARY_DIV: case EXPR_BINARY_MOD: case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: /* not that lazy and/or are not constant if their value is clear after * evaluating the left side. This is because we can't (always) evaluate the * left hand side until the ast2firm phase, and therefore can't determine * constness */ case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: return is_constant_expression(expression->binary.left) && is_constant_expression(expression->binary.right); case EXPR_ERROR: return true; case EXPR_INVALID: break; } panic("invalid expression in is_constant_expression"); } diff --git a/ast.h b/ast.h index 8200c77..512c0d1 100644 --- a/ast.h +++ b/ast.h @@ -1,78 +1,79 @@ #ifndef AST_H #define AST_H #include <stdbool.h> #include <stdio.h> typedef struct attribute_t attribute_t; typedef union declaration_t declaration_t; typedef union expression_t expression_t; typedef struct context_t context_t; typedef struct export_t export_t; +typedef struct import_t import_t; typedef struct declaration_base_t declaration_base_t; typedef struct expression_base_t expression_base_t; typedef struct int_const_t int_const_t; typedef struct float_const_t float_const_t; typedef struct string_const_t string_const_t; typedef struct bool_const_t bool_const_t; typedef struct cast_expression_t cast_expression_t; typedef struct reference_expression_t reference_expression_t; typedef struct call_argument_t call_argument_t; typedef struct call_expression_t call_expression_t; typedef struct binary_expression_t binary_expression_t; typedef struct unary_expression_t unary_expression_t; typedef struct select_expression_t select_expression_t; typedef struct array_access_expression_t array_access_expression_t; typedef struct sizeof_expression_t sizeof_expression_t; typedef struct func_expression_t func_expression_t; typedef struct statement_t statement_t; typedef struct block_statement_t block_statement_t; typedef struct return_statement_t return_statement_t; typedef struct if_statement_t if_statement_t; typedef struct variable_declaration_t variable_declaration_t; typedef struct variable_declaration_statement_t variable_declaration_statement_t; typedef struct expression_statement_t expression_statement_t; typedef struct goto_statement_t goto_statement_t; typedef struct label_declaration_t label_declaration_t; typedef struct label_statement_t label_statement_t; -typedef struct namespace_t namespace_t; +typedef struct module_t module_t; typedef struct method_parameter_t method_parameter_t; typedef struct method_t method_t; typedef struct method_declaration_t method_declaration_t; typedef struct iterator_declaration_t iterator_declaration_t; typedef struct constant_t constant_t; typedef struct global_variable_t global_variable_t; typedef struct typealias_t typealias_t; typedef struct concept_instance_t concept_instance_t; typedef struct concept_method_instance_t concept_method_instance_t; typedef struct concept_t concept_t; typedef struct concept_method_t concept_method_t; void init_ast_module(void); void exit_ast_module(void); -void print_ast(FILE *out, const namespace_t *namespace); +void print_ast(FILE *out, const context_t *context); void print_expression(const expression_t *expression); void *allocate_ast(size_t size); /** * Returns true if a given expression is a compile time * constant. */ bool is_constant_expression(const expression_t *expression); /** * An object with a fixed but at compiletime unknown adress which will be known * at link/load time. */ bool is_linktime_constant(const expression_t *expression); long fold_constant_to_int(const expression_t *expression); bool fold_constant_to_bool(const expression_t *expression); #endif diff --git a/ast2firm.c b/ast2firm.c index 8f955e3..898d96d 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -235,1739 +235,1731 @@ static unsigned get_type_size(type_t *type) return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if (result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_node *expression_to_firm(const expression_t *expression); static tarval *fold_constant_to_tarval(const expression_t *expression) { assert(is_constant_expression(expression)); ir_graph *old_current_ir_graph = current_ir_graph; current_ir_graph = get_const_code_irg(); ir_node *cnst = expression_to_firm(expression); current_ir_graph = old_current_ir_graph; if (!is_Const(cnst)) { panic("couldn't fold constant"); } tarval* tv = get_Const_tarval(cnst); return tv; } long fold_constant_to_int(const expression_t *expression) { if (expression->kind == EXPR_ERROR) return 0; tarval *tv = fold_constant_to_tarval(expression); if (!tarval_is_long(tv)) { panic("result of constant folding is not an integer"); } return get_tarval_long(tv); } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); int size = fold_constant_to_int(type->size_expression); set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->kind == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->kind != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = declaration->base.symbol; ident *ident = new_id_from_str(symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch (type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_method->base.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); - } else if (!is_polymorphic && method->export) { - set_entity_visibility(entity, visibility_external_visible); } else { - if (is_polymorphic && method->export) { - fprintf(stderr, "Warning: exporting polymorphic methods not " - "supported.\n"); - } set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch (declaration->kind) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } static long binexpr_kind_to_cmp_pn(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; case EXPR_BINARY_LESS: return pn_Cmp_Lt; case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; case EXPR_BINARY_GREATER: return pn_Cmp_Gt; case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_mode *mode = get_ir_mode(binary_expression->base.type); switch (kind) { case EXPR_BINARY_ADD: return new_d_Add(dbgi, left, right, mode); case EXPR_BINARY_SUB: return new_d_Sub(dbgi, left, right, mode); case EXPR_BINARY_MUL: return new_d_Mul(dbgi, left, right, mode); case EXPR_BINARY_AND: return new_d_And(dbgi, left, right, mode); case EXPR_BINARY_OR: return new_d_Or(dbgi, left, right, mode); case EXPR_BINARY_XOR: return new_d_Eor(dbgi, left, right, mode); case EXPR_BINARY_SHIFTLEFT: return new_d_Shl(dbgi, left, right, mode); case EXPR_BINARY_SHIFTRIGHT: return new_d_Shr(dbgi, left, right, mode); default: break; } /* a comparison expression? */ long compare_pn = binexpr_kind_to_cmp_pn(kind); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } -static ir_entity *assure_instance(method_t *method, symbol_t *symbol, +static ir_entity *assure_instance(declaration_t *declaration, type_argument_t *type_arguments) { + assert(declaration->kind == DECLARATION_METHOD); + method_t *method = &declaration->method.method; + symbol_t *symbol = declaration->base.symbol; + int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); + if (declaration->base.exported + && get_entity_visibility(entity) != visibility_external_allocated) { + set_entity_visibility(entity, visibility_external_visible); + } + pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } -static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, - type_argument_t *type_arguments, - const source_position_t *source_position) +static ir_node *method_reference_to_firm(declaration_t *declaration, + type_argument_t *type_arguments, + const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); - ir_entity *entity = assure_instance(method, symbol, type_arguments); + ir_entity *entity = assure_instance(declaration, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->base.type->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if (result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; - return method_reference_to_firm(&method_declaration->method, - declaration->base.symbol, - type_arguments, source_position); + return method_reference_to_firm(declaration, type_arguments, + source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->base.source_position); } static ir_node *expression_to_firm(const expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); EXPR_BINARY_CASES return binary_expression_to_firm( (const binary_expression_t*) expression); EXPR_UNARY_CASES return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if (statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while (statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { - method_declaration_t *method_declaration; - method_t *method; - /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: - method_declaration = (method_declaration_t*) declaration; - method = &method_declaration->method; - - if (!is_polymorphic_method(method)) { - assure_instance(method, declaration->base.symbol, NULL); + if (!is_polymorphic_method(&declaration->method.method)) { + assure_instance(declaration, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } -static void namespace2firm(namespace_t *namespace) -{ - context2firm(& namespace->context); -} - /** * Build a firm representation of the program */ -void ast2firm(void) +void ast2firm(const module_t *modules) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); init_ir_types(); assert(typevar_binding_stack_top() == 0); - namespace_t *namespace = namespaces; - while (namespace != NULL) { - namespace2firm(namespace); - namespace = namespace->next; + /* transform toplevel stuff */ + const module_t *module = modules; + for ( ; module != NULL; module = module->next) { + context2firm(&module->context); } + /* work generic code instantiation queue */ while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast2firm.h b/ast2firm.h index d95092b..feeb23a 100644 --- a/ast2firm.h +++ b/ast2firm.h @@ -1,17 +1,17 @@ #ifndef AST2FIRM_H #define AST2FIRM_H #include <libfirm/firm_types.h> #include "ast.h" -void ast2firm(void); +void ast2firm(const module_t *modules); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos); unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg); const char *dbg_retrieve(const dbg_info *dbg, unsigned *line); void init_ast2firm(void); void exit_ast2firm(void); #endif diff --git a/ast_t.h b/ast_t.h index 26a5e5d..7c68f00 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,485 +1,496 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; -extern namespace_t *namespaces; + +extern module_t *modules; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; + int refs; /**< temporarily used by semantic phase */ + bool exported : 1; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; +struct import_t { + symbol_t *module; + symbol_t *symbol; + import_t *next; + source_position_t source_position; +}; + /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; + import_t *imports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; - bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_base_t base; method_t method; }; struct iterator_declaration_t { declaration_base_t base; method_t method; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; - int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_method_t { declaration_base_t base; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; +struct module_t { + symbol_t *name; + context_t context; + module_t *next; + bool processing : 1; + bool processed : 1; +}; + union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; method_declaration_t method; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_method_t concept_method; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; method_t method; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *method; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; -struct namespace_t { - symbol_t *symbol; - const char *filename; - context_t context; - namespace_t *next; -}; - static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); expression_t *allocate_expression(expression_kind_t kind); +declaration_t *allocate_declaration(declaration_kind_t kind); #endif diff --git a/fluffy.vim b/fluffy.vim index 9fab06f..23c3c16 100644 --- a/fluffy.vim +++ b/fluffy.vim @@ -1,74 +1,75 @@ " Vim syntax file " Language: fluffy " " For version 5.x: Clear all syntax items " For version 6.x: Quit when a syntax file was already loaded if version < 600 syntax clear elseif exists("b:current_syntax") finish endif syn keyword fluffyType byte short int long float double void syn keyword fluffyType unsigned signed bool syn keyword fluffyStatement goto return continue break step syn keyword fluffyStatement instance syn keyword fluffyStatement export enum class syn keyword fluffyAttribute extern syn keyword fluffyRepeat for while loop syn keyword fluffyConditional if else +syn keyword fluffyStatement module import syn keyword fluffyConstant null true false syn keyword fluffyStatement struct nextgroup=fluffyIdentifier syn keyword fluffyStatement union nextgroup=fluffyIdentifier syn keyword fluffyStatement func nextgroup=fluffyIdentifier syn keyword fluffyStatement var nextgroup=fluffyIdentifier syn keyword fluffyStatement const nextgroup=fluffyIdentifier syn keyword fluffyStatement concept nextgroup=fluffyIdentifier syn keyword fluffyStatement typealias nextgroup=fluffyIdentifier syn match fluffyIdentifier "[a-zA-Z_][a-zA-Z0-9_]*" contained syn keyword fluffyOperator cast sizeof syn match fluffyComment +//.*$+ contains=fluffyTodo,fluffyComment syn region fluffyComment start=+/\*+ end=+\*/+ contains=fluffyTodo syn keyword fluffyTodo TODO FIXME XXX contained " strings syn region fluffyString start=+"+ end=+"+ skip=+\\\\\|\\"+ contains=fluffyEscape syn region fluffyCharacter start=+'+ end=+'+ skip=+\\\\\|\\'+ contains=fluffyEscape syn match fluffyEscape +\\[abfnrtv'"\\]+ contained syn match fluffyEscape "\\\o\{1,3}" contained syn match fluffyEscape "\\x\x\{2}" contained syn match fluffyNumber "\<0x\x\+[Ll]\=\>" syn match fluffyNumber "\<\d\+[LljJ]\=\>" syn match fluffyNumber "\.\d\+\([eE][+-]\=\d\+\)\=[jJ]\=\>" syn match fluffyNumber "\<\d\+\.\([eE][+-]\=\d\+\)\=[jJ]\=\>" syn match fluffyNumber "\<\d\+\.\d\+\([eE][+-]\=\d\+\)\=[jJ]\=\>" syn sync match fluffySync grouphere NONE "):$" syn sync maxlines=200 "syn sync minlines=2000 hi def link fluffyStatement Statement hi def link fluffyConditional Conditional hi def link fluffyConstant Constant hi def link fluffyString String hi def link fluffyCharacter Character hi def link fluffyOperator Operator hi def link fluffyEscape Special hi def link fluffyComment Comment hi def link fluffyTodo Todo hi def link fluffyNumber Number hi def link fluffyRepeat Repeat hi def link fluffyCondition Conditional hi def link fluffyType Type hi def link fluffyAttribute StorageClass hi def link fluffyIdentifier Identifier let b:current_syntax = "fluffy" diff --git a/main.c b/main.c index 0c599ad..a12ee84 100644 --- a/main.c +++ b/main.c @@ -1,354 +1,365 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" #include "driver/firm_cmdline.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" #include "mangle.h" #include "adt/error.h" #ifdef _WIN32 #define LINKER "gcc.exe" #define TMPDIR "" #else #define LINKER "gcc" #define TMPDIR "/tmp/" #endif -static bool dump_graphs = false; -static bool dump_asts = false; -static bool verbose = false; +static bool dump_graphs; +static bool dump_asts; +static bool verbose; +static bool had_parse_errors; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; static void initialize_firm(void) { firm_early_init(); dump_consts_local(1); dump_keepalive_edges(1); dbg_init(NULL, NULL, dbg_snprint); } static void get_output_name(char *buf, size_t buflen, const char *inputname, const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; for (const char *c = inputname; *c != 0; ++c) { if (*c == '.') last_dot = i; ++i; } if (last_dot == 0xffffffff) last_dot = i; if (last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if (extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } -static void dump_ast(const namespace_t *namespace, const char *name) +static void dump_ast(const context_t *context, const char *name, + const char *ext) { if (!dump_asts) return; - const char *fname = namespace->filename; - char filename[4096]; - get_output_name(filename, sizeof(filename), fname, name); + char filename[4096]; + get_output_name(filename, sizeof(filename), name, ext); FILE* out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { - print_ast(out, namespace); + print_ast(out, context); } fclose(out); } -static void parse_file(const char *fname) +static void do_parse_file(FILE *in, const char *input_name) { - FILE *in = fopen(fname, "r"); - if (in == NULL) { - fprintf(stderr, "couldn't open '%s' for reading: %s\n", fname, - strerror(errno)); - exit(1); - } - - namespace_t *namespace = parse(in, fname); - fclose(in); - - if (namespace == NULL) { - exit(1); + bool result = parse_file(in, input_name); + if (!result) { + fprintf(stderr, "syntax errors found...\n"); + had_parse_errors = true; + return; } - dump_ast(namespace, "-parse.txt"); } -static void check_semantic(void) +static void do_check_semantic(void) { - if (!check_static_semantic()) { + bool result = check_semantic(); + if (!result) { fprintf(stderr, "Semantic errors found\n"); - namespace_t *namespace = namespaces; - while (namespace != NULL) { - dump_ast(namespace, "-error.txt"); - namespace = namespace->next; - } exit(1); } - if (dump_asts) { - namespace_t *namespace = namespaces; - while (namespace != NULL) { - dump_ast(namespace, "-semantic.txt"); - namespace = namespace->next; - } + const module_t *module = modules; + for ( ; module != NULL; module = module->next) { + dump_ast(&module->context, module->name->string, + "-semantic.txt"); } } static void link(const char *in, const char *out) { char buf[4096]; if (out == NULL) { out = "a.out"; } - snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); + int res = snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); + if (res < 0 || res >= (int) sizeof(buf)) { + panic("Couldn't construct linker commandline (too long?)"); + } if (verbose) { puts(buf); } int err = system(buf); if (err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } void lower_compound_params(void) { } static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } static void init_os_support(void) { /* OS option must be set to the backend */ switch (firm_opt.os_support) { case OS_SUPPORT_MINGW: set_be_option("ia32-gasmode=mingw"); break; case OS_SUPPORT_LINUX: set_be_option("ia32-gasmode=elf"); break; case OS_SUPPORT_MACHO: set_be_option("ia32-gasmode=macho"); set_be_option("ia32-stackalign=4"); set_be_option("pic"); break; } } static void set_option(const char *arg) { int res = firm_option(arg); (void) res; assert(res); } int main(int argc, const char **argv) { int opt_level; init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); init_mangle(); /* early options parsing */ for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') continue; const char *option = &arg[1]; if (option[0] == 'O') { sscanf(&option[1], "%d", &opt_level); } if (strcmp(arg, "-fwin32") == 0) { firm_opt.os_support = OS_SUPPORT_MINGW; } else if (strcmp(arg, "-fmac") == 0) { firm_opt.os_support = OS_SUPPORT_MACHO; } else if (strcmp(arg, "-flinux") == 0) { firm_opt.os_support = OS_SUPPORT_LINUX; } } /* set target/os specific stuff */ init_os_support(); /* set optimisations based on optimisation level */ switch(opt_level) { case 0: set_option("no-opt"); break; case 1: set_option("no-inline"); break; default: case 4: set_option("strict-aliasing"); /* use_builtins = true; */ /* fallthrough */ case 3: set_option("cond-eval"); set_option("if-conv"); /* fallthrough */ case 2: set_option("inline"); set_option("deconv"); set_be_option("omitfp"); break; } const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (strcmp(arg, "-o") == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; } else if (strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if (strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if (strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if (strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; } else if (strcmp(arg, "-S") == 0) { mode = Compile; } else if (strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if (strcmp(arg, "-v") == 0) { verbose = 1; } else if (strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if (bearg[0] == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if (!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if (strcmp(bearg, "help") == 0) { return 1; } } else { + const char *filename = argv[i]; + FILE *in; + if (strcmp(filename, "-") == 0) { + in = stdin; + /* nitpicking: is there a way so we can't have a normal file + * with the same name? probably not... */ + filename = "<stdin>"; + } else { + in = fopen(filename, "r"); + if (in == NULL) { + fprintf(stderr, "Couldn't open file '%s' for reading: %s\n", + filename, strerror(errno)); + exit(1); + } + } + do_parse_file(in, filename); parsed++; - parse_file(argv[i]); + if (in != stdin) { + fclose(in); + } } } if (parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } + if (had_parse_errors) { + return 1; + } gen_firm_init(); - check_semantic(); + do_check_semantic(); - ast2firm(); + ast2firm(modules); const char *asmname; if (mode == Compile) { asmname = outname; } else { asmname = TMPDIR "fluffy.s"; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } set_ll_modes( mode_Ls, mode_Lu, mode_Is, mode_Iu); gen_firm_finish(asm_out, asmname, 1, true); fclose(asm_out); if (mode == CompileAndLink) { link(asmname, outname); } exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; } diff --git a/parser.c b/parser.c index a3a5d3b..eca5e7f 100644 --- a/parser.c +++ b/parser.c @@ -1,586 +1,590 @@ #include <config.h> #include "token_t.h" #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS -static expression_parse_function_t *expression_parsers = NULL; -static parse_statement_function *statement_parsers = NULL; -static parse_declaration_function *declaration_parsers = NULL; -static parse_attribute_function *attribute_parsers = NULL; +static expression_parse_function_t *expression_parsers; +static parse_statement_function *statement_parsers; +static parse_declaration_function *declaration_parsers; +static parse_attribute_function *attribute_parsers; static unsigned char token_anchor_set[T_LAST_TOKEN]; -static context_t *current_context = NULL; +static symbol_t *current_module_name; +static context_t *current_context; static int error = 0; token_t token; +module_t *modules; + static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_declaration_struct_size(declaration_kind_t kind) { static const size_t sizes[] = { [DECLARATION_ERROR] = sizeof(declaration_base_t), [DECLARATION_METHOD] = sizeof(method_declaration_t), [DECLARATION_METHOD_PARAMETER] = sizeof(method_parameter_t), [DECLARATION_ITERATOR] = sizeof(iterator_declaration_t), [DECLARATION_VARIABLE] = sizeof(variable_declaration_t), [DECLARATION_CONSTANT] = sizeof(constant_t), [DECLARATION_TYPE_VARIABLE] = sizeof(type_variable_t), [DECLARATION_TYPEALIAS] = sizeof(typealias_t), [DECLARATION_CONCEPT] = sizeof(concept_t), [DECLARATION_CONCEPT_METHOD] = sizeof(concept_method_t), [DECLARATION_LABEL] = sizeof(label_declaration_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } -static declaration_t *allocate_declaration(declaration_kind_t kind) +declaration_t *allocate_declaration(declaration_kind_t kind) { size_t size = get_declaration_struct_size(kind); declaration_t *declaration = allocate_ast_zero(size); declaration->kind = kind; return declaration; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { + [EXPR_ERROR] = sizeof(expression_base_t), [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch (token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if (result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *create_error_type(void) { type_t *error_type = allocate_type_zero(sizeof(error_type[0])); error_type->type = TYPE_ERROR; return error_type; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; parse_parameter_declarations(method_type, NULL); expect(':', end_error); method_type->result_type = parse_type(); return (type_t*) method_type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { @@ -641,1028 +645,1024 @@ type_t *parse_type(void) break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); expression_t *size = parse_expression(); rem_anchor_token(']'); expect(']', end_error); array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size_expression = size; type = (type_t*) array_type; break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); parse_method(&expression->func.method); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); expression->sizeofe.type = (type_t*) typeof_type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { expression_t *expression = allocate_expression(EXPR_CALL); expression->call.method = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \ return expression; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); register_expression_parser(parse_EXPR_UNARY_NOT, '!'); register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->base.source_position = start; while (true) { if (token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->base.source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } - - - - static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if (token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return (statement_t*) return_statement; } static statement_t *create_error_statement(void) { statement_t *statement = allocate_ast_zero(sizeof(statement[0])); statement->type = STATEMENT_ERROR; return statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return (statement_t*) goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->declaration.base.kind = DECLARATION_LABEL; label->declaration.base.source_position = source_position; label->declaration.base.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE, end_error); return (statement_t*) label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if (token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if (token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if (token.type == T_else) { next_token(); if (token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; if_statement->condition = condition; if_statement->true_statement = true_statement; if_statement->false_statement = false_statement; return (statement_t*) if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = symbol; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.source_position = source_position; assign->binary.left = expression; assign->binary.right = parse_expression(); expression_statement_t *expr_statement = allocate_ast_zero(sizeof(expr_statement[0])); expr_statement->statement.type = STATEMENT_EXPRESSION; expr_statement->expression = assign; return (statement_t*) expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } variable_declaration_statement_t *declaration_statement = allocate_ast_zero(sizeof(declaration_statement[0])); declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; declaration_t *declaration = (declaration_t*) &declaration_statement->declaration; declaration->base.kind = DECLARATION_VARIABLE; declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &declaration_statement->declaration; if (token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if (last_statement != NULL) { last_statement->next = (statement_t*) declaration_statement; } else { first_statement = (statement_t*) declaration_statement; } last_statement = (statement_t*) declaration_statement; /* do we have an assignment expression? */ if (token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->base.symbol); last_statement->next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if (token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { expression_statement_t *expression_statement = allocate_ast_zero(sizeof(expression_statement[0])); expression_statement->statement.type = STATEMENT_EXPRESSION; expression_statement->expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: return (statement_t*) expression_statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if (token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; parse_statement_function parser = NULL; if (token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; add_anchor_token(T_NEWLINE); if (parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if (token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if (declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } rem_anchor_token(T_NEWLINE); if (statement == NULL) return NULL; statement->source_position = start; statement_t *next = statement->next; while (next != NULL) { next->source_position = start; next = next->next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; context_t *last_context = current_context; current_context = &block->context; add_anchor_token(T_DEDENT); statement_t *last_statement = NULL; while (token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if (statement == NULL) continue; if (last_statement != NULL) { last_statement->next = statement; } else { block->statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while (last_statement->next != NULL) last_statement = last_statement->next; } assert(current_context == &block->context); current_context = last_context; block->end_position = source_position; rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: return (statement_t*) block; } static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if (parameters != NULL) *parameters = NULL; expect('(', end_error2); if (token.type == ')') { next_token(); return; } add_anchor_token(')'); add_anchor_token(','); while (true) { if (token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if (token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); goto end_error; } break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if (last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if (parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.base.kind = DECLARATION_METHOD_PARAMETER; method_param->declaration.base.symbol = symbol; method_param->declaration.base.source_position = source_position; method_param->type = param_type->type; if (last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if (token.type != ',') break; next_token(); } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error2); return; end_error: rem_anchor_token(','); rem_anchor_token(')'); end_error2: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while (token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if (last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static declaration_t *parse_type_parameter(void) { declaration_t *declaration = allocate_declaration(DECLARATION_TYPE_VARIABLE); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->type_variable.constraints = parse_type_constraints(); } return declaration; } static type_variable_t *parse_type_parameters(context_t *context) { declaration_t *first_variable = NULL; declaration_t *last_variable = NULL; while (true) { declaration_t *type_variable = parse_type_parameter(); if (last_variable != NULL) { last_variable->type_variable.next = &type_variable->type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if (context != NULL) { type_variable->base.next = context->declarations; context->declarations = type_variable; } if (token.type != ',') break; next_token(); } return &first_variable->type_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->base.source_position.input_name != NULL); assert(current_context != NULL); declaration->base.next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if (token.type == '<') { next_token(); add_anchor_token('>'); method->type_parameters = parse_type_parameters(current_context); rem_anchor_token('>'); expect('>', end_error); } parse_parameter_declarations(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ @@ -1678,701 +1678,783 @@ static void parse_method(method_t *method) next_token(); if (token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } method_type->result_type = parse_type(); if (token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } expect(T_NEWLINE, end_error); method_parser_end: assert(current_context == &method->context); current_context = last_context; end_error: ; } static void parse_method_declaration(void) { eat(T_func); declaration_t *declaration = allocate_declaration(DECLARATION_METHOD); if (token.type == T_extern) { declaration->method.method.is_extern = true; next_token(); } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_method(&declaration->method.method); add_declaration(declaration); } static void parse_global_variable(void) { eat(T_var); declaration_t *declaration = allocate_declaration(DECLARATION_VARIABLE); declaration->variable.is_global = true; if (token.type == T_extern) { next_token(); declaration->variable.is_extern = true; } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); declaration->variable.type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_declaration(declaration); } static void parse_constant(void) { eat(T_const); declaration_t *declaration = allocate_declaration(DECLARATION_CONSTANT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->constant.type = parse_type(); } expect('=', end_error); declaration->constant.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static void parse_typealias(void) { eat(T_typealias); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); expect('=', end_error); declaration->typealias.type = parse_type(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if (token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if (token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if (parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if (parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while (token.type == '$') { attribute_t *attribute = parse_attribute(); if (attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_class(void) { eat(T_class); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing class", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_CLASS; compound_type->symbol = declaration->base.symbol; compound_type->attributes = parse_attributes(); declaration->typealias.type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); context_t *last_context = current_context; current_context = &compound_type->context; while (token.type != T_EOF && token.type != T_DEDENT) { parse_declaration(); } next_token(); assert(current_context == &compound_type->context); current_context = last_context; } end_error: add_declaration(declaration); } static void parse_struct(void) { eat(T_struct); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->symbol = declaration->base.symbol; if (token.type == '<') { next_token(); compound_type->type_parameters = parse_type_parameters(&compound_type->context); expect('>', end_error); } compound_type->attributes = parse_attributes(); declaration->typealias.type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration(declaration); end_error: ; } static void parse_union(void) { eat(T_union); declaration_t *declaration = allocate_declaration(DECLARATION_TYPEALIAS); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->symbol = declaration->base.symbol; compound_type->attributes = parse_attributes(); declaration->typealias.type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } end_error: add_declaration(declaration); } static concept_method_t *parse_concept_method(void) { expect(T_func, end_error); declaration_t *declaration = allocate_declaration(DECLARATION_CONCEPT_METHOD); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); memset(method_type, 0, sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_parameter_declarations(method_type, &declaration->concept_method.parameters); if (token.type == ':') { next_token(); method_type->result_type = parse_type(); } else { method_type->result_type = type_void; } expect(T_NEWLINE, end_error); declaration->concept_method.method_type = method_type; add_declaration(declaration); return &declaration->concept_method; end_error: return NULL; } static void parse_concept(void) { eat(T_concept); declaration_t *declaration = allocate_declaration(DECLARATION_CONCEPT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); context_t *context = &declaration->concept.context; add_anchor_token('>'); declaration->concept.type_parameters = parse_type_parameters(context); rem_anchor_token('>'); expect('>', end_error); } expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_method_t *last_method = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_method_t *method = parse_concept_method(); method->concept = &declaration->concept; if (last_method != NULL) { last_method->next = method; } else { declaration->concept.methods = method; } last_method = method; } next_token(); end_of_parse_concept: add_declaration(declaration); return; end_error: ; } static concept_method_instance_t *parse_concept_method_instance(void) { concept_method_instance_t *method_instance = allocate_ast_zero(sizeof(method_instance[0])); expect(T_func, end_error); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method " "instance", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } method_instance->source_position = source_position; method_instance->symbol = token.v.symbol; next_token(); parse_method(& method_instance->method); return method_instance; end_error: return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if (token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect('>', end_error); } instance->type_arguments = parse_type_arguments(); expect(':', end_error); expect(T_NEWLINE, end_error); if (token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_method_instance_t *last_method = NULL; while (token.type != T_DEDENT) { if (token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if (token.type == T_NEWLINE) { next_token(); continue; } concept_method_instance_t *method = parse_concept_method_instance(); if (method == NULL) continue; if (last_method != NULL) { last_method->next = method; } else { instance->method_instances = method; } last_method = method; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; return; end_error: ; } static void skip_declaration(void) { next_token(); } +static void parse_import(void) +{ + eat(T_import); + if (token.type != T_STRING_LITERAL) { + parse_error_expected("problem while parsing import directive", + T_STRING_LITERAL, 0); + eat_until_anchor(); + return; + } + symbol_t *modulename = symbol_table_insert(token.v.string); + next_token(); + + while (true) { + if (token.type != T_IDENTIFIER) { + parse_error_expected("problem while parsing import directive", + T_IDENTIFIER, 0); + eat_until_anchor(); + return; + } + + import_t *import = allocate_ast_zero(sizeof(import[0])); + import->module = modulename; + import->symbol = token.v.symbol; + import->source_position = source_position; + + import->next = current_context->imports; + current_context->imports = import; + next_token(); + + if (token.type != ',') + break; + eat(','); + } + expect(T_NEWLINE, end_error); + +end_error: + ; +} + static void parse_export(void) { eat(T_export); while (true) { if (token.type == T_NEWLINE) { break; } if (token.type != T_IDENTIFIER) { - parse_error_expected("problem while parsing export declaration", + parse_error_expected("problem while parsing export directive", T_IDENTIFIER, 0); eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if (token.type != ',') { break; } next_token(); } expect(T_NEWLINE, end_error); end_error: ; } +static void parse_module(void) +{ + eat(T_module); + + /* a simple URL string without a protocol */ + if (token.type != T_STRING_LITERAL) { + parse_error_expected("problem while parsing module", T_STRING_LITERAL, 0); + return; + } + + symbol_t *new_module_name = symbol_table_insert(token.v.string); + next_token(); + + if (current_module_name != NULL && current_module_name != new_module_name) { + parser_print_error_prefix(); + fprintf(stderr, "new module name '%s' overrides old name '%s'\n", + new_module_name->string, current_module_name->string); + } + current_module_name = new_module_name; + + expect(T_NEWLINE, end_error); + +end_error: + ; +} + void parse_declaration(void) { if (token.type < 0) { if (token.type == T_EOF) return; /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } - parse_declaration_function parser = NULL; + parse_declaration_function parse = NULL; if (token.type < ARR_LEN(declaration_parsers)) - parser = declaration_parsers[token.type]; + parse = declaration_parsers[token.type]; - if (parser == NULL) { + if (parse == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_anchor(); return; } - if (parser != NULL) { - parser(); - } -} - -static namespace_t *get_namespace(symbol_t *symbol) -{ - /* search for an existing namespace */ - namespace_t *namespace = namespaces; - while (namespace != NULL) { - if (namespace->symbol == symbol) - return namespace; - - namespace = namespace->next; - } - - namespace = allocate_ast_zero(sizeof(namespace[0])); - namespace->symbol = symbol; - - namespace->next = namespaces; - namespaces = namespace; - - return namespace; -} - -static namespace_t *parse_namespace(void) -{ - symbol_t *namespace_symbol = NULL; - - /* parse namespace name */ - if (token.type == T_namespace) { - next_token(); - if (token.type != T_IDENTIFIER) { - parse_error_expected("problem while parsing namespace", - T_IDENTIFIER, 0); - eat_until_anchor(); - } - namespace_symbol = token.v.symbol; - next_token(); - - if (token.type != T_NEWLINE) { - parse_error("extra tokens after namespace definition"); - eat_until_anchor(); - } else { - next_token(); - } - } - - namespace_t *namespace = get_namespace(namespace_symbol); - assert(current_context == NULL); - current_context = &namespace->context; - - /* parse namespace entries */ - while (token.type != T_EOF) { - parse_declaration(); - } - - assert(current_context == &namespace->context); - current_context = NULL; - - return namespace; + parse(); } static void register_declaration_parsers(void) { register_declaration_parser(parse_method_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_class, T_class); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); + register_declaration_parser(parse_import, T_import); + register_declaration_parser(parse_module, T_module); register_declaration_parser(skip_declaration, T_NEWLINE); } -namespace_t *parse(FILE *in, const char *input_name) +static module_t *get_module(symbol_t *name) +{ + if (name == NULL) { + name = symbol_table_insert(""); + } + + /* search for an existing module */ + module_t *module = modules; + for ( ; module != NULL; module = module->next) { + if (module->name == name) + break; + } + if (module == NULL) { + module = allocate_ast_zero(sizeof(module[0])); + module->name = name; + module->next = modules; + modules = module; + } + return module; +} + +static void append_context(context_t *dest, const context_t *source) +{ + declaration_t *last = dest->declarations; + if (last != NULL) { + while (last->base.next != NULL) { + last = last->base.next; + } + last->base.next = source->declarations; + } else { + dest->declarations = source->declarations; + } + + concept_instance_t *last_concept_instance = dest->concept_instances; + if (last_concept_instance != NULL) { + while (last_concept_instance->next != NULL) { + last_concept_instance = last_concept_instance->next; + } + last_concept_instance->next = source->concept_instances; + } else { + dest->concept_instances = source->concept_instances; + } + + export_t *last_export = dest->exports; + if (last_export != NULL) { + while (last_export->next != NULL) { + last_export = last_export->next; + } + last_export->next = source->exports; + } else { + dest->exports = source->exports; + } + + import_t *last_import = dest->imports; + if (last_import != NULL) { + while (last_import->next != NULL) { + last_import = last_import->next; + } + last_import->next = source->imports; + } else { + dest->imports = source->imports; + } +} + +bool parse_file(FILE *in, const char *input_name) { memset(token_anchor_set, 0, sizeof(token_anchor_set)); + /* get the lexer running */ lexer_init(in, input_name); next_token(); - add_anchor_token(T_EOF); + context_t file_context; + memset(&file_context, 0, sizeof(file_context)); + + assert(current_context == NULL); + current_context = &file_context; - namespace_t *namespace = parse_namespace(); - namespace->filename = input_name; + current_module_name = NULL; + add_anchor_token(T_EOF); + while (token.type != T_EOF) { + parse_declaration(); + } rem_anchor_token(T_EOF); + assert(current_context == &file_context); + current_context = NULL; + + /* append stuff to module */ + module_t *module = get_module(current_module_name); + append_context(&module->context, &file_context); + + /* check that we have matching rem_anchor_token calls for each add */ #ifndef NDEBUG for (int i = 0; i < T_LAST_TOKEN; ++i) { if (token_anchor_set[i] > 0) { panic("leaked token"); } } #endif lexer_destroy(); - if (error) { - fprintf(stderr, "syntax errors found...\n"); - return NULL; - } - - return namespace; + return !error; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); } diff --git a/parser.h b/parser.h index f13fe3c..cae960b 100644 --- a/parser.h +++ b/parser.h @@ -1,12 +1,12 @@ #ifndef PARSER_H #define PARSER_H #include <stdio.h> #include "ast.h" -namespace_t *parse(FILE *in, const char *input_name); +bool parse_file(FILE *in, const char *input_name); void init_parser(void); void exit_parser(void); #endif diff --git a/semantic.c b/semantic.c index ca3929e..8e5749f 100644 --- a/semantic.c +++ b/semantic.c @@ -1,1057 +1,1061 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ -static inline +static void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; - if (declaration->kind == DECLARATION_VARIABLE) { - variable_declaration_t *variable - = (variable_declaration_t*) declaration; - if (variable->refs == 0 && !variable->is_extern) { + if (declaration->base.refs == 0 && !declaration->base.exported) { + switch (declaration->kind) { + /* only warn for methods/variables at the moment, we don't + count refs on types yet */ + case DECLARATION_METHOD: + case DECLARATION_VARIABLE: print_warning_prefix(declaration->base.source_position); - fprintf(stderr, "variable '%s' was declared but never read\n", + fprintf(stderr, "%s '%s' was declared but never read\n", + get_declaration_kind_name(declaration->kind), symbol->string); + default: + break; } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); type->size_expression = check_expression(type->size_expression); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; + declaration->base.refs++; + switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; - variable->refs++; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); - return NULL; } panic("reference to unknown declaration type encountered"); - return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->base.source_position); ref->base.type = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ - variable->refs--; + variable->base.refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; type_t *righttype = right->base.type; if (lefttype->type != TYPE_POINTER && righttype->type != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } if (lefttype->type == TYPE_POINTER && righttype->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->base.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if (method_instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->base.type = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->base.symbol->string, concept->base.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { @@ -1450,1098 +1454,1164 @@ static void check_take_address_expression(unary_expression_t *expression) } static bool is_arithmetic_type(type_t *type) { if (type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static expression_t *lower_incdec_expression(expression_t *expression_) { unary_expression_t *expression = (unary_expression_t*) expression_; expression_t *value = check_expression(expression->value); type_t *type = value->base.type; expression_kind_t kind = expression->base.kind; if (!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->base.source_position); fprintf(stderr, "%s expression needs an lvalue\n", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { constant = allocate_expression(EXPR_INT_CONST); constant->base.type = type; constant->int_const.value = 1; } else { constant = allocate_expression(EXPR_FLOAT_CONST); constant->base.type = type; constant->float_const.value = 1.0; } expression_t *add = allocate_expression(kind == EXPR_UNARY_INCREMENT ? EXPR_BINARY_ADD : EXPR_BINARY_SUB); add->base.type = type; add->binary.left = value; add->binary.right = constant; expression_t *assign = allocate_expression(EXPR_BINARY_ASSIGN); assign->base.type = type; assign->binary.left = value; assign->binary.right = add; return assign; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->base.type; if (type != type_bool) { print_error_prefix(expression->base.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->base.type = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->base.type; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if (datatype->type != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->base.source_position); select->base.type = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; if (type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->base.type != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if (last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ - statement->declaration.refs = 0; + statement->declaration.base.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; if (!is_constant_expression(expression)) { print_error_prefix(constant->base.source_position); fprintf(stderr, "Value for constant '%s' is not constant\n", constant->base.symbol->string); } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { - method_declaration_t *method; - variable_declaration_t *variable; - symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } - switch (declaration->kind) { - case DECLARATION_METHOD: - method = (method_declaration_t*) declaration; - method->method.export = 1; - break; - case DECLARATION_VARIABLE: - variable = (variable_declaration_t*) declaration; - variable->export = 1; - break; - default: - print_error_prefix(export->source_position); - fprintf(stderr, "Can only export functions and variables but '%s' " - "is a %s\n", symbol->string, - get_declaration_kind_name(declaration->kind)); - return; - } - - found_export = true; + declaration->base.exported = true; + found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } -static void check_namespace(namespace_t *namespace) -{ - int old_top = environment_top(); - - check_and_push_context(&namespace->context); - - environment_pop_to(old_top); -} - void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } -int check_static_semantic(void) +static module_t *find_module(symbol_t *name) +{ + module_t *module = modules; + for ( ; module != NULL; module = module->next) { + if (module->name == name) + break; + } + return module; +} + +static declaration_t *create_error_declarataion(symbol_t *symbol) +{ + declaration_t *declaration = allocate_declaration(DECLARATION_ERROR); + declaration->base.symbol = symbol; + declaration->base.exported = true; + return declaration; +} + +static declaration_t *find_declaration(const context_t *context, + symbol_t *symbol) +{ + declaration_t *declaration = context->declarations; + for ( ; declaration != NULL; declaration = declaration->base.next) { + if (declaration->base.symbol == symbol) + break; + } + return declaration; +} + +static void check_module(module_t *module) +{ + if (module->processed) + return; + assert(!module->processing); + module->processing = true; + + int old_top = environment_top(); + + /* check imports */ + import_t *import = module->context.imports; + for( ; import != NULL; import = import->next) { + const context_t *ref_context = NULL; + declaration_t *declaration; + + symbol_t *symbol = import->symbol; + symbol_t *modulename = import->module; + module_t *ref_module = find_module(modulename); + if (ref_module == NULL) { + print_error_prefix(import->source_position); + fprintf(stderr, "Referenced module \"%s\" does not exist\n", + modulename->string); + declaration = create_error_declarataion(symbol); + } else { + if (ref_module->processing) { + print_error_prefix(import->source_position); + fprintf(stderr, "Reference to module '%s' is recursive\n", + modulename->string); + declaration = create_error_declarataion(symbol); + } else { + check_module(ref_module); + declaration = find_declaration(&ref_module->context, symbol); + if (declaration == NULL) { + print_error_prefix(import->source_position); + fprintf(stderr, "Module '%s' does not declare '%s'\n", + modulename->string, symbol->string); + declaration = create_error_declarataion(symbol); + } else { + ref_context = &ref_module->context; + } + } + } + if (!declaration->base.exported) { + print_error_prefix(import->source_position); + fprintf(stderr, "Cannot import '%s' from \"%s\" because it is not exported\n", + symbol->string, modulename->string); + } + if (symbol->declaration == declaration) { + print_warning_prefix(import->source_position); + fprintf(stderr, "'%s' imported twice\n", symbol->string); + /* imported twice, ignore */ + continue; + } + + environment_push(declaration, ref_context); + } + + check_and_push_context(&module->context); + environment_pop_to(old_top); + + assert(module->processing); + module->processing = false; + assert(!module->processed); + module->processed = true; +} + +bool check_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; - namespace_t *namespace = namespaces; - for ( ; namespace != NULL; namespace = namespace->next) { - check_namespace(namespace); + module_t *module = modules; + for ( ; module != NULL; module = module->next) { + check_module(module); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); - obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/semantic.h b/semantic.h index 80e14e5..8c5c5b0 100644 --- a/semantic.h +++ b/semantic.h @@ -1,16 +1,18 @@ #ifndef SEMANTIC_H #define SEMANTIC_H #include "ast.h" -int check_static_semantic(void); +/* check static semantic of a bunch of files and organize them into modules + * if semantic is fine */ +bool check_semantic(void); concept_instance_t *find_concept_instance(concept_t *concept); concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method); void init_semantic_module(void); void exit_semantic_module(void); #endif diff --git a/test/modules/main.fluffy b/test/modules/main.fluffy new file mode 100644 index 0000000..3e5569f --- /dev/null +++ b/test/modules/main.fluffy @@ -0,0 +1,6 @@ +import "fluffy.org/compiler/test/moduletest" dosomething + +export main +func main() : int: + dosomething() + return 0 diff --git a/test/modules/module.fluffy b/test/modules/module.fluffy new file mode 100644 index 0000000..d074b40 --- /dev/null +++ b/test/modules/module.fluffy @@ -0,0 +1,8 @@ +module "fluffy.org/compiler/test/moduletest" +export dosomething + +func extern printf(str : byte*, ...) : int + +func dosomething(): + printf("Do Something\n") + diff --git a/tokens.inc b/tokens.inc index b12a4d8..890648c 100644 --- a/tokens.inc +++ b/tokens.inc @@ -1,91 +1,92 @@ #ifndef TS #define TS(x,str,val) #endif TS(NEWLINE, "newline", = 256) TS(INDENT, "indent",) TS(DEDENT, "dedent",) TS(IDENTIFIER, "identifier",) TS(INTEGER, "integer number",) TS(STRING_LITERAL, "string literal",) /* hack... */ #undef bool #undef true #undef false #define Keyword(x) T(x,#x,) Keyword(bool) Keyword(byte) Keyword(cast) Keyword(class) Keyword(const) Keyword(double) Keyword(else) +Keyword(import) Keyword(export) Keyword(extern) Keyword(false) Keyword(float) Keyword(func) Keyword(goto) Keyword(if) Keyword(instance) Keyword(int) Keyword(long) -Keyword(namespace) +Keyword(module) Keyword(null) Keyword(return) Keyword(short) Keyword(signed) Keyword(static) Keyword(struct) Keyword(true) Keyword(typealias) Keyword(concept) Keyword(union) Keyword(unsigned) Keyword(var) Keyword(void) Keyword(sizeof) Keyword(typeof) #undef S #define bool _Bool #define true 1 #define false 0 T(DOTDOT, "..",) T(DOTDOTDOT, "...",) T(EQUALEQUAL, "==",) T(TYPESTART, "<$",) T(SLASHEQUAL, "/=",) T(LESSEQUAL, "<=",) T(LESSLESS, "<<",) T(GREATEREQUAL, ">=",) T(GREATERGREATER, ">>",) T(PIPEPIPE, "||",) T(ANDAND, "&&",) T(PLUSPLUS, "++",) T(MINUSMINUS, "--",) T(MULTILINE_COMMENT_BEGIN, "/*",) T(MULTILINE_COMMENT_END, "*/",) T(SINGLELINE_COMMENT, "//",) #define T_LAST_TOKEN (T_SINGLELINE_COMMENT+1) T(PLUS, "+", = '+') T(MINUS, "-", = '-') T(MULT, "*", = '*') T(DIV, "/", = '/') T(MOD, "%", = '%') T(EQUAL, "=", = '=') T(LESS, "<", = '<') T(GREATER, ">", = '>') T(DOT, ".", = '.') T(CARET, "^", = '^') T(EXCLAMATION, "!", = '!') T(QUESTION, "?", = '?') T(AND, "&", = '&') T(TILDE, "~", = '~') T(PIPE, "|", = '|') T(DOLLAR, "$", = '$')
MatzeB/fluffy
aff4a8edb5a9a666d9015e681cffac14fb08518a
cleanup, remove now unnecessary stuff, use bool
diff --git a/main.c b/main.c index 745c96a..0c599ad 100644 --- a/main.c +++ b/main.c @@ -1,377 +1,354 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" #include "driver/firm_cmdline.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" #include "mangle.h" #include "adt/error.h" #ifdef _WIN32 #define LINKER "gcc.exe" #define TMPDIR "" #else #define LINKER "gcc" #define TMPDIR "/tmp/" #endif -typedef enum { - TARGET_OS_MINGW, - TARGET_OS_ELF, - TARGET_OS_MACHO -} target_os_t; - -static int dump_graphs = 0; -static int dump_asts = 0; -static int verbose = 0; -static int show_timers = 0; -static int noopt = 0; -static int do_inline = 1; +static bool dump_graphs = false; +static bool dump_asts = false; +static bool verbose = false; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; -const ir_settings_if_conv_t *if_conv_info = NULL; - -static void set_be_option(const char *arg) -{ - int res = be_parse_arg(arg); - (void) res; - assert(res); -} - static void initialize_firm(void) { firm_early_init(); dump_consts_local(1); dump_keepalive_edges(1); dbg_init(NULL, NULL, dbg_snprint); } static void get_output_name(char *buf, size_t buflen, const char *inputname, - const char *newext) + const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; for (const char *c = inputname; *c != 0; ++c) { if (*c == '.') last_dot = i; ++i; } if (last_dot == 0xffffffff) last_dot = i; if (last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if (extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } static void dump_ast(const namespace_t *namespace, const char *name) { if (!dump_asts) return; const char *fname = namespace->filename; char filename[4096]; get_output_name(filename, sizeof(filename), fname, name); FILE* out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { print_ast(out, namespace); } fclose(out); } static void parse_file(const char *fname) { FILE *in = fopen(fname, "r"); if (in == NULL) { fprintf(stderr, "couldn't open '%s' for reading: %s\n", fname, strerror(errno)); exit(1); } namespace_t *namespace = parse(in, fname); fclose(in); if (namespace == NULL) { exit(1); } dump_ast(namespace, "-parse.txt"); } static void check_semantic(void) { if (!check_static_semantic()) { fprintf(stderr, "Semantic errors found\n"); namespace_t *namespace = namespaces; while (namespace != NULL) { dump_ast(namespace, "-error.txt"); namespace = namespace->next; } exit(1); } if (dump_asts) { namespace_t *namespace = namespaces; while (namespace != NULL) { dump_ast(namespace, "-semantic.txt"); namespace = namespace->next; } } } static void link(const char *in, const char *out) { char buf[4096]; if (out == NULL) { out = "a.out"; } snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); if (verbose) { puts(buf); } int err = system(buf); if (err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } void lower_compound_params(void) { } +static void set_be_option(const char *arg) +{ + int res = be_parse_arg(arg); + (void) res; + assert(res); +} + static void init_os_support(void) { /* OS option must be set to the backend */ switch (firm_opt.os_support) { case OS_SUPPORT_MINGW: set_be_option("ia32-gasmode=mingw"); break; case OS_SUPPORT_LINUX: set_be_option("ia32-gasmode=elf"); break; case OS_SUPPORT_MACHO: set_be_option("ia32-gasmode=macho"); set_be_option("ia32-stackalign=4"); set_be_option("pic"); break; } } static void set_option(const char *arg) { int res = firm_option(arg); (void) res; assert(res); } int main(int argc, const char **argv) { int opt_level; init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); init_mangle(); /* early options parsing */ for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') continue; const char *option = &arg[1]; if (option[0] == 'O') { sscanf(&option[1], "%d", &opt_level); } if (strcmp(arg, "-fwin32") == 0) { firm_opt.os_support = OS_SUPPORT_MINGW; } else if (strcmp(arg, "-fmac") == 0) { firm_opt.os_support = OS_SUPPORT_MACHO; } else if (strcmp(arg, "-flinux") == 0) { firm_opt.os_support = OS_SUPPORT_LINUX; } } /* set target/os specific stuff */ init_os_support(); /* set optimisations based on optimisation level */ switch(opt_level) { case 0: set_option("no-opt"); break; case 1: set_option("no-inline"); break; default: case 4: set_option("strict-aliasing"); /* use_builtins = true; */ /* fallthrough */ case 3: set_option("cond-eval"); set_option("if-conv"); /* fallthrough */ case 2: set_option("inline"); set_option("deconv"); set_be_option("omitfp"); break; } const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (strcmp(arg, "-o") == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; } else if (strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if (strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if (strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if (strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; - } else if (strcmp(arg, "--time") == 0) { - show_timers = 1; - } else if (arg[0] == '-' && arg[1] == 'O') { - int optlevel = atoi(&arg[2]); - if (optlevel <= 0) { - noopt = 1; - } else if (optlevel > 1) { - do_inline = 1; - } else { - noopt = 0; - do_inline = 0; - } } else if (strcmp(arg, "-S") == 0) { mode = Compile; } else if (strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if (strcmp(arg, "-v") == 0) { verbose = 1; } else if (strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if (bearg[0] == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if (!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if (strcmp(bearg, "help") == 0) { return 1; } } else { parsed++; parse_file(argv[i]); } } if (parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } gen_firm_init(); check_semantic(); ast2firm(); const char *asmname; if (mode == Compile) { asmname = outname; } else { asmname = TMPDIR "fluffy.s"; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } set_ll_modes( mode_Ls, mode_Lu, mode_Is, mode_Iu); gen_firm_finish(asm_out, asmname, 1, true); fclose(asm_out); if (mode == CompileAndLink) { link(asmname, outname); } exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; }
MatzeB/fluffy
aa9f2c7e8c9ed8e9745789e2ae7c14c3fe6021e2
started working on constant expressions
diff --git a/TODO b/TODO index 384c357..0665c7d 100644 --- a/TODO +++ b/TODO @@ -1,30 +1,27 @@ - - This does not describe the goals and visions but short term things that should -not be forgotten and are not done yet because I was lazy or did not decide -about the right way to do it yet. +not be forgotten. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime - forbid same variable names in nested blocks - change firm to pass on debug info on unitialized_variable callback - introduce constant expressions Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Add an alloca operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) -Refactorings: +Refactorings (mindless but often labor intensive tasks): - make unions for type_t (see cparser) - rename type to kind - keep typerefs as long as possible (start the skip_typeref madness similar to cparser) diff --git a/ast.c b/ast.c index 30aee6d..0bc56be 100644 --- a/ast.c +++ b/ast.c @@ -173,512 +173,602 @@ static void print_binary_expression(const binary_expression_t *binexpr) case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; case EXPR_BINARY_GREATER: fprintf(out, ">"); break; case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->base.kind); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->kind) { case EXPR_ERROR: fprintf(out, "*error expression*"); break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; case EXPR_FLOAT_CONST: case EXPR_BOOL_CONST: case EXPR_FUNC: /* TODO */ fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while (statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->base.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch (statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if (method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->base.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->base.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while (method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if (method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->base.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch (declaration->kind) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type '%s'\n", get_declaration_kind_name(declaration->kind)); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%s)\n", get_declaration_kind_name(declaration->kind)); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { print_declaration(declaration); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_kind_name(declaration_kind_t type) { switch (type) { case DECLARATION_LAST: case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } + +bool is_linktime_constant(const expression_t *expression) +{ + switch (expression->kind) { + case EXPR_SELECT: + /* TODO */ + return false; + case EXPR_ARRAY_ACCESS: + /* TODO */ + return false; + case EXPR_UNARY_DEREFERENCE: + return is_constant_expression(expression->unary.value); + default: + return false; + } +} + +bool is_constant_expression(const expression_t *expression) +{ + switch (expression->kind) { + case EXPR_INT_CONST: + case EXPR_FLOAT_CONST: + case EXPR_BOOL_CONST: + case EXPR_NULL_POINTER: + case EXPR_SIZEOF: + return true; + + case EXPR_STRING_CONST: + case EXPR_FUNC: + case EXPR_UNARY_INCREMENT: + case EXPR_UNARY_DECREMENT: + case EXPR_UNARY_DEREFERENCE: + case EXPR_BINARY_ASSIGN: + case EXPR_SELECT: + case EXPR_ARRAY_ACCESS: + return false; + + case EXPR_UNARY_TAKE_ADDRESS: + return is_linktime_constant(expression->unary.value); + + case EXPR_REFERENCE: { + declaration_t *declaration = expression->reference.declaration; + if (declaration->kind == DECLARATION_CONSTANT) + return true; + return false; + } + + case EXPR_CALL: + /* TODO: we might introduce pure/side effect free calls */ + return false; + + case EXPR_UNARY_CAST: + case EXPR_UNARY_NEGATE: + case EXPR_UNARY_NOT: + case EXPR_UNARY_BITWISE_NOT: + return is_constant_expression(expression->unary.value); + + case EXPR_BINARY_ADD: + case EXPR_BINARY_SUB: + case EXPR_BINARY_MUL: + case EXPR_BINARY_DIV: + case EXPR_BINARY_MOD: + case EXPR_BINARY_EQUAL: + case EXPR_BINARY_NOTEQUAL: + case EXPR_BINARY_LESS: + case EXPR_BINARY_LESSEQUAL: + case EXPR_BINARY_GREATER: + case EXPR_BINARY_GREATEREQUAL: + case EXPR_BINARY_AND: + case EXPR_BINARY_OR: + case EXPR_BINARY_XOR: + case EXPR_BINARY_SHIFTLEFT: + case EXPR_BINARY_SHIFTRIGHT: + /* not that lazy and/or are not constant if their value is clear after + * evaluating the left side. This is because we can't (always) evaluate the + * left hand side until the ast2firm phase, and therefore can't determine + * constness */ + case EXPR_BINARY_LAZY_AND: + case EXPR_BINARY_LAZY_OR: + return is_constant_expression(expression->binary.left) + && is_constant_expression(expression->binary.right); + + case EXPR_ERROR: + return true; + case EXPR_INVALID: + break; + } + panic("invalid expression in is_constant_expression"); +} + diff --git a/ast.h b/ast.h index 71ae9f9..8200c77 100644 --- a/ast.h +++ b/ast.h @@ -1,62 +1,78 @@ #ifndef AST_H #define AST_H +#include <stdbool.h> #include <stdio.h> typedef struct attribute_t attribute_t; typedef union declaration_t declaration_t; typedef union expression_t expression_t; typedef struct context_t context_t; typedef struct export_t export_t; typedef struct declaration_base_t declaration_base_t; typedef struct expression_base_t expression_base_t; typedef struct int_const_t int_const_t; typedef struct float_const_t float_const_t; typedef struct string_const_t string_const_t; typedef struct bool_const_t bool_const_t; typedef struct cast_expression_t cast_expression_t; typedef struct reference_expression_t reference_expression_t; typedef struct call_argument_t call_argument_t; typedef struct call_expression_t call_expression_t; typedef struct binary_expression_t binary_expression_t; typedef struct unary_expression_t unary_expression_t; typedef struct select_expression_t select_expression_t; typedef struct array_access_expression_t array_access_expression_t; typedef struct sizeof_expression_t sizeof_expression_t; typedef struct func_expression_t func_expression_t; typedef struct statement_t statement_t; typedef struct block_statement_t block_statement_t; typedef struct return_statement_t return_statement_t; typedef struct if_statement_t if_statement_t; typedef struct variable_declaration_t variable_declaration_t; typedef struct variable_declaration_statement_t variable_declaration_statement_t; typedef struct expression_statement_t expression_statement_t; typedef struct goto_statement_t goto_statement_t; typedef struct label_declaration_t label_declaration_t; typedef struct label_statement_t label_statement_t; typedef struct namespace_t namespace_t; typedef struct method_parameter_t method_parameter_t; typedef struct method_t method_t; typedef struct method_declaration_t method_declaration_t; typedef struct iterator_declaration_t iterator_declaration_t; typedef struct constant_t constant_t; typedef struct global_variable_t global_variable_t; typedef struct typealias_t typealias_t; typedef struct concept_instance_t concept_instance_t; typedef struct concept_method_instance_t concept_method_instance_t; typedef struct concept_t concept_t; typedef struct concept_method_t concept_method_t; void init_ast_module(void); void exit_ast_module(void); void print_ast(FILE *out, const namespace_t *namespace); void print_expression(const expression_t *expression); void *allocate_ast(size_t size); +/** + * Returns true if a given expression is a compile time + * constant. + */ +bool is_constant_expression(const expression_t *expression); + +/** + * An object with a fixed but at compiletime unknown adress which will be known + * at link/load time. + */ +bool is_linktime_constant(const expression_t *expression); + +long fold_constant_to_int(const expression_t *expression); +bool fold_constant_to_bool(const expression_t *expression); + #endif diff --git a/ast2firm.c b/ast2firm.c index 73856d3..8f955e3 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1947 +1,1973 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_method_t instantiate_method_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_method_t { method_t *method; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_methods; static pdeq *instantiate_methods = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = (const declaration_t*) &value_numbers[pos]; print_warning_prefix(declaration->base.source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->base.symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) +{ +} + +static void init_ir_types(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.type.type = TYPE_ATOMIC; byte_type.atype = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch (type->atype) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch (type->type) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->base.type); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if (result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } +static ir_node *expression_to_firm(const expression_t *expression); + +static tarval *fold_constant_to_tarval(const expression_t *expression) +{ + assert(is_constant_expression(expression)); + + ir_graph *old_current_ir_graph = current_ir_graph; + current_ir_graph = get_const_code_irg(); + + ir_node *cnst = expression_to_firm(expression); + current_ir_graph = old_current_ir_graph; + + if (!is_Const(cnst)) { + panic("couldn't fold constant"); + } + + tarval* tv = get_Const_tarval(cnst); + return tv; +} + +long fold_constant_to_int(const expression_t *expression) +{ + if (expression->kind == EXPR_ERROR) + return 0; + + tarval *tv = fold_constant_to_tarval(expression); + if (!tarval_is_long(tv)) { + panic("result of constant folding is not an integer"); + } + + return get_tarval_long(tv); +} + static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); - set_array_bounds_int(ir_type, 0, 0, type->size); + int size = fold_constant_to_int(type->size_expression); + set_array_bounds_int(ir_type, 0, 0, size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } - set_type_size_bytes(ir_type, type->size * elemsize); + set_type_size_bytes(ir_type, size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->kind == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->kind != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = declaration->base.symbol; ident *ident = new_id_from_str(symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch (type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->base.type); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_method->base.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if (!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if (is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); -static ir_node *expression_to_firm(expression_t *expression); - static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->base.type); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->base.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->base.type); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->base.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->base.type); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->base.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch (declaration->kind) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { switch (expression->kind) { case EXPR_SELECT: { const select_expression_t *select = (const select_expression_t*) expression; return select_expression_addr(select); } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY_DEREFERENCE: { const unary_expression_t *unexpr = (const unary_expression_t*) expression; return expression_to_firm(unexpr->value); } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->kind == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->base.type; ir_node *result; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->base.source_position); return value; } -static ir_op *binexpr_kind_to_op(expression_kind_t kind) -{ - switch (kind) { - case EXPR_BINARY_ADD: - return op_Add; - case EXPR_BINARY_SUB: - return op_Sub; - case EXPR_BINARY_MUL: - return op_Mul; - case EXPR_BINARY_AND: - return op_And; - case EXPR_BINARY_OR: - return op_Or; - case EXPR_BINARY_XOR: - return op_Eor; - case EXPR_BINARY_SHIFTLEFT: - return op_Shl; - case EXPR_BINARY_SHIFTRIGHT: - return op_Shr; - default: - return NULL; - } -} - static long binexpr_kind_to_cmp_pn(expression_kind_t kind) { switch (kind) { case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; case EXPR_BINARY_LESS: return pn_Cmp_Lt; case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; case EXPR_BINARY_GREATER: return pn_Cmp_Gt; case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { bool is_or = binary_expression->base.kind == EXPR_BINARY_LAZY_OR; assert(is_or || binary_expression->base.kind == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm( const binary_expression_t *binary_expression) { expression_kind_t kind = binary_expression->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); case EXPR_BINARY_LAZY_OR: case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->base.source_position); if (kind == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (kind == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->base.type); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ - ir_op *irop = binexpr_kind_to_op(kind); - if (irop != NULL) { - ir_node *in[2] = { left, right }; - ir_mode *mode = get_ir_mode(binary_expression->base.type); - ir_node *block = get_cur_block(); - ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, - 2, in); - return node; + ir_mode *mode = get_ir_mode(binary_expression->base.type); + switch (kind) { + case EXPR_BINARY_ADD: + return new_d_Add(dbgi, left, right, mode); + case EXPR_BINARY_SUB: + return new_d_Sub(dbgi, left, right, mode); + case EXPR_BINARY_MUL: + return new_d_Mul(dbgi, left, right, mode); + case EXPR_BINARY_AND: + return new_d_And(dbgi, left, right, mode); + case EXPR_BINARY_OR: + return new_d_Or(dbgi, left, right, mode); + case EXPR_BINARY_XOR: + return new_d_Eor(dbgi, left, right, mode); + case EXPR_BINARY_SHIFTLEFT: + return new_d_Shl(dbgi, left, right, mode); + case EXPR_BINARY_SHIFTRIGHT: + return new_d_Shr(dbgi, left, right, mode); + default: + break; } /* a comparison expression? */ long compare_pn = binexpr_kind_to_cmp_pn(kind); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->base.type; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->base.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->base.source_position); type_t *type = expression->base.type; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm( const unary_expression_t *unary_expression) { ir_node *addr; switch (unary_expression->base.kind) { case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->base.type, addr, &unary_expression->base.source_position); case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); case EXPR_UNARY_BITWISE_NOT: case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); default: break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->base.type, addr, &select->base.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->base.type); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->base.type->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->base.type; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->base.type); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->base.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if (result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->base.symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->base.source_position); } -static ir_node *expression_to_firm(expression_t *expression) +static ir_node *expression_to_firm(const expression_t *expression) { ir_node *addr; switch (expression->kind) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); EXPR_BINARY_CASES return binary_expression_to_firm( (const binary_expression_t*) expression); EXPR_UNARY_CASES return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->base.type, addr, &expression->base.source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if (statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while (statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if (!is_polymorphic_method(method)) { assure_instance(method, declaration->base.symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); + init_ir_types(); + assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while (namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index 28e874a..26a5e5d 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,489 +1,485 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_base_t base; method_t method; }; struct iterator_declaration_t { declaration_base_t base; method_t method; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_method_t { declaration_base_t base; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; method_declaration_t method; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_method_t concept_method; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_kind_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_base_t { expression_kind_t kind; type_t *type; source_position_t source_position; bool lowered; }; struct bool_const_t { expression_base_t base; bool value; }; struct int_const_t { expression_base_t base; int value; }; struct float_const_t { expression_base_t base; double value; }; struct string_const_t { expression_base_t base; const char *value; }; struct func_expression_t { expression_base_t base; method_t method; }; struct reference_expression_t { expression_base_t base; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_base_t base; expression_t *method; call_argument_t *arguments; }; struct unary_expression_t { expression_base_t base; expression_t *value; }; struct binary_expression_t { expression_base_t base; expression_t *left; expression_t *right; }; struct select_expression_t { expression_base_t base; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_base_t base; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_base_t base; type_t *type; }; union expression_t { expression_kind_t kind; expression_base_t base; bool_const_t bool_const; int_const_t int_const; float_const_t float_const; string_const_t string_const; func_expression_t func; reference_expression_t reference; call_expression_t call; unary_expression_t unary; binary_expression_t binary; select_expression_t select; array_access_expression_t array_access; sizeof_expression_t sizeofe; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; - context_t context; type_variable_t *type_parameters; }; struct namespace_t { - symbol_t *symbol; - const char *filename; - - context_t context; - - namespace_t *next; + symbol_t *symbol; + const char *filename; + context_t context; + namespace_t *next; }; -static inline -void *_allocate_ast(size_t size) +static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); expression_t *allocate_expression(expression_kind_t kind); #endif diff --git a/main.c b/main.c index 6c3cb44..745c96a 100644 --- a/main.c +++ b/main.c @@ -1,321 +1,377 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" #include "driver/firm_cmdline.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" #include "mangle.h" #include "adt/error.h" #ifdef _WIN32 #define LINKER "gcc.exe" #define TMPDIR "" - #define DEFAULT_OS TARGET_OS_MINGW #else - #if defined(__APPLE__) - #define DEFAULT_OS TARGET_OS_MACHO - #else - #define DEFAULT_OS TARGET_OS_ELF - #endif #define LINKER "gcc" #define TMPDIR "/tmp/" #endif typedef enum { TARGET_OS_MINGW, TARGET_OS_ELF, TARGET_OS_MACHO } target_os_t; static int dump_graphs = 0; static int dump_asts = 0; static int verbose = 0; static int show_timers = 0; static int noopt = 0; static int do_inline = 1; -static target_os_t target_os = DEFAULT_OS; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; const ir_settings_if_conv_t *if_conv_info = NULL; static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } static void initialize_firm(void) { - be_opt_register(); + firm_early_init(); + dump_consts_local(1); + dump_keepalive_edges(1); dbg_init(NULL, NULL, dbg_snprint); - - switch (target_os) { - case TARGET_OS_MINGW: - set_be_option("ia32-gasmode=mingw"); - break; - case TARGET_OS_ELF: - set_be_option("ia32-gasmode=elf"); - break; - case TARGET_OS_MACHO: - set_be_option("ia32-gasmode=macho"); - set_be_option("ia32-stackalign=4"); - set_be_option("pic"); - break; - } } static void get_output_name(char *buf, size_t buflen, const char *inputname, const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; for (const char *c = inputname; *c != 0; ++c) { if (*c == '.') last_dot = i; ++i; } if (last_dot == 0xffffffff) last_dot = i; if (last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if (extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } static void dump_ast(const namespace_t *namespace, const char *name) { if (!dump_asts) return; const char *fname = namespace->filename; char filename[4096]; get_output_name(filename, sizeof(filename), fname, name); FILE* out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { print_ast(out, namespace); } fclose(out); } static void parse_file(const char *fname) { FILE *in = fopen(fname, "r"); if (in == NULL) { fprintf(stderr, "couldn't open '%s' for reading: %s\n", fname, strerror(errno)); exit(1); } namespace_t *namespace = parse(in, fname); fclose(in); if (namespace == NULL) { exit(1); } dump_ast(namespace, "-parse.txt"); } static void check_semantic(void) { if (!check_static_semantic()) { fprintf(stderr, "Semantic errors found\n"); namespace_t *namespace = namespaces; while (namespace != NULL) { dump_ast(namespace, "-error.txt"); namespace = namespace->next; } exit(1); } if (dump_asts) { namespace_t *namespace = namespaces; while (namespace != NULL) { dump_ast(namespace, "-semantic.txt"); namespace = namespace->next; } } } static void link(const char *in, const char *out) { char buf[4096]; if (out == NULL) { out = "a.out"; } snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); if (verbose) { puts(buf); } int err = system(buf); if (err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } void lower_compound_params(void) { } +static void init_os_support(void) +{ + /* OS option must be set to the backend */ + switch (firm_opt.os_support) { + case OS_SUPPORT_MINGW: + set_be_option("ia32-gasmode=mingw"); + break; + case OS_SUPPORT_LINUX: + set_be_option("ia32-gasmode=elf"); + break; + case OS_SUPPORT_MACHO: + set_be_option("ia32-gasmode=macho"); + set_be_option("ia32-stackalign=4"); + set_be_option("pic"); + break; + } +} + +static void set_option(const char *arg) +{ + int res = firm_option(arg); + (void) res; + assert(res); +} + int main(int argc, const char **argv) { - gen_firm_init(); + int opt_level; + init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); init_mangle(); - firm_opt.lower_ll = false; + /* early options parsing */ + for (int i = 1; i < argc; ++i) { + const char *arg = argv[i]; + if (arg[0] != '-') + continue; + + const char *option = &arg[1]; + if (option[0] == 'O') { + sscanf(&option[1], "%d", &opt_level); + } + if (strcmp(arg, "-fwin32") == 0) { + firm_opt.os_support = OS_SUPPORT_MINGW; + } else if (strcmp(arg, "-fmac") == 0) { + firm_opt.os_support = OS_SUPPORT_MACHO; + } else if (strcmp(arg, "-flinux") == 0) { + firm_opt.os_support = OS_SUPPORT_LINUX; + } + } + + /* set target/os specific stuff */ + init_os_support(); + + /* set optimisations based on optimisation level */ + switch(opt_level) { + case 0: + set_option("no-opt"); + break; + case 1: + set_option("no-inline"); + break; + default: + case 4: + set_option("strict-aliasing"); + /* use_builtins = true; */ + /* fallthrough */ + case 3: + set_option("cond-eval"); + set_option("if-conv"); + /* fallthrough */ + case 2: + set_option("inline"); + set_option("deconv"); + set_be_option("omitfp"); + break; + } const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (strcmp(arg, "-o") == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; } else if (strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if (strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if (strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if (strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; } else if (strcmp(arg, "--time") == 0) { show_timers = 1; } else if (arg[0] == '-' && arg[1] == 'O') { int optlevel = atoi(&arg[2]); if (optlevel <= 0) { noopt = 1; } else if (optlevel > 1) { do_inline = 1; } else { noopt = 0; do_inline = 0; } } else if (strcmp(arg, "-S") == 0) { mode = Compile; } else if (strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if (strcmp(arg, "-v") == 0) { verbose = 1; } else if (strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if (bearg[0] == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if (!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if (strcmp(bearg, "help") == 0) { return 1; } } else { parsed++; parse_file(argv[i]); } } if (parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } + gen_firm_init(); + check_semantic(); ast2firm(); const char *asmname; if (mode == Compile) { asmname = outname; } else { asmname = TMPDIR "fluffy.s"; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } + set_ll_modes( + mode_Ls, mode_Lu, + mode_Is, mode_Iu); gen_firm_finish(asm_out, asmname, 1, true); fclose(asm_out); if (mode == CompileAndLink) { link(asmname, outname); } exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; } diff --git a/mangle.c b/mangle.c index 834170b..a601659 100644 --- a/mangle.c +++ b/mangle.c @@ -1,229 +1,230 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" #include "type_t.h" #include "adt/error.h" #include <libfirm/firm.h> #include "driver/firm_cmdline.h" static struct obstack obst; static void mangle_string(const char *str) { size_t len = strlen(str); obstack_grow(&obst, str, len); } static void mangle_len_string(const char *string) { size_t len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); } static void mangle_atomic_type(const atomic_type_t *type) { char c; switch (type->atype) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(&obst, c); } static void mangle_type_variables(type_variable_t *type_variables) { type_variable_t *type_variable = type_variables; for ( ; type_variable != NULL; type_variable = type_variable->next) { /* is this a good char? */ obstack_1grow(&obst, 'T'); mangle_type(type_variable->current_type); } } static void mangle_compound_type(const compound_type_t *type) { mangle_len_string(type->symbol->string); mangle_type_variables(type->type_parameters); } static void mangle_pointer_type(const pointer_type_t *type) { obstack_1grow(&obst, 'P'); mangle_type(type->points_to); } static void mangle_array_type(const array_type_t *type) { obstack_1grow(&obst, 'A'); mangle_type(type->element_type); - obstack_printf(&obst, "%lu", type->size); + int size = fold_constant_to_int(type->size_expression); + obstack_printf(&obst, "%lu", size); } static void mangle_method_type(const method_type_t *type) { obstack_1grow(&obst, 'F'); mangle_type(type->result_type); method_parameter_type_t *parameter_type = type->parameter_types; while (parameter_type != NULL) { mangle_type(parameter_type->type); } obstack_1grow(&obst, 'E'); } static void mangle_reference_type_variable(const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if (current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(current_type); } static void mangle_bind_typevariables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); mangle_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void mangle_type(const type_t *type) { switch (type->type) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(&obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type((const atomic_type_t*) type); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; mangle_type(typeof_type->expression->base.type); return; } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: mangle_method_type((const method_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: mangle_bind_typevariables((const bind_typevariables_type_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable((const type_reference_t*) type); return; case TYPE_ERROR: panic("trying to mangle error type"); } panic("Unknown type mangled"); } void mangle_symbol_simple(symbol_t *symbol) { mangle_string(symbol->string); } void mangle_symbol(symbol_t *symbol) { mangle_len_string(symbol->string); } void mangle_concept_name(symbol_t *symbol) { obstack_grow(&obst, "tcv", 3); mangle_len_string(symbol->string); } void start_mangle(void) { if (firm_opt.os_support == OS_SUPPORT_MACHO || firm_opt.os_support == OS_SUPPORT_MINGW) { obstack_1grow(&obst, '_'); } } ident *finish_mangle(void) { size_t size = obstack_object_size(&obst); char *str = obstack_finish(&obst); ident *id = new_id_from_chars(str, size); obstack_free(&obst, str); return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/parser.c b/parser.c index 2bced05..a3a5d3b 100644 --- a/parser.c +++ b/parser.c @@ -1,1191 +1,1178 @@ #include <config.h> +#include "token_t.h" + #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static unsigned char token_anchor_set[T_LAST_TOKEN]; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static size_t get_declaration_struct_size(declaration_kind_t kind) { static const size_t sizes[] = { [DECLARATION_ERROR] = sizeof(declaration_base_t), [DECLARATION_METHOD] = sizeof(method_declaration_t), [DECLARATION_METHOD_PARAMETER] = sizeof(method_parameter_t), [DECLARATION_ITERATOR] = sizeof(iterator_declaration_t), [DECLARATION_VARIABLE] = sizeof(variable_declaration_t), [DECLARATION_CONSTANT] = sizeof(constant_t), [DECLARATION_TYPE_VARIABLE] = sizeof(type_variable_t), [DECLARATION_TYPEALIAS] = sizeof(typealias_t), [DECLARATION_CONCEPT] = sizeof(concept_t), [DECLARATION_CONCEPT_METHOD] = sizeof(concept_method_t), [DECLARATION_LABEL] = sizeof(label_declaration_t) }; assert(kind < sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } static declaration_t *allocate_declaration(declaration_kind_t kind) { size_t size = get_declaration_struct_size(kind); declaration_t *declaration = allocate_ast_zero(size); declaration->kind = kind; return declaration; } static size_t get_expression_struct_size(expression_kind_t kind) { static const size_t sizes[] = { [EXPR_INT_CONST] = sizeof(int_const_t), [EXPR_FLOAT_CONST] = sizeof(float_const_t), [EXPR_BOOL_CONST] = sizeof(bool_const_t), [EXPR_STRING_CONST] = sizeof(string_const_t), [EXPR_NULL_POINTER] = sizeof(expression_base_t), [EXPR_REFERENCE] = sizeof(reference_expression_t), [EXPR_CALL] = sizeof(call_expression_t), [EXPR_SELECT] = sizeof(select_expression_t), [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t), [EXPR_SIZEOF] = sizeof(sizeof_expression_t), [EXPR_FUNC] = sizeof(func_expression_t), }; if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) { return sizeof(unary_expression_t); } if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) { return sizeof(binary_expression_t); } assert(kind <= sizeof(sizes)/sizeof(sizes[0])); assert(sizes[kind] != 0); return sizes[kind]; } expression_t *allocate_expression(expression_kind_t kind) { size_t size = get_expression_struct_size(kind); expression_t *expression = allocate_ast_zero(size); expression->kind = kind; return expression; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch (token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if (result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *create_error_type(void) { type_t *error_type = allocate_type_zero(sizeof(error_type[0])); error_type->type = TYPE_ERROR; return error_type; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; parse_parameter_declarations(method_type, NULL); expect(':', end_error); method_type->result_type = parse_type(); return (type_t*) method_type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); - if (token.type != T_INTEGER) { - parse_error_expected("problem while parsing array type", - T_INTEGER, 0); - eat_until_anchor(); - rem_anchor_token(']'); - break; - } - int size = token.v.intvalue; - next_token(); - - if (size < 0) { - parse_error("negative array size not allowed"); - eat_until_anchor(); - rem_anchor_token(']'); - break; - } + expression_t *size = parse_expression(); + rem_anchor_token(']'); + expect(']', end_error); array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); - array_type->type.type = TYPE_ARRAY; - array_type->element_type = type; - array_type->size = size; + array_type->type.type = TYPE_ARRAY; + array_type->element_type = type; + array_type->size_expression = size; type = (type_t*) array_type; - rem_anchor_token(']'); - expect(']', end_error); break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { expression_t *expression = allocate_expression(EXPR_STRING_CONST); expression->string_const.value = token.v.string; next_token(); return expression; } static expression_t *parse_int_const(void) { expression_t *expression = allocate_expression(EXPR_INT_CONST); expression->int_const.value = token.v.intvalue; next_token(); return expression; } static expression_t *parse_true(void) { eat(T_true); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = true; return expression; } static expression_t *parse_false(void) { eat(T_false); expression_t *expression = allocate_expression(EXPR_BOOL_CONST); expression->bool_const.value = false; return expression; } static expression_t *parse_null(void) { eat(T_null); expression_t *expression = allocate_expression(EXPR_NULL_POINTER); expression->base.type = make_pointer_type(type_void); return expression; } static expression_t *parse_func_expression(void) { eat(T_func); expression_t *expression = allocate_expression(EXPR_FUNC); parse_method(&expression->func.method); return expression; } static expression_t *parse_reference(void) { expression_t *expression = allocate_expression(EXPR_REFERENCE); expression->reference.symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); expression->reference.type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return expression; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_expression(EXPR_ERROR); expression->base.type = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); expression_t *expression = allocate_expression(EXPR_SIZEOF); if (token.type == '(') { next_token(); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); expression->sizeofe.type = (type_t*) typeof_type; } else { expect('<', end_error); add_anchor_token('>'); expression->sizeofe.type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); return create_error_expression(); } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); expression_t *expression = allocate_expression(EXPR_UNARY_CAST); expect('<', end_error); expression->base.type = parse_type(); expect('>', end_error); expression->unary.value = parse_sub_expression(PREC_CAST); end_error: return expression; } static expression_t *parse_call_expression(expression_t *left) { expression_t *expression = allocate_expression(EXPR_CALL); expression->call.method = left; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { expression->call.arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return expression; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); expression_t *expression = allocate_expression(EXPR_SELECT); expression->select.compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } expression->select.symbol = token.v.symbol; next_token(); return expression; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); expression_t *expression = allocate_expression(EXPR_ARRAY_ACCESS); expression->array_access.array_ref = array_ref; expression->array_access.index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return expression; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(unexpression_type); \ expression->unary.value = parse_sub_expression(PREC_UNARY); \ \ return expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ expression_t *expression = allocate_expression(binexpression_type); \ expression->binary.left = left; \ expression->binary.right = parse_sub_expression(prec_r); \ \ return expression; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); register_expression_parser(parse_EXPR_UNARY_NOT, '!'); register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->base.source_position = start; while (true) { if (token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->base.source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if (token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return (statement_t*) return_statement; } static statement_t *create_error_statement(void) { statement_t *statement = allocate_ast_zero(sizeof(statement[0])); statement->type = STATEMENT_ERROR; return statement; diff --git a/parser_t.h b/parser_t.h index 11bbda2..350d232 100644 --- a/parser_t.h +++ b/parser_t.h @@ -1,53 +1,53 @@ #ifndef PARSER_T_H #define PARSER_T_H +#include "token_t.h" #include "parser.h" #include <assert.h> -#include "token_t.h" #include "lexer.h" #include "type.h" typedef expression_t* (*parse_expression_function) (void); typedef expression_t* (*parse_expression_infix_function) (expression_t *left); typedef statement_t* (*parse_statement_function) (void); typedef void (*parse_declaration_function) (void); typedef attribute_t* (*parse_attribute_function) (void); typedef struct expression_parse_function_t { parse_expression_function parser; unsigned infix_precedence; parse_expression_infix_function infix_parser; } expression_parse_function_t; extern token_t token; void register_expression_parser(parse_expression_function parser, int token_type); void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence); void register_statement_parser(parse_statement_function parser, int token_type); void register_declaration_parser(parse_declaration_function parser, int token_type); void register_attribute_parser(parse_attribute_function parser, int token_type); expression_t *parse_sub_expression(unsigned precedence); void add_declaration(declaration_t *entry); void parser_print_error_prefix(void); expression_t *parse_expression(void); statement_t *parse_statement(void); type_t *parse_type(void); void parse_declaration(void); attribute_t *parse_attributes(void); void next_token(void); #endif diff --git a/semantic.c b/semantic.c index 5cd963f..ca3929e 100644 --- a/semantic.c +++ b/semantic.c @@ -1,996 +1,997 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->base.source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); + type->size_expression = check_expression(type->size_expression); + return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->base.type; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->base.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->base.source_position); ref->base.type = type; } - static bool is_lvalue(const expression_t *expression) { switch (expression->kind) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->base.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->kind == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->base.type == NULL) { if (right->base.type == NULL) { print_error_prefix(assign->base.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->base.type; left->base.type = right->base.type; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->base.type == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->base.type; if (from_type == NULL) { print_error_prefix(from->base.source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->kind == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = source_position; cast->base.type = dest_type; cast->unary.value = from; return cast; } static expression_t *lower_sub_expression(expression_t *expression) { binary_expression_t *sub = (binary_expression_t*) expression; expression_t *left = check_expression(sub->left); expression_t *right = check_expression(sub->right); type_t *lefttype = left->base.type; type_t *righttype = right->base.type; if (lefttype->type != TYPE_POINTER && righttype->type != TYPE_POINTER) return expression; sub->base.type = type_uint; pointer_type_t *p1 = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = p1->points_to; expression_t *divexpr = allocate_expression(EXPR_BINARY_DIV); divexpr->base.type = type_uint; divexpr->binary.left = expression; divexpr->binary.right = sizeof_expr; sub->base.lowered = true; return divexpr; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_kind_t kind = binexpr->base.kind; switch (kind) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->base.type; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->base.type; lefttype = exprtype; righttype = right->base.type; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; expression_t *sizeof_expr = allocate_expression(EXPR_SIZEOF); sizeof_expr->base.type = type_uint; sizeof_expr->sizeofe.type = pointer_type->points_to; expression_t *mulexpr = allocate_expression(EXPR_BINARY_MUL); mulexpr->base.type = type_uint; mulexpr->binary.left = make_cast(right, type_uint, binexpr->base.source_position, false); mulexpr->binary.right = sizeof_expr; expression_t *cast = allocate_expression(EXPR_UNARY_CAST); cast->base.source_position = binexpr->base.source_position; cast->base.type = lefttype; cast->unary.value = mulexpr; right = cast; binexpr->right = cast; } if (lefttype->type == TYPE_POINTER && righttype->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) lefttype; pointer_type_t *p2 = (pointer_type_t*) righttype; if (p1->points_to != p2->points_to) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Can only subtract pointers to same type, but have type "); print_type(lefttype); fprintf(stderr, " and "); print_type(righttype); fprintf(stderr, "\n"); } exprtype = type_uint; } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = left->base.type; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->base.type)) { print_error_prefix(binexpr->base.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->base.type); fprintf(stderr, "is given\n"); } exprtype = left->base.type; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->base.type; righttype = left->base.type; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->base.type != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->base.source_position, false); } if (right->base.type != righttype) { binexpr->right = make_cast(right, righttype, binexpr->base.source_position, false); } binexpr->base.type = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->base.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->base.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->base.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); @@ -1637,904 +1638,910 @@ static void check_select_expression(select_expression_t *select) if (datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if (datatype->type != TYPE_POINTER) { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->base.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->base.source_position); select->base.type = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->base.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->base.type = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->base.type; if (type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->base.type = result_type; if (index->base.type == NULL || !is_type_int(index->base.type)) { print_error_prefix(access->base.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->base.type); fprintf(stderr, "\n"); return; } if (index->base.type != NULL && index->base.type != type_int) { access->index = make_cast(index, type_int, access->base.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->base.type = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->base.source_position); expression->base.type = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->kind < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->kind]; if (lowerer != NULL && !expression->base.lowered) { expression = lowerer(expression); } } switch (expression->kind) { case EXPR_INT_CONST: expression->base.type = type_int; break; case EXPR_FLOAT_CONST: expression->base.type = type_double; break; case EXPR_BOOL_CONST: expression->base.type = type_bool; break; case EXPR_STRING_CONST: expression->base.type = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->base.type = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->base.type != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->base.type != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->base.type != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->base.type); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if (last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->base.type == NULL) return; bool may_be_unused = false; if (expression->kind == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->kind == EXPR_UNARY_INCREMENT || expression->kind == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->kind == EXPR_CALL) { may_be_unused = true; } if (expression->base.type != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->kind == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->base.type != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; + + if (!is_constant_expression(expression)) { + print_error_prefix(constant->base.source_position); + fprintf(stderr, "Value for constant '%s' is not constant\n", + constant->base.symbol->string); + } } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch (declaration->kind) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; namespace_t *namespace = namespaces; for ( ; namespace != NULL; namespace = namespace->next) { check_namespace(namespace); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/test/expected_output/error1.fluffy.output b/test/expected_output/error1.fluffy.output new file mode 100644 index 0000000..e69de29 diff --git a/tokens.inc b/tokens.inc index 3540c58..b12a4d8 100644 --- a/tokens.inc +++ b/tokens.inc @@ -1,82 +1,91 @@ #ifndef TS #define TS(x,str,val) #endif TS(NEWLINE, "newline", = 256) TS(INDENT, "indent",) TS(DEDENT, "dedent",) TS(IDENTIFIER, "identifier",) TS(INTEGER, "integer number",) TS(STRING_LITERAL, "string literal",) +/* hack... */ +#undef bool +#undef true +#undef false + #define Keyword(x) T(x,#x,) Keyword(bool) Keyword(byte) Keyword(cast) Keyword(class) Keyword(const) Keyword(double) Keyword(else) Keyword(export) Keyword(extern) Keyword(false) Keyword(float) Keyword(func) Keyword(goto) Keyword(if) Keyword(instance) Keyword(int) Keyword(long) Keyword(namespace) Keyword(null) Keyword(return) Keyword(short) Keyword(signed) Keyword(static) Keyword(struct) Keyword(true) Keyword(typealias) Keyword(concept) Keyword(union) Keyword(unsigned) Keyword(var) Keyword(void) Keyword(sizeof) Keyword(typeof) #undef S +#define bool _Bool +#define true 1 +#define false 0 + T(DOTDOT, "..",) T(DOTDOTDOT, "...",) T(EQUALEQUAL, "==",) T(TYPESTART, "<$",) T(SLASHEQUAL, "/=",) T(LESSEQUAL, "<=",) T(LESSLESS, "<<",) T(GREATEREQUAL, ">=",) T(GREATERGREATER, ">>",) T(PIPEPIPE, "||",) T(ANDAND, "&&",) T(PLUSPLUS, "++",) T(MINUSMINUS, "--",) T(MULTILINE_COMMENT_BEGIN, "/*",) T(MULTILINE_COMMENT_END, "*/",) T(SINGLELINE_COMMENT, "//",) #define T_LAST_TOKEN (T_SINGLELINE_COMMENT+1) T(PLUS, "+", = '+') T(MINUS, "-", = '-') T(MULT, "*", = '*') T(DIV, "/", = '/') T(MOD, "%", = '%') T(EQUAL, "=", = '=') T(LESS, "<", = '<') T(GREATER, ">", = '>') T(DOT, ".", = '.') T(CARET, "^", = '^') T(EXCLAMATION, "!", = '!') T(QUESTION, "?", = '?') T(AND, "&", = '&') T(TILDE, "~", = '~') T(PIPE, "|", = '|') T(DOLLAR, "$", = '$') diff --git a/type.c b/type.c index 1f74a35..81fe746 100644 --- a/type.c +++ b/type.c @@ -1,587 +1,589 @@ #include <config.h> #include "type_t.h" #include "ast_t.h" #include "type_hash.h" #include "adt/error.h" #include "adt/array.h" //#define DEBUG_TYPEVAR_BINDING typedef struct typevar_binding_t typevar_binding_t; struct typevar_binding_t { type_variable_t *type_variable; type_t *old_current_type; }; static typevar_binding_t *typevar_binding_stack = NULL; static struct obstack _type_obst; struct obstack *type_obst = &_type_obst; static type_t type_void_ = { TYPE_VOID, NULL }; static type_t type_invalid_ = { TYPE_INVALID, NULL }; type_t *type_void = &type_void_; type_t *type_invalid = &type_invalid_; static FILE* out; void init_type_module() { obstack_init(type_obst); typevar_binding_stack = NEW_ARR_F(typevar_binding_t, 0); out = stderr; } void exit_type_module() { DEL_ARR_F(typevar_binding_stack); obstack_free(type_obst, NULL); } static void print_atomic_type(const atomic_type_t *type) { switch (type->atype) { case ATOMIC_TYPE_INVALID: fputs("INVALIDATOMIC", out); break; case ATOMIC_TYPE_BOOL: fputs("bool", out); break; case ATOMIC_TYPE_BYTE: fputs("byte", out); break; case ATOMIC_TYPE_UBYTE: fputs("unsigned byte", out); break; case ATOMIC_TYPE_INT: fputs("int", out); break; case ATOMIC_TYPE_UINT: fputs("unsigned int", out); break; case ATOMIC_TYPE_SHORT: fputs("short", out); break; case ATOMIC_TYPE_USHORT: fputs("unsigned short", out); break; case ATOMIC_TYPE_LONG: fputs("long", out); break; case ATOMIC_TYPE_ULONG: fputs("unsigned long", out); break; case ATOMIC_TYPE_LONGLONG: fputs("long long", out); break; case ATOMIC_TYPE_ULONGLONG: fputs("unsigned long long", out); break; case ATOMIC_TYPE_FLOAT: fputs("float", out); break; case ATOMIC_TYPE_DOUBLE: fputs("double", out); break; default: fputs("UNKNOWNATOMIC", out); break; } } static void print_method_type(const method_type_t *type) { fputs("<", out); fputs("func(", out); method_parameter_type_t *param_type = type->parameter_types; int first = 1; while (param_type != NULL) { if (first) { first = 0; } else { fputs(", ", out); } print_type(param_type->type); param_type = param_type->next; } fputs(")", out); if (type->result_type != NULL && type->result_type->type != TYPE_VOID) { fputs(" : ", out); print_type(type->result_type); } fputs(">", out); } static void print_pointer_type(const pointer_type_t *type) { print_type(type->points_to); fputs("*", out); } static void print_array_type(const array_type_t *type) { print_type(type->element_type); - fprintf(out, "[%lu]", type->size); + fputs("[", out); + print_expression(type->size_expression); + fputs("]", out); } static void print_type_reference(const type_reference_t *type) { fprintf(out, "<?%s>", type->symbol->string); } static void print_type_variable(const type_variable_t *type_variable) { if (type_variable->current_type != NULL) { print_type(type_variable->current_type); return; } fprintf(out, "%s:", type_variable->base.symbol->string); type_constraint_t *constraint = type_variable->constraints; int first = 1; while (constraint != NULL) { if (first) { first = 0; } else { fprintf(out, ", "); } fprintf(out, "%s", constraint->concept_symbol->string); constraint = constraint->next; } } static void print_type_reference_variable(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; print_type_variable(type_variable); } static void print_compound_type(const compound_type_t *type) { fprintf(out, "%s", type->symbol->string); type_variable_t *type_parameter = type->type_parameters; if (type_parameter != NULL) { fprintf(out, "<"); while (type_parameter != NULL) { if (type_parameter != type->type_parameters) { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } fprintf(out, ">"); } } static void print_bind_type_variables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); print_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void print_type(const type_t *type) { if (type == NULL) { fputs("nil type", out); return; } switch (type->type) { case TYPE_INVALID: fputs("invalid", out); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; fputs("typeof(", out); print_expression(typeof_type->expression); fputs(")", out); return; } case TYPE_ERROR: fputs("error", out); return; case TYPE_VOID: fputs("void", out); return; case TYPE_ATOMIC: print_atomic_type((const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: print_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: print_method_type((const method_type_t*) type); return; case TYPE_POINTER: print_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: print_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: print_type_reference((const type_reference_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: print_type_reference_variable((const type_reference_t*) type); return; case TYPE_BIND_TYPEVARIABLES: print_bind_type_variables((const bind_typevariables_type_t*) type); return; } fputs("unknown", out); } int type_valid(const type_t *type) { switch (type->type) { case TYPE_INVALID: case TYPE_REFERENCE: return 0; default: return 1; } } int is_type_int(const type_t *type) { if (type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return 1; default: return 0; } } int is_type_numeric(const type_t *type) { if (type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return 1; default: return 0; } } type_t* make_atomic_type(atomic_type_type_t atype) { atomic_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *normalized_type = typehash_insert((type_t*) type); if (normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } type_t* make_pointer_type(type_t *points_to) { pointer_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_POINTER; type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) type); if (normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } static type_t *create_concrete_compound_type(compound_type_t *type) { /* TODO: handle structs with typevars */ return (type_t*) type; } static type_t *create_concrete_method_type(method_type_t *type) { int need_new_type = 0; method_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_METHOD; type_t *result_type = create_concrete_type(type->result_type); if (result_type != type->result_type) need_new_type = 1; new_type->result_type = result_type; method_parameter_type_t *parameter_type = type->parameter_types; method_parameter_type_t *last_parameter_type = NULL; while (parameter_type != NULL) { type_t *param_type = parameter_type->type; type_t *new_param_type = create_concrete_type(param_type); if (new_param_type != param_type) need_new_type = 1; method_parameter_type_t *new_parameter_type = obstack_alloc(type_obst, sizeof(new_parameter_type[0])); memset(new_parameter_type, 0, sizeof(new_parameter_type[0])); new_parameter_type->type = new_param_type; if (last_parameter_type != NULL) { last_parameter_type->next = new_parameter_type; } else { new_type->parameter_types = new_parameter_type; } last_parameter_type = new_parameter_type; parameter_type = parameter_type->next; } if (!need_new_type) { obstack_free(type_obst, new_type); new_type = type; } return (type_t*) new_type; } static type_t *create_concrete_pointer_type(pointer_type_t *type) { type_t *points_to = create_concrete_type(type->points_to); if (points_to == type->points_to) return (type_t*) type; pointer_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_POINTER; new_type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_type_variable_reference_type(type_reference_t *type) { type_variable_t *type_variable = type->type_variable; type_t *current_type = type_variable->current_type; if (current_type != NULL) return current_type; return (type_t*) type; } static type_t *create_concrete_array_type(array_type_t *type) { type_t *element_type = create_concrete_type(type->element_type); if (element_type == type->element_type) return (type_t*) type; array_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); - new_type->type.type = TYPE_ARRAY; - new_type->element_type = element_type; - new_type->size = type->size; + new_type->type.type = TYPE_ARRAY; + new_type->element_type = element_type; + new_type->size_expression = type->size_expression; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_typevar_binding_type(bind_typevariables_type_t *type) { int changed = 0; type_argument_t *new_arguments; type_argument_t *last_argument = NULL; type_argument_t *type_argument = type->type_arguments; while (type_argument != NULL) { type_t *type = type_argument->type; type_t *new_type = create_concrete_type(type); if (new_type != type) { changed = 1; } type_argument_t *new_argument = obstack_alloc(type_obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = new_type; if (last_argument != NULL) { last_argument->next = new_argument; } else { new_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } if (!changed) { assert(new_arguments != NULL); obstack_free(type_obst, new_arguments); return (type_t*) type; } bind_typevariables_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_BIND_TYPEVARIABLES; new_type->polymorphic_type = type->polymorphic_type; new_type->type_arguments = new_arguments; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } type_t *create_concrete_type(type_t *type) { switch (type->type) { case TYPE_INVALID: return type_invalid; case TYPE_VOID: return type_void; case TYPE_ERROR: case TYPE_ATOMIC: return type; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return create_concrete_compound_type((compound_type_t*) type); case TYPE_METHOD: return create_concrete_method_type((method_type_t*) type); case TYPE_POINTER: return create_concrete_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return create_concrete_array_type((array_type_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return create_concrete_type_variable_reference_type( (type_reference_t*) type); case TYPE_BIND_TYPEVARIABLES: return create_concrete_typevar_binding_type( (bind_typevariables_type_t*) type); case TYPE_TYPEOF: panic("TODO: concrete type for typeof()"); case TYPE_REFERENCE: panic("trying to normalize unresolved type reference"); break; } return type; } int typevar_binding_stack_top() { return ARR_LEN(typevar_binding_stack); } void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments) { type_variable_t *type_parameter; type_argument_t *type_argument; if (type_parameters == NULL || type_arguments == NULL) return; /* we have to take care that all rebinding happens atomically, so we first * create the structures on the binding stack and misuse the * old_current_type value to temporarily save the new! current_type. * We can then walk the list and set the new types */ type_parameter = type_parameters; type_argument = type_arguments; int old_top = typevar_binding_stack_top(); int top = ARR_LEN(typevar_binding_stack) + 1; while (type_parameter != NULL) { type_t *type = type_argument->type; while (type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) type; type_variable_t *var = ref->type_variable; if (var->current_type == NULL) { break; } type = var->current_type; } top = ARR_LEN(typevar_binding_stack) + 1; ARR_RESIZE(typevar_binding_t, typevar_binding_stack, top); typevar_binding_t *binding = & typevar_binding_stack[top-1]; binding->type_variable = type_parameter; binding->old_current_type = type; type_parameter = type_parameter->next; type_argument = type_argument->next; } assert(type_parameter == NULL && type_argument == NULL); for (int i = old_top+1; i <= top; ++i) { typevar_binding_t *binding = & typevar_binding_stack[i-1]; type_variable_t *type_variable = binding->type_variable; type_t *new_type = binding->old_current_type; binding->old_current_type = type_variable->current_type; type_variable->current_type = new_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "binding '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, type_variable->current_type); fprintf(stderr, "\n"); #endif } } void pop_type_variable_bindings(int new_top) { int top = ARR_LEN(typevar_binding_stack) - 1; for (int i = top; i >= new_top; --i) { typevar_binding_t *binding = & typevar_binding_stack[i]; type_variable_t *type_variable = binding->type_variable; type_variable->current_type = binding->old_current_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "reset binding of '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, binding->old_current_type); fprintf(stderr, "\n"); #endif } ARR_SHRINKLEN(typevar_binding_stack, new_top); } type_t *skip_typeref(type_t *type) { if (type->type == TYPE_TYPEOF) { typeof_type_t *typeof_type = (typeof_type_t*) type; return skip_typeref(typeof_type->expression->base.type); } return type; } diff --git a/type_hash.c b/type_hash.c index 38b2454..20bdd51 100644 --- a/type_hash.c +++ b/type_hash.c @@ -1,291 +1,290 @@ #include <config.h> #include <stdbool.h> #include "type_hash.h" #include "adt/error.h" #include "type_t.h" #include <assert.h> #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #include "adt/hashset.h" #undef ValueType #undef HashSetIterator #undef HashSet typedef struct type_hash_iterator_t type_hash_iterator_t; typedef struct type_hash_t type_hash_t; static unsigned hash_ptr(const void *ptr) { unsigned ptr_int = ((const char*) ptr - (const char*) NULL); return ptr_int >> 3; } static unsigned hash_atomic_type(const atomic_type_t *type) { unsigned some_prime = 27644437; return type->atype * some_prime; } static unsigned hash_pointer_type(const pointer_type_t *type) { return hash_ptr(type->points_to); } static unsigned hash_array_type(const array_type_t *type) { - unsigned some_prime = 27644437; - return hash_ptr(type->element_type) ^ (type->size * some_prime); + return hash_ptr(type->element_type) ^ hash_ptr(type->size_expression); } static unsigned hash_compound_type(const compound_type_t *type) { unsigned result = hash_ptr(type->symbol); return result; } static unsigned hash_type(const type_t *type); static unsigned hash_method_type(const method_type_t *type) { unsigned result = hash_ptr(type->result_type); method_parameter_type_t *parameter = type->parameter_types; while (parameter != NULL) { result ^= hash_ptr(parameter->type); parameter = parameter->next; } if (type->variable_arguments) result = ~result; return result; } static unsigned hash_type_reference_type_variable(const type_reference_t *type) { return hash_ptr(type->type_variable); } static unsigned hash_bind_typevariables_type_t(const bind_typevariables_type_t *type) { unsigned hash = hash_compound_type(type->polymorphic_type); type_argument_t *argument = type->type_arguments; while (argument != NULL) { hash ^= hash_type(argument->type); argument = argument->next; } return hash; } static unsigned hash_type(const type_t *type) { switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: panic("internalizing void or invalid types not possible"); case TYPE_REFERENCE_TYPE_VARIABLE: return hash_type_reference_type_variable( (const type_reference_t*) type); case TYPE_ATOMIC: return hash_atomic_type((const atomic_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return hash_ptr(typeof_type->expression); } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return hash_compound_type((const compound_type_t*) type); case TYPE_METHOD: return hash_method_type((const method_type_t*) type); case TYPE_POINTER: return hash_pointer_type((const pointer_type_t*) type); case TYPE_ARRAY: return hash_array_type((const array_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return hash_bind_typevariables_type_t( (const bind_typevariables_type_t*) type); } abort(); } static bool atomic_types_equal(const atomic_type_t *type1, const atomic_type_t *type2) { return type1->atype == type2->atype; } static bool compound_types_equal(const compound_type_t *type1, const compound_type_t *type2) { if (type1->symbol != type2->symbol) return false; /* TODO: check type parameters? */ return true; } static bool method_types_equal(const method_type_t *type1, const method_type_t *type2) { if (type1->result_type != type2->result_type) return false; if (type1->variable_arguments != type2->variable_arguments) return false; method_parameter_type_t *param1 = type1->parameter_types; method_parameter_type_t *param2 = type2->parameter_types; while (param1 != NULL && param2 != NULL) { if (param1->type != param2->type) return false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) return false; return true; } static bool pointer_types_equal(const pointer_type_t *type1, const pointer_type_t *type2) { return type1->points_to == type2->points_to; } static bool array_types_equal(const array_type_t *type1, const array_type_t *type2) { return type1->element_type == type2->element_type - && type1->size == type2->size; + && type1->size_expression == type2->size_expression; } static bool type_references_type_variable_equal(const type_reference_t *type1, const type_reference_t *type2) { return type1->type_variable == type2->type_variable; } static bool bind_typevariables_type_equal(const bind_typevariables_type_t*type1, const bind_typevariables_type_t*type2) { if (type1->polymorphic_type != type2->polymorphic_type) return false; type_argument_t *argument1 = type1->type_arguments; type_argument_t *argument2 = type2->type_arguments; while (argument1 != NULL) { if (argument2 == NULL) return false; if (argument1->type != argument2->type) return false; argument1 = argument1->next; argument2 = argument2->next; } if (argument2 != NULL) return false; return true; } static bool types_equal(const type_t *type1, const type_t *type2) { if (type1 == type2) return true; if (type1->type != type2->type) return false; switch (type1->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: return false; case TYPE_TYPEOF: { const typeof_type_t *typeof_type1 = (const typeof_type_t*) type1; const typeof_type_t *typeof_type2 = (const typeof_type_t*) type2; return typeof_type1->expression == typeof_type2->expression; } case TYPE_REFERENCE_TYPE_VARIABLE: return type_references_type_variable_equal( (const type_reference_t*) type1, (const type_reference_t*) type2); case TYPE_ATOMIC: return atomic_types_equal((const atomic_type_t*) type1, (const atomic_type_t*) type2); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return compound_types_equal((const compound_type_t*) type1, (const compound_type_t*) type2); case TYPE_METHOD: return method_types_equal((const method_type_t*) type1, (const method_type_t*) type2); case TYPE_POINTER: return pointer_types_equal((const pointer_type_t*) type1, (const pointer_type_t*) type2); case TYPE_ARRAY: return array_types_equal((const array_type_t*) type1, (const array_type_t*) type2); case TYPE_BIND_TYPEVARIABLES: return bind_typevariables_type_equal( (const bind_typevariables_type_t*) type1, (const bind_typevariables_type_t*) type2); } panic("invalid type encountered"); } #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #define NullValue NULL #define DeletedValue ((type_t*)-1) #define Hash(this, key) hash_type(key) #define KeysEqual(this,key1,key2) types_equal(key1, key2) #define SetRangeEmpty(ptr,size) memset(ptr, 0, (size) * sizeof(*(ptr))) #define hashset_init _typehash_init #define hashset_init_size _typehash_init_size #define hashset_destroy _typehash_destroy #define hashset_insert _typehash_insert #define hashset_remove typehash_remove #define hashset_find typehash_find #define hashset_size typehash_size #define hashset_iterator_init typehash_iterator_init #define hashset_iterator_next typehash_iterator_next #define hashset_remove_iterator typehash_remove_iterator #define SCALAR_RETURN #include "adt/hashset.c" static type_hash_t typehash; void init_typehash(void) { _typehash_init(&typehash); } void exit_typehash(void) { _typehash_destroy(&typehash); } type_t *typehash_insert(type_t *type) { return _typehash_insert(&typehash, type); } int typehash_contains(type_t *type) { return typehash_find(&typehash, type) != NULL; } diff --git a/type_t.h b/type_t.h index a8c738f..afd24d8 100644 --- a/type_t.h +++ b/type_t.h @@ -1,149 +1,149 @@ #ifndef TYPE_T_H #define TYPE_T_H #include <stdbool.h> #include "type.h" #include "symbol.h" #include "lexer.h" #include "ast.h" #include "ast_t.h" #include "adt/obst.h" #include <libfirm/typerep.h> struct obstack *type_obst; typedef enum { TYPE_INVALID, TYPE_ERROR, TYPE_VOID, TYPE_ATOMIC, TYPE_COMPOUND_CLASS, TYPE_COMPOUND_STRUCT, TYPE_COMPOUND_UNION, TYPE_METHOD, TYPE_POINTER, TYPE_ARRAY, TYPE_TYPEOF, TYPE_REFERENCE, TYPE_REFERENCE_TYPE_VARIABLE, TYPE_BIND_TYPEVARIABLES } type_type_t; typedef enum { ATOMIC_TYPE_INVALID, ATOMIC_TYPE_BOOL, ATOMIC_TYPE_BYTE, ATOMIC_TYPE_UBYTE, ATOMIC_TYPE_SHORT, ATOMIC_TYPE_USHORT, ATOMIC_TYPE_INT, ATOMIC_TYPE_UINT, ATOMIC_TYPE_LONG, ATOMIC_TYPE_ULONG, ATOMIC_TYPE_LONGLONG, ATOMIC_TYPE_ULONGLONG, ATOMIC_TYPE_FLOAT, ATOMIC_TYPE_DOUBLE, } atomic_type_type_t; struct type_t { type_type_t type; ir_type *firm_type; }; struct atomic_type_t { type_t type; atomic_type_type_t atype; }; struct pointer_type_t { type_t type; type_t *points_to; }; struct array_type_t { type_t type; type_t *element_type; - unsigned long size; + expression_t *size_expression; }; struct typeof_type_t { type_t type; expression_t *expression; }; struct type_argument_t { type_t *type; type_argument_t *next; }; struct type_reference_t { type_t type; symbol_t *symbol; source_position_t source_position; type_argument_t *type_arguments; type_variable_t *type_variable; }; struct bind_typevariables_type_t { type_t type; type_argument_t *type_arguments; compound_type_t *polymorphic_type; }; struct method_parameter_type_t { type_t *type; method_parameter_type_t *next; }; struct type_constraint_t { symbol_t *concept_symbol; concept_t *concept; type_constraint_t *next; }; struct method_type_t { type_t type; type_t *result_type; method_parameter_type_t *parameter_types; bool variable_arguments; }; struct iterator_type_t { type_t type; type_t *element_type; method_parameter_type_t *parameter_types; }; struct compound_entry_t { type_t *type; symbol_t *symbol; compound_entry_t *next; attribute_t *attributes; source_position_t source_position; ir_entity *entity; }; struct compound_type_t { type_t type; compound_entry_t *entries; symbol_t *symbol; attribute_t *attributes; type_variable_t *type_parameters; context_t context; source_position_t source_position; }; type_t *make_atomic_type(atomic_type_type_t type); type_t *make_pointer_type(type_t *type); static inline bool is_type_array(const type_t *type) { return type->type == TYPE_ARRAY; } #endif
MatzeB/fluffy
7df892516e38164540d984850def55db320e74fa
add test for bug with bools not possible in structs
diff --git a/test/error1.fluffy b/test/error1.fluffy new file mode 100644 index 0000000..4b6fe19 --- /dev/null +++ b/test/error1.fluffy @@ -0,0 +1,10 @@ +// bool as compound element fails +struct Foo: + a : int + b : bool + +var k : Foo* + +func main() : int: + return 0 +export main
MatzeB/fluffy
114a9858daa1e3d8ef4b99750cd023b0ae48b9f3
TODO update
diff --git a/TODO b/TODO index 673fae0..883fc45 100644 --- a/TODO +++ b/TODO @@ -1,36 +1,30 @@ This does not describe the goals and visions but short term things that should not be forgotten and are not done yet because I was lazy or did not decide about the right way to do it yet. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected -- correct pointer arithmetic -- A typeof operator (resulting in the type of the enclosed expression) - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime -- fix ++ and -- expressions - forbid same variable names in nested blocks - change firm to pass on debug info on unitialized_variable callback - introduce constant expressions Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well -- Use more firm optimisations -- Create an eccp like wrapper script - Add an alloca operator -- create a ++ and -- operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) Refactorings: -- make unions for declaration_t, expression_t, type_t (see cparser) +- make unions for expression_t, type_t (see cparser) - rename type to kind, expression->datatype to expression->type - keep typerefs as long as possible (start the skip_typeref madness similar to cparser)
MatzeB/fluffy
d2d752e1d11af88d508be8e19e9a4e3cfa41646c
fixed subtraction of pointers
diff --git a/ast_t.h b/ast_t.h index 8e4dbe6..85cce87 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,473 +1,474 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_base_t base; method_t method; }; struct iterator_declaration_t { declaration_base_t base; method_t method; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_method_t { declaration_base_t base; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; method_declaration_t method; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_method_t concept_method; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_UNARY_FIRST, EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, EXPR_UNARY_NOT, EXPR_UNARY_BITWISE_NOT, EXPR_UNARY_DEREFERENCE, EXPR_UNARY_TAKE_ADDRESS, EXPR_UNARY_CAST, EXPR_UNARY_INCREMENT, EXPR_UNARY_DECREMENT, EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, EXPR_BINARY_FIRST, EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, EXPR_BINARY_ADD, EXPR_BINARY_SUB, EXPR_BINARY_MUL, EXPR_BINARY_DIV, EXPR_BINARY_MOD, EXPR_BINARY_EQUAL, EXPR_BINARY_NOTEQUAL, EXPR_BINARY_LESS, EXPR_BINARY_LESSEQUAL, EXPR_BINARY_GREATER, EXPR_BINARY_GREATEREQUAL, EXPR_BINARY_LAZY_AND, EXPR_BINARY_LAZY_OR, EXPR_BINARY_AND, EXPR_BINARY_OR, EXPR_BINARY_XOR, EXPR_BINARY_SHIFTLEFT, EXPR_BINARY_SHIFTRIGHT, EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, EXPR_LAST = EXPR_BINARY_LAST } expression_type_t; #define EXPR_UNARY_CASES \ case EXPR_UNARY_NEGATE: \ case EXPR_UNARY_NOT: \ case EXPR_UNARY_BITWISE_NOT: \ case EXPR_UNARY_DEREFERENCE: \ case EXPR_UNARY_TAKE_ADDRESS: \ case EXPR_UNARY_CAST: \ case EXPR_UNARY_INCREMENT: \ case EXPR_UNARY_DECREMENT: #define EXPR_BINARY_CASES \ case EXPR_BINARY_ASSIGN: \ case EXPR_BINARY_ADD: \ case EXPR_BINARY_SUB: \ case EXPR_BINARY_MUL: \ case EXPR_BINARY_DIV: \ case EXPR_BINARY_MOD: \ case EXPR_BINARY_EQUAL: \ case EXPR_BINARY_NOTEQUAL: \ case EXPR_BINARY_LESS: \ case EXPR_BINARY_LESSEQUAL: \ case EXPR_BINARY_GREATER: \ case EXPR_BINARY_GREATEREQUAL: \ case EXPR_BINARY_LAZY_AND: \ case EXPR_BINARY_LAZY_OR: \ case EXPR_BINARY_AND: \ case EXPR_BINARY_OR: \ case EXPR_BINARY_XOR: \ case EXPR_BINARY_SHIFTLEFT: \ case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_t { expression_type_t type; type_t *datatype; + bool lowered; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; struct unary_expression_t { expression_t expression; expression_t *value; }; struct binary_expression_t { expression_t expression; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/semantic.c b/semantic.c index 20f4b10..6b97275 100644 --- a/semantic.c +++ b/semantic.c @@ -187,1078 +187,1125 @@ static type_t *resolve_type_reference(type_reference_t *type_ref) if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { switch (expression->type) { case EXPR_REFERENCE: { const reference_expression_t *reference = (const reference_expression_t*) expression; const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY_DEREFERENCE: return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->datatype == NULL) { if (right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->datatype; if (from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->type == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY_CAST; cast->expression.source_position = source_position; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } +static expression_t *lower_sub_expression(expression_t *expression) +{ + binary_expression_t *sub = (binary_expression_t*) expression; + + expression_t *left = check_expression(sub->left); + expression_t *right = check_expression(sub->right); + type_t *lefttype = left->datatype; + type_t *righttype = right->datatype; + + if (lefttype->type != TYPE_POINTER && righttype->type != TYPE_POINTER) + return expression; + + sub->expression.datatype = type_uint; + + pointer_type_t *p1 = (pointer_type_t*) lefttype; + + sizeof_expression_t *sizeof_expr + = allocate_ast(sizeof(sizeof_expr[0])); + memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); + sizeof_expr->expression.type = EXPR_SIZEOF; + sizeof_expr->expression.datatype = type_uint; + sizeof_expr->type = p1->points_to; + + binary_expression_t *divexpr = allocate_ast(sizeof(divexpr[0])); + memset(divexpr, 0, sizeof(divexpr[0])); + divexpr->expression.type = EXPR_BINARY_DIV; + divexpr->expression.datatype = type_uint; + divexpr->left = expression; + divexpr->right = (expression_t*) sizeof_expr; + + sub->expression.lowered = true; + return (expression_t*) divexpr; +} + static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; expression_type_t binexpr_type = binexpr->expression.type; switch (binexpr_type) { case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case EXPR_BINARY_ADD: case EXPR_BINARY_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY_MUL; mulexpr->expression.datatype = type_uint; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY_CAST; cast->expression.source_position = binexpr->expression.source_position; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } + if (lefttype->type == TYPE_POINTER && righttype->type == TYPE_POINTER) { + pointer_type_t *p1 = (pointer_type_t*) lefttype; + pointer_type_t *p2 = (pointer_type_t*) righttype; + if (p1->points_to != p2->points_to) { + print_error_prefix(binexpr->expression.source_position); + fprintf(stderr, "Can only subtract pointers to same type, but have type "); + print_type(lefttype); + fprintf(stderr, " and "); + print_type(righttype); + fprintf(stderr, "\n"); + } + exprtype = type_uint; + } righttype = lefttype; break; case EXPR_BINARY_MUL: case EXPR_BINARY_MOD: case EXPR_BINARY_DIV: if (!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case EXPR_BINARY_AND: case EXPR_BINARY_OR: case EXPR_BINARY_XOR: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case EXPR_BINARY_SHIFTLEFT: case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case EXPR_BINARY_EQUAL: case EXPR_BINARY_NOTEQUAL: case EXPR_BINARY_LESS: case EXPR_BINARY_LESSEQUAL: case EXPR_BINARY_GREATER: case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case EXPR_BINARY_LAZY_AND: case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; default: panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if (right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if (method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->base.symbol->string, concept->base.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->base.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->base.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); switch (type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return error_type; case TYPE_ERROR: return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if (type == NULL) return; /* determine method type */ if (type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if (type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if (method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if (declaration->kind == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if (type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while (type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if (type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while (argument != NULL) { if (param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if (param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if (type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if (expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->source_position, lenient); if (new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->datatype); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if (param_type != NULL) param_type = param_type->next; ++i; } if (param_type != NULL) { @@ -1268,1256 +1315,1257 @@ static void check_call_expression(call_expression_t *call) /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while (type_var != NULL) { if (type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->base.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->base.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if (type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if (declaration->kind == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->kind == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if (cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if (value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if (value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if (type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(expression_t *expression_) { unary_expression_t *expression = (unary_expression_t*) expression_; expression_t *value = check_expression(expression->value); type_t *type = value->datatype; expression_type_t kind = expression->expression.type; if (!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.datatype = type; if (kind == EXPR_UNARY_INCREMENT) { add->expression.type = EXPR_BINARY_ADD; } else { assert(kind == EXPR_UNARY_DECREMENT); add->expression.type = EXPR_BINARY_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY_ASSIGN; assign->expression.datatype = type; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch (unary_expression->expression.type) { case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; case EXPR_UNARY_INCREMENT: case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); default: break; } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if (datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if (type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if (index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->datatype); fprintf(stderr, "\n"); return; } if (index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, access->expression.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; - if (lowerer != NULL) { + if (lowerer != NULL && !expression->lowered) { expression = lowerer(expression); } } switch (expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if (last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->datatype == NULL) return; bool may_be_unused = false; if (expression->type == EXPR_BINARY_ASSIGN) { may_be_unused = true; } else if (expression->type == EXPR_UNARY_INCREMENT || expression->type == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->type == EXPR_CALL) { may_be_unused = true; } if (expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->type == EXPR_BINARY_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch (declaration->kind) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; namespace_t *namespace = namespaces; for ( ; namespace != NULL; namespace = namespace->next) { check_namespace(namespace); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); + register_expression_lowerer(lower_sub_expression, EXPR_BINARY_SUB); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/test/expected_output/incdec.fluffy.output b/test/expected_output/incdec.fluffy.output new file mode 100644 index 0000000..8f44e1e --- /dev/null +++ b/test/expected_output/incdec.fluffy.output @@ -0,0 +1,4 @@ +L1: 43 +K1: 11 L1: 42 +Diff1: 1 +Diff2: 4 diff --git a/test/incdec.fluffy b/test/incdec.fluffy new file mode 100644 index 0000000..96d3f6c --- /dev/null +++ b/test/incdec.fluffy @@ -0,0 +1,24 @@ +func extern printf(format : byte*, ...) + +export main +func main() : int: + var l = 42 + var k = 11 + var m : int* = null + var pm : byte* = cast<byte*> m + + ++l + printf("L1: %d\n", l) + ++k + --k + --l + printf("K1: %d L1: %d\n", k, l) + + var m2 = m + ++m2 + printf("Diff1: %d\n", m2 - m) + + var pm2 = cast<byte*> m2 + printf("Diff2: %d\n", pm2 - pm) + + return 0
MatzeB/fluffy
74d19077797416d294431e8bb5dc31bf9c065f6e
move unary and binary expression types to toplevel expression_type enum
diff --git a/ast.c b/ast.c index ae73457..6a3c10f 100644 --- a/ast.c +++ b/ast.c @@ -1,683 +1,684 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; namespace_t *namespaces; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for (const char *c = string_const->value; *c != 0; ++c) { switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->base.symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); - switch (unexpr->type) { - case UNEXPR_CAST: + switch (unexpr->expression.type) { + case EXPR_UNARY_CAST: fprintf(out, "cast<"); print_type(unexpr->expression.datatype); fprintf(out, "> "); print_expression(unexpr->value); break; default: - fprintf(out, "*unexpr %d*", unexpr->type); + fprintf(out, "*unexpr %d*", unexpr->expression.type); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); - switch (binexpr->type) { - case BINEXPR_INVALID: - fprintf(out, "INVOP"); - break; - case BINEXPR_ASSIGN: + switch (binexpr->expression.type) { + case EXPR_BINARY_ASSIGN: fprintf(out, "<-"); break; - case BINEXPR_ADD: + case EXPR_BINARY_ADD: fprintf(out, "+"); break; - case BINEXPR_SUB: + case EXPR_BINARY_SUB: fprintf(out, "-"); break; - case BINEXPR_MUL: + case EXPR_BINARY_MUL: fprintf(out, "*"); break; - case BINEXPR_DIV: + case EXPR_BINARY_DIV: fprintf(out, "/"); break; - case BINEXPR_NOTEQUAL: + case EXPR_BINARY_NOTEQUAL: fprintf(out, "/="); break; - case BINEXPR_EQUAL: + case EXPR_BINARY_EQUAL: fprintf(out, "="); break; - case BINEXPR_LESS: + case EXPR_BINARY_LESS: fprintf(out, "<"); break; - case BINEXPR_LESSEQUAL: + case EXPR_BINARY_LESSEQUAL: fprintf(out, "<="); break; - case BINEXPR_GREATER: + case EXPR_BINARY_GREATER: fprintf(out, ">"); break; - case BINEXPR_GREATEREQUAL: + case EXPR_BINARY_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ - fprintf(out, "op%d", binexpr->type); + fprintf(out, "op%d", binexpr->expression.type); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } switch (expression->type) { - case EXPR_LAST: + case EXPR_ERROR: + fprintf(out, "*error expression*"); + break; case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; - case EXPR_BINARY: + EXPR_BINARY_CASES print_binary_expression((const binary_expression_t*) expression); break; - case EXPR_UNARY: + EXPR_UNARY_CASES print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; - default: + case EXPR_FLOAT_CONST: + case EXPR_BOOL_CONST: + case EXPR_FUNC: /* TODO */ - fprintf(out, "some expression of type %d", expression->type); + fprintf(out, "*expr TODO*"); break; } } static void print_indent(void) { for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while (statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->base.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.base.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->base.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch (statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->base.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->base.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.base.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if (method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->base.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->base.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->base.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while (method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if (method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->base.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->base.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->base.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->base.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch (declaration->kind) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type '%s'\n", get_declaration_kind_name(declaration->kind)); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%s)\n", get_declaration_kind_name(declaration->kind)); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { print_declaration(declaration); } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { print_concept_instance(instance); } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_kind_name(declaration_kind_t type) { switch (type) { case DECLARATION_LAST: case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } diff --git a/ast2firm.c b/ast2firm.c index e39352f..bced074 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -460,1488 +460,1488 @@ static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) if (declaration->kind == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->kind != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = declaration->base.symbol; ident *ident = new_id_from_str(symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->base.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch (type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->datatype); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->base.symbol); mangle_symbol(concept_method->base.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if (!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if (is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->base.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->base.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch (declaration->kind) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { - const unary_expression_t *unexpr; - const select_expression_t *select; switch (expression->type) { - case EXPR_SELECT: - select = (const select_expression_t*) expression; + case EXPR_SELECT: { + const select_expression_t *select + = (const select_expression_t*) expression; return select_expression_addr(select); + } case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); - case EXPR_UNARY: - unexpr = (const unary_expression_t*) expression; - if (unexpr->type == UNEXPR_DEREFERENCE) { - return expression_to_firm(unexpr->value); - } - break; + case EXPR_UNARY_DEREFERENCE: { + const unary_expression_t *unexpr + = (const unary_expression_t*) expression; + return expression_to_firm(unexpr->value); + } default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } -static ir_op *binexpr_type_to_op(binary_expression_type_t type) +static ir_op *binexpr_type_to_op(expression_type_t type) { switch (type) { - case BINEXPR_ADD: + case EXPR_BINARY_ADD: return op_Add; - case BINEXPR_SUB: + case EXPR_BINARY_SUB: return op_Sub; - case BINEXPR_MUL: + case EXPR_BINARY_MUL: return op_Mul; - case BINEXPR_AND: + case EXPR_BINARY_AND: return op_And; - case BINEXPR_OR: + case EXPR_BINARY_OR: return op_Or; - case BINEXPR_XOR: + case EXPR_BINARY_XOR: return op_Eor; - case BINEXPR_SHIFTLEFT: + case EXPR_BINARY_SHIFTLEFT: return op_Shl; - case BINEXPR_SHIFTRIGHT: + case EXPR_BINARY_SHIFTRIGHT: return op_Shr; default: return NULL; } } -static long binexpr_type_to_cmp_pn(binary_expression_type_t type) +static long binexpr_type_to_cmp_pn(expression_type_t type) { switch (type) { - case BINEXPR_EQUAL: + case EXPR_BINARY_EQUAL: return pn_Cmp_Eq; - case BINEXPR_NOTEQUAL: + case EXPR_BINARY_NOTEQUAL: return pn_Cmp_Lg; - case BINEXPR_LESS: + case EXPR_BINARY_LESS: return pn_Cmp_Lt; - case BINEXPR_LESSEQUAL: + case EXPR_BINARY_LESSEQUAL: return pn_Cmp_Le; - case BINEXPR_GREATER: + case EXPR_BINARY_GREATER: return pn_Cmp_Gt; - case BINEXPR_GREATEREQUAL: + case EXPR_BINARY_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { - int is_or = binary_expression->type == BINEXPR_LAZY_OR; - assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); + bool is_or = binary_expression->expression.type == EXPR_BINARY_LAZY_OR; + assert(is_or || binary_expression->expression.type == EXPR_BINARY_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } -static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) +static ir_node *binary_expression_to_firm( + const binary_expression_t *binary_expression) { - binary_expression_type_t btype = binary_expression->type; + expression_type_t type = binary_expression->expression.type; - switch (btype) { - case BINEXPR_ASSIGN: + switch (type) { + case EXPR_BINARY_ASSIGN: return assign_expression_to_firm(binary_expression); - case BINEXPR_LAZY_OR: - case BINEXPR_LAZY_AND: + case EXPR_BINARY_LAZY_OR: + case EXPR_BINARY_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); - if (btype == BINEXPR_DIV) { + if (type == EXPR_BINARY_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } - if (btype == BINEXPR_MOD) { + if (type == EXPR_BINARY_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ - ir_op *irop = binexpr_type_to_op(btype); + ir_op *irop = binexpr_type_to_op(type); if (irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ - long compare_pn = binexpr_type_to_cmp_pn(btype); + long compare_pn = binexpr_type_to_cmp_pn(type); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } - panic("found unknown binexpr type"); + panic("found unknown binary expression"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } -static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) +static ir_node *unary_expression_to_firm( + const unary_expression_t *unary_expression) { ir_node *addr; - switch (unary_expression->type) { - case UNEXPR_CAST: + switch (unary_expression->expression.type) { + case EXPR_UNARY_CAST: return cast_expression_to_firm(unary_expression); - case UNEXPR_DEREFERENCE: + case EXPR_UNARY_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); - case UNEXPR_TAKE_ADDRESS: + case EXPR_UNARY_TAKE_ADDRESS: return expression_addr(unary_expression->value); - case UNEXPR_BITWISE_NOT: - case UNEXPR_NOT: + case EXPR_UNARY_BITWISE_NOT: + case EXPR_UNARY_NOT: return create_unary_expression_node(unary_expression, new_d_Not); - case UNEXPR_NEGATE: + case EXPR_UNARY_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); - case UNEXPR_INCREMENT: - case UNEXPR_DECREMENT: + case EXPR_UNARY_INCREMENT: + case EXPR_UNARY_DECREMENT: panic("inc/dec expression not lowered"); - case UNEXPR_INVALID: - abort(); + default: + break; } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->base.symbol->string, concept->base.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if (result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->base.symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch (expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); - case EXPR_BINARY: + EXPR_BINARY_CASES return binary_expression_to_firm( (const binary_expression_t*) expression); - case EXPR_UNARY: + EXPR_UNARY_CASES return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); - case EXPR_LAST: case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if (statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while (statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch (statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if (!is_polymorphic_method(method)) { assure_instance(method, declaration->base.symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { create_concept_instance(instance); } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while (namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index 2e68b79..8e4dbe6 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,447 +1,473 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_kind_t; /** * base struct for a declaration */ struct declaration_base_t { declaration_kind_t kind; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_base_t base; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_base_t base; method_t method; }; struct iterator_declaration_t { declaration_base_t base; method_t method; }; struct variable_declaration_t { declaration_base_t base; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct label_declaration_t { declaration_base_t base; ir_node *block; label_declaration_t *next; }; struct constant_t { declaration_base_t base; type_t *type; expression_t *expression; }; struct typealias_t { declaration_base_t base; type_t *type; }; struct concept_method_t { declaration_base_t base; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_base_t base; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; union declaration_t { declaration_kind_t kind; declaration_base_t base; type_variable_t type_variable; method_declaration_t method; iterator_declaration_t iterator; variable_declaration_t variable; label_declaration_t label; constant_t constant; typealias_t typealias; concept_t concept; concept_method_t concept_method; }; typedef enum { EXPR_INVALID = 0, EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, - EXPR_UNARY, - EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, - EXPR_LAST -} expresion_type_t; + + EXPR_UNARY_FIRST, + EXPR_UNARY_NEGATE = EXPR_UNARY_FIRST, + EXPR_UNARY_NOT, + EXPR_UNARY_BITWISE_NOT, + EXPR_UNARY_DEREFERENCE, + EXPR_UNARY_TAKE_ADDRESS, + EXPR_UNARY_CAST, + EXPR_UNARY_INCREMENT, + EXPR_UNARY_DECREMENT, + EXPR_UNARY_LAST = EXPR_UNARY_DECREMENT, + + EXPR_BINARY_FIRST, + EXPR_BINARY_ASSIGN = EXPR_BINARY_FIRST, + EXPR_BINARY_ADD, + EXPR_BINARY_SUB, + EXPR_BINARY_MUL, + EXPR_BINARY_DIV, + EXPR_BINARY_MOD, + EXPR_BINARY_EQUAL, + EXPR_BINARY_NOTEQUAL, + EXPR_BINARY_LESS, + EXPR_BINARY_LESSEQUAL, + EXPR_BINARY_GREATER, + EXPR_BINARY_GREATEREQUAL, + EXPR_BINARY_LAZY_AND, + EXPR_BINARY_LAZY_OR, + EXPR_BINARY_AND, + EXPR_BINARY_OR, + EXPR_BINARY_XOR, + EXPR_BINARY_SHIFTLEFT, + EXPR_BINARY_SHIFTRIGHT, + EXPR_BINARY_LAST = EXPR_BINARY_SHIFTRIGHT, + + EXPR_LAST = EXPR_BINARY_LAST +} expression_type_t; + +#define EXPR_UNARY_CASES \ + case EXPR_UNARY_NEGATE: \ + case EXPR_UNARY_NOT: \ + case EXPR_UNARY_BITWISE_NOT: \ + case EXPR_UNARY_DEREFERENCE: \ + case EXPR_UNARY_TAKE_ADDRESS: \ + case EXPR_UNARY_CAST: \ + case EXPR_UNARY_INCREMENT: \ + case EXPR_UNARY_DECREMENT: + +#define EXPR_BINARY_CASES \ + case EXPR_BINARY_ASSIGN: \ + case EXPR_BINARY_ADD: \ + case EXPR_BINARY_SUB: \ + case EXPR_BINARY_MUL: \ + case EXPR_BINARY_DIV: \ + case EXPR_BINARY_MOD: \ + case EXPR_BINARY_EQUAL: \ + case EXPR_BINARY_NOTEQUAL: \ + case EXPR_BINARY_LESS: \ + case EXPR_BINARY_LESSEQUAL: \ + case EXPR_BINARY_GREATER: \ + case EXPR_BINARY_GREATEREQUAL: \ + case EXPR_BINARY_LAZY_AND: \ + case EXPR_BINARY_LAZY_OR: \ + case EXPR_BINARY_AND: \ + case EXPR_BINARY_OR: \ + case EXPR_BINARY_XOR: \ + case EXPR_BINARY_SHIFTLEFT: \ + case EXPR_BINARY_SHIFTRIGHT: /** * base structure for expressions */ struct expression_t { - expresion_type_t type; + expression_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; -typedef enum { - UNEXPR_INVALID = 0, - UNEXPR_NEGATE, - UNEXPR_NOT, - UNEXPR_BITWISE_NOT, - UNEXPR_DEREFERENCE, - UNEXPR_TAKE_ADDRESS, - UNEXPR_CAST, - UNEXPR_INCREMENT, - UNEXPR_DECREMENT -} unary_expression_type_t; - struct unary_expression_t { - expression_t expression; - unary_expression_type_t type; - expression_t *value; + expression_t expression; + expression_t *value; }; -typedef enum { - BINEXPR_INVALID = 0, - BINEXPR_ASSIGN, - BINEXPR_ADD, - BINEXPR_SUB, - BINEXPR_MUL, - BINEXPR_DIV, - BINEXPR_MOD, - BINEXPR_EQUAL, - BINEXPR_NOTEQUAL, - BINEXPR_LESS, - BINEXPR_LESSEQUAL, - BINEXPR_GREATER, - BINEXPR_GREATEREQUAL, - BINEXPR_LAZY_AND, - BINEXPR_LAZY_OR, - BINEXPR_AND, - BINEXPR_OR, - BINEXPR_XOR, - BINEXPR_SHIFTLEFT, - BINEXPR_SHIFTRIGHT, -} binary_expression_type_t; - struct binary_expression_t { - expression_t expression; - binary_expression_type_t type; - expression_t *left; - expression_t *right; + expression_t expression; + expression_t *left; + expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_kind_name(declaration_kind_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/parser.c b/parser.c index 382ec78..6137d96 100644 --- a/parser.c +++ b/parser.c @@ -420,1411 +420,1407 @@ static type_t *parse_type_ref(void) if (token.type == '<') { next_token(); add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *create_error_type(void) { type_t *error_type = allocate_type_zero(sizeof(error_type[0])); error_type->type = TYPE_ERROR; return error_type; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; parse_parameter_declarations(method_type, NULL); expect(':', end_error); method_type->result_type = parse_type(); return (type_t*) method_type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); if (token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); eat_until_anchor(); rem_anchor_token(']'); break; } int size = token.v.intvalue; next_token(); if (size < 0) { parse_error("negative array size not allowed"); eat_until_anchor(); rem_anchor_token(']'); break; } array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; rem_anchor_token(']'); expect(']', end_error); break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(void) { int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(void) { eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(void) { eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(void) { eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(void) { eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(void) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (expression_t*) ref; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_ERROR; expression->datatype = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; if (token.type == '(') { next_token(); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; expression->type = (type_t*) typeof_type; add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); } else { expect('<', end_error); add_anchor_token('>'); expression->type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return (expression_t*) expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); - unary_expression->expression.type = EXPR_UNARY; - unary_expression->type = UNEXPR_CAST; + unary_expression->expression.type = EXPR_UNARY_CAST; expect('<', end_error); unary_expression->expression.datatype = parse_type(); expect('>', end_error); unary_expression->value = parse_sub_expression(PREC_CAST); end_error: return (expression_t*) unary_expression; } static expression_t *parse_call_expression(expression_t *expression) { call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return (expression_t*) call; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ - unary_expression->expression.type = EXPR_UNARY; \ - unary_expression->type = unexpression_type; \ + unary_expression->expression.type = unexpression_type; \ unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } -CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) -CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) -CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) -CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) -CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) -CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) -CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) +CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE) +CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT) +CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NOT) +CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE) +CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS) +CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_INCREMENT) +CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(prec_r); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ - binexpr->expression.type = EXPR_BINARY; \ - binexpr->type = binexpression_type; \ + binexpr->expression.type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) -CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); -CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); -CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); -CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); -CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); -CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); -CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); -CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); -CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); -CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); -CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); -CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); -CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); -CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); -CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); -CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); -CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); -CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); -CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('*', EXPR_BINARY_MUL, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('/', EXPR_BINARY_DIV, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('%', EXPR_BINARY_MOD, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('+', EXPR_BINARY_ADD, PREC_ADDITIVE); +CREATE_BINEXPR_PARSER_LR('-', EXPR_BINARY_SUB, PREC_ADDITIVE); +CREATE_BINEXPR_PARSER_LR('<', EXPR_BINARY_LESS, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR('>', EXPR_BINARY_GREATER, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_EQUALITY); +CREATE_BINEXPR_PARSER_RL('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT); +CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, EXPR_BINARY_NOTEQUAL, PREC_EQUALITY); +CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR('&', EXPR_BINARY_AND, PREC_AND); +CREATE_BINEXPR_PARSER_LR('|', EXPR_BINARY_OR, PREC_OR); +CREATE_BINEXPR_PARSER_LR('^', EXPR_BINARY_XOR, PREC_XOR); +CREATE_BINEXPR_PARSER_LR(T_ANDAND, EXPR_BINARY_LAZY_AND, PREC_LAZY_AND); +CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, EXPR_BINARY_LAZY_OR, PREC_LAZY_OR); +CREATE_BINEXPR_PARSER_LR(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { - register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); - register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); - register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); - register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, + register_expression_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); - register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, + register_expression_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); - register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); - register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); - register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); - register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); - register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); - register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, + register_expression_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE); + register_expression_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE); + register_expression_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL); + register_expression_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL); + register_expression_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); + register_expression_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); - register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); - register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); - register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); - register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); - register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); - register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); - register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); - register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); + register_expression_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); + register_expression_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); + register_expression_infix_parser(parse_EXPR_BINARY_AND, '&', PREC_AND); + register_expression_infix_parser(parse_EXPR_BINARY_LAZY_AND, T_ANDAND, PREC_LAZY_AND); + register_expression_infix_parser(parse_EXPR_BINARY_XOR, '^', PREC_XOR); + register_expression_infix_parser(parse_EXPR_BINARY_OR, '|', PREC_OR); + register_expression_infix_parser(parse_EXPR_BINARY_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); + register_expression_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); - register_expression_parser(parse_UNEXPR_NEGATE, '-'); - register_expression_parser(parse_UNEXPR_NOT, '!'); - register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); - register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); - register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); + register_expression_parser(parse_EXPR_UNARY_NEGATE, '-'); + register_expression_parser(parse_EXPR_UNARY_NOT, '!'); + register_expression_parser(parse_EXPR_UNARY_BITWISE_NOT, '~'); + register_expression_parser(parse_EXPR_UNARY_INCREMENT, T_PLUSPLUS); + register_expression_parser(parse_EXPR_UNARY_DECREMENT, T_MINUSMINUS); - register_expression_parser(parse_UNEXPR_DEREFERENCE, '*'); - register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&'); + register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*'); + register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if (token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if (parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while (true) { if (token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if (parser->infix_parser == NULL) break; if (parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if (token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return (statement_t*) return_statement; } static statement_t *create_error_statement(void) { statement_t *statement = allocate_ast_zero(sizeof(statement[0])); statement->type = STATEMENT_ERROR; return statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return (statement_t*) goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->declaration.base.kind = DECLARATION_LABEL; label->declaration.base.source_position = source_position; label->declaration.base.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE, end_error); return (statement_t*) label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if (token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if (token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if (token.type == T_else) { next_token(); if (token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; if_statement->condition = condition; if_statement->true_statement = true_statement; if_statement->false_statement = false_statement; return (statement_t*) if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = symbol; binary_expression_t *assign = allocate_ast_zero(sizeof(assign[0])); - assign->expression.type = EXPR_BINARY; + assign->expression.type = EXPR_BINARY_ASSIGN; assign->expression.source_position = source_position; - assign->type = BINEXPR_ASSIGN; assign->left = (expression_t*) ref; assign->right = parse_expression(); expression_statement_t *expr_statement = allocate_ast_zero(sizeof(expr_statement[0])); expr_statement->statement.type = STATEMENT_EXPRESSION; expr_statement->expression = (expression_t*) assign; return (statement_t*) expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while (true) { if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } variable_declaration_statement_t *declaration_statement = allocate_ast_zero(sizeof(declaration_statement[0])); declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; declaration_t *declaration = (declaration_t*) &declaration_statement->declaration; declaration->base.kind = DECLARATION_VARIABLE; declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &declaration_statement->declaration; if (token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if (last_statement != NULL) { last_statement->next = (statement_t*) declaration_statement; } else { first_statement = (statement_t*) declaration_statement; } last_statement = (statement_t*) declaration_statement; /* do we have an assignment expression? */ if (token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->base.symbol); last_statement->next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if (token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { expression_statement_t *expression_statement = allocate_ast_zero(sizeof(expression_statement[0])); expression_statement->statement.type = STATEMENT_EXPRESSION; expression_statement->expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: return (statement_t*) expression_statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if (token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; parse_statement_function parser = NULL; if (token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; add_anchor_token(T_NEWLINE); if (parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if (token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if (declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } rem_anchor_token(T_NEWLINE); if (statement == NULL) return NULL; statement->source_position = start; statement_t *next = statement->next; while (next != NULL) { next->source_position = start; next = next->next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; context_t *last_context = current_context; current_context = &block->context; add_anchor_token(T_DEDENT); statement_t *last_statement = NULL; while (token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if (statement == NULL) continue; if (last_statement != NULL) { last_statement->next = statement; } else { block->statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while (last_statement->next != NULL) last_statement = last_statement->next; } assert(current_context == &block->context); current_context = last_context; block->end_position = source_position; rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: return (statement_t*) block; } static void parse_parameter_declarations(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if (parameters != NULL) *parameters = NULL; expect('(', end_error2); if (token.type == ')') { next_token(); return; } add_anchor_token(')'); add_anchor_token(','); while (true) { if (token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if (token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); goto end_error; } break; } if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if (last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if (parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.base.kind = DECLARATION_METHOD_PARAMETER; method_param->declaration.base.symbol = symbol; method_param->declaration.base.source_position = source_position; method_param->type = param_type->type; if (last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if (token.type != ',') break; next_token(); } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error2); return; end_error: rem_anchor_token(','); rem_anchor_token(')'); end_error2: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while (token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if (last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static declaration_t *parse_type_parameter(void) { declaration_t *declaration = allocate_declaration(DECLARATION_TYPE_VARIABLE); if (token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->type_variable.constraints = parse_type_constraints(); } return declaration; } static type_variable_t *parse_type_parameters(context_t *context) { declaration_t *first_variable = NULL; declaration_t *last_variable = NULL; while (true) { declaration_t *type_variable = parse_type_parameter(); if (last_variable != NULL) { last_variable->type_variable.next = &type_variable->type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if (context != NULL) { type_variable->base.next = context->declarations; context->declarations = type_variable; } if (token.type != ',') break; next_token(); } return &first_variable->type_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->base.source_position.input_name != NULL); assert(current_context != NULL); declaration->base.next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if (token.type == '<') { next_token(); add_anchor_token('>'); method->type_parameters = parse_type_parameters(current_context); rem_anchor_token('>'); expect('>', end_error); } parse_parameter_declarations(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { declaration_t *declaration = (declaration_t*) parameter; declaration->base.next = current_context->declarations; current_context->declarations = declaration; } method_type->result_type = type_void; if (token.type == ':') { next_token(); if (token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } method_type->result_type = parse_type(); if (token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } expect(T_NEWLINE, end_error); method_parser_end: assert(current_context == &method->context); current_context = last_context; end_error: ; } static void parse_method_declaration(void) { eat(T_func); declaration_t *declaration = allocate_declaration(DECLARATION_METHOD); if (token.type == T_extern) { declaration->method.method.is_extern = true; next_token(); } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); parse_method(&declaration->method.method); add_declaration(declaration); } static void parse_global_variable(void) { eat(T_var); declaration_t *declaration = allocate_declaration(DECLARATION_VARIABLE); declaration->variable.is_global = true; if (token.type == T_extern) { next_token(); declaration->variable.is_extern = true; } if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); declaration->variable.type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_declaration(declaration); } static void parse_constant(void) { eat(T_const); declaration_t *declaration = allocate_declaration(DECLARATION_CONSTANT); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } declaration->base.source_position = source_position; declaration->base.symbol = token.v.symbol; next_token(); if (token.type == ':') { next_token(); declaration->constant.type = parse_type(); } expect('=', end_error); declaration->constant.expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_declaration(declaration); } static void parse_typealias(void) { eat(T_typealias); diff --git a/semantic.c b/semantic.c index 54057db..20f4b10 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2550 +1,2523 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->base.symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->base.source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->base.source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->base.source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->kind == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->kind != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch (declaration->kind) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->base.symbol->string, get_declaration_kind_name(declaration->kind)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { - unary_expression_t *unexpr; - reference_expression_t *reference; - declaration_t *declaration; - switch (expression->type) { - case EXPR_REFERENCE: - reference = (reference_expression_t*) expression; - declaration = reference->declaration; + case EXPR_REFERENCE: { + const reference_expression_t *reference + = (const reference_expression_t*) expression; + const declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { return true; } break; + } case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; - case EXPR_UNARY: - unexpr = (unary_expression_t*) expression; - if (unexpr->type == UNEXPR_DEREFERENCE) - return true; - break; + case EXPR_UNARY_DEREFERENCE: + return true; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->base.symbol; /* do type inference if needed */ if (left->datatype == NULL) { if (right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->datatype; if (from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->type == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); - cast->expression.type = EXPR_UNARY; + cast->expression.type = EXPR_UNARY_CAST; cast->expression.source_position = source_position; - cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; - binary_expression_type_t binexpr_type = binexpr->type; + expression_type_t binexpr_type = binexpr->expression.type; switch (binexpr_type) { - case BINEXPR_ASSIGN: + case EXPR_BINARY_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; - case BINEXPR_ADD: - case BINEXPR_SUB: + case EXPR_BINARY_ADD: + case EXPR_BINARY_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); - mulexpr->expression.type = EXPR_BINARY; + mulexpr->expression.type = EXPR_BINARY_MUL; mulexpr->expression.datatype = type_uint; - mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); - cast->expression.type = EXPR_UNARY; + cast->expression.type = EXPR_UNARY_CAST; cast->expression.source_position = binexpr->expression.source_position; - cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; - case BINEXPR_MUL: - case BINEXPR_MOD: - case BINEXPR_DIV: + case EXPR_BINARY_MUL: + case EXPR_BINARY_MOD: + case EXPR_BINARY_DIV: if (!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; - case BINEXPR_AND: - case BINEXPR_OR: - case BINEXPR_XOR: + case EXPR_BINARY_AND: + case EXPR_BINARY_OR: + case EXPR_BINARY_XOR: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; - case BINEXPR_SHIFTLEFT: - case BINEXPR_SHIFTRIGHT: + case EXPR_BINARY_SHIFTLEFT: + case EXPR_BINARY_SHIFTRIGHT: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ - case BINEXPR_EQUAL: - case BINEXPR_NOTEQUAL: - case BINEXPR_LESS: - case BINEXPR_LESSEQUAL: - case BINEXPR_GREATER: - case BINEXPR_GREATEREQUAL: + case EXPR_BINARY_EQUAL: + case EXPR_BINARY_NOTEQUAL: + case EXPR_BINARY_LESS: + case EXPR_BINARY_LESSEQUAL: + case EXPR_BINARY_GREATER: + case EXPR_BINARY_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; - case BINEXPR_LAZY_AND: - case BINEXPR_LAZY_OR: + case EXPR_BINARY_LAZY_AND: + case EXPR_BINARY_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; - - case BINEXPR_INVALID: - abort(); + default: + panic("invalid type in binexpr"); } if (left == NULL || right == NULL) return; if (left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if (right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->base.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->kind == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->base.symbol->string, concept->base.symbol->string, concept_method->base.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->base.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if (method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->base.symbol->string, concept->base.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->base.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->base.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); switch (type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return error_type; case TYPE_ERROR: return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if (type == NULL) return; /* determine method type */ if (type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if (type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if (method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if (declaration->kind == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if (type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while (type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if (type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while (argument != NULL) { if (param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if (param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if (type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if (expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->source_position, lenient); if (new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->datatype); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if (param_type != NULL) param_type = param_type->next; ++i; } if (param_type != NULL) { error_at(call->expression.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while (type_var != NULL) { if (type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->base.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->base.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if (type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if (declaration->kind == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->kind == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if (cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if (value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if (value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if (declaration->kind == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if (type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } -static expression_t *lower_incdec_expression(unary_expression_t *expression) +static expression_t *lower_incdec_expression(expression_t *expression_) { + unary_expression_t *expression = (unary_expression_t*) expression_; + expression_t *value = check_expression(expression->value); type_t *type = value->datatype; + expression_type_t kind = expression->expression.type; + if (!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", - expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" + kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", - expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" + kind == EXPR_UNARY_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); - add->expression.type = EXPR_BINARY; add->expression.datatype = type; - if (expression->type == UNEXPR_INCREMENT) { - add->type = BINEXPR_ADD; + if (kind == EXPR_UNARY_INCREMENT) { + add->expression.type = EXPR_BINARY_ADD; } else { - add->type = BINEXPR_SUB; + assert(kind == EXPR_UNARY_DECREMENT); + add->expression.type = EXPR_BINARY_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); - assign->expression.type = EXPR_BINARY; + assign->expression.type = EXPR_BINARY_ASSIGN; assign->expression.datatype = type; - assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } -static expression_t *lower_unary_expression(expression_t *expression) -{ - assert(expression->type == EXPR_UNARY); - unary_expression_t *unary_expression = (unary_expression_t*) expression; - switch (unary_expression->type) { - case UNEXPR_INCREMENT: - case UNEXPR_DECREMENT: - return lower_incdec_expression(unary_expression); - default: - break; - } - - return expression; -} - static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { - switch (unary_expression->type) { - case UNEXPR_CAST: + switch (unary_expression->expression.type) { + case EXPR_UNARY_CAST: check_cast_expression(unary_expression); return; - case UNEXPR_DEREFERENCE: + case EXPR_UNARY_DEREFERENCE: check_dereference_expression(unary_expression); return; - case UNEXPR_TAKE_ADDRESS: + case EXPR_UNARY_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; - case UNEXPR_NOT: + case EXPR_UNARY_NOT: check_not_expression(unary_expression); return; - case UNEXPR_BITWISE_NOT: + case EXPR_UNARY_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; - case UNEXPR_NEGATE: + case EXPR_UNARY_NEGATE: check_negate_expression(unary_expression); return; - case UNEXPR_INCREMENT: - case UNEXPR_DECREMENT: + case EXPR_UNARY_INCREMENT: + case EXPR_UNARY_DECREMENT: panic("increment/decrement not lowered"); - - case UNEXPR_INVALID: - abort(); + default: + break; } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if (datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { if (declaration->base.symbol == symbol) break; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if (type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if (index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->datatype); fprintf(stderr, "\n"); return; } if (index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, access->expression.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; if (lowerer != NULL) { expression = lowerer(expression); } } switch (expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; - case EXPR_BINARY: + EXPR_BINARY_CASES check_binary_expression((binary_expression_t*) expression); break; - case EXPR_UNARY: + EXPR_UNARY_CASES check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; - case EXPR_LAST: case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { environment_push(declaration, context); } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if (last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->datatype == NULL) return; bool may_be_unused = false; - if (expression->type == EXPR_BINARY && - ((binary_expression_t*) expression)->type == BINEXPR_ASSIGN) { + if (expression->type == EXPR_BINARY_ASSIGN) { may_be_unused = true; - } else if (expression->type == EXPR_UNARY && - (((unary_expression_t*) expression)->type == UNEXPR_INCREMENT || - ((unary_expression_t*) expression)->type == UNEXPR_DECREMENT)) { + } else if (expression->type == EXPR_UNARY_INCREMENT + || expression->type == EXPR_UNARY_DECREMENT) { may_be_unused = true; } else if (expression->type == EXPR_CALL) { may_be_unused = true; } if (expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); - if (expression->type == EXPR_BINARY) { - binary_expression_t *binexpr = (binary_expression_t*) expression; - if (binexpr->type == BINEXPR_EQUAL) { - print_warning_prefix(statement->statement.source_position); - fprintf(stderr, "Did you mean '<-' instead of '='?\n"); - } + if (expression->type == EXPR_BINARY_EQUAL) { + print_warning_prefix(statement->statement.source_position); + fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->kind != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; switch (statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->base.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; for ( ; constraint != NULL; constraint = constraint->next) { resolve_type_constraint(constraint, type_var->base.source_position); } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; for ( ; parameter != NULL; parameter = parameter->next) { parameter->type = normalize_type(parameter->type); } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; for ( ; concept_method != NULL; concept_method = concept_method->next) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->kind != DECLARATION_CONCEPT) { print_error_prefix(declaration->base.source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->base.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->base.symbol->string, concept->base.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->base.symbol->string, method->base.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch (declaration->kind) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_kind_name(declaration->kind)); return; } found_export = true; } static void check_and_push_context(context_t *context) { push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_VARIABLE: declaration->variable.type = normalize_type(declaration->variable.type); break; case DECLARATION_METHOD: resolve_method_types(&declaration->method.method); break; case DECLARATION_TYPEALIAS: { type_t *type = normalize_type(declaration->typealias.type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } declaration->typealias.type = type; break; } case DECLARATION_CONCEPT: resolve_concept_types(&declaration->concept); break; default: break; } } concept_instance_t *instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { resolve_concept_instance(instance); } /* check semantics in conceptes */ instance = context->concept_instances; for ( ; instance != NULL; instance = instance->next) { check_concept_instance(instance); } /* check semantics in methods */ declaration = context->declarations; for ( ; declaration != NULL; declaration = declaration->base.next) { switch (declaration->kind) { case DECLARATION_METHOD: { check_method(&declaration->method.method, declaration->base.symbol, declaration->base.source_position); break; } case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } } /* handle export declarations */ export_t *export = context->exports; for ( ; export != NULL; export = export->next) { check_export(export); } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; namespace_t *namespace = namespaces; for ( ; namespace != NULL; namespace = namespace->next) { check_namespace(namespace); } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); - register_expression_lowerer(lower_unary_expression, EXPR_UNARY); + register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_INCREMENT); + register_expression_lowerer(lower_incdec_expression, EXPR_UNARY_DECREMENT); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); }
MatzeB/fluffy
0ec7cc53ae8f5d3f0081183a972fe3d45cb8e429
fix enum plugin
diff --git a/plugins/api.fluffy b/plugins/api.fluffy index 404fea3..1af7c48 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,381 +1,380 @@ struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: kind : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: type : unsigned int datatype : Type* source_position : SourcePosition struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 const STATEMENT_ERROR = 1 const STATEMENT_BLOCK = 2 const STATEMENT_RETURN = 3 const STATEMENT_VARIABLE_DECLARATION = 4 const STATEMENT_IF = 5 const STATEMENT_EXPRESSION = 6 const STATEMENT_GOTO = 7 const STATEMENT_LABEL = 8 const TYPE_INVALID = 0 const TYPE_ERROR = 1 const TYPE_VOID = 2 const TYPE_ATOMIC = 3 const TYPE_COMPOUND_CLASS = 4 const TYPE_COMPOUND_STRUCT = 5 const TYPE_COMPOUND_UNION = 6 const TYPE_METHOD = 7 const TYPE_POINTER = 8 const TYPE_ARRAY = 9 const TYPE_REFERENCE = 10 const TYPE_REFERENCE_TYPE_VARIABLE = 11 const TYPE_BIND_TYPEVARIABLES = 12 const DECLARATION_INVALID = 0 const DECLARATION_ERROR = 1 const DECLARATION_METHOD = 2 const DECLARATION_METHOD_PARAMETER = 3 const DECLARATION_ITERATOR = 4 const DECLARATION_VARIABLE = 5 const DECLARATION_CONSTANT = 6 const DECLARATION_TYPE_VARIABLE = 7 const DECLARATION_TYPEALIAS = 8 const DECLARATION_CONCEPT = 9 const DECLARATION_CONCEPT_METHOD = 10 const DECLARATION_LABEL = 11 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const EXPR_INVALID = 0 const EXPR_ERROR = 1 const EXPR_INT_CONST = 2 const EXPR_FLOAT_CONST = 3 const EXPR_BOOL_CONST = 4 const EXPR_STRING_CONST = 5 const EXPR_NULL_POINTER = 6 const EXPR_REFERENCE = 7 const EXPR_CALL = 8 const EXPR_UNARY = 9 const EXPR_BINARY = 10 const BINEXPR_INVALID = 0 const BINEXPR_ASSIGN = 1 const BINEXPR_ADD = 2 -const T_EOF = -1 +const T_EOF = 4 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 -const T_ASSIGN = 296 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* typealias ParseExpressionFunction = func () : Expression* typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.statement.type = STATEMENT_LABEL res.declaration.declaration.kind = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.declaration.kind = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() res.expression.type = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() res.expression.type = EXPR_INT_CONST return res func api_init(): stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): declaration.next = context.declarations context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label diff --git a/plugins/plugin_enum.fluffy b/plugins/plugin_enum.fluffy index c07cf9b..5c875c1 100644 --- a/plugins/plugin_enum.fluffy +++ b/plugins/plugin_enum.fluffy @@ -1,56 +1,56 @@ var token_enum : int var type_int : Type* func parse_enum(): assert(token.type == token_enum) next_token() expect(T_IDENTIFIER) expect(':') expect(T_NEWLINE) if token.type /= T_INDENT: return next_token() var idx = 0 var last_expression = cast<Expression* > null while token.type /= T_DEDENT && token.type /= T_EOF: assert(token.type == T_IDENTIFIER) var constant = allocate<$Constant>() constant.declaration.symbol = token.v.symbol constant.declaration.source_position = source_position constant.type = type_int next_token() - if token.type == T_ASSIGN: + if token.type == '=': next_token() var expression = parse_expression() last_expression = expression idx = 0 constant.expression = expression else: if last_expression /= null: var expression = allocate<$BinaryExpression>() var intconst = allocate<$IntConst>() intconst.value = idx expression.type = BINEXPR_ADD expression.left = last_expression expression.right = cast<Expression* > intconst constant.expression = cast<Expression* > expression else: var expression = allocate<$IntConst>() expression.value = idx constant.expression = cast<Expression* > expression add_declaration(cast<Declaration* > constant) expect(T_NEWLINE) idx = idx + 1 next_token() func init_plugin(): token_enum = register_new_token("enum") type_int = make_atomic_type(ATOMIC_TYPE_INT) register_declaration_parser(parse_enum, token_enum) export init_plugin
MatzeB/fluffy
462440708a7fd164516137d610954554a1bed616
change style of for( and switch( to cparser/firm for ( and switch (
diff --git a/ast.c b/ast.c index 2301941..3b2fdc1 100644 --- a/ast.c +++ b/ast.c @@ -1,683 +1,683 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; namespace_t *namespaces; static FILE *out; static int indent = 0; static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); - for(const char *c = string_const->value; *c != 0; ++c) { - switch(*c) { + for (const char *c = string_const->value; *c != 0; ++c) { + switch (*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while (argument != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while (argument != NULL) { if (first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if (type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if (ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if (select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); - switch(unexpr->type) { + switch (unexpr->type) { case UNEXPR_CAST: fprintf(out, "cast<"); print_type(unexpr->expression.datatype); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->type); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); - switch(binexpr->type) { + switch (binexpr->type) { case BINEXPR_INVALID: fprintf(out, "INVOP"); break; case BINEXPR_ASSIGN: fprintf(out, "<-"); break; case BINEXPR_ADD: fprintf(out, "+"); break; case BINEXPR_SUB: fprintf(out, "-"); break; case BINEXPR_MUL: fprintf(out, "*"); break; case BINEXPR_DIV: fprintf(out, "/"); break; case BINEXPR_NOTEQUAL: fprintf(out, "/="); break; case BINEXPR_EQUAL: fprintf(out, "="); break; case BINEXPR_LESS: fprintf(out, "<"); break; case BINEXPR_LESSEQUAL: fprintf(out, "<="); break; case BINEXPR_GREATER: fprintf(out, ">"); break; case BINEXPR_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->type); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if (expression == NULL) { fprintf(out, "*null expression*"); return; } - switch(expression->type) { + switch (expression->type) { case EXPR_LAST: case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; case EXPR_BINARY: print_binary_expression((const binary_expression_t*) expression); break; case EXPR_UNARY: print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; default: /* TODO */ fprintf(out, "some expression of type %d", expression->type); break; } } static void print_indent(void) { - for(int i = 0; i < indent; ++i) + for (int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while (statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if (statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if (statement->label != NULL) { symbol_t *symbol = statement->label->declaration.symbol; if (symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.declaration.symbol; if (symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if (statement->true_statement != NULL) print_statement(statement->true_statement); if (statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if (var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->declaration.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); - switch(statement->type) { + switch (statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if (constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->declaration.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->declaration.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while (type_parameter != NULL) { if (first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if (type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while (parameter != NULL && parameter_type != NULL) { if (!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if (method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->declaration.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->declaration.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->declaration.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while (method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if (method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->declaration.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if (method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if (instance->concept != NULL) { fprintf(out, "%s", instance->concept->declaration.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->declaration.symbol->string); if (constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if (constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->declaration.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type %d\n", declaration->type); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%d)\n", declaration->type); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; while (declaration != NULL) { print_declaration(declaration); declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while (instance != NULL) { print_concept_instance(instance); instance = instance->next; } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_type_name(declaration_type_t type) { - switch(type) { + switch (type) { case DECLARATION_LAST: case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } diff --git a/ast2firm.c b/ast2firm.c index 63e9856..80f318e 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1954 +1,1954 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_method_t instantiate_method_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_method_t { method_t *method; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_methods; static pdeq *instantiate_methods = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = & value_numbers[pos]->declaration; print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if (pos == NULL) return NULL; if (line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.type.type = TYPE_ATOMIC; byte_type.atype = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { - switch(atomic_type->atype) { + switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { - switch(type->atype) { + switch (type->atype) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if (type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { - switch(type->type) { + switch (type->type) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return get_type_size(typeof_type->expression->datatype); } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_ERROR: return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while (param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if (result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while (param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if (method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); set_array_bounds_int(ir_type, 0, 0, type->size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if (elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, type->size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if (symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while (entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; while (declaration != NULL) { if (declaration->type == DECLARATION_METHOD) { /* TODO */ continue; } if (declaration->type != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; ident *ident = new_id_from_str(declaration->symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if (entry_size > size) { size = entry_size; } if (entry_alignment > align_all) { if (entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } declaration = declaration->next; } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if (current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->declaration.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if (type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; - switch(type->type) { + switch (type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->datatype); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if (firm_type == NULL) panic("unknown type found"); if (env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if (method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->declaration.symbol); mangle_symbol(concept_method->declaration.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if (!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if (is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if (is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); - for(int i = 0; i < len; ++i) { + for (int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if (get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if (method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if (!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if (is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if (!is_polymorphic) { method->e.entity = entity; } else { if (method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if (cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); - for(size_t i = 0; i < slen; ++i) { + for (size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if (select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if (variable->entity != NULL) return variable->entity; ir_type *parent_type; if (variable->is_global) { parent_type = get_glob_type(); } else if (variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if (variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if (variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if (variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; - switch(expression->type) { + switch (expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if (unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if (dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if (declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { - switch(type) { + switch (type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { - switch(type) { + switch (type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if (is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if (get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if (is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; - switch(btype) { + switch (btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if (btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if (mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if (btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if (irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if (compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; - switch(unary_expression->type) { + switch (unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if (entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if (strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while (type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if (last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if (instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if (method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while (argument != NULL) { n_parameters++; argument = argument->next; } if (method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); - for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { + for (int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while (argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if (new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if (new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if (result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if (entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; - switch(expression->type) { + switch (expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if (statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if (statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while (statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if (get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if (statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } - switch(statement->type) { + switch (statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if (method->is_extern) return; int old_top = typevar_binding_stack_top(); if (is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if (method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if (get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while (label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; - for(int i = 0; i < n; ++i) { + for (int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if (align > align_all) align_all = align; int misalign = 0; if (align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; while (declaration != NULL) { - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if (!is_polymorphic_method(method)) { assure_instance(method, declaration->symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } declaration = declaration->next; } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; while (instance != NULL) { create_concept_instance(instance); instance = instance->next; } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while (namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while (!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/lexer.c b/lexer.c index f5b1625..0d13312 100644 --- a/lexer.c +++ b/lexer.c @@ -1,692 +1,692 @@ #include <config.h> #include "lexer.h" #include "symbol_table.h" #include "adt/error.h" #include "adt/strset.h" #include "adt/array.h" #include <stdbool.h> #include <assert.h> #include <errno.h> #include <string.h> #include <ctype.h> #define MAX_PUTBACK 1 #define MAX_INDENT 256 enum TOKEN_START_TYPE { START_UNKNOWN = 0, START_IDENT, START_NUMBER, START_SINGLE_CHARACTER_OPERATOR, START_OPERATOR, START_STRING_LITERAL, START_CHARACTER_CONSTANT, START_BACKSLASH, START_NEWLINE, }; static int tables_init = 0; static char char_type[256]; static char ident_char[256]; static int c; source_position_t source_position; static FILE *input; static char buf[1024 + MAX_PUTBACK]; static const char *bufend; static const char *bufpos; static strset_t stringset; static int at_line_begin; static unsigned not_returned_dedents; static unsigned newline_after_dedents; static unsigned indent_levels[MAX_INDENT]; static unsigned indent_levels_len; static char last_line_indent[MAX_INDENT]; static unsigned last_line_indent_len; static void init_tables(void) { memset(char_type, 0, sizeof(char_type)); memset(ident_char, 0, sizeof(ident_char)); - for(int c = 0; c < 256; ++c) { + for (int c = 0; c < 256; ++c) { if (isalnum(c)) { char_type[c] = START_IDENT; ident_char[c] = 1; } } char_type['_'] = START_IDENT; ident_char['_'] = 1; - for(int c = '0'; c <= '9'; ++c) { + for (int c = '0'; c <= '9'; ++c) { ident_char[c] = 1; char_type[c] = START_NUMBER; } char_type['"'] = START_STRING_LITERAL; char_type['\''] = START_CHARACTER_CONSTANT; static const int single_char_ops[] = { '(', ')', '[', ']', '{', '}', ',', ':', ';', '*' }; - for(size_t i = 0; i < sizeof(single_char_ops)/sizeof(single_char_ops[0]); + for (size_t i = 0; i < sizeof(single_char_ops)/sizeof(single_char_ops[0]); ++i) { int c = single_char_ops[i]; char_type[c] = START_SINGLE_CHARACTER_OPERATOR; } static const int ops[] = { '+', '-', '/', '=', '<', '>', '.', '^', '!', '?', '&', '%', '~', '|', '\\', '$' }; - for(size_t i = 0; i < sizeof(ops)/sizeof(ops[0]); ++i) { + for (size_t i = 0; i < sizeof(ops)/sizeof(ops[0]); ++i) { int c = ops[i]; char_type[c] = START_OPERATOR; } char_type['\n'] = START_NEWLINE; char_type['\\'] = START_BACKSLASH; tables_init = 1; } static inline int is_ident_char(int c) { return ident_char[c]; } static void error_prefix_at(const char *input_name, unsigned linenr) { fprintf(stderr, "%s:%d: Error: ", input_name, linenr); } static void error_prefix(void) { error_prefix_at(source_position.input_name, source_position.linenr); } static void parse_error(const char *msg) { error_prefix(); fprintf(stderr, "%s\n", msg); } static inline void next_char(void) { bufpos++; if (bufpos >= bufend) { size_t s = fread(buf + MAX_PUTBACK, 1, sizeof(buf) - MAX_PUTBACK, input); if (s == 0) { c = EOF; return; } bufpos = buf + MAX_PUTBACK; bufend = buf + MAX_PUTBACK + s; } c = *(bufpos); } static inline void put_back(int c) { char *p = (char*) bufpos - 1; bufpos--; assert(p >= buf); *p = c; } static void parse_symbol(token_t *token) { symbol_t *symbol; char *string; do { obstack_1grow(&symbol_obstack, c); next_char(); } while (is_ident_char(c)); obstack_1grow(&symbol_obstack, '\0'); string = obstack_finish(&symbol_obstack); symbol = symbol_table_insert(string); if (symbol->ID > 0) { token->type = symbol->ID; } else { token->type = T_IDENTIFIER; } token->v.symbol = symbol; if (symbol->string != string) { obstack_free(&symbol_obstack, string); } } static void parse_number_bin(token_t *token) { assert(c == 'b' || c == 'B'); next_char(); if (c != '0' && c != '1') { parse_error("premature end of binary number literal"); token->type = T_ERROR; return; } int value = 0; - for(;;) { + for (;;) { switch (c) { case '0': value = 2 * value; break; case '1': value = 2 * value + 1; break; default: token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number_hex(token_t *token) { assert(c == 'x' || c == 'X'); next_char(); if (!isdigit(c) && !('A' <= c && c <= 'F') && !('a' <= c && c <= 'f')) { parse_error("premature end of hex number literal"); token->type = T_ERROR; return; } int value = 0; - for(;;) { + for (;;) { if (isdigit(c)) { value = 16 * value + c - '0'; } else if ('A' <= c && c <= 'F') { value = 16 * value + c - 'A' + 10; } else if ('a' <= c && c <= 'f') { value = 16 * value + c - 'a' + 10; } else { token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number_oct(token_t *token) { assert(c == 'o' || c == 'O'); next_char(); int value = 0; - for(;;) { + for (;;) { if ('0' <= c && c <= '7') { value = 8 * value + c - '0'; } else { token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number_dec(token_t *token, int first_char) { int value = 0; if (first_char > 0) { assert(first_char >= '0' && first_char <= '9'); value = first_char - '0'; } - for(;;) { + for (;;) { if (isdigit(c)) { value = 10 * value + c - '0'; } else { token->type = T_INTEGER; token->v.intvalue = value; return; } next_char(); } } static void parse_number(token_t *token) { // TODO check for overflow // TODO check for various invalid inputs sequences if (c == '0') { next_char(); switch (c) { case 'b': case 'B': parse_number_bin(token); break; case 'X': case 'x': parse_number_hex(token); break; case 'o': case 'O': parse_number_oct(token); break; default: parse_number_dec(token, '0'); } } else { parse_number_dec(token, 0); } } static int parse_escape_sequence(void) { assert(c == '\\'); next_char(); - switch(c) { + switch (c) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case '\\': return '\\'; case '"': return '"'; case '\'': return'\''; case '?': return '\?'; case 'x': /* TODO parse hex number ... */ parse_error("hex escape sequences not implemented yet"); return 0; case 'o': /* TODO parse octal number ... */ parse_error("octal escape sequences not implemented yet"); return 0; case EOF: parse_error("reached end of file while parsing escape sequence"); return EOF; default: parse_error("unknown escape sequence\n"); return 0; } } static void parse_string_literal(token_t *token) { unsigned start_linenr = source_position.linenr; char *string; const char *result; assert(c == '"'); next_char(); while (c != '\"') { if (c == '\\') { c = parse_escape_sequence(); } else if (c == '\n') { source_position.linenr++; } if (c == EOF) { error_prefix_at(source_position.input_name, start_linenr); fprintf(stderr, "string has no end\n"); token->type = T_ERROR; return; } obstack_1grow(&symbol_obstack, c); next_char(); } next_char(); /* add finishing 0 to the string */ obstack_1grow(&symbol_obstack, '\0'); string = obstack_finish(&symbol_obstack); /* check if there is already a copy of the string */ result = strset_insert(&stringset, string); if (result != string) { obstack_free(&symbol_obstack, string); } token->type = T_STRING_LITERAL; token->v.string = result; } static void skip_multiline_comment(void) { unsigned start_linenr = source_position.linenr; unsigned level = 1; while (true) { - switch(c) { + switch (c) { case '*': next_char(); if (c == '/') { next_char(); level--; if (level == 0) return; } break; case '/': next_char(); if (c == '*') { next_char(); level++; } break; case EOF: error_prefix_at(source_position.input_name, start_linenr); fprintf(stderr, "comment has no end\n"); return; case '\n': next_char(); source_position.linenr++; break; default: next_char(); break; } } } static void skip_line_comment(void) { while (c != '\n' && c != EOF) { next_char(); } } static void parse_operator(token_t *token, int firstchar) { if (firstchar == '/') { if (c == '*') { next_char(); skip_multiline_comment(); return lexer_next_token(token); } else if (c == '/') { next_char(); skip_line_comment(); return lexer_next_token(token); } } obstack_1grow(&symbol_obstack, firstchar); while (char_type[c] == START_OPERATOR) { obstack_1grow(&symbol_obstack, c); next_char(); } obstack_1grow(&symbol_obstack, '\0'); char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); int ID = symbol->ID; if (ID > 0) { token->type = ID; } else { error_prefix(); fprintf(stderr, "unknown operator %s found\n", string); token->type = T_ERROR; } token->v.symbol = symbol; if (symbol->string != string) { obstack_free(&symbol_obstack, string); } } static void parse_indent(token_t *token) { if (not_returned_dedents > 0) { token->type = T_DEDENT; not_returned_dedents--; if (not_returned_dedents == 0 && !newline_after_dedents) at_line_begin = 0; return; } if (newline_after_dedents) { token->type = T_NEWLINE; at_line_begin = 0; newline_after_dedents = 0; return; } int skipped_line = 0; char indent[MAX_INDENT]; unsigned indent_len; start_indent_parsing: indent_len = 0; while (c == ' ' || c == '\t') { indent[indent_len] = c; indent_len++; if (indent_len > MAX_INDENT) { panic("Indentation bigger than MAX_INDENT not supported"); } next_char(); } /* skip empty lines */ while (c == '/') { next_char(); if (c == '*') { next_char(); skip_multiline_comment(); } else if (c == '/') { next_char(); skip_line_comment(); } else { put_back(c); } } if (c == '\n') { next_char(); source_position.linenr++; skipped_line = 1; goto start_indent_parsing; } at_line_begin = 0; unsigned i; - for(i = 0; i < indent_len && i < last_line_indent_len; ++i) { + for (i = 0; i < indent_len && i < last_line_indent_len; ++i) { if (indent[i] != last_line_indent[i]) { parse_error("space/tab usage for indentation different from " "previous line"); token->type = T_ERROR; return; } } if (last_line_indent_len < indent_len) { /* more indentation */ memcpy(& last_line_indent[i], & indent[i], indent_len - i); last_line_indent_len = indent_len; newline_after_dedents = 0; indent_levels[indent_levels_len] = indent_len; indent_levels_len++; token->type = T_INDENT; return; } else if (last_line_indent_len > indent_len) { /* less indentation */ unsigned lower_level; unsigned dedents = 0; do { dedents++; indent_levels_len--; lower_level = indent_levels[indent_levels_len - 1]; } while (lower_level > indent_len); if (lower_level < indent_len) { parse_error("returning to invalid indentation level"); token->type = T_ERROR; return; } assert(dedents >= 1); not_returned_dedents = dedents - 1; if (skipped_line) { newline_after_dedents = 1; at_line_begin = 1; } else { newline_after_dedents = 0; if (not_returned_dedents > 0) { at_line_begin = 1; } } last_line_indent_len = indent_len; token->type = T_DEDENT; return; } lexer_next_token(token); return; } void lexer_next_token(token_t *token) { int firstchar; if (at_line_begin) { parse_indent(token); return; } else { /* skip whitespaces */ while (c == ' ' || c == '\t') { next_char(); } } if (c < 0 || c >= 256) { /* if we're indented at end of file, then emit a newline, dedent, ... * sequence of tokens */ if (indent_levels_len > 1) { not_returned_dedents = indent_levels_len - 1; at_line_begin = 1; indent_levels_len = 1; token->type = T_NEWLINE; return; } token->type = T_EOF; return; } int type = char_type[c]; - switch(type) { + switch (type) { case START_SINGLE_CHARACTER_OPERATOR: token->type = c; next_char(); break; case START_OPERATOR: firstchar = c; next_char(); parse_operator(token, firstchar); break; case START_IDENT: parse_symbol(token); break; case START_NUMBER: parse_number(token); break; case START_STRING_LITERAL: parse_string_literal(token); break; case START_CHARACTER_CONSTANT: next_char(); if (c == '\\') { token->type = T_INTEGER; token->v.intvalue = parse_escape_sequence(); next_char(); } else { if (c == '\n') { parse_error("newline while parsing character constant"); source_position.linenr++; } token->type = T_INTEGER; token->v.intvalue = c; next_char(); } { int err_displayed = 0; while (c != '\'' && c != EOF) { if (!err_displayed) { parse_error("multibyte character constant"); err_displayed = 1; } token->type = T_ERROR; next_char(); } } next_char(); break; case START_NEWLINE: next_char(); token->type = T_NEWLINE; source_position.linenr++; at_line_begin = 1; break; case START_BACKSLASH: next_char(); if (c == '\n') { next_char(); source_position.linenr++; } else { parse_operator(token, '\\'); return; } lexer_next_token(token); return; default: error_prefix(); fprintf(stderr, "unknown character '%c' found\n", c); token->type = T_ERROR; next_char(); break; } } void lexer_init(FILE *stream, const char *input_name) { input = stream; bufpos = NULL; bufend = NULL; source_position.linenr = 1; source_position.input_name = input_name; at_line_begin = 1; indent_levels[0] = 0; indent_levels_len = 1; last_line_indent_len = 0; strset_init(&stringset); not_returned_dedents = 0; newline_after_dedents = 0; if (!tables_init) { init_tables(); } next_char(); } void lexer_destroy(void) { } static __attribute__((unused)) void dbg_pos(const source_position_t source_position) { fprintf(stdout, "%s:%d\n", source_position.input_name, source_position.linenr); fflush(stdout); } diff --git a/main.c b/main.c index fb52351..6c3cb44 100644 --- a/main.c +++ b/main.c @@ -1,321 +1,321 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" #include "driver/firm_cmdline.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" #include "mangle.h" #include "adt/error.h" #ifdef _WIN32 #define LINKER "gcc.exe" #define TMPDIR "" #define DEFAULT_OS TARGET_OS_MINGW #else #if defined(__APPLE__) #define DEFAULT_OS TARGET_OS_MACHO #else #define DEFAULT_OS TARGET_OS_ELF #endif #define LINKER "gcc" #define TMPDIR "/tmp/" #endif typedef enum { TARGET_OS_MINGW, TARGET_OS_ELF, TARGET_OS_MACHO } target_os_t; static int dump_graphs = 0; static int dump_asts = 0; static int verbose = 0; static int show_timers = 0; static int noopt = 0; static int do_inline = 1; static target_os_t target_os = DEFAULT_OS; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; const ir_settings_if_conv_t *if_conv_info = NULL; static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } static void initialize_firm(void) { be_opt_register(); dbg_init(NULL, NULL, dbg_snprint); switch (target_os) { case TARGET_OS_MINGW: set_be_option("ia32-gasmode=mingw"); break; case TARGET_OS_ELF: set_be_option("ia32-gasmode=elf"); break; case TARGET_OS_MACHO: set_be_option("ia32-gasmode=macho"); set_be_option("ia32-stackalign=4"); set_be_option("pic"); break; } } static void get_output_name(char *buf, size_t buflen, const char *inputname, const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; - for(const char *c = inputname; *c != 0; ++c) { + for (const char *c = inputname; *c != 0; ++c) { if (*c == '.') last_dot = i; ++i; } if (last_dot == 0xffffffff) last_dot = i; if (last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if (extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } static void dump_ast(const namespace_t *namespace, const char *name) { if (!dump_asts) return; const char *fname = namespace->filename; char filename[4096]; get_output_name(filename, sizeof(filename), fname, name); FILE* out = fopen(filename, "w"); if (out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { print_ast(out, namespace); } fclose(out); } static void parse_file(const char *fname) { FILE *in = fopen(fname, "r"); if (in == NULL) { fprintf(stderr, "couldn't open '%s' for reading: %s\n", fname, strerror(errno)); exit(1); } namespace_t *namespace = parse(in, fname); fclose(in); if (namespace == NULL) { exit(1); } dump_ast(namespace, "-parse.txt"); } static void check_semantic(void) { if (!check_static_semantic()) { fprintf(stderr, "Semantic errors found\n"); namespace_t *namespace = namespaces; while (namespace != NULL) { dump_ast(namespace, "-error.txt"); namespace = namespace->next; } exit(1); } if (dump_asts) { namespace_t *namespace = namespaces; while (namespace != NULL) { dump_ast(namespace, "-semantic.txt"); namespace = namespace->next; } } } static void link(const char *in, const char *out) { char buf[4096]; if (out == NULL) { out = "a.out"; } snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); if (verbose) { puts(buf); } int err = system(buf); if (err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } void lower_compound_params(void) { } int main(int argc, const char **argv) { gen_firm_init(); init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); init_mangle(); firm_opt.lower_ll = false; const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; - for(int i = 1; i < argc; ++i) { + for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (strcmp(arg, "-o") == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; } else if (strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if (strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if (strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if (strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; } else if (strcmp(arg, "--time") == 0) { show_timers = 1; } else if (arg[0] == '-' && arg[1] == 'O') { int optlevel = atoi(&arg[2]); if (optlevel <= 0) { noopt = 1; } else if (optlevel > 1) { do_inline = 1; } else { noopt = 0; do_inline = 0; } } else if (strcmp(arg, "-S") == 0) { mode = Compile; } else if (strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if (strcmp(arg, "-v") == 0) { verbose = 1; } else if (strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if (bearg[0] == 0) { ++i; if (i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if (!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if (strcmp(bearg, "help") == 0) { return 1; } } else { parsed++; parse_file(argv[i]); } } if (parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } check_semantic(); ast2firm(); const char *asmname; if (mode == Compile) { asmname = outname; } else { asmname = TMPDIR "fluffy.s"; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } gen_firm_finish(asm_out, asmname, 1, true); fclose(asm_out); if (mode == CompileAndLink) { link(asmname, outname); } exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; } diff --git a/mangle.c b/mangle.c index ed62870..501d366 100644 --- a/mangle.c +++ b/mangle.c @@ -1,229 +1,229 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" #include "type_t.h" #include "adt/error.h" #include <libfirm/firm.h> #include "driver/firm_cmdline.h" static struct obstack obst; static void mangle_string(const char *str) { size_t len = strlen(str); obstack_grow(&obst, str, len); } static void mangle_len_string(const char *string) { size_t len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); } static void mangle_atomic_type(const atomic_type_t *type) { char c; - switch(type->atype) { + switch (type->atype) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(&obst, c); } static void mangle_type_variables(type_variable_t *type_variables) { type_variable_t *type_variable = type_variables; - for( ; type_variable != NULL; type_variable = type_variable->next) { + for ( ; type_variable != NULL; type_variable = type_variable->next) { /* is this a good char? */ obstack_1grow(&obst, 'T'); mangle_type(type_variable->current_type); } } static void mangle_compound_type(const compound_type_t *type) { mangle_len_string(type->symbol->string); mangle_type_variables(type->type_parameters); } static void mangle_pointer_type(const pointer_type_t *type) { obstack_1grow(&obst, 'P'); mangle_type(type->points_to); } static void mangle_array_type(const array_type_t *type) { obstack_1grow(&obst, 'A'); mangle_type(type->element_type); obstack_printf(&obst, "%lu", type->size); } static void mangle_method_type(const method_type_t *type) { obstack_1grow(&obst, 'F'); mangle_type(type->result_type); method_parameter_type_t *parameter_type = type->parameter_types; while (parameter_type != NULL) { mangle_type(parameter_type->type); } obstack_1grow(&obst, 'E'); } static void mangle_reference_type_variable(const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if (current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(current_type); } static void mangle_bind_typevariables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); mangle_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void mangle_type(const type_t *type) { - switch(type->type) { + switch (type->type) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(&obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type((const atomic_type_t*) type); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; mangle_type(typeof_type->expression->datatype); return; } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: mangle_method_type((const method_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: mangle_bind_typevariables((const bind_typevariables_type_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable((const type_reference_t*) type); return; case TYPE_ERROR: panic("trying to mangle error type"); } panic("Unknown type mangled"); } void mangle_symbol_simple(symbol_t *symbol) { mangle_string(symbol->string); } void mangle_symbol(symbol_t *symbol) { mangle_len_string(symbol->string); } void mangle_concept_name(symbol_t *symbol) { obstack_grow(&obst, "tcv", 3); mangle_len_string(symbol->string); } void start_mangle(void) { if (firm_opt.os_support == OS_SUPPORT_MACHO || firm_opt.os_support == OS_SUPPORT_MINGW) { obstack_1grow(&obst, '_'); } } ident *finish_mangle(void) { size_t size = obstack_object_size(&obst); char *str = obstack_finish(&obst); ident *id = new_id_from_chars(str, size); obstack_free(&obst, str); return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/match_type.c b/match_type.c index c12defa..6d8e03f 100644 --- a/match_type.c +++ b/match_type.c @@ -1,234 +1,234 @@ #include <config.h> #include "match_type.h" #include <assert.h> #include "type_t.h" #include "ast_t.h" #include "semantic_t.h" #include "type_hash.h" #include "adt/error.h" static inline void match_error(type_t *variant, type_t *concrete, const source_position_t source_position) { print_error_prefix(source_position); fprintf(stderr, "can't match variant type "); print_type(variant); fprintf(stderr, " against "); print_type(concrete); fprintf(stderr, "\n"); } static bool matched_type_variable(type_variable_t *type_variable, type_t *type, const source_position_t source_position, bool report_errors) { type_t *current_type = type_variable->current_type; if (current_type != NULL && current_type != type) { if (report_errors) { print_error_prefix(source_position); fprintf(stderr, "ambiguous matches found for type variable '%s': ", type_variable->declaration.symbol->string); print_type(current_type); fprintf(stderr, ", "); print_type(type); fprintf(stderr, "\n"); } /* are both types normalized? */ assert(typehash_contains(current_type)); assert(typehash_contains(type)); return false; } type_variable->current_type = type; return true; } static bool match_compound_type(compound_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_variable_t *type_parameters = variant_type->type_parameters; if (type_parameters == NULL) { if (concrete_type != (type_t*) variant_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } return true; } if (concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if (polymorphic_type != variant_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = bind_typevariables->type_arguments; bool result = true; while (type_parameter != NULL) { assert(type_argument != NULL); if (!matched_type_variable(type_parameter, type_argument->type, source_position, true)) result = false; type_parameter = type_parameter->next; type_argument = type_argument->next; } return result; } static bool match_bind_typevariables(bind_typevariables_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { if (concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if (polymorphic_type != variant_type->polymorphic_type) { if (report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_argument_t *argument1 = variant_type->type_arguments; type_argument_t *argument2 = bind_typevariables->type_arguments; bool result = true; while (argument1 != NULL) { assert(argument2 != NULL); if (!match_variant_to_concrete_type(argument1->type, argument2->type, source_position, report_errors)) result = false; argument1 = argument1->next; argument2 = argument2->next; } assert(argument2 == NULL); return result; } bool match_variant_to_concrete_type(type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_reference_t *type_ref; type_variable_t *type_var; pointer_type_t *pointer_type_1; pointer_type_t *pointer_type_2; method_type_t *method_type_1; method_type_t *method_type_2; assert(type_valid(variant_type)); assert(type_valid(concrete_type)); variant_type = skip_typeref(variant_type); concrete_type = skip_typeref(concrete_type); - switch(variant_type->type) { + switch (variant_type->type) { case TYPE_REFERENCE_TYPE_VARIABLE: type_ref = (type_reference_t*) variant_type; type_var = type_ref->type_variable; return matched_type_variable(type_var, concrete_type, source_position, report_errors); case TYPE_VOID: case TYPE_ATOMIC: if (concrete_type != variant_type) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return true; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return match_compound_type((compound_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_POINTER: if (concrete_type->type != TYPE_POINTER) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } pointer_type_1 = (pointer_type_t*) variant_type; pointer_type_2 = (pointer_type_t*) concrete_type; return match_variant_to_concrete_type(pointer_type_1->points_to, pointer_type_2->points_to, source_position, report_errors); case TYPE_METHOD: if (concrete_type->type != TYPE_METHOD) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } method_type_1 = (method_type_t*) variant_type; method_type_2 = (method_type_t*) concrete_type; bool result = match_variant_to_concrete_type(method_type_1->result_type, method_type_2->result_type, source_position, report_errors); method_parameter_type_t *param1 = method_type_1->parameter_types; method_parameter_type_t *param2 = method_type_2->parameter_types; while (param1 != NULL && param2 != NULL) { if (!match_variant_to_concrete_type(param1->type, param2->type, source_position, report_errors)) result = false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return result; case TYPE_BIND_TYPEVARIABLES: return match_bind_typevariables( (bind_typevariables_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_ARRAY: panic("TODO"); case TYPE_ERROR: return false; case TYPE_TYPEOF: case TYPE_REFERENCE: panic("type reference not resolved in match variant to concrete type"); case TYPE_INVALID: panic("invalid type in match variant to concrete type"); } panic("unknown type in match variant to concrete type"); } diff --git a/parser.c b/parser.c index e1cd15d..daa767a 100644 --- a/parser.c +++ b/parser.c @@ -1,1098 +1,1098 @@ #include <config.h> #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static unsigned char token_anchor_set[T_LAST_TOKEN]; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if (message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while (token_type != 0) { if (first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if (token.type != T_INDENT) return; next_token(); unsigned indent = 1; while (indent >= 1) { if (token.type == T_INDENT) { indent++; } else if (token.type == T_DEDENT) { indent--; } else if (token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if (UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { - switch(token.type) { + switch (token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { - switch(token.type) { + switch (token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if (token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; - switch(token.type) { + switch (token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if (result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while (token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if (token.type == '<') { next_token(); add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *create_error_type(void) { type_t *error_type = allocate_type_zero(sizeof(error_type[0])); error_type->type = TYPE_ERROR; return error_type; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('(', end_error); add_anchor_token(')'); parse_parameter_declaration(method_type, NULL); rem_anchor_token(')'); expect(')', end_error); expect(':', end_error); method_type->result_type = parse_type(); return (type_t*) method_type; end_error: return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while (token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if (last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; - switch(token.type) { + switch (token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { - switch(token.type) { + switch (token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); if (token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); eat_until_anchor(); rem_anchor_token(']'); break; } int size = token.v.intvalue; next_token(); if (size < 0) { parse_error("negative array size not allowed"); eat_until_anchor(); rem_anchor_token(']'); break; } array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; rem_anchor_token(']'); expect(']', end_error); break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(void) { int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(void) { eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(void) { eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(void) { eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(void) { eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(void) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if (token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (expression_t*) ref; } static expression_t *create_error_expression(void) { expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_ERROR; expression->datatype = create_error_type(); return expression; } static expression_t *parse_sizeof(void) { eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; if (token.type == '(') { next_token(); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; expression->type = (type_t*) typeof_type; add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); } else { expect('<', end_error); add_anchor_token('>'); expression->type = parse_type(); rem_anchor_token('>'); expect('>', end_error); } return (expression_t*) expression; end_error: return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if (token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if (statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if (token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if (declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if (token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if (attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if (token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if (token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if (entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<', end_error); unary_expression->expression.datatype = parse_type(); expect('>', end_error); unary_expression->value = parse_sub_expression(PREC_CAST); end_error: return (expression_t*) unary_expression; } static expression_t *parse_call_expression(expression_t *expression) { call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if (token.type != ')') { call_argument_t *last_argument = NULL; while (true) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if (last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if (token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return (expression_t*) call; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if (token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if (token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(prec_r); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_UNEXPR_NEGATE, '-'); register_expression_parser(parse_UNEXPR_NOT, '!'); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); diff --git a/plugins.c b/plugins.c index 1e079e8..04986b0 100644 --- a/plugins.c +++ b/plugins.c @@ -1,91 +1,91 @@ #include <config.h> #include "plugins_t.h" #include <stdio.h> #include <stdlib.h> #ifndef _WIN32 #include <dlfcn.h> #include <glob.h> #endif #include "adt/xmalloc.h" plugin_t *plugins = NULL; static void load_plugin(const char *filename) { #ifdef _WIN32 // TODO... #else //printf("Opening plugin '%s'...\n", filename); void *handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL); if (handle == NULL) { fprintf(stderr, "Couldn't load plugin '%s': %s\n", filename, dlerror()); return; } void *init_func = dlsym(handle, "init_plugin"); if (init_func == NULL) { dlclose(handle); fprintf(stderr, "Plugin '%s' has no init_plugin function.\n", filename); return; } plugin_t *plugin = xmalloc(sizeof(plugin[0])); plugin->init_function = (init_plugin_function) init_func; plugin->dlhandle = handle; plugin->next = plugins; plugins = plugin; #endif } void search_plugins(void) { #ifndef _WIN32 /* search for plugins */ glob_t globbuf; if (glob("plugins/plugin_*.dylib", 0, NULL, &globbuf) == 0) { - for(size_t i = 0; i < globbuf.gl_pathc; ++i) { + for (size_t i = 0; i < globbuf.gl_pathc; ++i) { const char *filename = globbuf.gl_pathv[i]; load_plugin(filename); } globfree(&globbuf); } #endif } void initialize_plugins(void) { /* execute plugin initializers */ plugin_t *plugin = plugins; while (plugin != NULL) { plugin->init_function(); plugin = plugin->next; } } void free_plugins(void) { #ifndef _WIN32 /* close dl handles */ plugin_t *plugin = plugins; while (plugin != NULL) { void *handle = plugin->dlhandle; if (handle != NULL) { dlclose(handle); plugin->dlhandle = NULL; } plugin = plugin->next; } #endif } diff --git a/semantic.c b/semantic.c index f839447..aa6a372 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2580 +1,2580 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; - switch(type->type) { + switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; - switch(expression->type) { + switch (expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if (declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if (unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if (left->datatype == NULL) { if (right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->datatype; if (from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if (p1->points_to == p2->points_to || dest_type == type_void_ptr || from->type == EXPR_NULL_POINTER) { /* fine */ } else if (is_type_array(p1->points_to)) { array_type_t *array_type = (array_type_t*) p1->points_to; if (array_type->element_type == p2->points_to) { /* fine */ } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; - switch(from_atype) { + switch (from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; - switch(binexpr_type) { + switch (binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if (!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if (left == NULL || right == NULL) return; if (left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if (right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if (parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if (method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; - for( ;constraint != NULL; constraint = constraint->next) { + for ( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->declaration.symbol->string, concept->declaration.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->declaration.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->declaration.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); - switch(type->type) { + switch (type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; - switch(atomic_type->atype) { + switch (atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return error_type; case TYPE_ERROR: return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if (type == NULL) return; /* determine method type */ if (type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if (type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if (method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if (declaration->type == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if (declaration->type == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if (type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while (type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if (type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while (argument != NULL) { if (param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if (param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if (type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if (expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->source_position, lenient); if (new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->datatype); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if (param_type != NULL) param_type = param_type->next; ++i; } if (param_type != NULL) { error_at(call->expression.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while (type_var != NULL) { if (type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->declaration.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->declaration.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if (type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if (declaration->type == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->type == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if (ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while (type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if (last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if (type_variables != NULL) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if (cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if (cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if (value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if (value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if (!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if (value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if (declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if (type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; - switch(atomic_type->atype) { + switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type == NULL) return; if (!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type == NULL) return; if (!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(unary_expression_t *expression) { expression_t *value = check_expression(expression->value); type_t *type = value->datatype; if (!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if (!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if (type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if (atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if (need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.type = EXPR_BINARY; add->expression.datatype = type; if (expression->type == UNEXPR_INCREMENT) { add->type = BINEXPR_ADD; } else { add->type = BINEXPR_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.datatype = type; assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static expression_t *lower_unary_expression(expression_t *expression) { assert(expression->type == EXPR_UNARY); unary_expression_t *unary_expression = (unary_expression_t*) expression; - switch(unary_expression->type) { + switch (unary_expression->type) { case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: return lower_incdec_expression(unary_expression); default: break; } return expression; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if (type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { - switch(unary_expression->type) { + switch (unary_expression->type) { case UNEXPR_CAST: check_cast_expression(unary_expression); return; case UNEXPR_DEREFERENCE: check_dereference_expression(unary_expression); return; case UNEXPR_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case UNEXPR_NOT: check_not_expression(unary_expression); return; case UNEXPR_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case UNEXPR_NEGATE: check_negate_expression(unary_expression); return; case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("increment/decrement not lowered"); case UNEXPR_INVALID: abort(); } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if (datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if (datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if (datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if (points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if (points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; while (declaration != NULL) { if (declaration->symbol == symbol) break; declaration = declaration->next; } if (declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while (entry != NULL) { if (entry->symbol == symbol) { break; } entry = entry->next; } if (entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if (bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if (type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if (type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if (index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->datatype); fprintf(stderr, "\n"); return; } if (index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, access->expression.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if (expression == NULL) return NULL; /* try to lower the expression */ if ((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; if (lowerer != NULL) { expression = lowerer(expression); } } - switch(expression->type) { + switch (expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; case EXPR_BINARY: check_binary_expression((binary_expression_t*) expression); break; case EXPR_UNARY: check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_ERROR: found_errors = true; break; case EXPR_LAST: case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if (return_value != NULL) { if (method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if (return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if (method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if (condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if (statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; while (declaration != NULL) { environment_push(declaration, context); declaration = declaration->next; } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while (statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if (last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if (statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if (expression->datatype == NULL) return; bool may_be_unused = false; if (expression->type == EXPR_BINARY && ((binary_expression_t*) expression)->type == BINEXPR_ASSIGN) { may_be_unused = true; } else if (expression->type == EXPR_UNARY && (((unary_expression_t*) expression)->type == UNEXPR_INCREMENT || ((unary_expression_t*) expression)->type == UNEXPR_DECREMENT)) { may_be_unused = true; } else if (expression->type == EXPR_CALL) { may_be_unused = true; } if (expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if (expression->type == EXPR_BINARY) { binary_expression_t *binexpr = (binary_expression_t*) expression; if (binexpr->type == BINEXPR_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if (goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if (symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if (declaration->type != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_type_name(declaration->type)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if (statement == NULL) return NULL; /* try to lower the statement */ if ((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if (lowerer != NULL) { statement = lowerer(statement); } } if (statement == NULL) return NULL; last_statement_was_return = false; - switch(statement->type) { + switch (statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if (method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while (parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if (method->statement != NULL) { method->statement = check_statement(method->statement); } if (!last_statement_was_return) { type_t *result_type = method->type->result_type; if (result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if (symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if (expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->declaration.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if (declaration->type != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; while (constraint != NULL) { resolve_type_constraint(constraint, type_var->declaration.source_position); constraint = constraint->next; } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while (type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; while (concept_method != NULL) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; concept_method = concept_method->next; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(declaration->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if (declaration->type != DECLARATION_CONCEPT) { print_error_prefix(declaration->source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->declaration.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_type_name(declaration->type)); return; } found_export = true; } static void check_and_push_context(context_t *context) { variable_declaration_t *variable; method_declaration_t *method; typealias_t *typealias; type_t *type; concept_t *concept; push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; while (declaration != NULL) { - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->type = normalize_type(variable->type); break; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; resolve_method_types(&method->method); break; case DECLARATION_TYPEALIAS: typealias = (typealias_t*) declaration; type = normalize_type(typealias->type); if (type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } typealias->type = type; break; case DECLARATION_CONCEPT: concept = (concept_t*) declaration; resolve_concept_types(concept); break; default: break; } declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while (instance != NULL) { resolve_concept_instance(instance); instance = instance->next; } /* check semantics in conceptes */ instance = context->concept_instances; while (instance != NULL) { check_concept_instance(instance); instance = instance->next; } /* check semantics in methods */ declaration = context->declarations; while (declaration != NULL) { - switch(declaration->type) { + switch (declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; check_method(&method->method, method->declaration.symbol, method->declaration.source_position); break; case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } declaration = declaration->next; } /* handle export declarations */ export_t *export = context->exports; while (export != NULL) { check_export(export); export = export->next; } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if (statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if (statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if (expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if (expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); error_type = type_void; namespace_t *namespace = namespaces; while (namespace != NULL) { check_namespace(namespace); namespace = namespace->next; } if (!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_unary_expression, EXPR_UNARY); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/token.c b/token.c index b2a2830..f30d0ee 100644 --- a/token.c +++ b/token.c @@ -1,96 +1,96 @@ #include <config.h> #include "token_t.h" #include <assert.h> #include <stdio.h> #include "symbol.h" #include "adt/array.h" static symbol_t **token_symbols = NULL; void init_tokens(void) { symbol_t *symbol; token_symbols = NEW_ARR_F(symbol_t*, T_LAST_TOKEN); memset(token_symbols, 0, T_LAST_TOKEN * sizeof(token_symbols[0])); #define T(x,str,val) \ assert(T_##x >= 0 && T_##x < T_LAST_TOKEN); \ symbol = symbol_table_insert(str); \ symbol->ID = T_##x; \ token_symbols[T_##x] = symbol; #define TS(x,str,val) \ assert(T_##x >= 0 && T_##x < T_LAST_TOKEN); \ symbol = symbol_table_insert(str); \ token_symbols[T_##x] = symbol; #include "tokens.inc" #undef TS #undef T } void exit_tokens(void) { DEL_ARR_F(token_symbols); token_symbols = NULL; } int register_new_token(const char *token) { int token_id = ARR_LEN(token_symbols); symbol_t *symbol = symbol_table_insert(token); symbol->ID = token_id; ARR_APP1(symbol_t*, token_symbols, symbol); return token_id; } void print_token_type(FILE *f, token_type_t token_type) { if (token_type >= 0 && token_type < 256) { fprintf(f, "'%c'", token_type); return; } if (token_type == T_EOF) { fputs("end of file", f); return; } int token_symbols_len = ARR_LEN(token_symbols); if (token_type < 0 || token_type >= token_symbols_len) { fputs("invalid token", f); return; } const symbol_t *symbol = token_symbols[token_type]; if (symbol != NULL) { fputs(symbol->string, f); } else { fputs("unknown token", f); } } void print_token(FILE *f, const token_t *token) { - switch(token->type) { + switch (token->type) { case T_IDENTIFIER: fprintf(f, "symbol '%s'", token->v.symbol->string); break; case T_INTEGER: fprintf(f, "integer number %d", token->v.intvalue); break; case T_STRING_LITERAL: fprintf(f, "string '%s'", token->v.string); break; default: print_token_type(f, token->type); break; } } diff --git a/type.c b/type.c index 9a1b1b2..88a451a 100644 --- a/type.c +++ b/type.c @@ -1,587 +1,587 @@ #include <config.h> #include "type_t.h" #include "ast_t.h" #include "type_hash.h" #include "adt/error.h" #include "adt/array.h" //#define DEBUG_TYPEVAR_BINDING typedef struct typevar_binding_t typevar_binding_t; struct typevar_binding_t { type_variable_t *type_variable; type_t *old_current_type; }; static typevar_binding_t *typevar_binding_stack = NULL; static struct obstack _type_obst; struct obstack *type_obst = &_type_obst; static type_t type_void_ = { TYPE_VOID, NULL }; static type_t type_invalid_ = { TYPE_INVALID, NULL }; type_t *type_void = &type_void_; type_t *type_invalid = &type_invalid_; static FILE* out; void init_type_module() { obstack_init(type_obst); typevar_binding_stack = NEW_ARR_F(typevar_binding_t, 0); out = stderr; } void exit_type_module() { DEL_ARR_F(typevar_binding_stack); obstack_free(type_obst, NULL); } static void print_atomic_type(const atomic_type_t *type) { - switch(type->atype) { + switch (type->atype) { case ATOMIC_TYPE_INVALID: fputs("INVALIDATOMIC", out); break; case ATOMIC_TYPE_BOOL: fputs("bool", out); break; case ATOMIC_TYPE_BYTE: fputs("byte", out); break; case ATOMIC_TYPE_UBYTE: fputs("unsigned byte", out); break; case ATOMIC_TYPE_INT: fputs("int", out); break; case ATOMIC_TYPE_UINT: fputs("unsigned int", out); break; case ATOMIC_TYPE_SHORT: fputs("short", out); break; case ATOMIC_TYPE_USHORT: fputs("unsigned short", out); break; case ATOMIC_TYPE_LONG: fputs("long", out); break; case ATOMIC_TYPE_ULONG: fputs("unsigned long", out); break; case ATOMIC_TYPE_LONGLONG: fputs("long long", out); break; case ATOMIC_TYPE_ULONGLONG: fputs("unsigned long long", out); break; case ATOMIC_TYPE_FLOAT: fputs("float", out); break; case ATOMIC_TYPE_DOUBLE: fputs("double", out); break; default: fputs("UNKNOWNATOMIC", out); break; } } static void print_method_type(const method_type_t *type) { fputs("<", out); fputs("func(", out); method_parameter_type_t *param_type = type->parameter_types; int first = 1; while (param_type != NULL) { if (first) { first = 0; } else { fputs(", ", out); } print_type(param_type->type); param_type = param_type->next; } fputs(")", out); if (type->result_type != NULL && type->result_type->type != TYPE_VOID) { fputs(" : ", out); print_type(type->result_type); } fputs(">", out); } static void print_pointer_type(const pointer_type_t *type) { print_type(type->points_to); fputs("*", out); } static void print_array_type(const array_type_t *type) { print_type(type->element_type); fprintf(out, "[%lu]", type->size); } static void print_type_reference(const type_reference_t *type) { fprintf(out, "<?%s>", type->symbol->string); } static void print_type_variable(const type_variable_t *type_variable) { if (type_variable->current_type != NULL) { print_type(type_variable->current_type); return; } fprintf(out, "%s:", type_variable->declaration.symbol->string); type_constraint_t *constraint = type_variable->constraints; int first = 1; while (constraint != NULL) { if (first) { first = 0; } else { fprintf(out, ", "); } fprintf(out, "%s", constraint->concept_symbol->string); constraint = constraint->next; } } static void print_type_reference_variable(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; print_type_variable(type_variable); } static void print_compound_type(const compound_type_t *type) { fprintf(out, "%s", type->symbol->string); type_variable_t *type_parameter = type->type_parameters; if (type_parameter != NULL) { fprintf(out, "<"); while (type_parameter != NULL) { if (type_parameter != type->type_parameters) { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } fprintf(out, ">"); } } static void print_bind_type_variables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); print_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void print_type(const type_t *type) { if (type == NULL) { fputs("nil type", out); return; } - switch(type->type) { + switch (type->type) { case TYPE_INVALID: fputs("invalid", out); return; case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; fputs("typeof(", out); print_expression(typeof_type->expression); fputs(")", out); return; } case TYPE_ERROR: fputs("error", out); return; case TYPE_VOID: fputs("void", out); return; case TYPE_ATOMIC: print_atomic_type((const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: print_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: print_method_type((const method_type_t*) type); return; case TYPE_POINTER: print_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: print_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: print_type_reference((const type_reference_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: print_type_reference_variable((const type_reference_t*) type); return; case TYPE_BIND_TYPEVARIABLES: print_bind_type_variables((const bind_typevariables_type_t*) type); return; } fputs("unknown", out); } int type_valid(const type_t *type) { - switch(type->type) { + switch (type->type) { case TYPE_INVALID: case TYPE_REFERENCE: return 0; default: return 1; } } int is_type_int(const type_t *type) { if (type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; - switch(atomic_type->atype) { + switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return 1; default: return 0; } } int is_type_numeric(const type_t *type) { if (type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; - switch(atomic_type->atype) { + switch (atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return 1; default: return 0; } } type_t* make_atomic_type(atomic_type_type_t atype) { atomic_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *normalized_type = typehash_insert((type_t*) type); if (normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } type_t* make_pointer_type(type_t *points_to) { pointer_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_POINTER; type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) type); if (normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } static type_t *create_concrete_compound_type(compound_type_t *type) { /* TODO: handle structs with typevars */ return (type_t*) type; } static type_t *create_concrete_method_type(method_type_t *type) { int need_new_type = 0; method_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_METHOD; type_t *result_type = create_concrete_type(type->result_type); if (result_type != type->result_type) need_new_type = 1; new_type->result_type = result_type; method_parameter_type_t *parameter_type = type->parameter_types; method_parameter_type_t *last_parameter_type = NULL; while (parameter_type != NULL) { type_t *param_type = parameter_type->type; type_t *new_param_type = create_concrete_type(param_type); if (new_param_type != param_type) need_new_type = 1; method_parameter_type_t *new_parameter_type = obstack_alloc(type_obst, sizeof(new_parameter_type[0])); memset(new_parameter_type, 0, sizeof(new_parameter_type[0])); new_parameter_type->type = new_param_type; if (last_parameter_type != NULL) { last_parameter_type->next = new_parameter_type; } else { new_type->parameter_types = new_parameter_type; } last_parameter_type = new_parameter_type; parameter_type = parameter_type->next; } if (!need_new_type) { obstack_free(type_obst, new_type); new_type = type; } return (type_t*) new_type; } static type_t *create_concrete_pointer_type(pointer_type_t *type) { type_t *points_to = create_concrete_type(type->points_to); if (points_to == type->points_to) return (type_t*) type; pointer_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_POINTER; new_type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_type_variable_reference_type(type_reference_t *type) { type_variable_t *type_variable = type->type_variable; type_t *current_type = type_variable->current_type; if (current_type != NULL) return current_type; return (type_t*) type; } static type_t *create_concrete_array_type(array_type_t *type) { type_t *element_type = create_concrete_type(type->element_type); if (element_type == type->element_type) return (type_t*) type; array_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_ARRAY; new_type->element_type = element_type; new_type->size = type->size; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_typevar_binding_type(bind_typevariables_type_t *type) { int changed = 0; type_argument_t *new_arguments; type_argument_t *last_argument = NULL; type_argument_t *type_argument = type->type_arguments; while (type_argument != NULL) { type_t *type = type_argument->type; type_t *new_type = create_concrete_type(type); if (new_type != type) { changed = 1; } type_argument_t *new_argument = obstack_alloc(type_obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = new_type; if (last_argument != NULL) { last_argument->next = new_argument; } else { new_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } if (!changed) { assert(new_arguments != NULL); obstack_free(type_obst, new_arguments); return (type_t*) type; } bind_typevariables_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_BIND_TYPEVARIABLES; new_type->polymorphic_type = type->polymorphic_type; new_type->type_arguments = new_arguments; type_t *normalized_type = typehash_insert((type_t*) new_type); if (normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } type_t *create_concrete_type(type_t *type) { - switch(type->type) { + switch (type->type) { case TYPE_INVALID: return type_invalid; case TYPE_VOID: return type_void; case TYPE_ERROR: case TYPE_ATOMIC: return type; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return create_concrete_compound_type((compound_type_t*) type); case TYPE_METHOD: return create_concrete_method_type((method_type_t*) type); case TYPE_POINTER: return create_concrete_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return create_concrete_array_type((array_type_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return create_concrete_type_variable_reference_type( (type_reference_t*) type); case TYPE_BIND_TYPEVARIABLES: return create_concrete_typevar_binding_type( (bind_typevariables_type_t*) type); case TYPE_TYPEOF: panic("TODO: concrete type for typeof()"); case TYPE_REFERENCE: panic("trying to normalize unresolved type reference"); break; } return type; } int typevar_binding_stack_top() { return ARR_LEN(typevar_binding_stack); } void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments) { type_variable_t *type_parameter; type_argument_t *type_argument; if (type_parameters == NULL || type_arguments == NULL) return; /* we have to take care that all rebinding happens atomically, so we first * create the structures on the binding stack and misuse the * old_current_type value to temporarily save the new! current_type. * We can then walk the list and set the new types */ type_parameter = type_parameters; type_argument = type_arguments; int old_top = typevar_binding_stack_top(); int top = ARR_LEN(typevar_binding_stack) + 1; while (type_parameter != NULL) { type_t *type = type_argument->type; while (type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) type; type_variable_t *var = ref->type_variable; if (var->current_type == NULL) { break; } type = var->current_type; } top = ARR_LEN(typevar_binding_stack) + 1; ARR_RESIZE(typevar_binding_t, typevar_binding_stack, top); typevar_binding_t *binding = & typevar_binding_stack[top-1]; binding->type_variable = type_parameter; binding->old_current_type = type; type_parameter = type_parameter->next; type_argument = type_argument->next; } assert(type_parameter == NULL && type_argument == NULL); - for(int i = old_top+1; i <= top; ++i) { + for (int i = old_top+1; i <= top; ++i) { typevar_binding_t *binding = & typevar_binding_stack[i-1]; type_variable_t *type_variable = binding->type_variable; type_t *new_type = binding->old_current_type; binding->old_current_type = type_variable->current_type; type_variable->current_type = new_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "binding '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, type_variable->current_type); fprintf(stderr, "\n"); #endif } } void pop_type_variable_bindings(int new_top) { int top = ARR_LEN(typevar_binding_stack) - 1; - for(int i = top; i >= new_top; --i) { + for (int i = top; i >= new_top; --i) { typevar_binding_t *binding = & typevar_binding_stack[i]; type_variable_t *type_variable = binding->type_variable; type_variable->current_type = binding->old_current_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "reset binding of '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, binding->old_current_type); fprintf(stderr, "\n"); #endif } ARR_SHRINKLEN(typevar_binding_stack, new_top); } type_t *skip_typeref(type_t *type) { if (type->type == TYPE_TYPEOF) { typeof_type_t *typeof_type = (typeof_type_t*) type; return skip_typeref(typeof_type->expression->datatype); } return type; } diff --git a/type_hash.c b/type_hash.c index d201bd7..38b2454 100644 --- a/type_hash.c +++ b/type_hash.c @@ -1,291 +1,291 @@ #include <config.h> #include <stdbool.h> #include "type_hash.h" #include "adt/error.h" #include "type_t.h" #include <assert.h> #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #include "adt/hashset.h" #undef ValueType #undef HashSetIterator #undef HashSet typedef struct type_hash_iterator_t type_hash_iterator_t; typedef struct type_hash_t type_hash_t; static unsigned hash_ptr(const void *ptr) { unsigned ptr_int = ((const char*) ptr - (const char*) NULL); return ptr_int >> 3; } static unsigned hash_atomic_type(const atomic_type_t *type) { unsigned some_prime = 27644437; return type->atype * some_prime; } static unsigned hash_pointer_type(const pointer_type_t *type) { return hash_ptr(type->points_to); } static unsigned hash_array_type(const array_type_t *type) { unsigned some_prime = 27644437; return hash_ptr(type->element_type) ^ (type->size * some_prime); } static unsigned hash_compound_type(const compound_type_t *type) { unsigned result = hash_ptr(type->symbol); return result; } static unsigned hash_type(const type_t *type); static unsigned hash_method_type(const method_type_t *type) { unsigned result = hash_ptr(type->result_type); method_parameter_type_t *parameter = type->parameter_types; while (parameter != NULL) { result ^= hash_ptr(parameter->type); parameter = parameter->next; } if (type->variable_arguments) result = ~result; return result; } static unsigned hash_type_reference_type_variable(const type_reference_t *type) { return hash_ptr(type->type_variable); } static unsigned hash_bind_typevariables_type_t(const bind_typevariables_type_t *type) { unsigned hash = hash_compound_type(type->polymorphic_type); type_argument_t *argument = type->type_arguments; while (argument != NULL) { hash ^= hash_type(argument->type); argument = argument->next; } return hash; } static unsigned hash_type(const type_t *type) { - switch(type->type) { + switch (type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: panic("internalizing void or invalid types not possible"); case TYPE_REFERENCE_TYPE_VARIABLE: return hash_type_reference_type_variable( (const type_reference_t*) type); case TYPE_ATOMIC: return hash_atomic_type((const atomic_type_t*) type); case TYPE_TYPEOF: { const typeof_type_t *typeof_type = (const typeof_type_t*) type; return hash_ptr(typeof_type->expression); } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return hash_compound_type((const compound_type_t*) type); case TYPE_METHOD: return hash_method_type((const method_type_t*) type); case TYPE_POINTER: return hash_pointer_type((const pointer_type_t*) type); case TYPE_ARRAY: return hash_array_type((const array_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return hash_bind_typevariables_type_t( (const bind_typevariables_type_t*) type); } abort(); } static bool atomic_types_equal(const atomic_type_t *type1, const atomic_type_t *type2) { return type1->atype == type2->atype; } static bool compound_types_equal(const compound_type_t *type1, const compound_type_t *type2) { if (type1->symbol != type2->symbol) return false; /* TODO: check type parameters? */ return true; } static bool method_types_equal(const method_type_t *type1, const method_type_t *type2) { if (type1->result_type != type2->result_type) return false; if (type1->variable_arguments != type2->variable_arguments) return false; method_parameter_type_t *param1 = type1->parameter_types; method_parameter_type_t *param2 = type2->parameter_types; while (param1 != NULL && param2 != NULL) { if (param1->type != param2->type) return false; param1 = param1->next; param2 = param2->next; } if (param1 != NULL || param2 != NULL) return false; return true; } static bool pointer_types_equal(const pointer_type_t *type1, const pointer_type_t *type2) { return type1->points_to == type2->points_to; } static bool array_types_equal(const array_type_t *type1, const array_type_t *type2) { return type1->element_type == type2->element_type && type1->size == type2->size; } static bool type_references_type_variable_equal(const type_reference_t *type1, const type_reference_t *type2) { return type1->type_variable == type2->type_variable; } static bool bind_typevariables_type_equal(const bind_typevariables_type_t*type1, const bind_typevariables_type_t*type2) { if (type1->polymorphic_type != type2->polymorphic_type) return false; type_argument_t *argument1 = type1->type_arguments; type_argument_t *argument2 = type2->type_arguments; while (argument1 != NULL) { if (argument2 == NULL) return false; if (argument1->type != argument2->type) return false; argument1 = argument1->next; argument2 = argument2->next; } if (argument2 != NULL) return false; return true; } static bool types_equal(const type_t *type1, const type_t *type2) { if (type1 == type2) return true; if (type1->type != type2->type) return false; - switch(type1->type) { + switch (type1->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ERROR: case TYPE_REFERENCE: return false; case TYPE_TYPEOF: { const typeof_type_t *typeof_type1 = (const typeof_type_t*) type1; const typeof_type_t *typeof_type2 = (const typeof_type_t*) type2; return typeof_type1->expression == typeof_type2->expression; } case TYPE_REFERENCE_TYPE_VARIABLE: return type_references_type_variable_equal( (const type_reference_t*) type1, (const type_reference_t*) type2); case TYPE_ATOMIC: return atomic_types_equal((const atomic_type_t*) type1, (const atomic_type_t*) type2); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return compound_types_equal((const compound_type_t*) type1, (const compound_type_t*) type2); case TYPE_METHOD: return method_types_equal((const method_type_t*) type1, (const method_type_t*) type2); case TYPE_POINTER: return pointer_types_equal((const pointer_type_t*) type1, (const pointer_type_t*) type2); case TYPE_ARRAY: return array_types_equal((const array_type_t*) type1, (const array_type_t*) type2); case TYPE_BIND_TYPEVARIABLES: return bind_typevariables_type_equal( (const bind_typevariables_type_t*) type1, (const bind_typevariables_type_t*) type2); } panic("invalid type encountered"); } #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #define NullValue NULL #define DeletedValue ((type_t*)-1) #define Hash(this, key) hash_type(key) #define KeysEqual(this,key1,key2) types_equal(key1, key2) #define SetRangeEmpty(ptr,size) memset(ptr, 0, (size) * sizeof(*(ptr))) #define hashset_init _typehash_init #define hashset_init_size _typehash_init_size #define hashset_destroy _typehash_destroy #define hashset_insert _typehash_insert #define hashset_remove typehash_remove #define hashset_find typehash_find #define hashset_size typehash_size #define hashset_iterator_init typehash_iterator_init #define hashset_iterator_next typehash_iterator_next #define hashset_remove_iterator typehash_remove_iterator #define SCALAR_RETURN #include "adt/hashset.c" static type_hash_t typehash; void init_typehash(void) { _typehash_init(&typehash); } void exit_typehash(void) { _typehash_destroy(&typehash); } type_t *typehash_insert(type_t *type) { return _typehash_insert(&typehash, type); } int typehash_contains(type_t *type) { return typehash_find(&typehash, type) != NULL; }
MatzeB/fluffy
dd56244b9f42ce9d45996475e5db81f28a6d34f9
allow casting of pointer to array to pointer of the arrays element type
diff --git a/semantic.c b/semantic.c index fee8edf..f839447 100644 --- a/semantic.c +++ b/semantic.c @@ -78,1027 +78,1036 @@ void error_at(const source_position_t position, */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if (symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if (new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if (declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if (variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while (i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while (type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if (declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if (type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if (declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while (type_parameter != NULL) { if (type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if (type_argument != NULL) { print_error_prefix(type_ref->source_position); if (type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if (type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if (type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while (parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while (entry != NULL) { type_t *type = entry->type; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if (type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if (type == NULL) return NULL; if (type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if (constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_ERROR: found_errors = true; return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if (declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if (declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if (unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if (!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if (left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if (declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if (left->datatype == NULL) { if (right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if (dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->datatype; if (from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if (from_type->type == TYPE_POINTER) { if (dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ - if (p1->points_to != p2->points_to - && dest_type != type_void_ptr - && from->type != EXPR_NULL_POINTER) { + if (p1->points_to == p2->points_to + || dest_type == type_void_ptr + || from->type == EXPR_NULL_POINTER) { + /* fine */ + } else if (is_type_array(p1->points_to)) { + array_type_t *array_type = (array_type_t*) p1->points_to; + if (array_type->element_type == p2->points_to) { + /* fine */ + } else { + implicit_cast_allowed = false; + } + } else { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if (dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if (pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if (dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if (from_type->type == TYPE_ATOMIC) { if (dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if (!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if (lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if (!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if (!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if (left == NULL || right == NULL) return; if (left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if (right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while (argument != NULL && parameter != NULL) { if (parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if (parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if (match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if (match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while (constraint != NULL) { if (constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while (method_instance != NULL) { if (method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while (type_var != NULL) { type_t *current_type = type_var->current_type; if (current_type == NULL) return; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if (!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if (cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if (instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters; while (typevar != NULL) { if (typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if (method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while (type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if (concept == NULL) continue; if (current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if (!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->declaration.symbol->string, concept->declaration.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if (instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->declaration.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->declaration.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if (type == NULL) { return type_int; } type = skip_typeref(type); switch(type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(type); diff --git a/type_t.h b/type_t.h index e07be0d..a8c738f 100644 --- a/type_t.h +++ b/type_t.h @@ -1,144 +1,149 @@ #ifndef TYPE_T_H #define TYPE_T_H #include <stdbool.h> #include "type.h" #include "symbol.h" #include "lexer.h" #include "ast.h" #include "ast_t.h" #include "adt/obst.h" #include <libfirm/typerep.h> struct obstack *type_obst; typedef enum { TYPE_INVALID, TYPE_ERROR, TYPE_VOID, TYPE_ATOMIC, TYPE_COMPOUND_CLASS, TYPE_COMPOUND_STRUCT, TYPE_COMPOUND_UNION, TYPE_METHOD, TYPE_POINTER, TYPE_ARRAY, TYPE_TYPEOF, TYPE_REFERENCE, TYPE_REFERENCE_TYPE_VARIABLE, TYPE_BIND_TYPEVARIABLES } type_type_t; typedef enum { ATOMIC_TYPE_INVALID, ATOMIC_TYPE_BOOL, ATOMIC_TYPE_BYTE, ATOMIC_TYPE_UBYTE, ATOMIC_TYPE_SHORT, ATOMIC_TYPE_USHORT, ATOMIC_TYPE_INT, ATOMIC_TYPE_UINT, ATOMIC_TYPE_LONG, ATOMIC_TYPE_ULONG, ATOMIC_TYPE_LONGLONG, ATOMIC_TYPE_ULONGLONG, ATOMIC_TYPE_FLOAT, ATOMIC_TYPE_DOUBLE, } atomic_type_type_t; struct type_t { type_type_t type; ir_type *firm_type; }; struct atomic_type_t { type_t type; atomic_type_type_t atype; }; struct pointer_type_t { type_t type; type_t *points_to; }; struct array_type_t { type_t type; type_t *element_type; unsigned long size; }; struct typeof_type_t { type_t type; expression_t *expression; }; struct type_argument_t { type_t *type; type_argument_t *next; }; struct type_reference_t { type_t type; symbol_t *symbol; source_position_t source_position; type_argument_t *type_arguments; type_variable_t *type_variable; }; struct bind_typevariables_type_t { type_t type; type_argument_t *type_arguments; compound_type_t *polymorphic_type; }; struct method_parameter_type_t { type_t *type; method_parameter_type_t *next; }; struct type_constraint_t { symbol_t *concept_symbol; concept_t *concept; type_constraint_t *next; }; struct method_type_t { type_t type; type_t *result_type; method_parameter_type_t *parameter_types; bool variable_arguments; }; struct iterator_type_t { type_t type; type_t *element_type; method_parameter_type_t *parameter_types; }; struct compound_entry_t { type_t *type; symbol_t *symbol; compound_entry_t *next; attribute_t *attributes; source_position_t source_position; ir_entity *entity; }; struct compound_type_t { type_t type; compound_entry_t *entries; symbol_t *symbol; attribute_t *attributes; type_variable_t *type_parameters; context_t context; source_position_t source_position; }; type_t *make_atomic_type(atomic_type_type_t type); type_t *make_pointer_type(type_t *type); +static inline bool is_type_array(const type_t *type) +{ + return type->type == TYPE_ARRAY; +} + #endif
MatzeB/fluffy
45f7980b71d5264a728f119b2a8e8bbb3b4e22bd
some shouldfail tests
diff --git a/test/quicktest.sh b/test/quicktest.sh index 949651b..b540339 100755 --- a/test/quicktest.sh +++ b/test/quicktest.sh @@ -1,14 +1,20 @@ #!/bin/bash TEMPOUT="/tmp/fluffytest.txt" for i in *.fluffy; do echo -n "$i..." ../fluffy $i ./a.out >& "$TEMPOUT" || echo "(return status != 0)" if ! diff "$TEMPOUT" "expected_output/$i.output" > /dev/null; then echo "FAIL" else echo "" fi done + +for i in shouldfail/*.fluffy; do + echo -n "$i..." + ../fluffy $i >& /dev/null && echo -n "COMPILED (this is bad)" + echo "" +done rm -f a.out diff --git a/test/shouldfail/cast1.fluffy b/test/shouldfail/cast1.fluffy new file mode 100644 index 0000000..00d119a --- /dev/null +++ b/test/shouldfail/cast1.fluffy @@ -0,0 +1,5 @@ +export main +func main() : int: + var l : byte* + var l2 : unsigned byte* = l + return 0 diff --git a/test/shouldfail/cast2.fluffy b/test/shouldfail/cast2.fluffy new file mode 100644 index 0000000..31f29d8 --- /dev/null +++ b/test/shouldfail/cast2.fluffy @@ -0,0 +1,5 @@ +export main +func main() : int: + var l : void* + var l2 : unsigned byte* = l + return 0 diff --git a/test/shouldfail/cast3.fluffy b/test/shouldfail/cast3.fluffy new file mode 100644 index 0000000..2c79b27 --- /dev/null +++ b/test/shouldfail/cast3.fluffy @@ -0,0 +1,5 @@ +export main +func main() : int: + var l : void* = null + var l2 : unsigned byte* = l + return 0 diff --git a/test/shouldfail/cast4.fluffy b/test/shouldfail/cast4.fluffy new file mode 100644 index 0000000..6294592 --- /dev/null +++ b/test/shouldfail/cast4.fluffy @@ -0,0 +1,5 @@ +export main +func main() : int: + var l : int[10] + var l2 : unsigned int* = &l + return 0 diff --git a/test/shouldfail/syntax1.fluffy b/test/shouldfail/syntax1.fluffy new file mode 100644 index 0000000..6931845 --- /dev/null +++ b/test/shouldfail/syntax1.fluffy @@ -0,0 +1,2 @@ +bla bla +
MatzeB/fluffy
d6f515e9e7e2be194f6576dee63449898f3a20a4
implement sizeof(expression)
diff --git a/ast2firm.c b/ast2firm.c index b03ef09..6d29478 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1093,861 +1093,862 @@ static long binexpr_type_to_cmp_pn(binary_expression_type_t type) } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if(compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; switch(unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if(entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if(strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while(type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if(last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if(instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if(method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while(argument != NULL) { n_parameters++; argument = argument->next; } if(method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while(argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if(new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if(new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if(result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if(entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch(expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: + case EXPR_ERROR: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if(statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if(statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while(statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if(block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if(statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch(statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if(method->is_extern) return; int old_top = typevar_binding_stack_top(); if(is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if(method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if(get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while(label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for(int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if(align > align_all) align_all = align; int misalign = 0; if(align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if(!is_polymorphic_method(method)) { assure_instance(method, declaration->symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } declaration = declaration->next; } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; while(instance != NULL) { create_concept_instance(instance); instance = instance->next; } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while(namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while(!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index 3b2b8a1..454a829 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,435 +1,436 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; struct iterator_declaration_t { declaration_t declaration; method_t method; }; typedef enum { EXPR_INVALID = 0, + EXPR_ERROR, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/parser.c b/parser.c index d3fa543..3d9e10c 100644 --- a/parser.c +++ b/parser.c @@ -1,1261 +1,1291 @@ #include <config.h> #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static unsigned char token_anchor_set[T_LAST_TOKEN]; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } #if 0 static int save_and_reset_anchor_state(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); int count = token_anchor_set[token_type]; token_anchor_set[token_type] = 0; return count; } static void restore_anchor_state(int token_type, int count) { assert(0 <= token_type && token_type < T_LAST_TOKEN); token_anchor_set[token_type] = count; } #endif static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if(message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while(token_type != 0) { if(first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if(token.type != T_INDENT) return; next_token(); unsigned indent = 1; while(indent >= 1) { if(token.type == T_INDENT) { indent++; } else if(token.type == T_DEDENT) { indent--; } else if(token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch(token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch(token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch(token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); add_anchor_token(')'); typeof_type->expression = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } +static type_t *create_error_type(void) +{ + type_t *error_type = allocate_type_zero(sizeof(error_type[0])); + error_type->type = TYPE_ERROR; + return error_type; +} + static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('(', end_error); add_anchor_token(')'); parse_parameter_declaration(method_type, NULL); rem_anchor_token(')'); expect(')', end_error); expect(':', end_error); method_type->result_type = parse_type(); -end_error: return (type_t*) method_type; + +end_error: + return create_error_type(); } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); add_anchor_token(')'); type_t *type = parse_type(); rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); add_anchor_token(']'); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); eat_until_anchor(); rem_anchor_token(']'); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); eat_until_anchor(); rem_anchor_token(']'); break; } array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; rem_anchor_token(']'); expect(']', end_error); break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(void) { int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(void) { eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(void) { eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(void) { eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(void) { eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(void) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); add_anchor_token('>'); ref->type_arguments = parse_type_arguments(); rem_anchor_token('>'); expect('>', end_error); } end_error: return (expression_t*) ref; } +static expression_t *create_error_expression(void) +{ + expression_t *expression = allocate_ast_zero(sizeof(expression[0])); + expression->type = EXPR_ERROR; + expression->datatype = create_error_type(); + return expression; +} + static expression_t *parse_sizeof(void) { eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; - expect('<', end_error); - add_anchor_token('>'); - expression->type = parse_type(); - rem_anchor_token('>'); - expect('>', end_error); + if (token.type == '(') { + next_token(); + typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); + typeof_type->type.type = TYPE_TYPEOF; + expression->type = (type_t*) typeof_type; + + add_anchor_token(')'); + typeof_type->expression = parse_expression(); + rem_anchor_token(')'); + expect(')', end_error); + } else { + expect('<', end_error); + add_anchor_token('>'); + expression->type = parse_type(); + rem_anchor_token('>'); + expect('>', end_error); + } + return (expression_t*) expression; end_error: - return (expression_t*) expression; + return create_error_expression(); } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<', end_error); unary_expression->expression.datatype = parse_type(); expect('>', end_error); unary_expression->value = parse_sub_expression(PREC_CAST); end_error: return (expression_t*) unary_expression; } static expression_t *parse_call_expression(expression_t *expression) { call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return (expression_t*) call; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(prec_r); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_UNEXPR_NEGATE, '-'); register_expression_parser(parse_UNEXPR_NOT, '!'); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_UNEXPR_DEREFERENCE, '*'); register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return (statement_t*) return_statement; } static statement_t *create_error_statement(void) { statement_t *statement = allocate_ast_zero(sizeof(statement[0])); statement->type = STATEMENT_ERROR; return statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return (statement_t*) goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE, end_error); return (statement_t*) label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if(token.type == T_else) { next_token(); if(token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; diff --git a/plugins/api.fluffy b/plugins/api.fluffy index d8525a0..339d738 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,380 +1,381 @@ struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: type : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: type : unsigned int datatype : Type* source_position : SourcePosition struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 const STATEMENT_ERROR = 1 const STATEMENT_BLOCK = 2 const STATEMENT_RETURN = 3 const STATEMENT_VARIABLE_DECLARATION = 4 const STATEMENT_IF = 5 const STATEMENT_EXPRESSION = 6 const STATEMENT_GOTO = 7 const STATEMENT_LABEL = 8 const TYPE_INVALID = 0 const TYPE_ERROR = 1 const TYPE_VOID = 2 const TYPE_ATOMIC = 3 const TYPE_COMPOUND_CLASS = 4 const TYPE_COMPOUND_STRUCT = 5 const TYPE_COMPOUND_UNION = 6 const TYPE_METHOD = 7 const TYPE_POINTER = 8 const TYPE_ARRAY = 9 const TYPE_REFERENCE = 10 const TYPE_REFERENCE_TYPE_VARIABLE = 11 const TYPE_BIND_TYPEVARIABLES = 12 const DECLARATION_INVALID = 0 const DECLARATION_ERROR = 1 const DECLARATION_METHOD = 2 const DECLARATION_METHOD_PARAMETER = 3 const DECLARATION_ITERATOR = 4 const DECLARATION_VARIABLE = 5 const DECLARATION_CONSTANT = 6 const DECLARATION_TYPE_VARIABLE = 7 const DECLARATION_TYPEALIAS = 8 const DECLARATION_CONCEPT = 9 const DECLARATION_CONCEPT_METHOD = 10 const DECLARATION_LABEL = 11 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const EXPR_INVALID = 0 -const EXPR_INT_CONST = 1 -const EXPR_FLOAT_CONST = 2 -const EXPR_BOOL_CONST = 3 -const EXPR_STRING_CONST = 4 -const EXPR_NULL_POINTER = 5 -const EXPR_REFERENCE = 6 -const EXPR_CALL = 7 -const EXPR_UNARY = 8 -const EXPR_BINARY = 9 +const EXPR_ERROR = 1 +const EXPR_INT_CONST = 2 +const EXPR_FLOAT_CONST = 3 +const EXPR_BOOL_CONST = 4 +const EXPR_STRING_CONST = 5 +const EXPR_NULL_POINTER = 6 +const EXPR_REFERENCE = 7 +const EXPR_CALL = 8 +const EXPR_UNARY = 9 +const EXPR_BINARY = 10 const BINEXPR_INVALID = 0 const BINEXPR_ASSIGN = 1 const BINEXPR_ADD = 2 const T_EOF = -1 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 const T_ASSIGN = 296 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* typealias ParseExpressionFunction = func () : Expression* typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.statement.type = STATEMENT_LABEL res.declaration.declaration.type = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.declaration.type = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() res.expression.type = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() res.expression.type = EXPR_INT_CONST return res func api_init(): stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): declaration.next = context.declarations context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label diff --git a/semantic.c b/semantic.c index 2717eff..8cf1808 100644 --- a/semantic.c +++ b/semantic.c @@ -1335,1024 +1335,1027 @@ static void check_call_expression(call_expression_t *call) } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if(cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if(cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if(value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if(value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if(!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if(value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if(type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(unary_expression_t *expression) { expression_t *value = check_expression(expression->value); type_t *type = value->datatype; if(!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if(!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if(type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if(atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if(need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.type = EXPR_BINARY; add->expression.datatype = type; if(expression->type == UNEXPR_INCREMENT) { add->type = BINEXPR_ADD; } else { add->type = BINEXPR_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.datatype = type; assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static expression_t *lower_unary_expression(expression_t *expression) { assert(expression->type == EXPR_UNARY); unary_expression_t *unary_expression = (unary_expression_t*) expression; switch(unary_expression->type) { case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: return lower_incdec_expression(unary_expression); default: break; } return expression; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch(unary_expression->type) { case UNEXPR_CAST: check_cast_expression(unary_expression); return; case UNEXPR_DEREFERENCE: check_dereference_expression(unary_expression); return; case UNEXPR_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case UNEXPR_NOT: check_not_expression(unary_expression); return; case UNEXPR_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case UNEXPR_NEGATE: check_negate_expression(unary_expression); return; case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("increment/decrement not lowered"); case UNEXPR_INVALID: abort(); } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if(datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if(datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if(datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if(points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; while(declaration != NULL) { if(declaration->symbol == symbol) break; declaration = declaration->next; } if(declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while(entry != NULL) { if(entry->symbol == symbol) { break; } entry = entry->next; } if(entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if(bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if(type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if(type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if(index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(index->datatype); fprintf(stderr, "\n"); return; } if(index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, access->expression.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if(expression == NULL) return NULL; /* try to lower the expression */ if((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; if(lowerer != NULL) { expression = lowerer(expression); } } switch(expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; case EXPR_BINARY: check_binary_expression((binary_expression_t*) expression); break; case EXPR_UNARY: check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; + case EXPR_ERROR: + found_errors = true; + break; case EXPR_LAST: case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if(return_value != NULL) { if(method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if(return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if(method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if(condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if(statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { environment_push(declaration, context); declaration = declaration->next; } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while(statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if(last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if(statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if(expression->datatype == NULL) return; bool may_be_unused = false; if(expression->type == EXPR_BINARY && ((binary_expression_t*) expression)->type == BINEXPR_ASSIGN) { may_be_unused = true; } else if(expression->type == EXPR_UNARY && (((unary_expression_t*) expression)->type == UNEXPR_INCREMENT || ((unary_expression_t*) expression)->type == UNEXPR_DECREMENT)) { may_be_unused = true; } else if(expression->type == EXPR_CALL) { may_be_unused = true; } if(expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if(expression->type == EXPR_BINARY) { binary_expression_t *binexpr = (binary_expression_t*) expression; if(binexpr->type == BINEXPR_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if(goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if(symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if(declaration->type != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_type_name(declaration->type)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if(statement == NULL) return NULL; /* try to lower the statement */ if((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if(lowerer != NULL) { statement = lowerer(statement); } } if(statement == NULL) return NULL; last_statement_was_return = false; switch(statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if(method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while(parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if(method->statement != NULL) { method->statement = check_statement(method->statement); } if(!last_statement_was_return) { type_t *result_type = method->type->result_type; if(result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if(symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if(expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->declaration.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; while(constraint != NULL) { resolve_type_constraint(constraint, type_var->declaration.source_position); constraint = constraint->next; } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while(type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; while(concept_method != NULL) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; concept_method = concept_method->next; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(declaration->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(declaration->source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->declaration.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if(!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); }
MatzeB/fluffy
7f25fc8cbd6393360e83f7f23ee802420ef0ff56
fix plugins
diff --git a/ast.c b/ast.c index 7709867..b2203f2 100644 --- a/ast.c +++ b/ast.c @@ -67,615 +67,617 @@ static void print_type_arguments(const type_argument_t *type_arguments) const type_argument_t *argument = type_arguments; int first = 1; while(argument != NULL) { if(first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if(type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if(ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if(select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch(unexpr->type) { case UNEXPR_CAST: fprintf(out, "cast<"); print_type(unexpr->expression.datatype); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->type); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch(binexpr->type) { case BINEXPR_INVALID: fprintf(out, "INVOP"); break; case BINEXPR_ASSIGN: fprintf(out, "<-"); break; case BINEXPR_ADD: fprintf(out, "+"); break; case BINEXPR_SUB: fprintf(out, "-"); break; case BINEXPR_MUL: fprintf(out, "*"); break; case BINEXPR_DIV: fprintf(out, "/"); break; case BINEXPR_NOTEQUAL: fprintf(out, "/="); break; case BINEXPR_EQUAL: fprintf(out, "="); break; case BINEXPR_LESS: fprintf(out, "<"); break; case BINEXPR_LESSEQUAL: fprintf(out, "<="); break; case BINEXPR_GREATER: fprintf(out, ">"); break; case BINEXPR_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->type); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if(expression == NULL) { fprintf(out, "*null expression*"); return; } switch(expression->type) { case EXPR_LAST: case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; case EXPR_BINARY: print_binary_expression((const binary_expression_t*) expression); break; case EXPR_UNARY: print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; default: /* TODO */ fprintf(out, "some expression of type %d", expression->type); break; } } static void print_indent(void) { for(int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while(statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if(statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if(statement->label != NULL) { symbol_t *symbol = statement->label->declaration.symbol; if(symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.declaration.symbol; if(symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if(statement->true_statement != NULL) print_statement(statement->true_statement); if(statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if(var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->declaration.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch(statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if(constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->declaration.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->declaration.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while(type_parameter != NULL) { if(first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if(type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while(parameter != NULL && parameter_type != NULL) { if(!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if(method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->declaration.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->declaration.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->declaration.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while(method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if(method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->declaration.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if(instance->concept != NULL) { fprintf(out, "%s", instance->concept->declaration.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->declaration.symbol->string); if(constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if(constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->declaration.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch(declaration->type) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: + case DECLARATION_ERROR: // TODO fprintf(out, "some declaration of type %d\n", declaration->type); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%d)\n", declaration->type); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { print_declaration(declaration); declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { print_concept_instance(instance); instance = instance->next; } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_type_name(declaration_type_t type) { switch(type) { case DECLARATION_LAST: + case DECLARATION_ERROR: return "parse error"; case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } diff --git a/ast2firm.c b/ast2firm.c index eff1b99..b03ef09 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -440,1511 +440,1514 @@ static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; while(declaration != NULL) { if(declaration->type == DECLARATION_METHOD) { /* TODO */ continue; } if(declaration->type != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; ident *ident = new_id_from_str(declaration->symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } declaration = declaration->next; } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if(current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->declaration.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if(type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch(type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; firm_type = get_ir_type(typeof_type->expression->datatype); break; } case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_ERROR: case TYPE_INVALID: break; } if(firm_type == NULL) panic("unknown type found"); if(env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if(method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->declaration.symbol); mangle_symbol(concept_method->declaration.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if(!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if(is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if(is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for(int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if(get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if(method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if(!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if(is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if(!is_polymorphic) { method->e.entity = entity; } else { if(method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if(cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for(size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if(select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if(variable->entity != NULL) return variable->entity; ir_type *parent_type; if(variable->is_global) { parent_type = get_glob_type(); } else if(variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if(variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if(variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if(variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch(declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: + case DECLARATION_ERROR: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; switch(expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if(dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { switch(type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { switch(type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if(compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; switch(unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if(entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if(strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while(type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if(last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if(instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if(method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while(argument != NULL) { n_parameters++; argument = argument->next; } if(method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while(argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if(new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if(new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if(result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if(entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: + case DECLARATION_ERROR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch(expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if(statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if(statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while(statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if(block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if(statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch(statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if(method->is_extern) return; int old_top = typevar_binding_stack_top(); if(is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if(method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if(get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while(label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for(int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if(align > align_all) align_all = align; int misalign = 0; if(align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if(!is_polymorphic_method(method)) { assure_instance(method, declaration->symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: + case DECLARATION_ERROR: panic("Invalid namespace entry type found"); } declaration = declaration->next; } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; while(instance != NULL) { create_concept_instance(instance); instance = instance->next; } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while(namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while(!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index 46554da..3b2b8a1 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,434 +1,435 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, + DECLARATION_ERROR, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; struct iterator_declaration_t { declaration_t declaration; method_t method; }; typedef enum { EXPR_INVALID = 0, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/parser.c b/parser.c index 856f70a..d3fa543 100644 --- a/parser.c +++ b/parser.c @@ -1,1238 +1,1257 @@ #include <config.h> #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static unsigned char token_anchor_set[T_LAST_TOKEN]; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static void add_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); ++token_anchor_set[token_type]; } #if 0 static int save_and_reset_anchor_state(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); int count = token_anchor_set[token_type]; token_anchor_set[token_type] = 0; return count; } static void restore_anchor_state(int token_type, int count) { assert(0 <= token_type && token_type < T_LAST_TOKEN); token_anchor_set[token_type] = count; } #endif static void rem_anchor_token(int token_type) { assert(0 <= token_type && token_type < T_LAST_TOKEN); assert(token_anchor_set[token_type] != 0); --token_anchor_set[token_type]; } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if(message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while(token_type != 0) { if(first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if(token.type != T_INDENT) return; next_token(); unsigned indent = 1; while(indent >= 1) { if(token.type == T_INDENT) { indent++; } else if(token.type == T_DEDENT) { indent--; } else if(token.type == T_EOF) { break; } next_token(); } } /** * eats nested brace groups */ static void eat_until_matching_token(int type) { int end_token; switch (type) { case '(': end_token = ')'; break; case '{': end_token = '}'; break; case '[': end_token = ']'; break; default: end_token = type; break; } unsigned parenthesis_count = 0; unsigned brace_count = 0; unsigned bracket_count = 0; while (token.type != end_token || parenthesis_count != 0 || brace_count != 0 || bracket_count != 0) { switch (token.type) { case T_EOF: return; case '(': ++parenthesis_count; break; case '{': ++brace_count; break; case '[': ++bracket_count; break; case ')': if (parenthesis_count > 0) --parenthesis_count; goto check_stop; case '}': if (brace_count > 0) --brace_count; goto check_stop; case ']': if (bracket_count > 0) --bracket_count; check_stop: if (token.type == end_token && parenthesis_count == 0 && brace_count == 0 && bracket_count == 0) return; break; default: break; } next_token(); } } /** * Eat input tokens until an anchor is found. */ static void eat_until_anchor(void) { while (token_anchor_set[token.type] == 0) { if (token.type == '(' || token.type == '{' || token.type == '[') eat_until_matching_token(token.type); if (token.type == ':') { next_token(); if (!token_anchor_set[token.type] == 0) { maybe_eat_block(); } } else { next_token(); } } } #define expect(expected, error_label) \ do { \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ add_anchor_token(expected); \ eat_until_anchor(); \ if (token.type == expected) \ next_token(); \ rem_anchor_token(expected); \ goto error_label; \ } \ next_token(); \ } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch(token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch(token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch(token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); - typeof_type->expression = parse_expression(); + add_anchor_token(')'); + typeof_type->expression = parse_expression(); + rem_anchor_token(')'); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); + add_anchor_token('>'); type_ref->type_arguments = parse_type_arguments(); + rem_anchor_token('>'); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('(', end_error); + add_anchor_token(')'); parse_parameter_declaration(method_type, NULL); + rem_anchor_token(')'); expect(')', end_error); expect(':', end_error); method_type->result_type = parse_type(); end_error: return (type_t*) method_type; } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); - + + add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ + rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); - + + add_anchor_token(T_DEDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ + rem_anchor_token(T_DEDENT); assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); + add_anchor_token(')'); type_t *type = parse_type(); + rem_anchor_token(')'); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); + add_anchor_token(']'); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); + eat_until_anchor(); + rem_anchor_token(']'); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); - expect(']', end_error); + eat_until_anchor(); + rem_anchor_token(']'); break; } array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; + rem_anchor_token(']'); expect(']', end_error); break; } default: return type; } } end_error: return type; } - - static expression_t *parse_string_const(void) { string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(void) { int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(void) { eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(void) { eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(void) { eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(void) { eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(void) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); + add_anchor_token('>'); ref->type_arguments = parse_type_arguments(); + rem_anchor_token('>'); expect('>', end_error); } end_error: return (expression_t*) ref; } static expression_t *parse_sizeof(void) { eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; expect('<', end_error); + add_anchor_token('>'); expression->type = parse_type(); + rem_anchor_token('>'); expect('>', end_error); end_error: return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_parenthesized_expression(void) { eat('('); add_anchor_token(')'); expression_t *result = parse_expression(); rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<', end_error); unary_expression->expression.datatype = parse_type(); expect('>', end_error); unary_expression->value = parse_sub_expression(PREC_CAST); end_error: return (expression_t*) unary_expression; } static expression_t *parse_call_expression(expression_t *expression) { call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); add_anchor_token(')'); add_anchor_token(','); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } rem_anchor_token(','); rem_anchor_token(')'); expect(')', end_error); end_error: return (expression_t*) call; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(prec_r); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_UNEXPR_NEGATE, '-'); register_expression_parser(parse_UNEXPR_NOT, '!'); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_UNEXPR_DEREFERENCE, '*'); register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return (statement_t*) return_statement; } static statement_t *create_error_statement(void) { statement_t *statement = allocate_ast_zero(sizeof(statement[0])); statement->type = STATEMENT_ERROR; return statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return (statement_t*) goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE, end_error); return (statement_t*) label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if(token.type == T_else) { next_token(); if(token.type == ':') next_token(); false_statement = parse_sub_block(); } diff --git a/plugins/api.fluffy b/plugins/api.fluffy index 5373d83..d8525a0 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,375 +1,380 @@ struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: type : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: type : unsigned int datatype : Type* source_position : SourcePosition struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 const STATEMENT_ERROR = 1 const STATEMENT_BLOCK = 2 const STATEMENT_RETURN = 3 const STATEMENT_VARIABLE_DECLARATION = 4 const STATEMENT_IF = 5 const STATEMENT_EXPRESSION = 6 const STATEMENT_GOTO = 7 const STATEMENT_LABEL = 8 const TYPE_INVALID = 0 -const TYPE_VOID = 1 -const TYPE_ATOMIC = 2 -const TYPE_COMPOUND_STRUCT = 3 -const TYPE_COMPOUND_UNION = 4 -const TYPE_METHOD = 5 -const TYPE_POINTER = 6 -const TYPE_ARRAY = 7 -const TYPE_REFERENCE = 8 -const TYPE_REFERENCE_TYPE_VARIABLE = 9 +const TYPE_ERROR = 1 +const TYPE_VOID = 2 +const TYPE_ATOMIC = 3 +const TYPE_COMPOUND_CLASS = 4 +const TYPE_COMPOUND_STRUCT = 5 +const TYPE_COMPOUND_UNION = 6 +const TYPE_METHOD = 7 +const TYPE_POINTER = 8 +const TYPE_ARRAY = 9 +const TYPE_REFERENCE = 10 +const TYPE_REFERENCE_TYPE_VARIABLE = 11 +const TYPE_BIND_TYPEVARIABLES = 12 const DECLARATION_INVALID = 0 -const DECLARATION_METHOD = 1 -const DECLARATION_METHOD_PARAMETER = 2 -const DECLARATION_VARIABLE = 3 -const DECLARATION_CONSTANT = 4 -const DECLARATION_TYPE_VARIABLE = 5 -const DECLARATION_TYPEALIAS = 6 -const DECLARATION_TYPECLASS = 7 -const DECLARATION_TYPECLASS_METHOD = 8 -const DECLARATION_LABEL = 9 +const DECLARATION_ERROR = 1 +const DECLARATION_METHOD = 2 +const DECLARATION_METHOD_PARAMETER = 3 +const DECLARATION_ITERATOR = 4 +const DECLARATION_VARIABLE = 5 +const DECLARATION_CONSTANT = 6 +const DECLARATION_TYPE_VARIABLE = 7 +const DECLARATION_TYPEALIAS = 8 +const DECLARATION_CONCEPT = 9 +const DECLARATION_CONCEPT_METHOD = 10 +const DECLARATION_LABEL = 11 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const EXPR_INVALID = 0 const EXPR_INT_CONST = 1 const EXPR_FLOAT_CONST = 2 const EXPR_BOOL_CONST = 3 const EXPR_STRING_CONST = 4 const EXPR_NULL_POINTER = 5 const EXPR_REFERENCE = 6 const EXPR_CALL = 7 const EXPR_UNARY = 8 const EXPR_BINARY = 9 const BINEXPR_INVALID = 0 const BINEXPR_ASSIGN = 1 const BINEXPR_ADD = 2 const T_EOF = -1 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 const T_ASSIGN = 296 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* typealias ParseExpressionFunction = func () : Expression* typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.statement.type = STATEMENT_LABEL res.declaration.declaration.type = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.declaration.type = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() res.expression.type = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() res.expression.type = EXPR_INT_CONST return res func api_init(): stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): declaration.next = context.declarations context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label diff --git a/semantic.c b/semantic.c index 97de7dd..2717eff 100644 --- a/semantic.c +++ b/semantic.c @@ -1,966 +1,969 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static type_t *error_type = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if(symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if(new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while(i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if(declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if(type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if(declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while(type_parameter != NULL) { if(type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if(type_argument != NULL) { print_error_prefix(type_ref->source_position); if(type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if(type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if(type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while(entry != NULL) { type_t *type = entry->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if(type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: case TYPE_ERROR: return type; case TYPE_TYPEOF: { typeof_type_t *typeof_type = (typeof_type_t*) type; typeof_type->expression = check_expression(typeof_type->expression); return type; } case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if(type == NULL) return NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if(constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; + case DECLARATION_ERROR: + found_errors = true; + return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if(!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if(left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if(left->datatype == NULL) { if(right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if(dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ dest_type = skip_typeref(dest_type); type_t *from_type = from->datatype; if(from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } from_type = skip_typeref(from_type); bool implicit_cast_allowed = true; if(from_type->type == TYPE_POINTER) { if(dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if(p1->points_to != p2->points_to && dest_type != type_void_ptr && from->type != EXPR_NULL_POINTER) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if(dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if(pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if(from_type->type == TYPE_ATOMIC) { if(dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if(!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if(lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if(!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if(left == NULL || right == NULL) return; if(left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if(right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while(argument != NULL && parameter != NULL) { if(parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if(parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if(match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if(match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { if(constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { if(method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while(type_var != NULL) { type_t *current_type = type_var->current_type; if(current_type == NULL) return; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if(!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if(cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if(instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters;
MatzeB/fluffy
b0bb370cce4b66bce2409b3586fdd04795b2fa90
make more use of anchor sets
diff --git a/parser.c b/parser.c index 5ad0c37..856f70a 100644 --- a/parser.c +++ b/parser.c @@ -346,1991 +346,2010 @@ static type_t *parse_atomic_type(void) atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; eat(T_typeof); expect('(', end_error); typeof_type->expression = parse_expression(); expect(')', end_error); end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); type_ref->type_arguments = parse_type_arguments(); expect('>', end_error); } end_error: return (type_t*) type_ref; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('(', end_error); parse_parameter_declaration(method_type, NULL); expect(')', end_error); expect(':', end_error); method_type->result_type = parse_type(); end_error: return (type_t*) method_type; } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); continue; } entry->symbol = token.v.symbol; next_token(); expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE, end_error); } end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':', end_error); expect(T_NEWLINE, end_error); expect(T_INDENT, end_error); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } static type_t *parse_brace_type(void) { eat('('); type_t *type = parse_type(); expect(')', end_error); end_error: return type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ while (true) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); expect(']', end_error); break; } array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; expect(']', end_error); break; } default: return type; } } end_error: return type; } static expression_t *parse_string_const(void) { string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(void) { int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(void) { eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(void) { eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(void) { eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(void) { eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(void) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); ref->type_arguments = parse_type_arguments(); expect('>', end_error); } end_error: return (expression_t*) ref; } static expression_t *parse_sizeof(void) { eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; expect('<', end_error); expression->type = parse_type(); expect('>', end_error); end_error: return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } -static expression_t *parse_brace_expression(void) +static expression_t *parse_parenthesized_expression(void) { eat('('); + + add_anchor_token(')'); expression_t *result = parse_expression(); + rem_anchor_token(')'); expect(')', end_error); end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<', end_error); unary_expression->expression.datatype = parse_type(); expect('>', end_error); unary_expression->value = parse_sub_expression(PREC_CAST); end_error: return (expression_t*) unary_expression; } static expression_t *parse_call_expression(expression_t *expression) { call_expression_t *call = allocate_ast_zero(sizeof(call[0])); - call->expression.type = EXPR_CALL; - call->method = expression; + call->expression.type = EXPR_CALL; + call->method = expression; /* parse arguments */ eat('('); + add_anchor_token(')'); + add_anchor_token(','); + if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } + rem_anchor_token(','); + rem_anchor_token(')'); expect(')', end_error); end_error: return (expression_t*) call; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(prec_r); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_UNEXPR_NEGATE, '-'); register_expression_parser(parse_UNEXPR_NOT, '!'); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_UNEXPR_DEREFERENCE, '*'); register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); - register_expression_parser(parse_brace_expression, '('); + register_expression_parser(parse_parenthesized_expression,'('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE, end_error); end_error: return (statement_t*) return_statement; } static statement_t *create_error_statement(void) { statement_t *statement = allocate_ast_zero(sizeof(statement[0])); statement->type = STATEMENT_ERROR; return statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE, end_error); return (statement_t*) goto_statement; end_error: return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE, end_error); return (statement_t*) label; end_error: return create_error_statement(); } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if(token.type == T_else) { next_token(); if(token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; if_statement->condition = condition; if_statement->true_statement = true_statement; if_statement->false_statement = false_statement; return (statement_t*) if_statement; end_error: return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = symbol; binary_expression_t *assign = allocate_ast_zero(sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.source_position = source_position; assign->type = BINEXPR_ASSIGN; assign->left = (expression_t*) ref; assign->right = parse_expression(); expression_statement_t *expr_statement = allocate_ast_zero(sizeof(expr_statement[0])); expr_statement->statement.type = STATEMENT_EXPRESSION; expr_statement->expression = (expression_t*) assign; return (statement_t*) expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while(1) { if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } variable_declaration_statement_t *declaration_statement = allocate_ast_zero(sizeof(declaration_statement[0])); declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; declaration_t *declaration = &declaration_statement->declaration.declaration; declaration->type = DECLARATION_VARIABLE; declaration->source_position = source_position; declaration->symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &declaration_statement->declaration; if(token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if(last_statement != NULL) { last_statement->next = (statement_t*) declaration_statement; } else { first_statement = (statement_t*) declaration_statement; } last_statement = (statement_t*) declaration_statement; /* do we have an assignment expression? */ if(token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->symbol); last_statement->next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if(token.type != ',') break; next_token(); } expect(T_NEWLINE, end_error); end_error: return first_statement; } static statement_t *parse_expression_statement(void) { expression_statement_t *expression_statement = allocate_ast_zero(sizeof(expression_statement[0])); expression_statement->statement.type = STATEMENT_EXPRESSION; expression_statement->expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: return (statement_t*) expression_statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if(token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; - if(token.type < 0) { - /* this shouldn't happen if the lexer is correct... */ - parse_error_expected("problem while parsing statement", - T_DEDENT, 0); - return NULL; - } - parse_statement_function parser = NULL; if(token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; + add_anchor_token(T_NEWLINE); if(parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if(declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } + rem_anchor_token(T_NEWLINE); if(statement == NULL) return NULL; statement->source_position = start; statement_t *next = statement->next; while(next != NULL) { next->source_position = start; next = next->next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; context_t *last_context = current_context; current_context = &block->context; + add_anchor_token(T_DEDENT); + statement_t *last_statement = NULL; - while(token.type != T_DEDENT && token.type != T_EOF) { + while(token.type != T_DEDENT) { /* parse statement */ statement_t *statement = parse_statement(); if(statement == NULL) continue; if(last_statement != NULL) { last_statement->next = statement; } else { block->statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while(last_statement->next != NULL) last_statement = last_statement->next; } assert(current_context == &block->context); current_context = last_context; block->end_position = source_position; + rem_anchor_token(T_DEDENT); expect(T_DEDENT, end_error); end_error: return (statement_t*) block; } static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); if(token.type == ')') return; method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if(parameters != NULL) *parameters = NULL; while(1) { if(token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if(token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_anchor(); return; } break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_anchor(); return; } symbol_t *symbol = token.v.symbol; next_token(); expect(':', end_error); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if(last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if(parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.type = DECLARATION_METHOD_PARAMETER; method_param->declaration.symbol = symbol; method_param->declaration.source_position = source_position; method_param->type = param_type->type; if(last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if(token.type != ',') break; next_token(); } end_error: ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while(token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if(last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static type_variable_t *parse_type_parameter(void) { type_variable_t *type_variable = allocate_ast_zero(sizeof(type_variable[0])); type_variable->declaration.type = DECLARATION_TYPE_VARIABLE; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_anchor(); return NULL; } type_variable->declaration.source_position = source_position; type_variable->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); type_variable->constraints = parse_type_constraints(); } return type_variable; } static type_variable_t *parse_type_parameters(context_t *context) { type_variable_t *first_variable = NULL; type_variable_t *last_variable = NULL; while(1) { type_variable_t *type_variable = parse_type_parameter(); if(last_variable != NULL) { last_variable->next = type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if(context != NULL) { declaration_t *declaration = & type_variable->declaration; declaration->next = context->declarations; context->declarations = declaration; } if(token.type != ',') break; next_token(); } return first_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->source_position.input_name != NULL); assert(current_context != NULL); declaration->next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if(token.type == '<') { next_token(); method->type_parameters = parse_type_parameters(current_context); expect('>', end_error); } expect('(', end_error); parse_parameter_declaration(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { declaration_t *declaration = (declaration_t*) parameter; declaration->next = current_context->declarations; current_context->declarations = declaration; parameter = parameter->next; } expect(')', end_error); method_type->result_type = type_void; if(token.type == ':') { next_token(); if(token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } method_type->result_type = parse_type(); if(token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } expect(T_NEWLINE, end_error); method_parser_end: assert(current_context == &method->context); current_context = last_context; end_error: ; } static void parse_method_declaration(void) { eat(T_func); method_declaration_t *method_declaration = allocate_ast_zero(sizeof(method_declaration[0])); method_declaration->declaration.type = DECLARATION_METHOD; if(token.type == T_extern) { method_declaration->method.is_extern = 1; next_token(); } if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_anchor(); return; } method_declaration->declaration.source_position = source_position; method_declaration->declaration.symbol = token.v.symbol; next_token(); parse_method(&method_declaration->method); add_declaration((declaration_t*) method_declaration); } static void parse_global_variable(void) { eat(T_var); variable_declaration_t *variable = allocate_ast_zero(sizeof(variable[0])); variable->declaration.type = DECLARATION_VARIABLE; variable->is_global = 1; if(token.type == T_extern) { next_token(); variable->is_extern = 1; } if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_anchor(); return; } variable->declaration.source_position = source_position; variable->declaration.symbol = token.v.symbol; next_token(); if(token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_anchor(); } else { next_token(); variable->type = parse_type(); expect(T_NEWLINE, end_error); } end_error: add_declaration((declaration_t*) variable); } static void parse_constant(void) { eat(T_const); constant_t *constant = allocate_ast_zero(sizeof(constant[0])); constant->declaration.type = DECLARATION_CONSTANT; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_anchor(); return; } constant->declaration.source_position = source_position; constant->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); constant->type = parse_type(); } expect('=', end_error); constant->expression = parse_expression(); expect(T_NEWLINE, end_error); end_error: add_declaration((declaration_t*) constant); } static void parse_typealias(void) { eat(T_typealias); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); expect('=', end_error); typealias->type = parse_type(); expect(T_NEWLINE, end_error); end_error: add_declaration((declaration_t*) typealias); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if(token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if(token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if(parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if(parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while(token.type == '$') { attribute_t *attribute = parse_attribute(); if(attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_class(void) { eat(T_class); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing class", T_IDENTIFIER, 0); eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_CLASS; compound_type->symbol = typealias->declaration.symbol; compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if(token.type == T_INDENT) { next_token(); context_t *last_context = current_context; current_context = &compound_type->context; while(token.type != T_EOF && token.type != T_DEDENT) { parse_declaration(); } next_token(); assert(current_context == &compound_type->context); current_context = last_context; } end_error: add_declaration((declaration_t*) typealias); } static void parse_struct(void) { eat(T_struct); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->symbol = typealias->declaration.symbol; if(token.type == '<') { next_token(); compound_type->type_parameters = parse_type_parameters(&compound_type->context); expect('>', end_error); } compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if(token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration((declaration_t*) typealias); end_error: ; } static void parse_union(void) { eat(T_union); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->symbol = typealias->declaration.symbol; compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; expect(':', end_error); expect(T_NEWLINE, end_error); if(token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } end_error: add_declaration((declaration_t*) typealias); } static concept_method_t *parse_concept_method(void) { expect(T_func, end_error); concept_method_t *method = allocate_ast_zero(sizeof(method[0])); method->declaration.type = DECLARATION_CONCEPT_METHOD; method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); memset(method_type, 0, sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } method->declaration.source_position = source_position; method->declaration.symbol = token.v.symbol; next_token(); expect('(', end_error); parse_parameter_declaration(method_type, &method->parameters); expect(')', end_error); if(token.type == ':') { next_token(); method_type->result_type = parse_type(); } else { method_type->result_type = type_void; } expect(T_NEWLINE, end_error); method->method_type = method_type; add_declaration((declaration_t*) method); return method; end_error: return NULL; } static void parse_concept(void) { eat(T_concept); concept_t *concept = allocate_ast_zero(sizeof(concept[0])); concept->declaration.type = DECLARATION_CONCEPT; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_anchor(); return; } concept->declaration.source_position = source_position; concept->declaration.symbol = token.v.symbol; next_token(); if(token.type == '<') { next_token(); context_t *context = &concept->context; concept->type_parameters = parse_type_parameters(context); expect('>', end_error); } expect(':', end_error); expect(T_NEWLINE, end_error); if(token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_method_t *last_method = NULL; while(token.type != T_DEDENT) { if(token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_method_t *method = parse_concept_method(); method->concept = concept; if(last_method != NULL) { last_method->next = method; } else { concept->methods = method; } last_method = method; } next_token(); end_of_parse_concept: add_declaration((declaration_t*) concept); return; end_error: ; } static concept_method_instance_t *parse_concept_method_instance(void) { concept_method_instance_t *method_instance = allocate_ast_zero(sizeof(method_instance[0])); expect(T_func, end_error); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method " "instance", T_IDENTIFIER, 0); eat_until_anchor(); goto end_error; } method_instance->source_position = source_position; method_instance->symbol = token.v.symbol; next_token(); parse_method(& method_instance->method); return method_instance; end_error: return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if(token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect('>', end_error); } instance->type_arguments = parse_type_arguments(); expect(':', end_error); expect(T_NEWLINE, end_error); if(token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_method_instance_t *last_method = NULL; while(token.type != T_DEDENT) { if(token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if(token.type == T_NEWLINE) { next_token(); continue; } concept_method_instance_t *method = parse_concept_method_instance(); if(method == NULL) continue; if(last_method != NULL) { last_method->next = method; } else { instance->method_instances = method; } last_method = method; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; return; end_error: ; } static void skip_declaration(void) { next_token(); } static void parse_export(void) { eat(T_export); while(1) { if(token.type == T_NEWLINE) { break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export declaration", T_IDENTIFIER, 0); eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if(token.type != ',') { break; } next_token(); } expect(T_NEWLINE, end_error); end_error: ; } void parse_declaration(void) { if(token.type < 0) { if(token.type == T_EOF) return; /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) parser = declaration_parsers[token.type]; if(parser == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_anchor(); return; } if(parser != NULL) { parser(); } } static namespace_t *get_namespace(symbol_t *symbol) { /* search for an existing namespace */ namespace_t *namespace = namespaces; while(namespace != NULL) { if(namespace->symbol == symbol) return namespace; namespace = namespace->next; } namespace = allocate_ast_zero(sizeof(namespace[0])); namespace->symbol = symbol; namespace->next = namespaces; namespaces = namespace; return namespace; } static namespace_t *parse_namespace(void) { symbol_t *namespace_symbol = NULL; /* parse namespace name */ if(token.type == T_namespace) { next_token(); if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing namespace", T_IDENTIFIER, 0); eat_until_anchor(); } namespace_symbol = token.v.symbol; next_token(); if(token.type != T_NEWLINE) { parse_error("extra tokens after namespace definition"); eat_until_anchor(); } else { next_token(); } } namespace_t *namespace = get_namespace(namespace_symbol); assert(current_context == NULL); current_context = &namespace->context; /* parse namespace entries */ while(token.type != T_EOF) { parse_declaration(); } assert(current_context == &namespace->context); current_context = NULL; return namespace; } static void register_declaration_parsers(void) { register_declaration_parser(parse_method_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_class, T_class); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); register_declaration_parser(skip_declaration, T_NEWLINE); } namespace_t *parse(FILE *in, const char *input_name) { - lexer_init(in, input_name); + memset(token_anchor_set, 0, sizeof(token_anchor_set)); + lexer_init(in, input_name); next_token(); + add_anchor_token(T_EOF); + namespace_t *namespace = parse_namespace(); namespace->filename = input_name; + rem_anchor_token(T_EOF); + +#ifndef NDEBUG + for (int i = 0; i < T_LAST_TOKEN; ++i) { + if (token_anchor_set[i] > 0) { + panic("leaked token"); + } + } +#endif + lexer_destroy(); if(error) { fprintf(stderr, "syntax errors found...\n"); return NULL; } return namespace; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); } diff --git a/token_t.h b/token_t.h index 49a4578..6a003bb 100644 --- a/token_t.h +++ b/token_t.h @@ -1,35 +1,35 @@ #ifndef TOKEN_T_H #define TOKEN_T_H #include <stdio.h> #include "symbol.h" #include "symbol_table.h" typedef enum { + T_ERROR = -1, + T_EOF = '\x04', // EOT #define T(x,str,val) T_##x val, #define TS(x,str,val) T_##x val, #include "tokens.inc" #undef TS #undef T - T_EOF = -1, - T_ERROR = -2 } token_type_t; typedef struct { int type; union { symbol_t *symbol; int intvalue; const char *string; } v; } token_t; void init_tokens(void); void exit_tokens(void); void print_token_type(FILE *out, token_type_t token_type); void print_token(FILE *out, const token_t *token); int register_new_token(const char *token); #endif
MatzeB/fluffy
4474ad433daacd37907e3aa5763f9eacdc47a85f
improve error reporting
diff --git a/TODO b/TODO index 8bf17d2..bd15400 100644 --- a/TODO +++ b/TODO @@ -1,38 +1,38 @@ This does not describe the goals and visions but short term things that should not be forgotten and are not done yet because I was lazy or did not decide about the right way to do it yet. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - correct pointer arithmetic - A typeof operator (resulting in the type of the enclosed expression) - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime - fix ++ and -- expressions - forbid same variable names in nested blocks - change firm to pass on debug info on unitialized_variable callback - improve expect_macro behaviour (see cparser) - introduce error type, error expression (see cparser) Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Use more firm optimisations - Create an eccp like wrapper script - Add an alloca operator - create a ++ and -- operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) Refactorings: - make unions for declaration_t, expression_t, type_t (see cparser) - rename type to kind, expression->datatype to expression->type - keep typerefs as long as possible (start the skip_typeref madness similar to cparser) - +- change coding style if (, while ( diff --git a/ast_t.h b/ast_t.h index 20cc1ec..46554da 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,433 +1,434 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; /** * Operator precedence classes */ typedef enum precedence_t { PREC_BOTTOM, PREC_ASSIGNMENT, PREC_LAZY_OR, PREC_LAZY_AND, PREC_OR, PREC_XOR, PREC_AND, PREC_EQUALITY, PREC_RELATIONAL, PREC_ADDITIVE, PREC_MULTIPLICATIVE, PREC_CAST, PREC_UNARY, PREC_POSTFIX, PREC_TOP } precedence_t; typedef enum { DECLARATION_INVALID, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; struct iterator_declaration_t { declaration_t declaration; method_t method; }; typedef enum { EXPR_INVALID = 0, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, + STATEMENT_ERROR, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/parser.c b/parser.c index 9c53fd5..5ad0c37 100644 --- a/parser.c +++ b/parser.c @@ -1,2188 +1,2336 @@ #include <config.h> #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR //#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; +static unsigned char token_anchor_set[T_LAST_TOKEN]; + static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } -static inline -void eat(token_type_t type) +static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } -static inline -void parser_found_error(void) +static void add_anchor_token(int token_type) +{ + assert(0 <= token_type && token_type < T_LAST_TOKEN); + ++token_anchor_set[token_type]; +} + +#if 0 +static int save_and_reset_anchor_state(int token_type) +{ + assert(0 <= token_type && token_type < T_LAST_TOKEN); + int count = token_anchor_set[token_type]; + token_anchor_set[token_type] = 0; + return count; +} + +static void restore_anchor_state(int token_type, int count) +{ + assert(0 <= token_type && token_type < T_LAST_TOKEN); + token_anchor_set[token_type] = count; +} +#endif + +static void rem_anchor_token(int token_type) +{ + assert(0 <= token_type && token_type < T_LAST_TOKEN); + assert(token_anchor_set[token_type] != 0); + --token_anchor_set[token_type]; +} + +static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if(message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while(token_type != 0) { if(first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if(token.type != T_INDENT) return; next_token(); unsigned indent = 1; while(indent >= 1) { if(token.type == T_INDENT) { indent++; } else if(token.type == T_DEDENT) { indent--; } else if(token.type == T_EOF) { break; } next_token(); } } /** - * error recovery: try to got to the next line. If the current line ends in ':' - * then we skip blocks that might follow + * eats nested brace groups */ -static void eat_until_newline(void) -{ - int prev = -1; +static void eat_until_matching_token(int type) +{ + int end_token; + switch (type) { + case '(': end_token = ')'; break; + case '{': end_token = '}'; break; + case '[': end_token = ']'; break; + default: end_token = type; break; + } + + unsigned parenthesis_count = 0; + unsigned brace_count = 0; + unsigned bracket_count = 0; + while (token.type != end_token || + parenthesis_count != 0 || + brace_count != 0 || + bracket_count != 0) { + switch (token.type) { + case T_EOF: return; + case '(': ++parenthesis_count; break; + case '{': ++brace_count; break; + case '[': ++bracket_count; break; + + case ')': + if (parenthesis_count > 0) + --parenthesis_count; + goto check_stop; + + case '}': + if (brace_count > 0) + --brace_count; + goto check_stop; + + case ']': + if (bracket_count > 0) + --bracket_count; +check_stop: + if (token.type == end_token && + parenthesis_count == 0 && + brace_count == 0 && + bracket_count == 0) + return; + break; - while(token.type != T_NEWLINE) { - prev = token.type; + default: + break; + } next_token(); - if(token.type == T_EOF) - return; } - next_token(); +} - if(prev == ':') { - maybe_eat_block(); +/** + * Eat input tokens until an anchor is found. + */ +static void eat_until_anchor(void) +{ + while (token_anchor_set[token.type] == 0) { + if (token.type == '(' || token.type == '{' || token.type == '[') + eat_until_matching_token(token.type); + if (token.type == ':') { + next_token(); + if (!token_anchor_set[token.type] == 0) { + maybe_eat_block(); + } + } else { + next_token(); + } } } -#define expect(expected) \ - if(UNLIKELY(token.type != (expected))) { \ - parse_error_expected(NULL, (expected), 0); \ - eat_until_newline(); \ - return NULL; \ - } \ - next_token(); - -#define expect_void(expected) \ - if(UNLIKELY(token.type != (expected))) { \ - parse_error_expected(NULL, (expected), 0); \ - eat_until_newline(); \ - return; \ - } \ - next_token(); - +#define expect(expected, error_label) \ + do { \ + if(UNLIKELY(token.type != (expected))) { \ + parse_error_expected(NULL, (expected), 0); \ + add_anchor_token(expected); \ + eat_until_anchor(); \ + if (token.type == expected) \ + next_token(); \ + rem_anchor_token(expected); \ + goto error_label; \ + } \ + next_token(); \ + } while (0) static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch(token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch(token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch(token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { - eat(T_typeof); - expect('('); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; + + eat(T_typeof); + expect('(', end_error); typeof_type->expression = parse_expression(); - expect(')'); + expect(')', end_error); +end_error: return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); type_ref->type_arguments = parse_type_arguments(); - expect('>'); + expect('>', end_error); } +end_error: return (type_t*) type_ref; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; - expect('('); + expect('(', end_error); parse_parameter_declaration(method_type, NULL); - expect(')'); - - expect(':'); + expect(')', end_error); + expect(':', end_error); method_type->result_type = parse_type(); +end_error: return (type_t*) method_type; } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); - eat_until_newline(); continue; } entry->symbol = token.v.symbol; next_token(); - expect(':'); + expect(':', end_error); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); } +end_error: return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); - expect(':'); - expect(T_NEWLINE); - expect(T_INDENT); + expect(':', end_error); + expect(T_NEWLINE, end_error); + expect(T_INDENT, end_error); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); +end_error: return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); - expect(':'); - expect(T_NEWLINE); - expect(T_INDENT); + expect(':', end_error); + expect(T_NEWLINE, end_error); + expect(T_INDENT, end_error); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); +end_error: return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } +static type_t *parse_brace_type(void) +{ + eat('('); + type_t *type = parse_type(); + expect(')', end_error); + +end_error: + return type; +} + type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': - next_token(); - type = parse_type(); - expect(')'); + type = parse_brace_type(); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ - array_type_t *array_type; - while(1) { + while (true) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); - expect(']'); + expect(']', end_error); break; } - array_type = allocate_type_zero(sizeof(array_type[0])); + array_type_t *array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; - expect(']'); + expect(']', end_error); break; } default: return type; } } + +end_error: + return type; } static expression_t *parse_string_const(void) { string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(void) { int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(void) { eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(void) { eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(void) { eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(void) { eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(void) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); ref->type_arguments = parse_type_arguments(); - expect('>'); + expect('>', end_error); } +end_error: return (expression_t*) ref; } static expression_t *parse_sizeof(void) { eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; - expect('<'); + expect('<', end_error); expression->type = parse_type(); - expect('>'); + expect('>', end_error); +end_error: return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_brace_expression(void) { eat('('); - expression_t *result = parse_expression(); + expect(')', end_error); - expect(')'); - +end_error: return result; } static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; - expect('<'); + expect('<', end_error); unary_expression->expression.datatype = parse_type(); - expect('>'); + expect('>', end_error); unary_expression->value = parse_sub_expression(PREC_CAST); +end_error: return (expression_t*) unary_expression; } static expression_t *parse_call_expression(expression_t *expression) { call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } - expect(')'); + expect(')', end_error); +end_error: return (expression_t*) call; } static expression_t *parse_select_expression(expression_t *compound) { eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(expression_t *array_ref) { eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ static expression_t *parse_##binexpression_type(expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(prec_r); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } #define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); register_expression_parser(parse_UNEXPR_NEGATE, '-'); register_expression_parser(parse_UNEXPR_NOT, '!'); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); register_expression_parser(parse_UNEXPR_DEREFERENCE, '*'); register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&'); register_expression_parser(parse_cast_expression, T_cast); register_expression_parser(parse_brace_expression, '('); register_expression_parser(parse_sizeof, T_sizeof); register_expression_parser(parse_int_const, T_INTEGER); register_expression_parser(parse_true, T_true); register_expression_parser(parse_false, T_false); register_expression_parser(parse_string_const, T_STRING_LITERAL); register_expression_parser(parse_null, T_null); register_expression_parser(parse_reference, T_IDENTIFIER); register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; left = parser->infix_parser(left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); +end_error: return (statement_t*) return_statement; } +static statement_t *create_error_statement(void) +{ + statement_t *statement = allocate_ast_zero(sizeof(statement[0])); + statement->type = STATEMENT_ERROR; + return statement; +} + static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); - eat_until_newline(); - return NULL; + eat_until_anchor(); + goto end_error; } goto_statement->label_symbol = token.v.symbol; next_token(); - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); return (statement_t*) goto_statement; + +end_error: + return create_error_statement(); } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); - eat_until_newline(); - return NULL; + eat_until_anchor(); + goto end_error; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); return (statement_t*) label; + +end_error: + return create_error_statement(); } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); - expect(':'); + expect(':', end_error); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if(token.type == T_else) { next_token(); if(token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; if_statement->condition = condition; if_statement->true_statement = true_statement; if_statement->false_statement = false_statement; return (statement_t*) if_statement; + +end_error: + return create_error_statement(); } static statement_t *parse_initial_assignment(symbol_t *symbol) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = symbol; binary_expression_t *assign = allocate_ast_zero(sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.source_position = source_position; assign->type = BINEXPR_ASSIGN; assign->left = (expression_t*) ref; assign->right = parse_expression(); expression_statement_t *expr_statement = allocate_ast_zero(sizeof(expr_statement[0])); expr_statement->statement.type = STATEMENT_EXPRESSION; expr_statement->expression = (expression_t*) assign; return (statement_t*) expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while(1) { if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); - eat_until_newline(); - return NULL; + eat_until_anchor(); + goto end_error; } variable_declaration_statement_t *declaration_statement = allocate_ast_zero(sizeof(declaration_statement[0])); declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; declaration_t *declaration = &declaration_statement->declaration.declaration; declaration->type = DECLARATION_VARIABLE; declaration->source_position = source_position; declaration->symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &declaration_statement->declaration; if(token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if(last_statement != NULL) { last_statement->next = (statement_t*) declaration_statement; } else { first_statement = (statement_t*) declaration_statement; } last_statement = (statement_t*) declaration_statement; /* do we have an assignment expression? */ if(token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->symbol); last_statement->next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if(token.type != ',') break; next_token(); } - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); + +end_error: return first_statement; } static statement_t *parse_expression_statement(void) { expression_statement_t *expression_statement = allocate_ast_zero(sizeof(expression_statement[0])); expression_statement->statement.type = STATEMENT_EXPRESSION; expression_statement->expression = parse_expression(); - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); +end_error: return (statement_t*) expression_statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if(token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; if(token.type < 0) { /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing statement", T_DEDENT, 0); return NULL; } parse_statement_function parser = NULL; if(token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; if(parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if(declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } if(statement == NULL) return NULL; statement->source_position = start; statement_t *next = statement->next; while(next != NULL) { next->source_position = start; next = next->next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; context_t *last_context = current_context; current_context = &block->context; statement_t *last_statement = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { /* parse statement */ statement_t *statement = parse_statement(); if(statement == NULL) continue; if(last_statement != NULL) { last_statement->next = statement; } else { block->statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while(last_statement->next != NULL) last_statement = last_statement->next; } assert(current_context == &block->context); current_context = last_context; block->end_position = source_position; - expect(T_DEDENT); + expect(T_DEDENT, end_error); +end_error: return (statement_t*) block; } static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); if(token.type == ')') return; method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if(parameters != NULL) *parameters = NULL; while(1) { if(token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if(token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); - eat_until_newline(); + eat_until_anchor(); return; } break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } symbol_t *symbol = token.v.symbol; next_token(); - expect_void(':'); + expect(':', end_error); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if(last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if(parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.type = DECLARATION_METHOD_PARAMETER; method_param->declaration.symbol = symbol; method_param->declaration.source_position = source_position; method_param->type = param_type->type; if(last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if(token.type != ',') break; next_token(); } + +end_error: + ; } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while(token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if(last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static type_variable_t *parse_type_parameter(void) { type_variable_t *type_variable = allocate_ast_zero(sizeof(type_variable[0])); type_variable->declaration.type = DECLARATION_TYPE_VARIABLE; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return NULL; } type_variable->declaration.source_position = source_position; type_variable->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); type_variable->constraints = parse_type_constraints(); } return type_variable; } static type_variable_t *parse_type_parameters(context_t *context) { type_variable_t *first_variable = NULL; type_variable_t *last_variable = NULL; while(1) { type_variable_t *type_variable = parse_type_parameter(); if(last_variable != NULL) { last_variable->next = type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if(context != NULL) { declaration_t *declaration = & type_variable->declaration; declaration->next = context->declarations; context->declarations = declaration; } if(token.type != ',') break; next_token(); } return first_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->source_position.input_name != NULL); assert(current_context != NULL); declaration->next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if(token.type == '<') { next_token(); method->type_parameters = parse_type_parameters(current_context); - expect_void('>'); + expect('>', end_error); } - expect_void('('); + expect('(', end_error); parse_parameter_declaration(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { declaration_t *declaration = (declaration_t*) parameter; declaration->next = current_context->declarations; current_context->declarations = declaration; parameter = parameter->next; } - expect_void(')'); + expect(')', end_error); method_type->result_type = type_void; if(token.type == ':') { next_token(); if(token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } method_type->result_type = parse_type(); if(token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } - expect_void(T_NEWLINE); + expect(T_NEWLINE, end_error); method_parser_end: assert(current_context == &method->context); current_context = last_context; + +end_error: + ; } static void parse_method_declaration(void) { eat(T_func); method_declaration_t *method_declaration = allocate_ast_zero(sizeof(method_declaration[0])); method_declaration->declaration.type = DECLARATION_METHOD; if(token.type == T_extern) { method_declaration->method.is_extern = 1; next_token(); } if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } method_declaration->declaration.source_position = source_position; method_declaration->declaration.symbol = token.v.symbol; next_token(); parse_method(&method_declaration->method); add_declaration((declaration_t*) method_declaration); } static void parse_global_variable(void) { eat(T_var); variable_declaration_t *variable = allocate_ast_zero(sizeof(variable[0])); variable->declaration.type = DECLARATION_VARIABLE; variable->is_global = 1; if(token.type == T_extern) { next_token(); variable->is_extern = 1; } if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } variable->declaration.source_position = source_position; variable->declaration.symbol = token.v.symbol; next_token(); if(token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); - eat_until_newline(); + eat_until_anchor(); } else { next_token(); variable->type = parse_type(); - expect_void(T_NEWLINE); + expect(T_NEWLINE, end_error); } +end_error: add_declaration((declaration_t*) variable); } static void parse_constant(void) { eat(T_const); constant_t *constant = allocate_ast_zero(sizeof(constant[0])); constant->declaration.type = DECLARATION_CONSTANT; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } constant->declaration.source_position = source_position; constant->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); constant->type = parse_type(); } - expect_void('='); + expect('=', end_error); constant->expression = parse_expression(); - expect_void(T_NEWLINE); + expect(T_NEWLINE, end_error); + +end_error: add_declaration((declaration_t*) constant); } static void parse_typealias(void) { eat(T_typealias); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); - expect_void('='); + expect('=', end_error); typealias->type = parse_type(); + expect(T_NEWLINE, end_error); - expect_void(T_NEWLINE); +end_error: add_declaration((declaration_t*) typealias); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if(token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if(token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if(parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if(parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while(token.type == '$') { attribute_t *attribute = parse_attribute(); if(attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_class(void) { eat(T_class); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing class", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_CLASS; compound_type->symbol = typealias->declaration.symbol; compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; - expect_void(':'); - expect_void(T_NEWLINE); + expect(':', end_error); + expect(T_NEWLINE, end_error); if(token.type == T_INDENT) { next_token(); context_t *last_context = current_context; current_context = &compound_type->context; while(token.type != T_EOF && token.type != T_DEDENT) { parse_declaration(); } next_token(); assert(current_context == &compound_type->context); current_context = last_context; } +end_error: add_declaration((declaration_t*) typealias); } static void parse_struct(void) { eat(T_struct); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->symbol = typealias->declaration.symbol; if(token.type == '<') { next_token(); compound_type->type_parameters = parse_type_parameters(&compound_type->context); - expect_void('>'); + expect('>', end_error); } compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; - expect_void(':'); - expect_void(T_NEWLINE); + expect(':', end_error); + expect(T_NEWLINE, end_error); if(token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration((declaration_t*) typealias); + +end_error: + ; } static void parse_union(void) { eat(T_union); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->symbol = typealias->declaration.symbol; compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; - expect_void(':'); - expect_void(T_NEWLINE); + expect(':', end_error); + expect(T_NEWLINE, end_error); if(token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } +end_error: add_declaration((declaration_t*) typealias); } static concept_method_t *parse_concept_method(void) { - expect(T_func); + expect(T_func, end_error); concept_method_t *method = allocate_ast_zero(sizeof(method[0])); method->declaration.type = DECLARATION_CONCEPT_METHOD; method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); memset(method_type, 0, sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method", T_IDENTIFIER, 0); - eat_until_newline(); - return NULL; + eat_until_anchor(); + goto end_error; } method->declaration.source_position = source_position; method->declaration.symbol = token.v.symbol; next_token(); - expect('('); + expect('(', end_error); parse_parameter_declaration(method_type, &method->parameters); - expect(')'); + expect(')', end_error); if(token.type == ':') { next_token(); method_type->result_type = parse_type(); } else { method_type->result_type = type_void; } - expect(T_NEWLINE); + expect(T_NEWLINE, end_error); method->method_type = method_type; add_declaration((declaration_t*) method); return method; + +end_error: + return NULL; } static void parse_concept(void) { eat(T_concept); concept_t *concept = allocate_ast_zero(sizeof(concept[0])); concept->declaration.type = DECLARATION_CONCEPT; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } concept->declaration.source_position = source_position; concept->declaration.symbol = token.v.symbol; next_token(); if(token.type == '<') { next_token(); context_t *context = &concept->context; concept->type_parameters = parse_type_parameters(context); - expect_void('>'); + expect('>', end_error); } - expect_void(':'); - expect_void(T_NEWLINE); + expect(':', end_error); + expect(T_NEWLINE, end_error); if(token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_method_t *last_method = NULL; while(token.type != T_DEDENT) { if(token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_method_t *method = parse_concept_method(); method->concept = concept; if(last_method != NULL) { last_method->next = method; } else { concept->methods = method; } last_method = method; } next_token(); end_of_parse_concept: add_declaration((declaration_t*) concept); + return; + +end_error: + ; } static concept_method_instance_t *parse_concept_method_instance(void) { concept_method_instance_t *method_instance = allocate_ast_zero(sizeof(method_instance[0])); - expect(T_func); + expect(T_func, end_error); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method " "instance", T_IDENTIFIER, 0); - eat_until_newline(); - return NULL; + eat_until_anchor(); + goto end_error; } method_instance->source_position = source_position; method_instance->symbol = token.v.symbol; next_token(); parse_method(& method_instance->method); - return method_instance; + +end_error: + return NULL; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } instance->concept_symbol = token.v.symbol; next_token(); if(token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); - expect_void('>'); + expect('>', end_error); } instance->type_arguments = parse_type_arguments(); - expect_void(':'); - expect_void(T_NEWLINE); + expect(':', end_error); + expect(T_NEWLINE, end_error); if(token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_method_instance_t *last_method = NULL; while(token.type != T_DEDENT) { if(token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if(token.type == T_NEWLINE) { next_token(); continue; } concept_method_instance_t *method = parse_concept_method_instance(); if(method == NULL) continue; if(last_method != NULL) { last_method->next = method; } else { instance->method_instances = method; } last_method = method; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; + return; + +end_error: + ; } static void skip_declaration(void) { next_token(); } static void parse_export(void) { eat(T_export); while(1) { if(token.type == T_NEWLINE) { break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export declaration", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if(token.type != ',') { break; } next_token(); } - expect_void(T_NEWLINE); + expect(T_NEWLINE, end_error); + +end_error: + ; } void parse_declaration(void) { if(token.type < 0) { if(token.type == T_EOF) return; /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) parser = declaration_parsers[token.type]; if(parser == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); - eat_until_newline(); + eat_until_anchor(); return; } if(parser != NULL) { parser(); } } static namespace_t *get_namespace(symbol_t *symbol) { /* search for an existing namespace */ namespace_t *namespace = namespaces; while(namespace != NULL) { if(namespace->symbol == symbol) return namespace; namespace = namespace->next; } namespace = allocate_ast_zero(sizeof(namespace[0])); namespace->symbol = symbol; namespace->next = namespaces; namespaces = namespace; return namespace; } static namespace_t *parse_namespace(void) { symbol_t *namespace_symbol = NULL; /* parse namespace name */ if(token.type == T_namespace) { next_token(); if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing namespace", T_IDENTIFIER, 0); - eat_until_newline(); + eat_until_anchor(); } namespace_symbol = token.v.symbol; next_token(); if(token.type != T_NEWLINE) { parse_error("extra tokens after namespace definition"); - eat_until_newline(); + eat_until_anchor(); } else { next_token(); } } namespace_t *namespace = get_namespace(namespace_symbol); assert(current_context == NULL); current_context = &namespace->context; /* parse namespace entries */ while(token.type != T_EOF) { parse_declaration(); } assert(current_context == &namespace->context); current_context = NULL; return namespace; } static void register_declaration_parsers(void) { register_declaration_parser(parse_method_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_class, T_class); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); register_declaration_parser(skip_declaration, T_NEWLINE); } namespace_t *parse(FILE *in, const char *input_name) { lexer_init(in, input_name); next_token(); namespace_t *namespace = parse_namespace(); namespace->filename = input_name; lexer_destroy(); if(error) { fprintf(stderr, "syntax errors found...\n"); return NULL; } return namespace; } void init_parser(void) { expression_parsers = NEW_ARR_F(expression_parse_function_t, 0); statement_parsers = NEW_ARR_F(parse_statement_function, 0); declaration_parsers = NEW_ARR_F(parse_declaration_function, 0); attribute_parsers = NEW_ARR_F(parse_attribute_function, 0); register_expression_parsers(); register_statement_parsers(); register_declaration_parsers(); } void exit_parser(void) { DEL_ARR_F(attribute_parsers); DEL_ARR_F(declaration_parsers); DEL_ARR_F(expression_parsers); DEL_ARR_F(statement_parsers); } diff --git a/plugins/api.fluffy b/plugins/api.fluffy index 60214be..5373d83 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,374 +1,375 @@ struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: type : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: type : unsigned int datatype : Type* source_position : SourcePosition struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 -const STATEMENT_BLOCK = 1 -const STATEMENT_RETURN = 2 -const STATEMENT_VARIABLE_DECLARATION = 3 -const STATEMENT_IF = 4 -const STATEMENT_EXPRESSION = 5 -const STATEMENT_GOTO = 6 -const STATEMENT_LABEL = 7 +const STATEMENT_ERROR = 1 +const STATEMENT_BLOCK = 2 +const STATEMENT_RETURN = 3 +const STATEMENT_VARIABLE_DECLARATION = 4 +const STATEMENT_IF = 5 +const STATEMENT_EXPRESSION = 6 +const STATEMENT_GOTO = 7 +const STATEMENT_LABEL = 8 const TYPE_INVALID = 0 const TYPE_VOID = 1 const TYPE_ATOMIC = 2 const TYPE_COMPOUND_STRUCT = 3 const TYPE_COMPOUND_UNION = 4 const TYPE_METHOD = 5 const TYPE_POINTER = 6 const TYPE_ARRAY = 7 const TYPE_REFERENCE = 8 const TYPE_REFERENCE_TYPE_VARIABLE = 9 const DECLARATION_INVALID = 0 const DECLARATION_METHOD = 1 const DECLARATION_METHOD_PARAMETER = 2 const DECLARATION_VARIABLE = 3 const DECLARATION_CONSTANT = 4 const DECLARATION_TYPE_VARIABLE = 5 const DECLARATION_TYPEALIAS = 6 const DECLARATION_TYPECLASS = 7 const DECLARATION_TYPECLASS_METHOD = 8 const DECLARATION_LABEL = 9 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const EXPR_INVALID = 0 const EXPR_INT_CONST = 1 const EXPR_FLOAT_CONST = 2 const EXPR_BOOL_CONST = 3 const EXPR_STRING_CONST = 4 const EXPR_NULL_POINTER = 5 const EXPR_REFERENCE = 6 const EXPR_CALL = 7 const EXPR_UNARY = 8 const EXPR_BINARY = 9 const BINEXPR_INVALID = 0 const BINEXPR_ASSIGN = 1 const BINEXPR_ADD = 2 const T_EOF = -1 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 const T_ASSIGN = 296 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* typealias ParseExpressionFunction = func () : Expression* typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.statement.type = STATEMENT_LABEL res.declaration.declaration.type = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.declaration.type = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() res.expression.type = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() res.expression.type = EXPR_INT_CONST return res func api_init(): stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): declaration.next = context.declarations context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label diff --git a/test/quicktest.sh b/test/quicktest.sh index 2216c2b..949651b 100755 --- a/test/quicktest.sh +++ b/test/quicktest.sh @@ -1,13 +1,14 @@ #!/bin/bash TEMPOUT="/tmp/fluffytest.txt" for i in *.fluffy; do echo -n "$i..." ../fluffy $i ./a.out >& "$TEMPOUT" || echo "(return status != 0)" if ! diff "$TEMPOUT" "expected_output/$i.output" > /dev/null; then echo "FAIL" else echo "" fi done +rm -f a.out
MatzeB/fluffy
13ed8fd107ad1c2405caa12fbf582b10962c0d81
simplify expression parsing precedence handling, fix left-right right-left associativity
diff --git a/ast_t.h b/ast_t.h index af1d3ea..20cc1ec 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,412 +1,433 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; +/** + * Operator precedence classes + */ +typedef enum precedence_t { + PREC_BOTTOM, + PREC_ASSIGNMENT, + PREC_LAZY_OR, + PREC_LAZY_AND, + PREC_OR, + PREC_XOR, + PREC_AND, + PREC_EQUALITY, + PREC_RELATIONAL, + PREC_ADDITIVE, + PREC_MULTIPLICATIVE, + PREC_CAST, + PREC_UNARY, + PREC_POSTFIX, + PREC_TOP +} precedence_t; + typedef enum { DECLARATION_INVALID, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; struct iterator_declaration_t { declaration_t declaration; method_t method; }; typedef enum { EXPR_INVALID = 0, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/parser.c b/parser.c index d19f231..9c53fd5 100644 --- a/parser.c +++ b/parser.c @@ -23,1524 +23,1499 @@ static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if(message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while(token_type != 0) { if(first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if(token.type != T_INDENT) return; next_token(); unsigned indent = 1; while(indent >= 1) { if(token.type == T_INDENT) { indent++; } else if(token.type == T_DEDENT) { indent--; } else if(token.type == T_EOF) { break; } next_token(); } } /** * error recovery: try to got to the next line. If the current line ends in ':' * then we skip blocks that might follow */ static void eat_until_newline(void) { int prev = -1; while(token.type != T_NEWLINE) { prev = token.type; next_token(); if(token.type == T_EOF) return; } next_token(); if(prev == ':') { maybe_eat_block(); } } #define expect(expected) \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ eat_until_newline(); \ return NULL; \ } \ next_token(); #define expect_void(expected) \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ eat_until_newline(); \ return; \ } \ next_token(); static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch(token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch(token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch(token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_typeof(void) { eat(T_typeof); expect('('); typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); typeof_type->type.type = TYPE_TYPEOF; typeof_type->expression = parse_expression(); expect(')'); return (type_t*) typeof_type; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); type_ref->type_arguments = parse_type_arguments(); expect('>'); } return (type_t*) type_ref; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('('); parse_parameter_declaration(method_type, NULL); expect(')'); expect(':'); method_type->result_type = parse_type(); return (type_t*) method_type; } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); eat_until_newline(); continue; } entry->symbol = token.v.symbol; next_token(); expect(':'); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE); } return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':'); expect(T_NEWLINE); expect(T_INDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':'); expect(T_NEWLINE); expect(T_INDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_typeof: type = parse_typeof(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': next_token(); type = parse_type(); expect(')'); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ array_type_t *array_type; while(1) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); expect(']'); break; } array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; expect(']'); break; } default: return type; } } } -static expression_t *parse_string_const(unsigned precedence) +static expression_t *parse_string_const(void) { - (void) precedence; - string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } -static expression_t *parse_int_const(unsigned precedence) +static expression_t *parse_int_const(void) { - (void) precedence; - int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } -static expression_t *parse_true(unsigned precedence) +static expression_t *parse_true(void) { - (void) precedence; eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } -static expression_t *parse_false(unsigned precedence) +static expression_t *parse_false(void) { - (void) precedence; eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } -static expression_t *parse_null(unsigned precedence) +static expression_t *parse_null(void) { - (void) precedence; - eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } -static expression_t *parse_func_expression(unsigned precedence) +static expression_t *parse_func_expression(void) { - (void) precedence; - eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } -static expression_t *parse_reference(unsigned precedence) +static expression_t *parse_reference(void) { - (void) precedence; - reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); ref->type_arguments = parse_type_arguments(); expect('>'); } return (expression_t*) ref; } -static expression_t *parse_sizeof(unsigned precedence) +static expression_t *parse_sizeof(void) { - (void) precedence; - eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; expect('<'); expression->type = parse_type(); expect('>'); return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, - int token_type, unsigned precedence) + int token_type) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; - entry->precedence = precedence; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } -static expression_t *parse_brace_expression(unsigned precedence) +static expression_t *parse_brace_expression(void) { - (void) precedence; - eat('('); expression_t *result = parse_expression(); expect(')'); return result; } -static expression_t *parse_cast_expression(unsigned precedence) +static expression_t *parse_cast_expression(void) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<'); unary_expression->expression.datatype = parse_type(); expect('>'); - unary_expression->value = parse_sub_expression(precedence); + unary_expression->value = parse_sub_expression(PREC_CAST); return (expression_t*) unary_expression; } -static expression_t *parse_call_expression(unsigned precedence, - expression_t *expression) +static expression_t *parse_call_expression(expression_t *expression) { - (void) precedence; call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } expect(')'); return (expression_t*) call; } -static expression_t *parse_select_expression(unsigned precedence, - expression_t *compound) +static expression_t *parse_select_expression(expression_t *compound) { - (void) precedence; - eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } -static expression_t *parse_array_expression(unsigned precedence, - expression_t *array_ref) +static expression_t *parse_array_expression(expression_t *array_ref) { - (void) precedence; - eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ -static \ -expression_t *parse_##unexpression_type(unsigned precedence) \ +static expression_t *parse_##unexpression_type(void) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ - unary_expression->value = parse_sub_expression(precedence); \ + unary_expression->value = parse_sub_expression(PREC_UNARY); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) -#define CREATE_BINEXPR_PARSER(token_type, binexpression_type) \ -static \ -expression_t *parse_##binexpression_type(unsigned precedence, \ - expression_t *left) \ -{ \ - eat(token_type); \ - \ - expression_t *right = parse_sub_expression(precedence); \ - \ - binary_expression_t *binexpr \ - = allocate_ast_zero(sizeof(binexpr[0])); \ - binexpr->expression.type = EXPR_BINARY; \ - binexpr->type = binexpression_type; \ - binexpr->left = left; \ - binexpr->right = right; \ - \ - return (expression_t*) binexpr; \ -} - -CREATE_BINEXPR_PARSER('*', BINEXPR_MUL); -CREATE_BINEXPR_PARSER('/', BINEXPR_DIV); -CREATE_BINEXPR_PARSER('%', BINEXPR_MOD); -CREATE_BINEXPR_PARSER('+', BINEXPR_ADD); -CREATE_BINEXPR_PARSER('-', BINEXPR_SUB); -CREATE_BINEXPR_PARSER('<', BINEXPR_LESS); -CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER); -CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL); -CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN); -CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_NOTEQUAL); -CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL); -CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL); -CREATE_BINEXPR_PARSER('&', BINEXPR_AND); -CREATE_BINEXPR_PARSER('|', BINEXPR_OR); -CREATE_BINEXPR_PARSER('^', BINEXPR_XOR); -CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LAZY_AND); -CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LAZY_OR); -CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT); -CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT); +#define CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r) \ +static expression_t *parse_##binexpression_type(expression_t *left) \ +{ \ + eat(token_type); \ + \ + expression_t *right = parse_sub_expression(prec_r); \ + \ + binary_expression_t *binexpr \ + = allocate_ast_zero(sizeof(binexpr[0])); \ + binexpr->expression.type = EXPR_BINARY; \ + binexpr->type = binexpression_type; \ + binexpr->left = left; \ + binexpr->right = right; \ + \ + return (expression_t*) binexpr; \ +} + +#define CREATE_BINEXPR_PARSER_LR(token_type, binexpression_type, prec_r) \ + CREATE_BINEXPR_PARSER_RL(token_type, binexpression_type, prec_r+1) + +CREATE_BINEXPR_PARSER_LR('*', BINEXPR_MUL, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('/', BINEXPR_DIV, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('%', BINEXPR_MOD, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR('+', BINEXPR_ADD, PREC_ADDITIVE); +CREATE_BINEXPR_PARSER_LR('-', BINEXPR_SUB, PREC_ADDITIVE); +CREATE_BINEXPR_PARSER_LR('<', BINEXPR_LESS, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR('>', BINEXPR_GREATER, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR(T_EQUALEQUAL, BINEXPR_EQUAL, PREC_EQUALITY); +CREATE_BINEXPR_PARSER_RL('=', BINEXPR_ASSIGN, PREC_ASSIGNMENT); +CREATE_BINEXPR_PARSER_LR(T_SLASHEQUAL, BINEXPR_NOTEQUAL, PREC_EQUALITY); +CREATE_BINEXPR_PARSER_LR(T_LESSEQUAL, BINEXPR_LESSEQUAL, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR(T_GREATEREQUAL, BINEXPR_GREATEREQUAL, PREC_RELATIONAL); +CREATE_BINEXPR_PARSER_LR('&', BINEXPR_AND, PREC_AND); +CREATE_BINEXPR_PARSER_LR('|', BINEXPR_OR, PREC_OR); +CREATE_BINEXPR_PARSER_LR('^', BINEXPR_XOR, PREC_XOR); +CREATE_BINEXPR_PARSER_LR(T_ANDAND, BINEXPR_LAZY_AND, PREC_LAZY_AND); +CREATE_BINEXPR_PARSER_LR(T_PIPEPIPE, BINEXPR_LAZY_OR, PREC_LAZY_OR); +CREATE_BINEXPR_PARSER_LR(T_LESSLESS, BINEXPR_SHIFTLEFT, PREC_MULTIPLICATIVE); +CREATE_BINEXPR_PARSER_LR(T_GREATERGREATER, BINEXPR_SHIFTRIGHT, PREC_MULTIPLICATIVE); static void register_expression_parsers(void) { - register_expression_infix_parser(parse_BINEXPR_MUL, '*', 16); - register_expression_infix_parser(parse_BINEXPR_DIV, '/', 16); - register_expression_infix_parser(parse_BINEXPR_MOD, '%', 16); + register_expression_infix_parser(parse_BINEXPR_MUL, '*', PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_BINEXPR_DIV, '/', PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_BINEXPR_MOD, '%', PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, - T_LESSLESS, 16); + T_LESSLESS, PREC_MULTIPLICATIVE); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, - T_GREATERGREATER, 16); - register_expression_infix_parser(parse_BINEXPR_ADD, '+', 15); - register_expression_infix_parser(parse_BINEXPR_SUB, '-', 15); - register_expression_infix_parser(parse_BINEXPR_LESS, '<', 14); - register_expression_infix_parser(parse_BINEXPR_GREATER, '>', 14); - register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, 14); + T_GREATERGREATER, PREC_MULTIPLICATIVE); + register_expression_infix_parser(parse_BINEXPR_ADD, '+', PREC_ADDITIVE); + register_expression_infix_parser(parse_BINEXPR_SUB, '-', PREC_ADDITIVE); + register_expression_infix_parser(parse_BINEXPR_LESS, '<', PREC_RELATIONAL); + register_expression_infix_parser(parse_BINEXPR_GREATER, '>', PREC_RELATIONAL); + register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, - T_GREATEREQUAL, 14); - register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, 13); - register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, 13); - register_expression_infix_parser(parse_BINEXPR_AND, '&', 12); - register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, 12); - register_expression_infix_parser(parse_BINEXPR_XOR, '^', 11); - register_expression_infix_parser(parse_BINEXPR_OR, '|', 10); - register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, 10); - register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', 2); - - register_expression_infix_parser(parse_array_expression, '[', 25); - - register_expression_infix_parser(parse_call_expression, '(', 30); - register_expression_infix_parser(parse_select_expression, '.', 30); - - register_expression_parser(parse_UNEXPR_NEGATE, '-', 25); - register_expression_parser(parse_UNEXPR_NOT, '!', 25); - register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~', 25); - register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS, 25); - register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS, 25); - - register_expression_parser(parse_UNEXPR_DEREFERENCE, '*', 20); - register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&', 20); - register_expression_parser(parse_cast_expression, T_cast, 19); - - register_expression_parser(parse_brace_expression, '(', 1); - register_expression_parser(parse_sizeof, T_sizeof, 1); - register_expression_parser(parse_int_const, T_INTEGER, 1); - register_expression_parser(parse_true, T_true, 1); - register_expression_parser(parse_false, T_false, 1); - register_expression_parser(parse_string_const, T_STRING_LITERAL, 1); - register_expression_parser(parse_null, T_null, 1); - register_expression_parser(parse_reference, T_IDENTIFIER, 1); - register_expression_parser(parse_func_expression, T_func, 1); + T_GREATEREQUAL, PREC_RELATIONAL); + register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, PREC_EQUALITY); + register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, PREC_EQUALITY); + register_expression_infix_parser(parse_BINEXPR_AND, '&', PREC_AND); + register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, PREC_LAZY_AND); + register_expression_infix_parser(parse_BINEXPR_XOR, '^', PREC_XOR); + register_expression_infix_parser(parse_BINEXPR_OR, '|', PREC_OR); + register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, PREC_LAZY_OR); + register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', PREC_ASSIGNMENT); + + register_expression_infix_parser(parse_array_expression, '[', PREC_POSTFIX); + + register_expression_infix_parser(parse_call_expression, '(', PREC_POSTFIX); + register_expression_infix_parser(parse_select_expression, '.', PREC_POSTFIX); + + register_expression_parser(parse_UNEXPR_NEGATE, '-'); + register_expression_parser(parse_UNEXPR_NOT, '!'); + register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~'); + register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS); + register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS); + + register_expression_parser(parse_UNEXPR_DEREFERENCE, '*'); + register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&'); + register_expression_parser(parse_cast_expression, T_cast); + + register_expression_parser(parse_brace_expression, '('); + register_expression_parser(parse_sizeof, T_sizeof); + register_expression_parser(parse_int_const, T_INTEGER); + register_expression_parser(parse_true, T_true); + register_expression_parser(parse_false, T_false); + register_expression_parser(parse_string_const, T_STRING_LITERAL); + register_expression_parser(parse_null, T_null); + register_expression_parser(parse_reference, T_IDENTIFIER); + register_expression_parser(parse_func_expression, T_func); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { - left = parser->parser(parser->precedence); + left = parser->parser(); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; - left = parser->infix_parser(parser->infix_precedence, left); + left = parser->infix_parser(left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE); return (statement_t*) return_statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE); return (statement_t*) goto_statement; } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE); return (statement_t*) label; } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':'); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if(token.type == T_else) { next_token(); if(token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; if_statement->condition = condition; if_statement->true_statement = true_statement; if_statement->false_statement = false_statement; return (statement_t*) if_statement; } static statement_t *parse_initial_assignment(symbol_t *symbol) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = symbol; binary_expression_t *assign = allocate_ast_zero(sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.source_position = source_position; assign->type = BINEXPR_ASSIGN; assign->left = (expression_t*) ref; assign->right = parse_expression(); expression_statement_t *expr_statement = allocate_ast_zero(sizeof(expr_statement[0])); expr_statement->statement.type = STATEMENT_EXPRESSION; expr_statement->expression = (expression_t*) assign; return (statement_t*) expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while(1) { if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } variable_declaration_statement_t *declaration_statement = allocate_ast_zero(sizeof(declaration_statement[0])); declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; declaration_t *declaration = &declaration_statement->declaration.declaration; declaration->type = DECLARATION_VARIABLE; declaration->source_position = source_position; declaration->symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &declaration_statement->declaration; if(token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if(last_statement != NULL) { last_statement->next = (statement_t*) declaration_statement; } else { first_statement = (statement_t*) declaration_statement; } last_statement = (statement_t*) declaration_statement; /* do we have an assignment expression? */ if(token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->symbol); last_statement->next = assign; last_statement = assign; } /* check if we have more declared symbols separated by ',' */ if(token.type != ',') break; next_token(); } expect(T_NEWLINE); return first_statement; } static statement_t *parse_expression_statement(void) { expression_statement_t *expression_statement = allocate_ast_zero(sizeof(expression_statement[0])); expression_statement->statement.type = STATEMENT_EXPRESSION; expression_statement->expression = parse_expression(); expect(T_NEWLINE); return (statement_t*) expression_statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if(token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; if(token.type < 0) { /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing statement", T_DEDENT, 0); return NULL; } parse_statement_function parser = NULL; if(token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; if(parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if(declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } if(statement == NULL) return NULL; statement->source_position = start; statement_t *next = statement->next; while(next != NULL) { next->source_position = start; next = next->next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; context_t *last_context = current_context; current_context = &block->context; statement_t *last_statement = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { /* parse statement */ statement_t *statement = parse_statement(); if(statement == NULL) continue; if(last_statement != NULL) { last_statement->next = statement; } else { block->statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while(last_statement->next != NULL) last_statement = last_statement->next; } assert(current_context == &block->context); current_context = last_context; block->end_position = source_position; expect(T_DEDENT); return (statement_t*) block; } static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); if(token.type == ')') return; method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if(parameters != NULL) *parameters = NULL; while(1) { if(token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if(token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_newline(); return; } break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_newline(); return; } symbol_t *symbol = token.v.symbol; next_token(); expect_void(':'); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if(last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if(parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.type = DECLARATION_METHOD_PARAMETER; method_param->declaration.symbol = symbol; method_param->declaration.source_position = source_position; method_param->type = param_type->type; if(last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if(token.type != ',') break; next_token(); } } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while(token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if(last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static type_variable_t *parse_type_parameter(void) { type_variable_t *type_variable = allocate_ast_zero(sizeof(type_variable[0])); type_variable->declaration.type = DECLARATION_TYPE_VARIABLE; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } type_variable->declaration.source_position = source_position; type_variable->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); type_variable->constraints = parse_type_constraints(); } return type_variable; } static type_variable_t *parse_type_parameters(context_t *context) { type_variable_t *first_variable = NULL; type_variable_t *last_variable = NULL; while(1) { type_variable_t *type_variable = parse_type_parameter(); if(last_variable != NULL) { last_variable->next = type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if(context != NULL) { declaration_t *declaration = & type_variable->declaration; declaration->next = context->declarations; context->declarations = declaration; } if(token.type != ',') break; next_token(); } return first_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->source_position.input_name != NULL); assert(current_context != NULL); declaration->next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if(token.type == '<') { next_token(); method->type_parameters = parse_type_parameters(current_context); expect_void('>'); } expect_void('('); parse_parameter_declaration(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { declaration_t *declaration = (declaration_t*) parameter; declaration->next = current_context->declarations; current_context->declarations = declaration; parameter = parameter->next; } expect_void(')'); method_type->result_type = type_void; if(token.type == ':') { next_token(); diff --git a/parser_t.h b/parser_t.h index 630c11c..11bbda2 100644 --- a/parser_t.h +++ b/parser_t.h @@ -1,55 +1,53 @@ #ifndef PARSER_T_H #define PARSER_T_H #include "parser.h" #include <assert.h> #include "token_t.h" #include "lexer.h" #include "type.h" -typedef expression_t* (*parse_expression_function) (unsigned precedence); -typedef expression_t* (*parse_expression_infix_function) (unsigned precedence, - expression_t *left); +typedef expression_t* (*parse_expression_function) (void); +typedef expression_t* (*parse_expression_infix_function) (expression_t *left); typedef statement_t* (*parse_statement_function) (void); typedef void (*parse_declaration_function) (void); typedef attribute_t* (*parse_attribute_function) (void); typedef struct expression_parse_function_t { - unsigned precedence; parse_expression_function parser; unsigned infix_precedence; parse_expression_infix_function infix_parser; } expression_parse_function_t; extern token_t token; void register_expression_parser(parse_expression_function parser, - int token_type, unsigned precedence); + int token_type); void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence); void register_statement_parser(parse_statement_function parser, int token_type); void register_declaration_parser(parse_declaration_function parser, int token_type); void register_attribute_parser(parse_attribute_function parser, int token_type); expression_t *parse_sub_expression(unsigned precedence); void add_declaration(declaration_t *entry); void parser_print_error_prefix(void); expression_t *parse_expression(void); statement_t *parse_statement(void); type_t *parse_type(void); void parse_declaration(void); attribute_t *parse_attributes(void); void next_token(void); #endif diff --git a/plugins/api.fluffy b/plugins/api.fluffy index a7a7da7..60214be 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,376 +1,374 @@ struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: type : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: type : unsigned int datatype : Type* source_position : SourcePosition struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... const STATEMENT_INAVLID = 0 const STATEMENT_BLOCK = 1 const STATEMENT_RETURN = 2 const STATEMENT_VARIABLE_DECLARATION = 3 const STATEMENT_IF = 4 const STATEMENT_EXPRESSION = 5 const STATEMENT_GOTO = 6 const STATEMENT_LABEL = 7 const TYPE_INVALID = 0 const TYPE_VOID = 1 const TYPE_ATOMIC = 2 const TYPE_COMPOUND_STRUCT = 3 const TYPE_COMPOUND_UNION = 4 const TYPE_METHOD = 5 const TYPE_POINTER = 6 const TYPE_ARRAY = 7 const TYPE_REFERENCE = 8 const TYPE_REFERENCE_TYPE_VARIABLE = 9 const DECLARATION_INVALID = 0 const DECLARATION_METHOD = 1 const DECLARATION_METHOD_PARAMETER = 2 const DECLARATION_VARIABLE = 3 const DECLARATION_CONSTANT = 4 const DECLARATION_TYPE_VARIABLE = 5 const DECLARATION_TYPEALIAS = 6 const DECLARATION_TYPECLASS = 7 const DECLARATION_TYPECLASS_METHOD = 8 const DECLARATION_LABEL = 9 const ATOMIC_TYPE_INVALID = 0 const ATOMIC_TYPE_BOOL = 1 const ATOMIC_TYPE_BYTE = 2 const ATOMIC_TYPE_UBYTE = 3 const ATOMIC_TYPE_SHORT = 4 const ATOMIC_TYPE_USHORT = 5 const ATOMIC_TYPE_INT = 6 const ATOMIC_TYPE_UINT = 7 const ATOMIC_TYPE_LONG = 8 const ATOMIC_TYPE_ULONG = 9 const EXPR_INVALID = 0 const EXPR_INT_CONST = 1 const EXPR_FLOAT_CONST = 2 const EXPR_BOOL_CONST = 3 const EXPR_STRING_CONST = 4 const EXPR_NULL_POINTER = 5 const EXPR_REFERENCE = 6 const EXPR_CALL = 7 const EXPR_UNARY = 8 const EXPR_BINARY = 9 const BINEXPR_INVALID = 0 const BINEXPR_ASSIGN = 1 const BINEXPR_ADD = 2 const T_EOF = -1 const T_NEWLINE = 256 const T_INDENT = 257 const T_DEDENT = 258 const T_IDENTIFIER = 259 const T_INTEGER = 260 const T_STRING_LITERAL = 261 const T_ASSIGN = 296 typealias FILE = void typealias EnvironmentEntry = void typealias IrNode = void typealias IrType = void typealias IrEntity = void typealias ParseStatementFunction = func () : Statement* typealias ParseAttributeFunction = func () : Attribute* -typealias ParseExpressionFunction = func (precedence : unsigned int) : Expression* -typealias ParseExpressionInfixFunction = func (precedence : unsigned int, \ - left : Expression*) : Expression* +typealias ParseExpressionFunction = func () : Expression* +typealias ParseExpressionInfixFunction = func (left : Expression*) : Expression* typealias LowerStatementFunction = func (statement : Statement*) : Statement* typealias LowerExpressionFunction = func (expression : Expression*) : Expression* typealias ParseDeclarationFunction = func() : void typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ - token_type : int, \ - precedence : unsigned int) + token_type : int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: var res = allocate_zero<$BlockStatement>() res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: var res = allocate_zero<$IfStatement>() res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: var res = allocate_zero<$ExpressionStatement>() res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: var res = allocate_zero<$GotoStatement>() res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: var res = allocate_zero<$LabelStatement>() res.statement.type = STATEMENT_LABEL res.declaration.declaration.type = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: var res = allocate_zero<$Constant>() res.declaration.type = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: var res = allocate_zero<$BinaryExpression>() res.expression.type = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: var res = allocate_zero<$IntConst>() res.expression.type = EXPR_INT_CONST return res func api_init(): stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): declaration.next = context.declarations context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): var statement = block.statements if block.statements == null: block.statements = append return :label if statement.next == null: statement.next = append return statement = statement.next goto label diff --git a/test/typeof.fluffy b/test/typeof.fluffy index 64001f1..7cf2929 100644 --- a/test/typeof.fluffy +++ b/test/typeof.fluffy @@ -1,7 +1,7 @@ var k : int func main() : int: k = 42 var l : typeof(k) = 22 - return (cast<typeof(l)>(k) - l) - 20 + return cast<typeof(l)>(k) - l - 20 export main
MatzeB/fluffy
f2677e983c9631215abc726bfd53436fcb4b55c7
crude not complete implementation of typeof type
diff --git a/TODO b/TODO index f72a452..8bf17d2 100644 --- a/TODO +++ b/TODO @@ -1,28 +1,38 @@ + + This does not describe the goals and visions but short term things that should not be forgotten and are not done yet because I was lazy or did not decide about the right way to do it yet. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - correct pointer arithmetic - A typeof operator (resulting in the type of the enclosed expression) - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime - fix ++ and -- expressions - forbid same variable names in nested blocks - change firm to pass on debug info on unitialized_variable callback +- improve expect_macro behaviour (see cparser) +- introduce error type, error expression (see cparser) Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Use more firm optimisations - Create an eccp like wrapper script - Add an alloca operator - create a ++ and -- operator - make lexer accept \r, \r\n and \n as newline - make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) + +Refactorings: +- make unions for declaration_t, expression_t, type_t (see cparser) +- rename type to kind, expression->datatype to expression->type +- keep typerefs as long as possible (start the skip_typeref madness similar to cparser) + diff --git a/ast.c b/ast.c index a4035e2..7709867 100644 --- a/ast.c +++ b/ast.c @@ -1,681 +1,681 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; namespace_t *namespaces; static FILE *out; static int indent = 0; -static void print_expression(const expression_t *expression); static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for(const char *c = string_const->value; *c != 0; ++c) { switch(*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while(argument != NULL) { if(!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while(argument != NULL) { if(first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(argument->type); argument = argument->next; } if(type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if(ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if(select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch(unexpr->type) { case UNEXPR_CAST: fprintf(out, "cast<"); print_type(unexpr->expression.datatype); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->type); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch(binexpr->type) { case BINEXPR_INVALID: fprintf(out, "INVOP"); break; case BINEXPR_ASSIGN: fprintf(out, "<-"); break; case BINEXPR_ADD: fprintf(out, "+"); break; case BINEXPR_SUB: fprintf(out, "-"); break; case BINEXPR_MUL: fprintf(out, "*"); break; case BINEXPR_DIV: fprintf(out, "/"); break; case BINEXPR_NOTEQUAL: fprintf(out, "/="); break; case BINEXPR_EQUAL: fprintf(out, "="); break; case BINEXPR_LESS: fprintf(out, "<"); break; case BINEXPR_LESSEQUAL: fprintf(out, "<="); break; case BINEXPR_GREATER: fprintf(out, ">"); break; case BINEXPR_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->type); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if(expression == NULL) { fprintf(out, "*null expression*"); return; } switch(expression->type) { case EXPR_LAST: case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; case EXPR_BINARY: print_binary_expression((const binary_expression_t*) expression); break; case EXPR_UNARY: print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; default: /* TODO */ fprintf(out, "some expression of type %d", expression->type); break; } } static void print_indent(void) { for(int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while(statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if(statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if(statement->label != NULL) { symbol_t *symbol = statement->label->declaration.symbol; if(symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.declaration.symbol; if(symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if(statement->true_statement != NULL) print_statement(statement->true_statement); if(statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if(var->type != NULL) { fprintf(out, "<"); print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->declaration.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch(statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if(constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->declaration.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->declaration.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while(type_parameter != NULL) { if(first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if(type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while(parameter != NULL && parameter_type != NULL) { if(!first) { fprintf(out, ", "); } else { first = 0; } print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if(method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->declaration.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->declaration.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->declaration.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while(method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if(method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->declaration.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(method_instance->method.type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if(instance->concept != NULL) { fprintf(out, "%s", instance->concept->declaration.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->declaration.symbol->string); if(constant->type != NULL) { fprintf(out, " "); print_type(constant->type); } if(constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->declaration.symbol->string); print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch(declaration->type) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: // TODO fprintf(out, "some declaration of type %d\n", declaration->type); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%d)\n", declaration->type); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { print_declaration(declaration); declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { print_concept_instance(instance); instance = instance->next; } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_type_name(declaration_type_t type) { switch(type) { case DECLARATION_LAST: case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { + out = stderr; obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } diff --git a/ast.h b/ast.h index 8bffef8..d904611 100644 --- a/ast.h +++ b/ast.h @@ -1,60 +1,61 @@ #ifndef AST_H #define AST_H #include <stdio.h> typedef struct attribute_t attribute_t; typedef struct declaration_t declaration_t; typedef struct context_t context_t; typedef struct export_t export_t; typedef struct expression_t expression_t; typedef struct int_const_t int_const_t; typedef struct float_const_t float_const_t; typedef struct string_const_t string_const_t; typedef struct bool_const_t bool_const_t; typedef struct null_pointer_t null_pointer_t; typedef struct cast_expression_t cast_expression_t; typedef struct reference_expression_t reference_expression_t; typedef struct call_argument_t call_argument_t; typedef struct call_expression_t call_expression_t; typedef struct binary_expression_t binary_expression_t; typedef struct unary_expression_t unary_expression_t; typedef struct select_expression_t select_expression_t; typedef struct array_access_expression_t array_access_expression_t; typedef struct sizeof_expression_t sizeof_expression_t; typedef struct func_expression_t func_expression_t; typedef struct statement_t statement_t; typedef struct block_statement_t block_statement_t; typedef struct return_statement_t return_statement_t; typedef struct if_statement_t if_statement_t; typedef struct variable_declaration_t variable_declaration_t; typedef struct variable_declaration_statement_t variable_declaration_statement_t; typedef struct expression_statement_t expression_statement_t; typedef struct goto_statement_t goto_statement_t; typedef struct label_declaration_t label_declaration_t; typedef struct label_statement_t label_statement_t; typedef struct namespace_t namespace_t; typedef struct method_parameter_t method_parameter_t; typedef struct method_t method_t; typedef struct method_declaration_t method_declaration_t; typedef struct constant_t constant_t; typedef struct global_variable_t global_variable_t; typedef struct typealias_t typealias_t; typedef struct concept_instance_t concept_instance_t; typedef struct concept_method_instance_t concept_method_instance_t; typedef struct concept_t concept_t; typedef struct concept_method_t concept_method_t; void init_ast_module(void); void exit_ast_module(void); void print_ast(FILE *out, const namespace_t *namespace); +void print_expression(const expression_t *expression); void *allocate_ast(size_t size); #endif diff --git a/ast2firm.c b/ast2firm.c index 07268cc..eff1b99 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1804 +1,1816 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_method_t instantiate_method_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_method_t { method_t *method; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_methods; static pdeq *instantiate_methods = NULL; static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = & value_numbers[pos]->declaration; print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if(pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if(pos == NULL) return NULL; if(line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.type.type = TYPE_ATOMIC; byte_type.atype = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch(type->atype) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if(type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch(type->type) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); + case TYPE_TYPEOF: { + const typeof_type_t *typeof_type = (const typeof_type_t*) type; + return get_type_size(typeof_type->expression->datatype); + } case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); + case TYPE_ERROR: + return 0; case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while(param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if(result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while(param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if(method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); set_array_bounds_int(ir_type, 0, 0, type->size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if(elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, type->size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if(symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while(entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if(symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while(entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; while(declaration != NULL) { if(declaration->type == DECLARATION_METHOD) { /* TODO */ continue; } if(declaration->type != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; ident *ident = new_id_from_str(declaration->symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } declaration = declaration->next; } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if(current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->declaration.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if(type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch(type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; + case TYPE_TYPEOF: { + typeof_type_t *typeof_type = (typeof_type_t*) type; + firm_type = get_ir_type(typeof_type->expression->datatype); + break; + } case TYPE_REFERENCE: panic("unresolved reference type found"); break; + case TYPE_ERROR: case TYPE_INVALID: break; } if(firm_type == NULL) panic("unknown type found"); if(env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if(method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; start_mangle(); mangle_concept_name(concept->declaration.symbol); mangle_symbol(concept_method->declaration.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; for ( ; argument != NULL; argument = argument->next) { mangle_type(argument->type); } ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if(!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } start_mangle(); mangle_symbol_simple(symbol); if(is_polymorphic) { type_variable_t *type_variable = method->type_parameters; for ( ; type_variable != NULL; type_variable = type_variable->next) { mangle_type(type_variable->current_type); } } ident *id = finish_mangle(); /* search for an existing entity */ if(is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for(int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if(get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if(method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if(!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if(is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if(!is_polymorphic) { method->e.entity = entity; } else { if(method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if(cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for(size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if(select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if(variable->entity != NULL) return variable->entity; ir_type *parent_type; if(variable->is_global) { parent_type = get_glob_type(); } else if(variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if(variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if(variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if(variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch(declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; switch(expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if(dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { switch(type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { switch(type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if(compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; switch(unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if(entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, - type_argument_t *type_arguments) + type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if(strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while(type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if(last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if(instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if(method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while(argument != NULL) { n_parameters++; argument = argument->next; } if(method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while(argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if(new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if(new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if(result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if(entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch(expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if(statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if(statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while(statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if(block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if(statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch(statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if(method->is_extern) return; int old_top = typevar_binding_stack_top(); if(is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if(method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if(get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while(label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; diff --git a/ast_t.h b/ast_t.h index 542c5d7..af1d3ea 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,413 +1,412 @@ #ifndef AST_T_H #define AST_T_H #include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; typedef enum { DECLARATION_INVALID, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; bool export; bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; struct iterator_declaration_t { declaration_t declaration; method_t method; }; typedef enum { EXPR_INVALID = 0, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; - typedef enum { STATEMENT_INVALID, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; bool is_extern; bool export; bool is_global; bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/mangle.c b/mangle.c index fb29521..544d032 100644 --- a/mangle.c +++ b/mangle.c @@ -1,222 +1,229 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" #include "type_t.h" #include "adt/error.h" #include <libfirm/firm.h> #include "driver/firm_cmdline.h" static struct obstack obst; static void mangle_string(const char *str) { size_t len = strlen(str); obstack_grow(&obst, str, len); } static void mangle_len_string(const char *string) { size_t len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); } static void mangle_atomic_type(const atomic_type_t *type) { char c; switch(type->atype) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(&obst, c); } static void mangle_type_variables(type_variable_t *type_variables) { type_variable_t *type_variable = type_variables; for( ; type_variable != NULL; type_variable = type_variable->next) { /* is this a good char? */ obstack_1grow(&obst, 'T'); mangle_type(type_variable->current_type); } } static void mangle_compound_type(const compound_type_t *type) { mangle_len_string(type->symbol->string); mangle_type_variables(type->type_parameters); } static void mangle_pointer_type(const pointer_type_t *type) { obstack_1grow(&obst, 'P'); mangle_type(type->points_to); } static void mangle_array_type(const array_type_t *type) { obstack_1grow(&obst, 'A'); mangle_type(type->element_type); obstack_printf(&obst, "%lu", type->size); } static void mangle_method_type(const method_type_t *type) { obstack_1grow(&obst, 'F'); mangle_type(type->result_type); method_parameter_type_t *parameter_type = type->parameter_types; while(parameter_type != NULL) { mangle_type(parameter_type->type); } obstack_1grow(&obst, 'E'); } static void mangle_reference_type_variable(const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if(current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(current_type); } static void mangle_bind_typevariables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); mangle_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void mangle_type(const type_t *type) { switch(type->type) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(&obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type((const atomic_type_t*) type); return; + case TYPE_TYPEOF: { + const typeof_type_t *typeof_type = (const typeof_type_t*) type; + mangle_type(typeof_type->expression->datatype); + return; + } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: mangle_method_type((const method_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: mangle_bind_typevariables((const bind_typevariables_type_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable((const type_reference_t*) type); return; + case TYPE_ERROR: + panic("trying to mangle error type"); } panic("Unknown type mangled"); } void mangle_symbol_simple(symbol_t *symbol) { mangle_string(symbol->string); } void mangle_symbol(symbol_t *symbol) { mangle_len_string(symbol->string); } void mangle_concept_name(symbol_t *symbol) { obstack_grow(&obst, "tcv", 3); mangle_len_string(symbol->string); } void start_mangle(void) { if (firm_opt.os_support == OS_SUPPORT_MACHO || firm_opt.os_support == OS_SUPPORT_MINGW) { obstack_1grow(&obst, '_'); } } ident *finish_mangle(void) { size_t size = obstack_object_size(&obst); char *str = obstack_finish(&obst); ident *id = new_id_from_chars(str, size); obstack_free(&obst, str); return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/match_type.c b/match_type.c index dca76ec..21569c9 100644 --- a/match_type.c +++ b/match_type.c @@ -1,228 +1,234 @@ #include <config.h> #include "match_type.h" #include <assert.h> #include "type_t.h" #include "ast_t.h" #include "semantic_t.h" #include "type_hash.h" #include "adt/error.h" static inline void match_error(type_t *variant, type_t *concrete, const source_position_t source_position) { print_error_prefix(source_position); fprintf(stderr, "can't match variant type "); print_type(variant); fprintf(stderr, " against "); print_type(concrete); fprintf(stderr, "\n"); } static bool matched_type_variable(type_variable_t *type_variable, type_t *type, const source_position_t source_position, bool report_errors) { type_t *current_type = type_variable->current_type; if(current_type != NULL && current_type != type) { if (report_errors) { print_error_prefix(source_position); fprintf(stderr, "ambiguous matches found for type variable '%s': ", type_variable->declaration.symbol->string); print_type(current_type); fprintf(stderr, ", "); print_type(type); fprintf(stderr, "\n"); } /* are both types normalized? */ assert(typehash_contains(current_type)); assert(typehash_contains(type)); return false; } type_variable->current_type = type; return true; } static bool match_compound_type(compound_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_variable_t *type_parameters = variant_type->type_parameters; if(type_parameters == NULL) { if(concrete_type != (type_t*) variant_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } return true; } if(concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if(polymorphic_type != variant_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = bind_typevariables->type_arguments; bool result = true; while(type_parameter != NULL) { assert(type_argument != NULL); if(!matched_type_variable(type_parameter, type_argument->type, source_position, true)) result = false; type_parameter = type_parameter->next; type_argument = type_argument->next; } return result; } static bool match_bind_typevariables(bind_typevariables_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { if(concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if(polymorphic_type != variant_type->polymorphic_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_argument_t *argument1 = variant_type->type_arguments; type_argument_t *argument2 = bind_typevariables->type_arguments; bool result = true; while(argument1 != NULL) { assert(argument2 != NULL); if(!match_variant_to_concrete_type(argument1->type, argument2->type, source_position, report_errors)) result = false; argument1 = argument1->next; argument2 = argument2->next; } assert(argument2 == NULL); return result; } bool match_variant_to_concrete_type(type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_reference_t *type_ref; type_variable_t *type_var; pointer_type_t *pointer_type_1; pointer_type_t *pointer_type_2; method_type_t *method_type_1; method_type_t *method_type_2; assert(type_valid(variant_type)); assert(type_valid(concrete_type)); + variant_type = skip_typeref(variant_type); + concrete_type = skip_typeref(concrete_type); + switch(variant_type->type) { case TYPE_REFERENCE_TYPE_VARIABLE: type_ref = (type_reference_t*) variant_type; type_var = type_ref->type_variable; return matched_type_variable(type_var, concrete_type, source_position, report_errors); case TYPE_VOID: case TYPE_ATOMIC: if(concrete_type != variant_type) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } return true; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return match_compound_type((compound_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_POINTER: if(concrete_type->type != TYPE_POINTER) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } pointer_type_1 = (pointer_type_t*) variant_type; pointer_type_2 = (pointer_type_t*) concrete_type; return match_variant_to_concrete_type(pointer_type_1->points_to, pointer_type_2->points_to, source_position, report_errors); case TYPE_METHOD: if(concrete_type->type != TYPE_METHOD) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } method_type_1 = (method_type_t*) variant_type; method_type_2 = (method_type_t*) concrete_type; bool result = match_variant_to_concrete_type(method_type_1->result_type, method_type_2->result_type, source_position, report_errors); method_parameter_type_t *param1 = method_type_1->parameter_types; method_parameter_type_t *param2 = method_type_2->parameter_types; while(param1 != NULL && param2 != NULL) { if(!match_variant_to_concrete_type(param1->type, param2->type, source_position, report_errors)) result = false; param1 = param1->next; param2 = param2->next; } if(param1 != NULL || param2 != NULL) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return result; case TYPE_BIND_TYPEVARIABLES: return match_bind_typevariables( (bind_typevariables_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_ARRAY: panic("TODO"); + case TYPE_ERROR: + return false; + case TYPE_TYPEOF: case TYPE_REFERENCE: panic("type reference not resolved in match variant to concrete type"); case TYPE_INVALID: panic("invalid type in match variant to concrete type"); } panic("unknown type in match variant to concrete type"); } diff --git a/parser.c b/parser.c index eeb00bf..d19f231 100644 --- a/parser.c +++ b/parser.c @@ -1,959 +1,974 @@ #include <config.h> #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR -//////////////#define PRINT_TOKENS +//#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if(message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while(token_type != 0) { if(first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if(token.type != T_INDENT) return; next_token(); unsigned indent = 1; while(indent >= 1) { if(token.type == T_INDENT) { indent++; } else if(token.type == T_DEDENT) { indent--; } else if(token.type == T_EOF) { break; } next_token(); } } /** * error recovery: try to got to the next line. If the current line ends in ':' * then we skip blocks that might follow */ static void eat_until_newline(void) { int prev = -1; while(token.type != T_NEWLINE) { prev = token.type; next_token(); if(token.type == T_EOF) return; } next_token(); if(prev == ':') { maybe_eat_block(); } } #define expect(expected) \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ eat_until_newline(); \ return NULL; \ } \ next_token(); #define expect_void(expected) \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ eat_until_newline(); \ return; \ } \ next_token(); static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch(token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch(token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch(token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } +static type_t *parse_typeof(void) +{ + eat(T_typeof); + expect('('); + typeof_type_t *typeof_type = allocate_type_zero(sizeof(typeof_type[0])); + typeof_type->type.type = TYPE_TYPEOF; + typeof_type->expression = parse_expression(); + expect(')'); + + return (type_t*) typeof_type; +} + static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); type_ref->type_arguments = parse_type_arguments(); expect('>'); } return (type_t*) type_ref; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('('); parse_parameter_declaration(method_type, NULL); expect(')'); expect(':'); method_type->result_type = parse_type(); return (type_t*) method_type; } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); eat_until_newline(); continue; } entry->symbol = token.v.symbol; next_token(); expect(':'); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE); } return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':'); expect(T_NEWLINE); expect(T_INDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':'); expect(T_NEWLINE); expect(T_INDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; + case T_typeof: + type = parse_typeof(); + break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': next_token(); type = parse_type(); expect(')'); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ array_type_t *array_type; while(1) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); expect(']'); break; } array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; expect(']'); break; } default: return type; } } } static expression_t *parse_string_const(unsigned precedence) { (void) precedence; string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(unsigned precedence) { (void) precedence; int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(unsigned precedence) { (void) precedence; eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(unsigned precedence) { (void) precedence; eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(unsigned precedence) { (void) precedence; eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(unsigned precedence) { (void) precedence; eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); return (expression_t*) expression; } static expression_t *parse_reference(unsigned precedence) { (void) precedence; reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); ref->type_arguments = parse_type_arguments(); expect('>'); } return (expression_t*) ref; } static expression_t *parse_sizeof(unsigned precedence) { (void) precedence; eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; expect('<'); expression->type = parse_type(); expect('>'); return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; entry->precedence = precedence; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_brace_expression(unsigned precedence) { (void) precedence; eat('('); expression_t *result = parse_expression(); expect(')'); return result; } static expression_t *parse_cast_expression(unsigned precedence) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<'); unary_expression->expression.datatype = parse_type(); expect('>'); unary_expression->value = parse_sub_expression(precedence); return (expression_t*) unary_expression; } static expression_t *parse_call_expression(unsigned precedence, expression_t *expression) { (void) precedence; call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } expect(')'); return (expression_t*) call; } static expression_t *parse_select_expression(unsigned precedence, expression_t *compound) { (void) precedence; eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(unsigned precedence, expression_t *array_ref) { (void) precedence; eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static \ expression_t *parse_##unexpression_type(unsigned precedence) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(precedence); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER(token_type, binexpression_type) \ static \ expression_t *parse_##binexpression_type(unsigned precedence, \ expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(precedence); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } CREATE_BINEXPR_PARSER('*', BINEXPR_MUL); CREATE_BINEXPR_PARSER('/', BINEXPR_DIV); CREATE_BINEXPR_PARSER('%', BINEXPR_MOD); CREATE_BINEXPR_PARSER('+', BINEXPR_ADD); CREATE_BINEXPR_PARSER('-', BINEXPR_SUB); CREATE_BINEXPR_PARSER('<', BINEXPR_LESS); CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER); CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL); CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN); CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_NOTEQUAL); CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL); CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL); CREATE_BINEXPR_PARSER('&', BINEXPR_AND); CREATE_BINEXPR_PARSER('|', BINEXPR_OR); CREATE_BINEXPR_PARSER('^', BINEXPR_XOR); CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LAZY_AND); CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LAZY_OR); CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT); CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', 16); register_expression_infix_parser(parse_BINEXPR_DIV, '/', 16); register_expression_infix_parser(parse_BINEXPR_MOD, '%', 16); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, 16); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, 16); register_expression_infix_parser(parse_BINEXPR_ADD, '+', 15); register_expression_infix_parser(parse_BINEXPR_SUB, '-', 15); register_expression_infix_parser(parse_BINEXPR_LESS, '<', 14); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', 14); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, 14); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, 14); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, 13); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, 13); register_expression_infix_parser(parse_BINEXPR_AND, '&', 12); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, 12); register_expression_infix_parser(parse_BINEXPR_XOR, '^', 11); register_expression_infix_parser(parse_BINEXPR_OR, '|', 10); diff --git a/semantic.c b/semantic.c index bedc7f6..97de7dd 100644 --- a/semantic.c +++ b/semantic.c @@ -1,1621 +1,1639 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; +static type_t *error_type = NULL; + static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if(symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if(new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while(i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if(declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if(type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if(declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while(type_parameter != NULL) { if(type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if(type_argument != NULL) { print_error_prefix(type_ref->source_position); if(type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if(type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if(type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while(entry != NULL) { type_t *type = entry->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if(type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: + case TYPE_ERROR: return type; + case TYPE_TYPEOF: { + typeof_type_t *typeof_type = (typeof_type_t*) type; + typeof_type->expression = check_expression(typeof_type->expression); + return type; + } + case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if(type == NULL) return NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if(constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if(!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if(left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if(left->datatype == NULL) { if(right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if(dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ + dest_type = skip_typeref(dest_type); type_t *from_type = from->datatype; if(from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } + from_type = skip_typeref(from_type); + bool implicit_cast_allowed = true; if(from_type->type == TYPE_POINTER) { if(dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if(p1->points_to != p2->points_to && dest_type != type_void_ptr && from->type != EXPR_NULL_POINTER) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if(dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if(pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if(from_type->type == TYPE_ATOMIC) { if(dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if(!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if(lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if(!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if(left == NULL || right == NULL) return; if(left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if(right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while(argument != NULL && parameter != NULL) { if(parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if(parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if(match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if(match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { if(constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { if(method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while(type_var != NULL) { type_t *current_type = type_var->current_type; if(current_type == NULL) return; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if(!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if(cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if(instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters; while(typevar != NULL) { if(typevar->current_type != NULL) { print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if(method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if(concept == NULL) continue; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if(!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->declaration.symbol->string, concept->declaration.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if(instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->declaration.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->declaration.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if(type == NULL) { return type_int; } + type = skip_typeref(type); + switch(type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); - return type; + return error_type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); - return type; + return error_type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); - return type; + return error_type; + + case TYPE_ERROR: + return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: + case TYPE_TYPEOF: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(type); fprintf(stderr, "\n"); - return type; + return error_type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if(type == NULL) return; /* determine method type */ if(type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if(type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if(method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if(declaration->type == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if(type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while(type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if(type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while(argument != NULL) { if(param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if(param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if(type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if(expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->source_position, lenient); if(new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(expression->datatype); fprintf(stderr, " should be "); print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if(param_type != NULL) param_type = param_type->next; ++i; } if(param_type != NULL) { error_at(call->expression.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while(type_var != NULL) { if(type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->declaration.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->declaration.symbol->string, type_var); print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if(type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if(declaration->type == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->type == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if(ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while(type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if(last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if(cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if(cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if(value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if(value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if(!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if(value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if(type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(unary_expression_t *expression) { expression_t *value = check_expression(expression->value); type_t *type = value->datatype; if(!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); print_type(type); fprintf(stderr, "\n"); } if(!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if(type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if(atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if(need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.type = EXPR_BINARY; add->expression.datatype = type; if(expression->type == UNEXPR_INCREMENT) { add->type = BINEXPR_ADD; } else { add->type = BINEXPR_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.datatype = type; assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static expression_t *lower_unary_expression(expression_t *expression) { assert(expression->type == EXPR_UNARY); unary_expression_t *unary_expression = (unary_expression_t*) expression; switch(unary_expression->type) { case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: return lower_incdec_expression(unary_expression); default: break; } return expression; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch(unary_expression->type) { case UNEXPR_CAST: check_cast_expression(unary_expression); return; case UNEXPR_DEREFERENCE: check_dereference_expression(unary_expression); return; case UNEXPR_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case UNEXPR_NOT: check_not_expression(unary_expression); return; case UNEXPR_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case UNEXPR_NEGATE: check_negate_expression(unary_expression); return; case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("increment/decrement not lowered"); case UNEXPR_INVALID: abort(); } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if(datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if(datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type @@ -2002,545 +2020,546 @@ static void check_goto_statement(goto_statement_t *goto_statement) if(symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if(declaration->type != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_type_name(declaration->type)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if(statement == NULL) return NULL; /* try to lower the statement */ if((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if(lowerer != NULL) { statement = lowerer(statement); } } if(statement == NULL) return NULL; last_statement_was_return = false; switch(statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if(method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while(parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if(method->statement != NULL) { method->statement = check_statement(method->statement); } if(!last_statement_was_return) { type_t *result_type = method->type->result_type; if(result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if(symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if(expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->declaration.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; while(constraint != NULL) { resolve_type_constraint(constraint, type_var->declaration.source_position); constraint = constraint->next; } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while(type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; while(concept_method != NULL) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; concept_method = concept_method->next; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(declaration->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(declaration->source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->declaration.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if(!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_type_name(declaration->type)); return; } found_export = true; } static void check_and_push_context(context_t *context) { variable_declaration_t *variable; method_declaration_t *method; typealias_t *typealias; type_t *type; concept_t *concept; push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->type = normalize_type(variable->type); break; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; resolve_method_types(&method->method); break; case DECLARATION_TYPEALIAS: typealias = (typealias_t*) declaration; type = normalize_type(typealias->type); if(type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } typealias->type = type; break; case DECLARATION_CONCEPT: concept = (concept_t*) declaration; resolve_concept_types(concept); break; default: break; } declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { resolve_concept_instance(instance); instance = instance->next; } /* check semantics in conceptes */ instance = context->concept_instances; while(instance != NULL) { check_concept_instance(instance); instance = instance->next; } /* check semantics in methods */ declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; check_method(&method->method, method->declaration.symbol, method->declaration.source_position); break; case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } declaration = declaration->next; } /* handle export declarations */ export_t *export = context->exports; while(export != NULL) { check_export(export); export = export->next; } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if(statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if(statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if(expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if(expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); + error_type = type_void; namespace_t *namespace = namespaces; while(namespace != NULL) { check_namespace(namespace); namespace = namespace->next; } if(!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_unary_expression, EXPR_UNARY); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/test/expected_output/typeof.fluffy.output b/test/expected_output/typeof.fluffy.output new file mode 100644 index 0000000..e69de29 diff --git a/test/typeof.fluffy b/test/typeof.fluffy new file mode 100644 index 0000000..64001f1 --- /dev/null +++ b/test/typeof.fluffy @@ -0,0 +1,7 @@ +var k : int + +func main() : int: + k = 42 + var l : typeof(k) = 22 + return (cast<typeof(l)>(k) - l) - 20 +export main diff --git a/tokens.inc b/tokens.inc index 1f1d20c..3540c58 100644 --- a/tokens.inc +++ b/tokens.inc @@ -1,81 +1,82 @@ #ifndef TS #define TS(x,str,val) #endif TS(NEWLINE, "newline", = 256) TS(INDENT, "indent",) TS(DEDENT, "dedent",) TS(IDENTIFIER, "identifier",) TS(INTEGER, "integer number",) TS(STRING_LITERAL, "string literal",) #define Keyword(x) T(x,#x,) Keyword(bool) Keyword(byte) Keyword(cast) Keyword(class) Keyword(const) Keyword(double) Keyword(else) Keyword(export) Keyword(extern) Keyword(false) Keyword(float) Keyword(func) Keyword(goto) Keyword(if) Keyword(instance) Keyword(int) Keyword(long) Keyword(namespace) Keyword(null) Keyword(return) Keyword(short) Keyword(signed) Keyword(static) Keyword(struct) Keyword(true) Keyword(typealias) Keyword(concept) Keyword(union) Keyword(unsigned) Keyword(var) Keyword(void) Keyword(sizeof) +Keyword(typeof) #undef S T(DOTDOT, "..",) T(DOTDOTDOT, "...",) T(EQUALEQUAL, "==",) T(TYPESTART, "<$",) T(SLASHEQUAL, "/=",) T(LESSEQUAL, "<=",) T(LESSLESS, "<<",) T(GREATEREQUAL, ">=",) T(GREATERGREATER, ">>",) T(PIPEPIPE, "||",) T(ANDAND, "&&",) T(PLUSPLUS, "++",) T(MINUSMINUS, "--",) T(MULTILINE_COMMENT_BEGIN, "/*",) T(MULTILINE_COMMENT_END, "*/",) T(SINGLELINE_COMMENT, "//",) #define T_LAST_TOKEN (T_SINGLELINE_COMMENT+1) T(PLUS, "+", = '+') T(MINUS, "-", = '-') T(MULT, "*", = '*') T(DIV, "/", = '/') T(MOD, "%", = '%') T(EQUAL, "=", = '=') T(LESS, "<", = '<') T(GREATER, ">", = '>') T(DOT, ".", = '.') T(CARET, "^", = '^') T(EXCLAMATION, "!", = '!') T(QUESTION, "?", = '?') T(AND, "&", = '&') T(TILDE, "~", = '~') T(PIPE, "|", = '|') T(DOLLAR, "$", = '$') diff --git a/type.c b/type.c index e4ccf00..aa53ec9 100644 --- a/type.c +++ b/type.c @@ -1,566 +1,587 @@ #include <config.h> #include "type_t.h" #include "ast_t.h" #include "type_hash.h" #include "adt/error.h" #include "adt/array.h" //#define DEBUG_TYPEVAR_BINDING typedef struct typevar_binding_t typevar_binding_t; struct typevar_binding_t { type_variable_t *type_variable; type_t *old_current_type; }; static typevar_binding_t *typevar_binding_stack = NULL; static struct obstack _type_obst; struct obstack *type_obst = &_type_obst; static type_t type_void_ = { TYPE_VOID, NULL }; static type_t type_invalid_ = { TYPE_INVALID, NULL }; type_t *type_void = &type_void_; type_t *type_invalid = &type_invalid_; static FILE* out; void init_type_module() { obstack_init(type_obst); typevar_binding_stack = NEW_ARR_F(typevar_binding_t, 0); out = stderr; } void exit_type_module() { DEL_ARR_F(typevar_binding_stack); obstack_free(type_obst, NULL); } static void print_atomic_type(const atomic_type_t *type) { switch(type->atype) { case ATOMIC_TYPE_INVALID: fputs("INVALIDATOMIC", out); break; case ATOMIC_TYPE_BOOL: fputs("bool", out); break; case ATOMIC_TYPE_BYTE: fputs("byte", out); break; case ATOMIC_TYPE_UBYTE: fputs("unsigned byte", out); break; case ATOMIC_TYPE_INT: fputs("int", out); break; case ATOMIC_TYPE_UINT: fputs("unsigned int", out); break; case ATOMIC_TYPE_SHORT: fputs("short", out); break; case ATOMIC_TYPE_USHORT: fputs("unsigned short", out); break; case ATOMIC_TYPE_LONG: fputs("long", out); break; case ATOMIC_TYPE_ULONG: fputs("unsigned long", out); break; case ATOMIC_TYPE_LONGLONG: fputs("long long", out); break; case ATOMIC_TYPE_ULONGLONG: fputs("unsigned long long", out); break; case ATOMIC_TYPE_FLOAT: fputs("float", out); break; case ATOMIC_TYPE_DOUBLE: fputs("double", out); break; default: fputs("UNKNOWNATOMIC", out); break; } } static void print_method_type(const method_type_t *type) { fputs("<", out); fputs("func(", out); method_parameter_type_t *param_type = type->parameter_types; int first = 1; while(param_type != NULL) { if(first) { first = 0; } else { fputs(", ", out); } print_type(param_type->type); param_type = param_type->next; } fputs(")", out); if(type->result_type != NULL && type->result_type->type != TYPE_VOID) { fputs(" : ", out); print_type(type->result_type); } fputs(">", out); } static void print_pointer_type(const pointer_type_t *type) { print_type(type->points_to); fputs("*", out); } static void print_array_type(const array_type_t *type) { print_type(type->element_type); fprintf(out, "[%lu]", type->size); } static void print_type_reference(const type_reference_t *type) { fprintf(out, "<?%s>", type->symbol->string); } static void print_type_variable(const type_variable_t *type_variable) { if(type_variable->current_type != NULL) { print_type(type_variable->current_type); return; } fprintf(out, "%s:", type_variable->declaration.symbol->string); type_constraint_t *constraint = type_variable->constraints; int first = 1; while(constraint != NULL) { if(first) { first = 0; } else { fprintf(out, ", "); } fprintf(out, "%s", constraint->concept_symbol->string); constraint = constraint->next; } } static void print_type_reference_variable(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; print_type_variable(type_variable); } static void print_compound_type(const compound_type_t *type) { fprintf(out, "%s", type->symbol->string); type_variable_t *type_parameter = type->type_parameters; if(type_parameter != NULL) { fprintf(out, "<"); while(type_parameter != NULL) { if(type_parameter != type->type_parameters) { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } fprintf(out, ">"); } } static void print_bind_type_variables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); print_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } void print_type(const type_t *type) { if(type == NULL) { fputs("nil type", out); return; } switch(type->type) { case TYPE_INVALID: fputs("invalid", out); return; + case TYPE_TYPEOF: { + const typeof_type_t *typeof_type = (const typeof_type_t*) type; + fputs("typeof(", out); + print_expression(typeof_type->expression); + fputs(")", out); + return; + } + case TYPE_ERROR: + fputs("error", out); + return; case TYPE_VOID: fputs("void", out); return; case TYPE_ATOMIC: print_atomic_type((const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: print_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: print_method_type((const method_type_t*) type); return; case TYPE_POINTER: print_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: print_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: print_type_reference((const type_reference_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: print_type_reference_variable((const type_reference_t*) type); return; case TYPE_BIND_TYPEVARIABLES: print_bind_type_variables((const bind_typevariables_type_t*) type); return; } fputs("unknown", out); } int type_valid(const type_t *type) { switch(type->type) { case TYPE_INVALID: case TYPE_REFERENCE: return 0; default: return 1; } } int is_type_int(const type_t *type) { if(type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return 1; default: return 0; } } int is_type_numeric(const type_t *type) { if(type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return 1; default: return 0; } } type_t* make_atomic_type(atomic_type_type_t atype) { atomic_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *normalized_type = typehash_insert((type_t*) type); if(normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } type_t* make_pointer_type(type_t *points_to) { pointer_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_POINTER; type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) type); if(normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } static type_t *create_concrete_compound_type(compound_type_t *type) { /* TODO: handle structs with typevars */ return (type_t*) type; } static type_t *create_concrete_method_type(method_type_t *type) { int need_new_type = 0; method_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_METHOD; type_t *result_type = create_concrete_type(type->result_type); if(result_type != type->result_type) need_new_type = 1; new_type->result_type = result_type; method_parameter_type_t *parameter_type = type->parameter_types; method_parameter_type_t *last_parameter_type = NULL; while(parameter_type != NULL) { type_t *param_type = parameter_type->type; type_t *new_param_type = create_concrete_type(param_type); if(new_param_type != param_type) need_new_type = 1; method_parameter_type_t *new_parameter_type = obstack_alloc(type_obst, sizeof(new_parameter_type[0])); memset(new_parameter_type, 0, sizeof(new_parameter_type[0])); new_parameter_type->type = new_param_type; if(last_parameter_type != NULL) { last_parameter_type->next = new_parameter_type; } else { new_type->parameter_types = new_parameter_type; } last_parameter_type = new_parameter_type; parameter_type = parameter_type->next; } if(!need_new_type) { obstack_free(type_obst, new_type); new_type = type; } return (type_t*) new_type; } static type_t *create_concrete_pointer_type(pointer_type_t *type) { type_t *points_to = create_concrete_type(type->points_to); if(points_to == type->points_to) return (type_t*) type; pointer_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_POINTER; new_type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) new_type); if(normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_type_variable_reference_type(type_reference_t *type) { type_variable_t *type_variable = type->type_variable; type_t *current_type = type_variable->current_type; if(current_type != NULL) return current_type; return (type_t*) type; } static type_t *create_concrete_array_type(array_type_t *type) { type_t *element_type = create_concrete_type(type->element_type); if(element_type == type->element_type) return (type_t*) type; array_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_ARRAY; new_type->element_type = element_type; new_type->size = type->size; type_t *normalized_type = typehash_insert((type_t*) new_type); if(normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_typevar_binding_type(bind_typevariables_type_t *type) { int changed = 0; type_argument_t *new_arguments; type_argument_t *last_argument = NULL; type_argument_t *type_argument = type->type_arguments; while(type_argument != NULL) { type_t *type = type_argument->type; type_t *new_type = create_concrete_type(type); if(new_type != type) { changed = 1; } type_argument_t *new_argument = obstack_alloc(type_obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = new_type; if(last_argument != NULL) { last_argument->next = new_argument; } else { new_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } if(!changed) { assert(new_arguments != NULL); obstack_free(type_obst, new_arguments); return (type_t*) type; } bind_typevariables_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_BIND_TYPEVARIABLES; new_type->polymorphic_type = type->polymorphic_type; new_type->type_arguments = new_arguments; type_t *normalized_type = typehash_insert((type_t*) new_type); if(normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } type_t *create_concrete_type(type_t *type) { switch(type->type) { case TYPE_INVALID: return type_invalid; case TYPE_VOID: return type_void; + case TYPE_ERROR: case TYPE_ATOMIC: return type; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return create_concrete_compound_type((compound_type_t*) type); case TYPE_METHOD: return create_concrete_method_type((method_type_t*) type); case TYPE_POINTER: return create_concrete_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return create_concrete_array_type((array_type_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return create_concrete_type_variable_reference_type( (type_reference_t*) type); case TYPE_BIND_TYPEVARIABLES: return create_concrete_typevar_binding_type( (bind_typevariables_type_t*) type); + case TYPE_TYPEOF: + panic("TODO: concrete type for typeof()"); case TYPE_REFERENCE: panic("trying to normalize unresolved type reference"); break; } return type; } int typevar_binding_stack_top() { return ARR_LEN(typevar_binding_stack); } void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments) { type_variable_t *type_parameter; type_argument_t *type_argument; if(type_parameters == NULL || type_arguments == NULL) return; /* we have to take care that all rebinding happens atomically, so we first * create the structures on the binding stack and misuse the * old_current_type value to temporarily save the new! current_type. * We can then walk the list and set the new types */ type_parameter = type_parameters; type_argument = type_arguments; int old_top = typevar_binding_stack_top(); int top = ARR_LEN(typevar_binding_stack) + 1; while(type_parameter != NULL) { type_t *type = type_argument->type; while(type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) type; type_variable_t *var = ref->type_variable; if(var->current_type == NULL) { break; } type = var->current_type; } top = ARR_LEN(typevar_binding_stack) + 1; ARR_RESIZE(typevar_binding_t, typevar_binding_stack, top); typevar_binding_t *binding = & typevar_binding_stack[top-1]; binding->type_variable = type_parameter; binding->old_current_type = type; type_parameter = type_parameter->next; type_argument = type_argument->next; } assert(type_parameter == NULL && type_argument == NULL); for(int i = old_top+1; i <= top; ++i) { typevar_binding_t *binding = & typevar_binding_stack[i-1]; type_variable_t *type_variable = binding->type_variable; type_t *new_type = binding->old_current_type; binding->old_current_type = type_variable->current_type; type_variable->current_type = new_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "binding '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, type_variable->current_type); fprintf(stderr, "\n"); #endif } } void pop_type_variable_bindings(int new_top) { int top = ARR_LEN(typevar_binding_stack) - 1; for(int i = top; i >= new_top; --i) { typevar_binding_t *binding = & typevar_binding_stack[i]; type_variable_t *type_variable = binding->type_variable; type_variable->current_type = binding->old_current_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "reset binding of '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, binding->old_current_type); fprintf(stderr, "\n"); #endif } ARR_SHRINKLEN(typevar_binding_stack, new_top); } +type_t *skip_typeref(type_t *type) +{ + if (type->type == TYPE_TYPEOF) { + typeof_type_t *typeof_type = (typeof_type_t*) type; + return skip_typeref(typeof_type->expression->datatype); + } + return type; +} diff --git a/type.h b/type.h index 4b62217..c7954f8 100644 --- a/type.h +++ b/type.h @@ -1,61 +1,64 @@ #ifndef TYPE_H #define TYPE_H #include <stdio.h> typedef struct type_t type_t; typedef struct atomic_type_t atomic_type_t; typedef struct type_reference_t type_reference_t; typedef struct compound_entry_t compound_entry_t; typedef struct compound_type_t compound_type_t; typedef struct type_constraint_t type_constraint_t; typedef struct type_variable_t type_variable_t; typedef struct type_argument_t type_argument_t; typedef struct bind_typevariables_type_t bind_typevariables_type_t; typedef struct method_parameter_type_t method_parameter_type_t; typedef struct method_type_t method_type_t; typedef struct pointer_type_t pointer_type_t; typedef struct array_type_t array_type_t; +typedef struct typeof_type_t typeof_type_t; extern type_t *type_void; extern type_t *type_invalid; void init_type_module(void); void exit_type_module(void); /** * prints a human readable form of @p type to a stream */ void print_type(const type_t *type); /** * returns 1 if type contains integer numbers */ int is_type_int(const type_t *type); /** * returns 1 if type contains numbers (float or int) */ int is_type_numeric(const type_t *type); /** * returns 1 if the type is valid. A type is valid if it contains no unresolved * references anymore and is not of TYPE_INVALID. */ int type_valid(const type_t *type); /** * returns a normalized copy of a type with type variables replaced by their * current type. The given type (and all its hierarchy) is not modified. */ type_t *create_concrete_type(type_t *type); +type_t *skip_typeref(type_t *type); + int typevar_binding_stack_top(void); void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments); void pop_type_variable_bindings(int new_top); #endif diff --git a/type_hash.c b/type_hash.c index c405b53..5c03ad1 100644 --- a/type_hash.c +++ b/type_hash.c @@ -1,280 +1,291 @@ #include <config.h> #include <stdbool.h> #include "type_hash.h" #include "adt/error.h" #include "type_t.h" #include <assert.h> #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #include "adt/hashset.h" #undef ValueType #undef HashSetIterator #undef HashSet typedef struct type_hash_iterator_t type_hash_iterator_t; typedef struct type_hash_t type_hash_t; static unsigned hash_ptr(const void *ptr) { unsigned ptr_int = ((const char*) ptr - (const char*) NULL); return ptr_int >> 3; } static unsigned hash_atomic_type(const atomic_type_t *type) { unsigned some_prime = 27644437; return type->atype * some_prime; } static unsigned hash_pointer_type(const pointer_type_t *type) { return hash_ptr(type->points_to); } static unsigned hash_array_type(const array_type_t *type) { unsigned some_prime = 27644437; return hash_ptr(type->element_type) ^ (type->size * some_prime); } static unsigned hash_compound_type(const compound_type_t *type) { unsigned result = hash_ptr(type->symbol); return result; } static unsigned hash_type(const type_t *type); static unsigned hash_method_type(const method_type_t *type) { unsigned result = hash_ptr(type->result_type); method_parameter_type_t *parameter = type->parameter_types; while(parameter != NULL) { result ^= hash_ptr(parameter->type); parameter = parameter->next; } if(type->variable_arguments) result = ~result; return result; } static unsigned hash_type_reference_type_variable(const type_reference_t *type) { return hash_ptr(type->type_variable); } static unsigned hash_bind_typevariables_type_t(const bind_typevariables_type_t *type) { unsigned hash = hash_compound_type(type->polymorphic_type); type_argument_t *argument = type->type_arguments; while(argument != NULL) { hash ^= hash_type(argument->type); argument = argument->next; } return hash; } static unsigned hash_type(const type_t *type) { switch(type->type) { case TYPE_INVALID: case TYPE_VOID: + case TYPE_ERROR: case TYPE_REFERENCE: panic("internalizing void or invalid types not possible"); case TYPE_REFERENCE_TYPE_VARIABLE: return hash_type_reference_type_variable( (const type_reference_t*) type); case TYPE_ATOMIC: return hash_atomic_type((const atomic_type_t*) type); + case TYPE_TYPEOF: { + const typeof_type_t *typeof_type = (const typeof_type_t*) type; + return hash_ptr(typeof_type->expression); + } case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return hash_compound_type((const compound_type_t*) type); case TYPE_METHOD: return hash_method_type((const method_type_t*) type); case TYPE_POINTER: return hash_pointer_type((const pointer_type_t*) type); case TYPE_ARRAY: return hash_array_type((const array_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return hash_bind_typevariables_type_t( (const bind_typevariables_type_t*) type); } abort(); } static bool atomic_types_equal(const atomic_type_t *type1, const atomic_type_t *type2) { return type1->atype == type2->atype; } static bool compound_types_equal(const compound_type_t *type1, const compound_type_t *type2) { if(type1->symbol != type2->symbol) return false; /* TODO: check type parameters? */ return true; } static bool method_types_equal(const method_type_t *type1, const method_type_t *type2) { if(type1->result_type != type2->result_type) return false; if(type1->variable_arguments != type2->variable_arguments) return false; method_parameter_type_t *param1 = type1->parameter_types; method_parameter_type_t *param2 = type2->parameter_types; while(param1 != NULL && param2 != NULL) { if(param1->type != param2->type) return false; param1 = param1->next; param2 = param2->next; } if(param1 != NULL || param2 != NULL) return false; return true; } static bool pointer_types_equal(const pointer_type_t *type1, const pointer_type_t *type2) { return type1->points_to == type2->points_to; } static bool array_types_equal(const array_type_t *type1, const array_type_t *type2) { return type1->element_type == type2->element_type && type1->size == type2->size; } static bool type_references_type_variable_equal(const type_reference_t *type1, const type_reference_t *type2) { return type1->type_variable == type2->type_variable; } static bool bind_typevariables_type_equal(const bind_typevariables_type_t*type1, const bind_typevariables_type_t*type2) { if(type1->polymorphic_type != type2->polymorphic_type) return false; type_argument_t *argument1 = type1->type_arguments; type_argument_t *argument2 = type2->type_arguments; while(argument1 != NULL) { if(argument2 == NULL) return false; if(argument1->type != argument2->type) return false; argument1 = argument1->next; argument2 = argument2->next; } if(argument2 != NULL) return false; return true; } static bool types_equal(const type_t *type1, const type_t *type2) { if(type1 == type2) return true; if(type1->type != type2->type) return false; switch(type1->type) { case TYPE_INVALID: case TYPE_VOID: + case TYPE_ERROR: case TYPE_REFERENCE: return false; + case TYPE_TYPEOF: { + const typeof_type_t *typeof_type1 = (const typeof_type_t*) type1; + const typeof_type_t *typeof_type2 = (const typeof_type_t*) type2; + return typeof_type1->expression == typeof_type2->expression; + } case TYPE_REFERENCE_TYPE_VARIABLE: return type_references_type_variable_equal( (const type_reference_t*) type1, (const type_reference_t*) type2); case TYPE_ATOMIC: return atomic_types_equal((const atomic_type_t*) type1, (const atomic_type_t*) type2); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return compound_types_equal((const compound_type_t*) type1, (const compound_type_t*) type2); case TYPE_METHOD: return method_types_equal((const method_type_t*) type1, (const method_type_t*) type2); case TYPE_POINTER: return pointer_types_equal((const pointer_type_t*) type1, (const pointer_type_t*) type2); case TYPE_ARRAY: return array_types_equal((const array_type_t*) type1, (const array_type_t*) type2); case TYPE_BIND_TYPEVARIABLES: return bind_typevariables_type_equal( (const bind_typevariables_type_t*) type1, (const bind_typevariables_type_t*) type2); } panic("invalid type encountered"); } #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #define NullValue NULL #define DeletedValue ((type_t*)-1) #define Hash(this, key) hash_type(key) #define KeysEqual(this,key1,key2) types_equal(key1, key2) #define SetRangeEmpty(ptr,size) memset(ptr, 0, (size) * sizeof(*(ptr))) #define hashset_init _typehash_init #define hashset_init_size _typehash_init_size #define hashset_destroy _typehash_destroy #define hashset_insert _typehash_insert #define hashset_remove typehash_remove #define hashset_find typehash_find #define hashset_size typehash_size #define hashset_iterator_init typehash_iterator_init #define hashset_iterator_next typehash_iterator_next #define hashset_remove_iterator typehash_remove_iterator #define SCALAR_RETURN #include "adt/hashset.c" static type_hash_t typehash; void init_typehash(void) { _typehash_init(&typehash); } void exit_typehash(void) { _typehash_destroy(&typehash); } type_t *typehash_insert(type_t *type) { return _typehash_insert(&typehash, type); } int typehash_contains(type_t *type) { return typehash_find(&typehash, type) != NULL; } diff --git a/type_t.h b/type_t.h index 4ef2c2c..e07be0d 100644 --- a/type_t.h +++ b/type_t.h @@ -1,137 +1,144 @@ #ifndef TYPE_T_H #define TYPE_T_H #include <stdbool.h> #include "type.h" #include "symbol.h" #include "lexer.h" #include "ast.h" #include "ast_t.h" #include "adt/obst.h" #include <libfirm/typerep.h> struct obstack *type_obst; typedef enum { TYPE_INVALID, + TYPE_ERROR, TYPE_VOID, TYPE_ATOMIC, TYPE_COMPOUND_CLASS, TYPE_COMPOUND_STRUCT, TYPE_COMPOUND_UNION, TYPE_METHOD, TYPE_POINTER, TYPE_ARRAY, + TYPE_TYPEOF, TYPE_REFERENCE, TYPE_REFERENCE_TYPE_VARIABLE, TYPE_BIND_TYPEVARIABLES } type_type_t; typedef enum { ATOMIC_TYPE_INVALID, ATOMIC_TYPE_BOOL, ATOMIC_TYPE_BYTE, ATOMIC_TYPE_UBYTE, ATOMIC_TYPE_SHORT, ATOMIC_TYPE_USHORT, ATOMIC_TYPE_INT, ATOMIC_TYPE_UINT, ATOMIC_TYPE_LONG, ATOMIC_TYPE_ULONG, ATOMIC_TYPE_LONGLONG, ATOMIC_TYPE_ULONGLONG, ATOMIC_TYPE_FLOAT, ATOMIC_TYPE_DOUBLE, } atomic_type_type_t; struct type_t { type_type_t type; ir_type *firm_type; }; struct atomic_type_t { type_t type; atomic_type_type_t atype; }; struct pointer_type_t { type_t type; type_t *points_to; }; struct array_type_t { type_t type; type_t *element_type; unsigned long size; }; +struct typeof_type_t { + type_t type; + expression_t *expression; +}; + struct type_argument_t { type_t *type; type_argument_t *next; }; struct type_reference_t { type_t type; symbol_t *symbol; source_position_t source_position; type_argument_t *type_arguments; type_variable_t *type_variable; }; struct bind_typevariables_type_t { type_t type; type_argument_t *type_arguments; compound_type_t *polymorphic_type; }; struct method_parameter_type_t { type_t *type; method_parameter_type_t *next; }; struct type_constraint_t { symbol_t *concept_symbol; concept_t *concept; type_constraint_t *next; }; struct method_type_t { type_t type; type_t *result_type; method_parameter_type_t *parameter_types; bool variable_arguments; }; struct iterator_type_t { type_t type; type_t *element_type; method_parameter_type_t *parameter_types; }; struct compound_entry_t { type_t *type; symbol_t *symbol; compound_entry_t *next; attribute_t *attributes; source_position_t source_position; ir_entity *entity; }; struct compound_type_t { type_t type; compound_entry_t *entries; symbol_t *symbol; attribute_t *attributes; type_variable_t *type_parameters; context_t context; source_position_t source_position; }; type_t *make_atomic_type(atomic_type_type_t type); type_t *make_pointer_type(type_t *type); #endif
MatzeB/fluffy
ee20ea8d3a445fe2fe67675d91b7d6921277bded
reindent, use bool where possible
diff --git a/type_hash.c b/type_hash.c index d11868e..c405b53 100644 --- a/type_hash.c +++ b/type_hash.c @@ -1,291 +1,280 @@ #include <config.h> +#include <stdbool.h> #include "type_hash.h" #include "adt/error.h" #include "type_t.h" #include <assert.h> #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #include "adt/hashset.h" #undef ValueType #undef HashSetIterator #undef HashSet typedef struct type_hash_iterator_t type_hash_iterator_t; typedef struct type_hash_t type_hash_t; static unsigned hash_ptr(const void *ptr) { unsigned ptr_int = ((const char*) ptr - (const char*) NULL); return ptr_int >> 3; } static unsigned hash_atomic_type(const atomic_type_t *type) { unsigned some_prime = 27644437; return type->atype * some_prime; } static unsigned hash_pointer_type(const pointer_type_t *type) { return hash_ptr(type->points_to); } static unsigned hash_array_type(const array_type_t *type) { unsigned some_prime = 27644437; return hash_ptr(type->element_type) ^ (type->size * some_prime); } static unsigned hash_compound_type(const compound_type_t *type) { unsigned result = hash_ptr(type->symbol); return result; } static unsigned hash_type(const type_t *type); static unsigned hash_method_type(const method_type_t *type) { unsigned result = hash_ptr(type->result_type); method_parameter_type_t *parameter = type->parameter_types; while(parameter != NULL) { result ^= hash_ptr(parameter->type); parameter = parameter->next; } if(type->variable_arguments) result = ~result; return result; } static unsigned hash_type_reference_type_variable(const type_reference_t *type) { return hash_ptr(type->type_variable); } static unsigned hash_bind_typevariables_type_t(const bind_typevariables_type_t *type) { unsigned hash = hash_compound_type(type->polymorphic_type); type_argument_t *argument = type->type_arguments; while(argument != NULL) { hash ^= hash_type(argument->type); argument = argument->next; } return hash; } static unsigned hash_type(const type_t *type) { switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_REFERENCE: panic("internalizing void or invalid types not possible"); case TYPE_REFERENCE_TYPE_VARIABLE: return hash_type_reference_type_variable( (const type_reference_t*) type); case TYPE_ATOMIC: return hash_atomic_type((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return hash_compound_type((const compound_type_t*) type); case TYPE_METHOD: return hash_method_type((const method_type_t*) type); case TYPE_POINTER: return hash_pointer_type((const pointer_type_t*) type); case TYPE_ARRAY: return hash_array_type((const array_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return hash_bind_typevariables_type_t( (const bind_typevariables_type_t*) type); } abort(); } -static int atomic_types_equal(const atomic_type_t *type1, const atomic_type_t *type2) +static bool atomic_types_equal(const atomic_type_t *type1, + const atomic_type_t *type2) { return type1->atype == type2->atype; } -static int compound_types_equal(const compound_type_t *type1, - const compound_type_t *type2) +static bool compound_types_equal(const compound_type_t *type1, + const compound_type_t *type2) { if(type1->symbol != type2->symbol) - return 0; + return false; + /* TODO: check type parameters? */ -#if 0 - struct_entry_t *entry1 = type1->entries; - struct_entry_t *entry2 = type2->entries; - - while(entry1 != NULL && entry2 != NULL) { - if(entry1->type != entry2->type) - return 0; - entry1 = entry1->next; - entry2 = entry2->next; - } - if(entry1 != NULL || entry2 != NULL) - return 0; -#endif - - return 1; + return true; } -static int method_types_equal(const method_type_t *type1, const method_type_t *type2) +static bool method_types_equal(const method_type_t *type1, + const method_type_t *type2) { if(type1->result_type != type2->result_type) - return 0; + return false; if(type1->variable_arguments != type2->variable_arguments) - return 0; + return false; method_parameter_type_t *param1 = type1->parameter_types; method_parameter_type_t *param2 = type2->parameter_types; while(param1 != NULL && param2 != NULL) { if(param1->type != param2->type) - return 0; + return false; param1 = param1->next; param2 = param2->next; } if(param1 != NULL || param2 != NULL) - return 0; + return false; - return 1; + return true; } -static int pointer_types_equal(const pointer_type_t *type1, - const pointer_type_t *type2) +static bool pointer_types_equal(const pointer_type_t *type1, + const pointer_type_t *type2) { return type1->points_to == type2->points_to; } -static int array_types_equal(const array_type_t *type1, - const array_type_t *type2) +static bool array_types_equal(const array_type_t *type1, + const array_type_t *type2) { - return type1->element_type == type2->element_type && - type1->size == type2->size; + return type1->element_type == type2->element_type + && type1->size == type2->size; } -static int type_references_type_variable_equal(const type_reference_t *type1, - const type_reference_t *type2) +static bool type_references_type_variable_equal(const type_reference_t *type1, + const type_reference_t *type2) { return type1->type_variable == type2->type_variable; } -static int bind_typevariables_type_equal(const bind_typevariables_type_t *type1, - const bind_typevariables_type_t *type2) +static bool bind_typevariables_type_equal(const bind_typevariables_type_t*type1, + const bind_typevariables_type_t*type2) { if(type1->polymorphic_type != type2->polymorphic_type) - return 0; + return false; type_argument_t *argument1 = type1->type_arguments; type_argument_t *argument2 = type2->type_arguments; while(argument1 != NULL) { if(argument2 == NULL) - return 0; + return false; if(argument1->type != argument2->type) - return 0; + return false; argument1 = argument1->next; argument2 = argument2->next; } if(argument2 != NULL) - return 0; + return false; - return 1; + return true; } -static int types_equal(const type_t *type1, const type_t *type2) +static bool types_equal(const type_t *type1, const type_t *type2) { if(type1 == type2) - return 1; + return true; if(type1->type != type2->type) - return 0; + return false; switch(type1->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_REFERENCE: - return 0; + return false; case TYPE_REFERENCE_TYPE_VARIABLE: return type_references_type_variable_equal( (const type_reference_t*) type1, (const type_reference_t*) type2); case TYPE_ATOMIC: return atomic_types_equal((const atomic_type_t*) type1, (const atomic_type_t*) type2); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return compound_types_equal((const compound_type_t*) type1, (const compound_type_t*) type2); case TYPE_METHOD: return method_types_equal((const method_type_t*) type1, (const method_type_t*) type2); case TYPE_POINTER: return pointer_types_equal((const pointer_type_t*) type1, (const pointer_type_t*) type2); case TYPE_ARRAY: return array_types_equal((const array_type_t*) type1, (const array_type_t*) type2); case TYPE_BIND_TYPEVARIABLES: return bind_typevariables_type_equal( (const bind_typevariables_type_t*) type1, (const bind_typevariables_type_t*) type2); } - - abort(); + panic("invalid type encountered"); } #define HashSet type_hash_t #define HashSetIterator type_hash_iterator_t #define ValueType type_t* #define NullValue NULL #define DeletedValue ((type_t*)-1) #define Hash(this, key) hash_type(key) #define KeysEqual(this,key1,key2) types_equal(key1, key2) #define SetRangeEmpty(ptr,size) memset(ptr, 0, (size) * sizeof(*(ptr))) #define hashset_init _typehash_init #define hashset_init_size _typehash_init_size #define hashset_destroy _typehash_destroy #define hashset_insert _typehash_insert #define hashset_remove typehash_remove #define hashset_find typehash_find #define hashset_size typehash_size #define hashset_iterator_init typehash_iterator_init #define hashset_iterator_next typehash_iterator_next #define hashset_remove_iterator typehash_remove_iterator #define SCALAR_RETURN #include "adt/hashset.c" static type_hash_t typehash; void init_typehash(void) { _typehash_init(&typehash); } void exit_typehash(void) { _typehash_destroy(&typehash); } type_t *typehash_insert(type_t *type) { return _typehash_insert(&typehash, type); } int typehash_contains(type_t *type) { return typehash_find(&typehash, type) != NULL; }
MatzeB/fluffy
2d00ed73abafa8a219a3096dcb7851c5ec6b6b6c
fix type mangling for variadic structs
diff --git a/mangle.c b/mangle.c index e185f91..fb29521 100644 --- a/mangle.c +++ b/mangle.c @@ -1,201 +1,222 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" #include "type_t.h" #include "adt/error.h" #include <libfirm/firm.h> #include "driver/firm_cmdline.h" static struct obstack obst; static void mangle_string(const char *str) { size_t len = strlen(str); obstack_grow(&obst, str, len); } static void mangle_len_string(const char *string) { size_t len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); } static void mangle_atomic_type(const atomic_type_t *type) { char c; switch(type->atype) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(&obst, c); } +static void mangle_type_variables(type_variable_t *type_variables) +{ + type_variable_t *type_variable = type_variables; + for( ; type_variable != NULL; type_variable = type_variable->next) { + /* is this a good char? */ + obstack_1grow(&obst, 'T'); + mangle_type(type_variable->current_type); + } +} + static void mangle_compound_type(const compound_type_t *type) { mangle_len_string(type->symbol->string); + mangle_type_variables(type->type_parameters); } static void mangle_pointer_type(const pointer_type_t *type) { obstack_1grow(&obst, 'P'); mangle_type(type->points_to); } static void mangle_array_type(const array_type_t *type) { obstack_1grow(&obst, 'A'); mangle_type(type->element_type); obstack_printf(&obst, "%lu", type->size); } static void mangle_method_type(const method_type_t *type) { obstack_1grow(&obst, 'F'); mangle_type(type->result_type); method_parameter_type_t *parameter_type = type->parameter_types; while(parameter_type != NULL) { mangle_type(parameter_type->type); } obstack_1grow(&obst, 'E'); } static void mangle_reference_type_variable(const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if(current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(current_type); } +static void mangle_bind_typevariables(const bind_typevariables_type_t *type) +{ + compound_type_t *polymorphic_type = type->polymorphic_type; + + int old_top = typevar_binding_stack_top(); + push_type_variable_bindings(polymorphic_type->type_parameters, + type->type_arguments); + mangle_type((type_t*) polymorphic_type); + pop_type_variable_bindings(old_top); +} + void mangle_type(const type_t *type) { switch(type->type) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(&obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type((const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: mangle_method_type((const method_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: - /* should have been normalized already in semantic phase... */ - panic("can't mangle type variable bindings"); + mangle_bind_typevariables((const bind_typevariables_type_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable((const type_reference_t*) type); return; } panic("Unknown type mangled"); } void mangle_symbol_simple(symbol_t *symbol) { mangle_string(symbol->string); } void mangle_symbol(symbol_t *symbol) { mangle_len_string(symbol->string); } void mangle_concept_name(symbol_t *symbol) { obstack_grow(&obst, "tcv", 3); mangle_len_string(symbol->string); } void start_mangle(void) { if (firm_opt.os_support == OS_SUPPORT_MACHO || firm_opt.os_support == OS_SUPPORT_MINGW) { obstack_1grow(&obst, '_'); } } ident *finish_mangle(void) { size_t size = obstack_object_size(&obst); char *str = obstack_finish(&obst); ident *id = new_id_from_chars(str, size); obstack_free(&obst, str); return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/semantic.c b/semantic.c index 6b7daf2..bedc7f6 100644 --- a/semantic.c +++ b/semantic.c @@ -1,904 +1,901 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if(symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if(new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while(i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if(declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if(type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if(declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while(type_parameter != NULL) { if(type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if(type_argument != NULL) { print_error_prefix(type_ref->source_position); if(type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(type); fprintf(stderr, " takes no type parameters\n"); } if(type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if(type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while(entry != NULL) { type_t *type = entry->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if(type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: return type; case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } - - - static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if(type == NULL) return NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if(constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if(!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if(left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if(left->datatype == NULL) { if(right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if(dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ type_t *from_type = from->datatype; if(from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } bool implicit_cast_allowed = true; if(from_type->type == TYPE_POINTER) { if(dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if(p1->points_to != p2->points_to && dest_type != type_void_ptr && from->type != EXPR_NULL_POINTER) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if(dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if(pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if(from_type->type == TYPE_ATOMIC) { if(dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if(!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(from_type); fprintf(stderr, " to "); print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if(lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if(!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if(left == NULL || right == NULL) return; if(left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if(right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while(argument != NULL && parameter != NULL) { if(parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if(parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if(match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if(match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { if(constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { if(method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } diff --git a/test/polystruct.fluffy b/test/polystruct.fluffy index af022e4..56a206a 100644 --- a/test/polystruct.fluffy +++ b/test/polystruct.fluffy @@ -1,63 +1,75 @@ typealias String = byte* func extern malloc(size : unsigned int) : void* func extern printf(format : String, ...) : int func extern puts(val : String) func extern strcmp(s1 : String, s2 : String) : int concept Printable<T>: func print(obj : T) instance Printable String: func print(obj : String): puts(obj) instance Printable int: func print(obj : int): printf("%d\n", obj) struct ListElement<T>: val : T next : ListElement<T>* struct List<T>: first : ListElement<T>* func AddToList<T>(list : List<T>*, element : ListElement<T>*): element.next = list.first list.first = element func AddMakeElement<T>(list : List<T>*, value : T): var element = cast<ListElement<T>*> malloc( sizeof<T> ) element.val = value AddToList(list, element) func PrintList<T : Printable>(list : List<T>*): var elem = list.first :beginloop if elem == null: return print(elem.val) elem = elem.next goto beginloop +instance Printable List<int>*: + func print(obj : List<int>*): + PrintList(obj) + +instance Printable List<String>*: + func print(obj : List<String>*): + PrintList(obj) + func main() : int: var l : List<String> l.first = null var e1 : ListElement<String> e1.val = "Hallo" var e2 : ListElement<String> e2.val = "Welt" AddToList(&l, &e1) AddToList(&l, &e2) - PrintList(&l) + print(&l) var l2 : List<int> l2.first = null AddMakeElement(&l2, 42) AddMakeElement(&l2, 13) - PrintList(&l2) + print(&l2) + + var l3 : List<List<int>*> + l3.first = null + PrintList(&l3) return 0 export main
MatzeB/fluffy
84dacb5a9615231c804be95d4ce1c885a034c2b8
redo mangling
diff --git a/Makefile b/Makefile index 5f8b375..b27277a 100644 --- a/Makefile +++ b/Makefile @@ -1,75 +1,74 @@ -include config.mak GOAL = fluffy FIRM_CFLAGS ?= `pkg-config --cflags libfirm` FIRM_LIBS ?= `pkg-config --libs libfirm` CPPFLAGS = -I. CPPFLAGS += $(FIRM_CFLAGS) CFLAGS += -Wall -W -Wstrict-prototypes -Wmissing-prototypes -Werror -std=c99 CFLAGS += -O0 -g3 LFLAGS += $(FIRM_LIBS) -ldl SOURCES := \ adt/strset.c \ adt/obstack.c \ adt/obstack_printf.c \ adt/xmalloc.c \ ast.c \ ast2firm.c \ lexer.c \ main.c \ - mangle_type.c \ mangle.c \ match_type.c \ parser.c \ plugins.c \ semantic.c \ symbol_table.c \ token.c \ type.c \ type_hash.c \ driver/firm_cmdline.c \ driver/firm_codegen.c \ driver/firm_opt.c \ driver/firm_timing.c \ driver/gen_firm_asm.c OBJECTS = $(SOURCES:%.c=build/%.o) Q = @ .PHONY : all clean dirs all: $(GOAL) ifeq ($(findstring $(MAKECMDGOALS), clean depend),) -include .depend endif .depend: $(SOURCES) @echo "===> DEPEND" @rm -f $@ && touch $@ && makedepend -p "$@ build/" -Y -f $@ -- $(CPPFLAGS) -- $(SOURCES) 2> /dev/null && rm [email protected] $(GOAL): build/driver build/adt $(OBJECTS) @echo "===> LD $@" $(Q)$(CC) -rdynamic $(OBJECTS) $(LFLAGS) -o $(GOAL) build/adt: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/driver: @echo "===> MKDIR $@" $(Q)mkdir -p $@ build/%.o: %.c @echo '===> CC $<' $(Q)$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ clean: @echo '===> CLEAN' $(Q)rm -rf build $(GOAL) .depend diff --git a/ast2firm.c b/ast2firm.c index 1d0375b..07268cc 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -1,1224 +1,1192 @@ #include <config.h> #include <assert.h> #include <string.h> #include <libfirm/firm.h> #include "ast_t.h" #include "type_t.h" #include "semantic_t.h" #include "mangle.h" -#include "mangle_type.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/strset.h" #include "adt/error.h" #include "adt/xmalloc.h" #include <libfirm/adt/pdeq.h> static const variable_declaration_t **value_numbers = NULL; static label_declaration_t *labels = NULL; /** context for the variables, this is usually the stack frame but might * be something else for things like coroutines */ static ir_node *variable_context = NULL; typedef struct instantiate_method_t instantiate_method_t; static ir_type *byte_ir_type = NULL; static ir_type *void_ptr_type = NULL; static type_t *type_bool = NULL; struct instantiate_method_t { method_t *method; ir_entity *entity; type_argument_t *type_arguments; }; typedef struct type2firm_env_t type2firm_env_t; struct type2firm_env_t { int can_cache; /* nonzero if type can safely be cached because no typevariables are in the hierarchy */ }; static struct obstack obst; static strset_t instantiated_methods; static pdeq *instantiate_methods = NULL; -//static ident* (*create_ld_ident)(declaration_t*) = create_name_linux_elf; - static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type); static ir_type *get_ir_type(type_t *type); static void context2firm(const context_t *context); ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos) { const declaration_t *declaration = & value_numbers[pos]->declaration; print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' might be used uninitialized\n", declaration->symbol->string); return new_r_Unknown(irg, mode); } unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg) { const source_position_t *pos = (const source_position_t*) dbg; if(pos == NULL) return 0; return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name, pos->linenr); } const char *dbg_retrieve(const dbg_info *dbg, unsigned *line) { const source_position_t *pos = (const source_position_t*) dbg; if(pos == NULL) return NULL; if(line != NULL) *line = pos->linenr; return pos->input_name; } void init_ast2firm(void) { type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); atomic_type_t byte_type; memset(&byte_type, 0, sizeof(byte_type)); byte_type.type.type = TYPE_ATOMIC; byte_type.atype = ATOMIC_TYPE_BYTE; byte_ir_type = get_ir_type((type_t*) &byte_type); ir_type *ir_type_void = get_ir_type(type_void); void_ptr_type = new_type_pointer(new_id_from_str("void_ptr"), ir_type_void, mode_P_data); } void exit_ast2firm(void) { } static unsigned unique_id = 0; static ident *unique_ident(const char *tag) { char buf[256]; snprintf(buf, sizeof(buf), "%s.%d", tag, unique_id); unique_id++; return new_id_from_str(buf); } static symbol_t *unique_symbol(const char *tag) { obstack_printf(&symbol_obstack, "%s.%d", tag, unique_id); unique_id++; const char *string = obstack_finish(&symbol_obstack); symbol_t *symbol = symbol_table_insert(string); assert(symbol->string == string); return symbol; } static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) { switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch(type->atype) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if(type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch(type->type) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while(param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if(result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while(param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if(method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); set_array_bounds_int(ir_type, 0, 0, type->size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if(elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, type->size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if(symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while(entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if(symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while(entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; while(declaration != NULL) { if(declaration->type == DECLARATION_METHOD) { /* TODO */ continue; } if(declaration->type != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; ident *ident = new_id_from_str(declaration->symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } declaration = declaration->next; } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if(current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->declaration.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if(type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch(type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_INVALID: break; } if(firm_type == NULL) panic("unknown type found"); if(env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if(method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; - const char *string - = concept->declaration.symbol->string; - size_t len = strlen(string); - obstack_printf(&obst, "_tcv%zu%s", len, string); - string = concept_method->declaration.symbol->string; - len = strlen(string); - obstack_printf(&obst, "%zu%s", len, string); + start_mangle(); + mangle_concept_name(concept->declaration.symbol); + mangle_symbol(concept_method->declaration.symbol); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; - while(argument != NULL) { - mangle_type(&obst, argument->type); - argument = argument->next; + for ( ; argument != NULL; argument = argument->next) { + mangle_type(argument->type); } - obstack_1grow(&obst, 0); - - char *str = obstack_finish(&obst); - - ident *id = new_id_from_str(str); - obstack_free(&obst, str); + ident *id = finish_mangle(); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if(!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } - ident *id; - if(!is_polymorphic) { - //id = new_id_from_str(symbol->string); - obstack_printf(&obst, "_%s", symbol->string); - obstack_1grow(&obst, 0); - - char *str = obstack_finish(&obst); - - id = new_id_from_str(str); - obstack_free(&obst, str); - } else { - const char *string = symbol->string; - size_t len = strlen(string); - obstack_printf(&obst, "_v%zu%s", len, string); - + start_mangle(); + mangle_symbol_simple(symbol); + if(is_polymorphic) { type_variable_t *type_variable = method->type_parameters; - while(type_variable != NULL) { - mangle_type(&obst, type_variable->current_type); - - type_variable = type_variable->next; + for ( ; type_variable != NULL; type_variable = type_variable->next) { + mangle_type(type_variable->current_type); } - obstack_1grow(&obst, 0); - - char *str = obstack_finish(&obst); - - id = new_id_from_str(str); - obstack_free(&obst, str); } + ident *id = finish_mangle(); /* search for an existing entity */ if(is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for(int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if(get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if(method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if(!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if(is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if(!is_polymorphic) { method->e.entity = entity; } else { if(method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if(cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for(size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if(select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if(variable->entity != NULL) return variable->entity; ir_type *parent_type; if(variable->is_global) { parent_type = get_glob_type(); } else if(variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if(variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if(variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if(variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch(declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; switch(expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if(dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { switch(type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { switch(type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, diff --git a/main.c b/main.c index a59e185..b1ba441 100644 --- a/main.c +++ b/main.c @@ -1,318 +1,321 @@ #include <config.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <libfirm/firm.h> #include <libfirm/be.h> #include "driver/firm_opt.h" #include "driver/firm_cmdline.h" #include "type.h" #include "parser.h" #include "ast_t.h" #include "semantic.h" #include "ast2firm.h" #include "plugins.h" #include "type_hash.h" +#include "mangle.h" #include "adt/error.h" #ifdef _WIN32 #define LINKER "gcc.exe" #define TMPDIR "" #define DEFAULT_OS TARGET_OS_MINGW #else #if defined(__APPLE__) #define DEFAULT_OS TARGET_OS_MACHO #else #define DEFAULT_OS TARGET_OS_ELF #endif #define LINKER "gcc" #define TMPDIR "/tmp/" #endif typedef enum { TARGET_OS_MINGW, TARGET_OS_ELF, TARGET_OS_MACHO } target_os_t; static int dump_graphs = 0; static int dump_asts = 0; static int verbose = 0; static int show_timers = 0; static int noopt = 0; static int do_inline = 1; static target_os_t target_os = DEFAULT_OS; typedef enum compile_mode_t { Compile, CompileAndLink } compile_mode_t; const ir_settings_if_conv_t *if_conv_info = NULL; static void set_be_option(const char *arg) { int res = be_parse_arg(arg); (void) res; assert(res); } static void initialize_firm(void) { be_opt_register(); dbg_init(NULL, NULL, dbg_snprint); switch (target_os) { case TARGET_OS_MINGW: set_be_option("ia32-gasmode=mingw"); break; case TARGET_OS_ELF: set_be_option("ia32-gasmode=elf"); break; case TARGET_OS_MACHO: set_be_option("ia32-gasmode=macho"); set_be_option("ia32-stackalign=4"); set_be_option("pic"); break; } } static void get_output_name(char *buf, size_t buflen, const char *inputname, const char *newext) { size_t last_dot = 0xffffffff; size_t i = 0; for(const char *c = inputname; *c != 0; ++c) { if(*c == '.') last_dot = i; ++i; } if(last_dot == 0xffffffff) last_dot = i; if(last_dot >= buflen) panic("filename too long"); memcpy(buf, inputname, last_dot); size_t extlen = strlen(newext) + 1; if(extlen + last_dot >= buflen) panic("filename too long"); memcpy(buf+last_dot, newext, extlen); } static void dump_ast(const namespace_t *namespace, const char *name) { if(!dump_asts) return; const char *fname = namespace->filename; char filename[4096]; get_output_name(filename, sizeof(filename), fname, name); FILE* out = fopen(filename, "w"); if(out == NULL) { fprintf(stderr, "Warning: couldn't open '%s': %s\n", filename, strerror(errno)); } else { print_ast(out, namespace); } fclose(out); } static void parse_file(const char *fname) { FILE *in = fopen(fname, "r"); if(in == NULL) { fprintf(stderr, "couldn't open '%s' for reading: %s\n", fname, strerror(errno)); exit(1); } namespace_t *namespace = parse(in, fname); fclose(in); if(namespace == NULL) { exit(1); } dump_ast(namespace, "-parse.txt"); } static void check_semantic(void) { if(!check_static_semantic()) { fprintf(stderr, "Semantic errors found\n"); namespace_t *namespace = namespaces; while(namespace != NULL) { dump_ast(namespace, "-error.txt"); namespace = namespace->next; } exit(1); } if(dump_asts) { namespace_t *namespace = namespaces; while(namespace != NULL) { dump_ast(namespace, "-semantic.txt"); namespace = namespace->next; } } } static void link(const char *in, const char *out) { char buf[4096]; if(out == NULL) { out = "a.out"; } snprintf(buf, sizeof(buf), "%s %s -o %s", LINKER, in, out); if(verbose) { puts(buf); } int err = system(buf); if(err != 0) { fprintf(stderr, "linker reported an error\n"); exit(1); } } static void usage(const char *argv0) { fprintf(stderr, "Usage: %s input1 input2 [-o output]\n", argv0); } void lower_compound_params(void) { } int main(int argc, const char **argv) { gen_firm_init(); init_symbol_table(); init_tokens(); init_type_module(); init_typehash(); init_ast_module(); init_parser(); init_semantic_module(); search_plugins(); initialize_plugins(); initialize_firm(); init_ast2firm(); + init_mangle(); firm_opt.lower_ll = false; const char *outname = NULL; compile_mode_t mode = CompileAndLink; int parsed = 0; for(int i = 1; i < argc; ++i) { const char *arg = argv[i]; if(strcmp(arg, "-o") == 0) { ++i; if(i >= argc) { usage(argv[0]); return 1; } outname = argv[i]; } else if(strcmp(arg, "--dump") == 0) { dump_graphs = 1; dump_asts = 1; } else if(strcmp(arg, "--dump-ast") == 0) { dump_asts = 1; } else if(strcmp(arg, "--dump-graph") == 0) { dump_graphs = 1; } else if(strcmp(arg, "--help") == 0) { usage(argv[0]); return 0; } else if(strcmp(arg, "--time") == 0) { show_timers = 1; } else if(arg[0] == '-' && arg[1] == 'O') { int optlevel = atoi(&arg[2]); if(optlevel <= 0) { noopt = 1; } else if(optlevel > 1) { do_inline = 1; } else { noopt = 0; do_inline = 0; } } else if(strcmp(arg, "-S") == 0) { mode = Compile; } else if(strcmp(arg, "-c") == 0) { mode = CompileAndLink; } else if(strcmp(arg, "-v") == 0) { verbose = 1; } else if(strncmp(arg, "-b", 2) == 0) { const char *bearg = arg+2; if(bearg[0] == 0) { ++i; if(i >= argc) { usage(argv[0]); return 1; } bearg = argv[i]; } if(!be_parse_arg(bearg)) { fprintf(stderr, "Invalid backend option: %s\n", bearg); usage(argv[0]); return 1; } if(strcmp(bearg, "help") == 0) { return 1; } } else { parsed++; parse_file(argv[i]); } } if(parsed == 0) { fprintf(stderr, "Error: no input files specified\n"); return 0; } check_semantic(); ast2firm(); const char *asmname; if(mode == Compile) { asmname = outname; } else { asmname = TMPDIR "fluffy.s"; } FILE* asm_out = fopen(asmname, "w"); if (asm_out == NULL) { fprintf(stderr, "Couldn't open output '%s'\n", asmname); return 1; } gen_firm_finish(asm_out, asmname, 1, true); fclose(asm_out); if(mode == CompileAndLink) { link(asmname, outname); } + exit_mangle(); exit_ast2firm(); free_plugins(); exit_semantic_module(); exit_parser(); exit_ast_module(); exit_type_module(); exit_typehash(); exit_tokens(); exit_symbol_table(); return 0; } diff --git a/mangle.c b/mangle.c index fd8379d..e185f91 100644 --- a/mangle.c +++ b/mangle.c @@ -1,157 +1,201 @@ #include <config.h> #include <stdbool.h> #include "mangle.h" #include "ast_t.h" +#include "type_t.h" +#include "adt/error.h" #include <libfirm/firm.h> +#include "driver/firm_cmdline.h" static struct obstack obst; -static ident *make_id_from_obst(void) +static void mangle_string(const char *str) { - size_t size = obstack_object_size(&obst); - char *str = obstack_finish(&obst); - ident *id = new_id_from_chars(str, size); - obstack_free(&obst, str); - return id; + size_t len = strlen(str); + obstack_grow(&obst, str, len); } -/** - * Mangles an entity linker (ld) name for win32 usage. - * - * @param ent the entity to be mangled - * @param declaration the declaration - */ -ident *create_name_win32(declaration_t *declaration) -{ - struct obstack *o = &obst; - -#if 0 - if (declaration->type == DECLARATION_METHOD) { - if (declaration->declaration.modifiers & DM_DLLIMPORT) - /* add prefix for imported symbols */ - obstack_printf(o, "__imp_"); - - cc_kind_t cc = declaration->declaration.type->function.calling_convention; - - /* calling convention prefix */ - switch (cc) { - case CC_DEFAULT: - case CC_CDECL: - case CC_STDCALL: obstack_1grow(o, '_'); break; - case CC_FASTCALL: obstack_1grow(o, '@'); break; - default: panic("unhandled calling convention"); - } - - switch (declaration->declaration.type->function.linkage) { - case LINKAGE_INVALID: - panic("linkage type of function is invalid"); - - case LINKAGE_C: - obstack_printf(o, "%s", declaration->base.symbol->string); - break; - - case LINKAGE_CXX: - mangle_entity(declaration); - break; - } - - /* calling convention suffix */ - switch (cc) { - case CC_DEFAULT: - case CC_CDECL: - break; - - case CC_STDCALL: - case CC_FASTCALL: { - ir_type *irtype = get_ir_type(declaration->declaration.type); - unsigned size = 0; - for (int i = get_method_n_params(irtype) - 1; i >= 0; --i) { - size += get_type_size_bytes(get_method_param_type(irtype, i)); - } - obstack_printf(o, "@%u", size); - break; - } - - default: - panic("unhandled calling convention"); - } - } else { - obstack_printf(o, "_%s", declaration->base.symbol->string); +static void mangle_len_string(const char *string) +{ + size_t len = strlen(string); + obstack_printf(&obst, "%zu%s", len, string); +} + +static void mangle_atomic_type(const atomic_type_t *type) +{ + char c; + + switch(type->atype) { + case ATOMIC_TYPE_INVALID: + abort(); + break; + case ATOMIC_TYPE_BOOL: + c = 'b'; + break; + case ATOMIC_TYPE_BYTE: + c = 'c'; + break; + case ATOMIC_TYPE_UBYTE: + c = 'h'; + break; + case ATOMIC_TYPE_INT: + c = 'i'; + break; + case ATOMIC_TYPE_UINT: + c = 'j'; + break; + case ATOMIC_TYPE_SHORT: + c = 's'; + break; + case ATOMIC_TYPE_USHORT: + c = 't'; + break; + case ATOMIC_TYPE_LONG: + c = 'l'; + break; + case ATOMIC_TYPE_ULONG: + c = 'm'; + break; + case ATOMIC_TYPE_LONGLONG: + c = 'n'; + break; + case ATOMIC_TYPE_ULONGLONG: + c = 'o'; + break; + case ATOMIC_TYPE_FLOAT: + c = 'f'; + break; + case ATOMIC_TYPE_DOUBLE: + c = 'd'; + break; + default: + abort(); + break; } -#endif - obstack_printf(o, "_%s", declaration->symbol->string); - return make_id_from_obst(); + obstack_1grow(&obst, c); } -/** - * Mangles an entity linker (ld) name for Linux ELF usage. - * - * @param ent the entity to be mangled - * @param declaration the declaration - */ -ident *create_name_linux_elf(declaration_t *declaration) +static void mangle_compound_type(const compound_type_t *type) { -#if 0 - bool needs_mangling = false; + mangle_len_string(type->symbol->string); +} + +static void mangle_pointer_type(const pointer_type_t *type) +{ + obstack_1grow(&obst, 'P'); + mangle_type(type->points_to); +} + +static void mangle_array_type(const array_type_t *type) +{ + obstack_1grow(&obst, 'A'); + mangle_type(type->element_type); + obstack_printf(&obst, "%lu", type->size); +} + +static void mangle_method_type(const method_type_t *type) +{ + obstack_1grow(&obst, 'F'); + mangle_type(type->result_type); + + method_parameter_type_t *parameter_type = type->parameter_types; + while(parameter_type != NULL) { + mangle_type(parameter_type->type); + } + obstack_1grow(&obst, 'E'); +} - if (declaration->kind == ENTITY_FUNCTION) { - switch (declaration->declaration.type->function.linkage) { - case LINKAGE_INVALID: - panic("linkage type of function is invalid"); +static void mangle_reference_type_variable(const type_reference_t* ref) +{ + type_variable_t *type_var = ref->type_variable; + type_t *current_type = type_var->current_type; - case LINKAGE_C: break; - case LINKAGE_CXX: needs_mangling = true; break; - } + if(current_type == NULL) { + panic("can't mangle unbound type variable"); } + mangle_type(current_type); +} - if (needs_mangling) { - mangle_entity(declaration); - return make_id_from_obst(); +void mangle_type(const type_t *type) +{ + switch(type->type) { + case TYPE_INVALID: + break; + case TYPE_VOID: + obstack_1grow(&obst, 'v'); + return; + case TYPE_ATOMIC: + mangle_atomic_type((const atomic_type_t*) type); + return; + case TYPE_COMPOUND_CLASS: + case TYPE_COMPOUND_UNION: + case TYPE_COMPOUND_STRUCT: + mangle_compound_type((const compound_type_t*) type); + return; + case TYPE_METHOD: + mangle_method_type((const method_type_t*) type); + return; + case TYPE_POINTER: + mangle_pointer_type((const pointer_type_t*) type); + return; + case TYPE_ARRAY: + mangle_array_type((const array_type_t*) type); + return; + case TYPE_REFERENCE: + panic("can't mangle unresolved type reference"); + return; + case TYPE_BIND_TYPEVARIABLES: + /* should have been normalized already in semantic phase... */ + panic("can't mangle type variable bindings"); + return; + case TYPE_REFERENCE_TYPE_VARIABLE: + mangle_reference_type_variable((const type_reference_t*) type); + return; } -#endif + panic("Unknown type mangled"); +} - return new_id_from_str(declaration->symbol->string); +void mangle_symbol_simple(symbol_t *symbol) +{ + mangle_string(symbol->string); } -/** - * Mangles an entity linker (ld) name for Mach-O usage. - * - * @param ent the entity to be mangled - * @param declaration the declaration - */ -ident *create_name_macho(declaration_t *declaration) +void mangle_symbol(symbol_t *symbol) { -#if 0 - bool needs_mangling = false; - if (declaration->kind == ENTITY_FUNCTION) { - switch (declaration->declaration.type->function.linkage) { - case LINKAGE_INVALID: - panic("linkage type of function is invalid"); + mangle_len_string(symbol->string); +} - case LINKAGE_C: break; - case LINKAGE_CXX: needs_mangling = true; break; - } - } +void mangle_concept_name(symbol_t *symbol) +{ + obstack_grow(&obst, "tcv", 3); + mangle_len_string(symbol->string); +} - if (needs_mangling) { +void start_mangle(void) +{ + if (firm_opt.os_support == OS_SUPPORT_MACHO + || firm_opt.os_support == OS_SUPPORT_MINGW) { obstack_1grow(&obst, '_'); - mangle_entity(declaration); - return make_id_from_obst(); } -#endif +} - obstack_printf(&obst, "_%s", declaration->symbol->string); - return make_id_from_obst(); +ident *finish_mangle(void) +{ + size_t size = obstack_object_size(&obst); + char *str = obstack_finish(&obst); + ident *id = new_id_from_chars(str, size); + obstack_free(&obst, str); + return id; } void init_mangle(void) { obstack_init(&obst); } void exit_mangle(void) { obstack_free(&obst, NULL); } diff --git a/mangle.h b/mangle.h index aeca9a2..8936269 100644 --- a/mangle.h +++ b/mangle.h @@ -1,15 +1,20 @@ #ifndef MANGE_H #define MANGE_H #include "ast.h" +#include "symbol.h" +#include "type.h" #include <libfirm/firm_types.h> -ident *create_name_linux_elf(declaration_t *decl); -ident *create_name_macho(declaration_t *decl); -ident *create_name_win32(declaration_t *decl); +void start_mangle(void); +void mangle_symbol_simple(symbol_t *symbol); +void mangle_symbol(symbol_t *symbol); +void mangle_concept_name(symbol_t *symbol); +ident *finish_mangle(void); +void mangle_type(const type_t *type); void init_mangle(void); void exit_mangle(void); #endif diff --git a/mangle_type.c b/mangle_type.c deleted file mode 100644 index 27b270e..0000000 --- a/mangle_type.c +++ /dev/null @@ -1,146 +0,0 @@ -#include <config.h> - -#include "mangle_type.h" -#include "type_t.h" -#include "ast_t.h" -#include "adt/error.h" - -static void mangle_atomic_type(struct obstack *obst, const atomic_type_t *type) -{ - char c; - - switch(type->atype) { - case ATOMIC_TYPE_INVALID: - abort(); - break; - case ATOMIC_TYPE_BOOL: - c = 'b'; - break; - case ATOMIC_TYPE_BYTE: - c = 'c'; - break; - case ATOMIC_TYPE_UBYTE: - c = 'h'; - break; - case ATOMIC_TYPE_INT: - c = 'i'; - break; - case ATOMIC_TYPE_UINT: - c = 'j'; - break; - case ATOMIC_TYPE_SHORT: - c = 's'; - break; - case ATOMIC_TYPE_USHORT: - c = 't'; - break; - case ATOMIC_TYPE_LONG: - c = 'l'; - break; - case ATOMIC_TYPE_ULONG: - c = 'm'; - break; - case ATOMIC_TYPE_LONGLONG: - c = 'n'; - break; - case ATOMIC_TYPE_ULONGLONG: - c = 'o'; - break; - case ATOMIC_TYPE_FLOAT: - c = 'f'; - break; - case ATOMIC_TYPE_DOUBLE: - c = 'd'; - break; - default: - abort(); - break; - } - - obstack_1grow(obst, c); -} - -static void mangle_compound_type(struct obstack *obst, const compound_type_t *type) -{ - const char *string = type->symbol->string; - size_t string_len = strlen(string); - obstack_printf(obst, "%zu%s", string_len, string); -} - -static void mangle_pointer_type(struct obstack *obst, const pointer_type_t *type) -{ - obstack_1grow(obst, 'P'); - mangle_type(obst, type->points_to); -} - -static void mangle_array_type(struct obstack *obst, const array_type_t *type) -{ - obstack_1grow(obst, 'A'); - mangle_type(obst, type->element_type); - obstack_printf(obst, "%lu", type->size); -} - -static void mangle_method_type(struct obstack *obst, const method_type_t *type) -{ - obstack_1grow(obst, 'F'); - mangle_type(obst, type->result_type); - - method_parameter_type_t *parameter_type = type->parameter_types; - while(parameter_type != NULL) { - mangle_type(obst, parameter_type->type); - } - obstack_1grow(obst, 'E'); -} - -static void mangle_reference_type_variable(struct obstack *obst, - const type_reference_t* ref) -{ - type_variable_t *type_var = ref->type_variable; - type_t *current_type = type_var->current_type; - - if(current_type == NULL) { - panic("can't mangle unbound type variable"); - } - mangle_type(obst, current_type); -} - -void mangle_type(struct obstack *obst, const type_t *type) -{ - switch(type->type) { - case TYPE_INVALID: - break; - case TYPE_VOID: - obstack_1grow(obst, 'v'); - return; - case TYPE_ATOMIC: - mangle_atomic_type(obst, (const atomic_type_t*) type); - return; - case TYPE_COMPOUND_CLASS: - case TYPE_COMPOUND_UNION: - case TYPE_COMPOUND_STRUCT: - mangle_compound_type(obst, (const compound_type_t*) type); - return; - case TYPE_METHOD: - mangle_method_type(obst, (const method_type_t*) type); - return; - case TYPE_POINTER: - mangle_pointer_type(obst, (const pointer_type_t*) type); - return; - case TYPE_ARRAY: - mangle_array_type(obst, (const array_type_t*) type); - return; - case TYPE_REFERENCE: - panic("can't mangle unresolved type reference"); - return; - case TYPE_BIND_TYPEVARIABLES: - /* should have been normalized already in semantic phase... */ - panic("can't mangle type variable bindings"); - return; - case TYPE_REFERENCE_TYPE_VARIABLE: - mangle_reference_type_variable(obst, (const type_reference_t*) type); - return; - } - panic("Unknown type mangled"); - abort(); -} - diff --git a/mangle_type.h b/mangle_type.h deleted file mode 100644 index b4b6c9f..0000000 --- a/mangle_type.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef MANGLE_TYPE_H -#define MANGLE_TYPE_H - -#include "adt/obst.h" -#include "type.h" - -/** - * Pushes type mangled as string onto the obstack. - */ -void mangle_type(struct obstack *obst, const type_t *type); - -#endif -
MatzeB/fluffy
1900e213046daaebc6713fc6dd03ed864c485118
don't pass output FILE around, make it a global state in type.c
diff --git a/.gitignore b/.gitignore index 0760677..c107dfc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ *.o *.dylib .*.swp a.out /config.mak +/.depend +/fluffy +/fluffy.exe diff --git a/ast.c b/ast.c index 280d347..a4035e2 100644 --- a/ast.c +++ b/ast.c @@ -1,681 +1,681 @@ #include <config.h> #include "ast_t.h" #include "type_t.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include "adt/error.h" struct obstack ast_obstack; namespace_t *namespaces; static FILE *out; static int indent = 0; static void print_expression(const expression_t *expression); static void print_statement(const statement_t *statement); static void print_int_const(const int_const_t *int_const) { fprintf(out, "%d", int_const->value); } static void print_string_const(const string_const_t *string_const) { /* TODO escape " and non-printable chars */ fputc('"', out); for(const char *c = string_const->value; *c != 0; ++c) { switch(*c) { case '\a': fputs("\\a", out); break; case '\b': fputs("\\b", out); break; case '\f': fputs("\\f", out); break; case '\n': fputs("\\n", out); break; case '\r': fputs("\\r", out); break; case '\t': fputs("\\t", out); break; case '\v': fputs("\\v", out); break; case '\\': fputs("\\\\", out); break; case '"': fputs("\\\"", out); break; default: fputc(*c, out); break; } } fputc('"', out); } static void print_call_expression(const call_expression_t *call) { print_expression(call->method); fprintf(out, "("); call_argument_t *argument = call->arguments; int first = 1; while(argument != NULL) { if(!first) { fprintf(out, ", "); } else { first = 0; } print_expression(argument->expression); argument = argument->next; } fprintf(out, ")"); } static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while(argument != NULL) { if(first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } - print_type(out, argument->type); + print_type(argument->type); argument = argument->next; } if(type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if(ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if(select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); - print_type(out, expr->type); + print_type(expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch(unexpr->type) { case UNEXPR_CAST: fprintf(out, "cast<"); - print_type(out, unexpr->expression.datatype); + print_type(unexpr->expression.datatype); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->type); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch(binexpr->type) { case BINEXPR_INVALID: fprintf(out, "INVOP"); break; case BINEXPR_ASSIGN: fprintf(out, "<-"); break; case BINEXPR_ADD: fprintf(out, "+"); break; case BINEXPR_SUB: fprintf(out, "-"); break; case BINEXPR_MUL: fprintf(out, "*"); break; case BINEXPR_DIV: fprintf(out, "/"); break; case BINEXPR_NOTEQUAL: fprintf(out, "/="); break; case BINEXPR_EQUAL: fprintf(out, "="); break; case BINEXPR_LESS: fprintf(out, "<"); break; case BINEXPR_LESSEQUAL: fprintf(out, "<="); break; case BINEXPR_GREATER: fprintf(out, ">"); break; case BINEXPR_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->type); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if(expression == NULL) { fprintf(out, "*null expression*"); return; } switch(expression->type) { case EXPR_LAST: case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; case EXPR_BINARY: print_binary_expression((const binary_expression_t*) expression); break; case EXPR_UNARY: print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; default: /* TODO */ fprintf(out, "some expression of type %d", expression->type); break; } } static void print_indent(void) { for(int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while(statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if(statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if(statement->label != NULL) { symbol_t *symbol = statement->label->declaration.symbol; if(symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.declaration.symbol; if(symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if(statement->true_statement != NULL) print_statement(statement->true_statement); if(statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if(var->type != NULL) { fprintf(out, "<"); - print_type(out, var->type); + print_type(var->type); fprintf(out, ">"); } fprintf(out, " %s", var->declaration.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch(statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if(constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->declaration.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->declaration.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while(type_parameter != NULL) { if(first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if(type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while(parameter != NULL && parameter_type != NULL) { if(!first) { fprintf(out, ", "); } else { first = 0; } - print_type(out, parameter_type->type); + print_type(parameter_type->type); fprintf(out, " %s", parameter->declaration.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if(method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->declaration.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); - print_type(out, type->result_type); + print_type(type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->declaration.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); - print_type(out, method->method_type->result_type); + print_type(method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->declaration.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while(method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if(method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->declaration.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); - print_type(out, method_instance->method.type->result_type); + print_type(method_instance->method.type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if(instance->concept != NULL) { fprintf(out, "%s", instance->concept->declaration.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->declaration.symbol->string); if(constant->type != NULL) { fprintf(out, " "); - print_type(out, constant->type); + print_type(constant->type); } if(constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->declaration.symbol->string); - print_type(out, alias->type); + print_type(alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch(declaration->type) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: // TODO fprintf(out, "some declaration of type %d\n", declaration->type); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%d)\n", declaration->type); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { print_declaration(declaration); declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { print_concept_instance(instance); instance = instance->next; } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_type_name(declaration_type_t type) { switch(type) { case DECLARATION_LAST: case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } diff --git a/ast2firm.c b/ast2firm.c index 7c8e509..1d0375b 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -882,1025 +882,1025 @@ static ir_entity *create_variable_entity(variable_declaration_t *variable) } else if(variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if(variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if(variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if(variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch(declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; switch(expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if(dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { switch(type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { switch(type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if(compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; switch(unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if(entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if(strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while(type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if(last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if(instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); - print_type(stderr, concept->type_parameters->current_type); + print_type(concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if(method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while(argument != NULL) { n_parameters++; argument = argument->next; } if(method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while(argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if(new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if(new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if(result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if(entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); case DECLARATION_ITERATOR: // TODO panic("TODO: iterator to firm"); break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch(expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if(statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if(statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while(statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if(block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if(statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch(statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if(method->is_extern) return; int old_top = typevar_binding_stack_top(); if(is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if(method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if(get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while(label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for(int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if(align > align_all) align_all = align; int misalign = 0; if(align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if(!is_polymorphic_method(method)) { assure_instance(method, declaration->symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_ITERATOR: diff --git a/mangle_type.c b/mangle_type.c index 61ccfa0..27b270e 100644 --- a/mangle_type.c +++ b/mangle_type.c @@ -1,145 +1,146 @@ #include <config.h> #include "mangle_type.h" #include "type_t.h" #include "ast_t.h" #include "adt/error.h" static void mangle_atomic_type(struct obstack *obst, const atomic_type_t *type) { char c; switch(type->atype) { case ATOMIC_TYPE_INVALID: abort(); break; case ATOMIC_TYPE_BOOL: c = 'b'; break; case ATOMIC_TYPE_BYTE: c = 'c'; break; case ATOMIC_TYPE_UBYTE: c = 'h'; break; case ATOMIC_TYPE_INT: c = 'i'; break; case ATOMIC_TYPE_UINT: c = 'j'; break; case ATOMIC_TYPE_SHORT: c = 's'; break; case ATOMIC_TYPE_USHORT: c = 't'; break; case ATOMIC_TYPE_LONG: c = 'l'; break; case ATOMIC_TYPE_ULONG: c = 'm'; break; case ATOMIC_TYPE_LONGLONG: c = 'n'; break; case ATOMIC_TYPE_ULONGLONG: c = 'o'; break; case ATOMIC_TYPE_FLOAT: c = 'f'; break; case ATOMIC_TYPE_DOUBLE: c = 'd'; break; default: abort(); break; } obstack_1grow(obst, c); } static void mangle_compound_type(struct obstack *obst, const compound_type_t *type) { const char *string = type->symbol->string; size_t string_len = strlen(string); obstack_printf(obst, "%zu%s", string_len, string); } static void mangle_pointer_type(struct obstack *obst, const pointer_type_t *type) { obstack_1grow(obst, 'P'); mangle_type(obst, type->points_to); } static void mangle_array_type(struct obstack *obst, const array_type_t *type) { obstack_1grow(obst, 'A'); mangle_type(obst, type->element_type); obstack_printf(obst, "%lu", type->size); } static void mangle_method_type(struct obstack *obst, const method_type_t *type) { obstack_1grow(obst, 'F'); mangle_type(obst, type->result_type); method_parameter_type_t *parameter_type = type->parameter_types; while(parameter_type != NULL) { mangle_type(obst, parameter_type->type); } obstack_1grow(obst, 'E'); } static void mangle_reference_type_variable(struct obstack *obst, const type_reference_t* ref) { type_variable_t *type_var = ref->type_variable; type_t *current_type = type_var->current_type; if(current_type == NULL) { panic("can't mangle unbound type variable"); } mangle_type(obst, current_type); } void mangle_type(struct obstack *obst, const type_t *type) { switch(type->type) { case TYPE_INVALID: break; case TYPE_VOID: obstack_1grow(obst, 'v'); return; case TYPE_ATOMIC: mangle_atomic_type(obst, (const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: mangle_compound_type(obst, (const compound_type_t*) type); return; case TYPE_METHOD: mangle_method_type(obst, (const method_type_t*) type); return; case TYPE_POINTER: mangle_pointer_type(obst, (const pointer_type_t*) type); return; case TYPE_ARRAY: mangle_array_type(obst, (const array_type_t*) type); return; case TYPE_REFERENCE: panic("can't mangle unresolved type reference"); return; case TYPE_BIND_TYPEVARIABLES: + /* should have been normalized already in semantic phase... */ panic("can't mangle type variable bindings"); return; case TYPE_REFERENCE_TYPE_VARIABLE: mangle_reference_type_variable(obst, (const type_reference_t*) type); return; } panic("Unknown type mangled"); abort(); } diff --git a/match_type.c b/match_type.c index f34febf..dca76ec 100644 --- a/match_type.c +++ b/match_type.c @@ -1,228 +1,228 @@ #include <config.h> #include "match_type.h" #include <assert.h> #include "type_t.h" #include "ast_t.h" #include "semantic_t.h" #include "type_hash.h" #include "adt/error.h" static inline void match_error(type_t *variant, type_t *concrete, const source_position_t source_position) { print_error_prefix(source_position); fprintf(stderr, "can't match variant type "); - print_type(stderr, variant); + print_type(variant); fprintf(stderr, " against "); - print_type(stderr, concrete); + print_type(concrete); fprintf(stderr, "\n"); } static bool matched_type_variable(type_variable_t *type_variable, type_t *type, const source_position_t source_position, bool report_errors) { type_t *current_type = type_variable->current_type; if(current_type != NULL && current_type != type) { if (report_errors) { print_error_prefix(source_position); fprintf(stderr, "ambiguous matches found for type variable '%s': ", type_variable->declaration.symbol->string); - print_type(stderr, current_type); + print_type(current_type); fprintf(stderr, ", "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); } /* are both types normalized? */ assert(typehash_contains(current_type)); assert(typehash_contains(type)); return false; } type_variable->current_type = type; return true; } static bool match_compound_type(compound_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_variable_t *type_parameters = variant_type->type_parameters; if(type_parameters == NULL) { if(concrete_type != (type_t*) variant_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } return true; } if(concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if(polymorphic_type != variant_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = bind_typevariables->type_arguments; bool result = true; while(type_parameter != NULL) { assert(type_argument != NULL); if(!matched_type_variable(type_parameter, type_argument->type, source_position, true)) result = false; type_parameter = type_parameter->next; type_argument = type_argument->next; } return result; } static bool match_bind_typevariables(bind_typevariables_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { if(concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if(polymorphic_type != variant_type->polymorphic_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_argument_t *argument1 = variant_type->type_arguments; type_argument_t *argument2 = bind_typevariables->type_arguments; bool result = true; while(argument1 != NULL) { assert(argument2 != NULL); if(!match_variant_to_concrete_type(argument1->type, argument2->type, source_position, report_errors)) result = false; argument1 = argument1->next; argument2 = argument2->next; } assert(argument2 == NULL); return result; } bool match_variant_to_concrete_type(type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_reference_t *type_ref; type_variable_t *type_var; pointer_type_t *pointer_type_1; pointer_type_t *pointer_type_2; method_type_t *method_type_1; method_type_t *method_type_2; assert(type_valid(variant_type)); assert(type_valid(concrete_type)); switch(variant_type->type) { case TYPE_REFERENCE_TYPE_VARIABLE: type_ref = (type_reference_t*) variant_type; type_var = type_ref->type_variable; return matched_type_variable(type_var, concrete_type, source_position, report_errors); case TYPE_VOID: case TYPE_ATOMIC: if(concrete_type != variant_type) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } return true; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return match_compound_type((compound_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_POINTER: if(concrete_type->type != TYPE_POINTER) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } pointer_type_1 = (pointer_type_t*) variant_type; pointer_type_2 = (pointer_type_t*) concrete_type; return match_variant_to_concrete_type(pointer_type_1->points_to, pointer_type_2->points_to, source_position, report_errors); case TYPE_METHOD: if(concrete_type->type != TYPE_METHOD) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } method_type_1 = (method_type_t*) variant_type; method_type_2 = (method_type_t*) concrete_type; bool result = match_variant_to_concrete_type(method_type_1->result_type, method_type_2->result_type, source_position, report_errors); method_parameter_type_t *param1 = method_type_1->parameter_types; method_parameter_type_t *param2 = method_type_2->parameter_types; while(param1 != NULL && param2 != NULL) { if(!match_variant_to_concrete_type(param1->type, param2->type, source_position, report_errors)) result = false; param1 = param1->next; param2 = param2->next; } if(param1 != NULL || param2 != NULL) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return result; case TYPE_BIND_TYPEVARIABLES: return match_bind_typevariables( (bind_typevariables_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_ARRAY: panic("TODO"); case TYPE_REFERENCE: panic("type reference not resolved in match variant to concrete type"); case TYPE_INVALID: panic("invalid type in match variant to concrete type"); } panic("unknown type in match variant to concrete type"); } diff --git a/semantic.c b/semantic.c index d2a4c59..6b7daf2 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2396 +1,2396 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if(symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if(new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while(i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if(declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if(type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if(declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while(type_parameter != NULL) { if(type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if(type_argument != NULL) { print_error_prefix(type_ref->source_position); if(type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } - print_type(stderr, type); + print_type(type); fprintf(stderr, " takes no type parameters\n"); } if(type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if(type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while(entry != NULL) { type_t *type = entry->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if(type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: return type; case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if(type == NULL) return NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if(constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_ITERATOR: panic("TODO iterator reference"); break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if(!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if(left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if(left->datatype == NULL) { if(right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position, bool lenient) { if(dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ type_t *from_type = from->datatype; if(from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); - print_type(stderr, dest_type); + print_type(dest_type); fprintf(stderr, "\n"); return NULL; } bool implicit_cast_allowed = true; if(from_type->type == TYPE_POINTER) { if(dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if(p1->points_to != p2->points_to && dest_type != type_void_ptr && from->type != EXPR_NULL_POINTER) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if(dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if(pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if(from_type->type == TYPE_ATOMIC) { if(dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { case ATOMIC_TYPE_BOOL: if (!lenient) { implicit_cast_allowed = false; break; } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if(!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); - print_type(stderr, from_type); + print_type(from_type); fprintf(stderr, " to "); - print_type(stderr, dest_type); + print_type(dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if(lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position, false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if(!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); - print_type(stderr, left->datatype); + print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); - print_type(stderr, left->datatype); + print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); - print_type(stderr, left->datatype); + print_type(left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if(left == NULL || right == NULL) return; if(left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position, false); } if(right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position, false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while(argument != NULL && parameter != NULL) { if(parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if(parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if(match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if(match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { if(constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { if(method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while(type_var != NULL) { type_t *current_type = type_var->current_type; if(current_type == NULL) return; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if(!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if(cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if(instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters; while(typevar != NULL) { if(typevar->current_type != NULL) { - print_type(stderr, typevar->current_type); + print_type(typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if(method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if(concept == NULL) continue; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if(!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->declaration.symbol->string, concept->declaration.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if(instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->declaration.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); - print_type(stderr, type_var->current_type); + print_type(type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->declaration.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if(type == NULL) { return type_int; } switch(type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); - print_type(stderr, type); + print_type(type); fprintf(stderr, ") not supported for function parameters.\n"); return type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); - print_type(stderr, type); + print_type(type); fprintf(stderr, ") not supported for function parameter.\n"); return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); return type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if(type == NULL) return; /* determine method type */ if(type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if(type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if(method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if(declaration->type == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if(type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while(type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if(type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while(argument != NULL) { if(param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if(param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if(type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if(expression_type != wanted_type) { /* be a bit lenient for varargs function, to not make using C printf too much of a pain... */ bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, expression->source_position, lenient); if(new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); - print_type(stderr, expression->datatype); + print_type(expression->datatype); fprintf(stderr, " should be "); - print_type(stderr, wanted_type); + print_type(wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if(param_type != NULL) param_type = param_type->next; ++i; } if(param_type != NULL) { error_at(call->expression.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while(type_var != NULL) { if(type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->declaration.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->declaration.symbol->string, type_var); - print_type(stderr, type_var->current_type); + print_type(type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if(type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if(declaration->type == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->type == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if(ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while(type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if(last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if(cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if(cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if(value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if(value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if(!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if(value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if(type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(unary_expression_t *expression) { expression_t *value = check_expression(expression->value); type_t *type = value->datatype; if(!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); } if(!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if(type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if(atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if(need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.type = EXPR_BINARY; add->expression.datatype = type; if(expression->type == UNEXPR_INCREMENT) { add->type = BINEXPR_ADD; } else { add->type = BINEXPR_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.datatype = type; assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static expression_t *lower_unary_expression(expression_t *expression) { assert(expression->type == EXPR_UNARY); unary_expression_t *unary_expression = (unary_expression_t*) expression; switch(unary_expression->type) { case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: return lower_incdec_expression(unary_expression); default: break; } return expression; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch(unary_expression->type) { case UNEXPR_CAST: check_cast_expression(unary_expression); return; case UNEXPR_DEREFERENCE: check_dereference_expression(unary_expression); return; case UNEXPR_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case UNEXPR_NOT: check_not_expression(unary_expression); return; case UNEXPR_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case UNEXPR_NEGATE: check_negate_expression(unary_expression); return; case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("increment/decrement not lowered"); case UNEXPR_INVALID: abort(); } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if(datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if(datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if(datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); - print_type(stderr, datatype); + print_type(datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if(points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); - print_type(stderr, datatype); + print_type(datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; while(declaration != NULL) { if(declaration->symbol == symbol) break; declaration = declaration->next; } if(declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while(entry != NULL) { if(entry->symbol == symbol) { break; } entry = entry->next; } if(entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); - print_type(stderr, (type_t*) compound_type); + print_type((type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if(bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if(type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); - print_type(stderr, type); + print_type(type); fprintf(stderr, "\n"); return; } type_t *result_type; if(type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if(index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); - print_type(stderr, index->datatype); + print_type(index->datatype); fprintf(stderr, "\n"); return; } if(index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, access->expression.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if(expression == NULL) return NULL; /* try to lower the expression */ if((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; if(lowerer != NULL) { expression = lowerer(expression); } } switch(expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; case EXPR_BINARY: check_binary_expression((binary_expression_t*) expression); break; case EXPR_UNARY: check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_LAST: case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if(return_value != NULL) { if(method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if(return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position, false); statement->return_value = return_value; } } else { if(method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if(condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); - print_type(stderr, condition->datatype); + print_type(condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if(statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { environment_push(declaration, context); declaration = declaration->next; } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while(statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if(last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if(statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if(expression->datatype == NULL) return; bool may_be_unused = false; if(expression->type == EXPR_BINARY && ((binary_expression_t*) expression)->type == BINEXPR_ASSIGN) { may_be_unused = true; } else if(expression->type == EXPR_UNARY && (((unary_expression_t*) expression)->type == UNEXPR_INCREMENT || ((unary_expression_t*) expression)->type == UNEXPR_DECREMENT)) { may_be_unused = true; } else if(expression->type == EXPR_CALL) { may_be_unused = true; } if(expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if(expression->type == EXPR_BINARY) { binary_expression_t *binexpr = (binary_expression_t*) expression; if(binexpr->type == BINEXPR_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if(goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if(symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if(declaration->type != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_type_name(declaration->type)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if(statement == NULL) return NULL; /* try to lower the statement */ if((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if(lowerer != NULL) { statement = lowerer(statement); } } if(statement == NULL) return NULL; last_statement_was_return = false; switch(statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if(method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while(parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if(method->statement != NULL) { method->statement = check_statement(method->statement); } if(!last_statement_was_return) { type_t *result_type = method->type->result_type; if(result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if(symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if(expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->declaration.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; while(constraint != NULL) { resolve_type_constraint(constraint, type_var->declaration.source_position); constraint = constraint->next; } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while(type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; while(concept_method != NULL) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; concept_method = concept_method->next; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(declaration->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(declaration->source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->declaration.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if(!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_type_name(declaration->type)); return; } found_export = true; } static void check_and_push_context(context_t *context) { variable_declaration_t *variable; method_declaration_t *method; typealias_t *typealias; type_t *type; concept_t *concept; push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->type = normalize_type(variable->type); diff --git a/test/wip/polyinstance.fluffy b/test/wip/polyinstance.fluffy index bd223b6..579f3cd 100644 --- a/test/wip/polyinstance.fluffy +++ b/test/wip/polyinstance.fluffy @@ -1,54 +1,53 @@ typealias String = byte* func extern malloc(size : unsigned int) : void* func extern printf(format : String, ...) : int func extern puts(val : String) func extern strcmp(s1 : String, s2 : String) : int concept Printable<T>: func print(obj : T) instance Printable String: func print(obj : String): puts(obj) instance Printable int: func print(obj : int): printf("%d\n", obj) struct ListElement<T>: val : T next : ListElement<T>* struct List<T>: first : ListElement<T>* func AddToList<T>(list : List<T>*, element : ListElement<T>*): element.next = list.first list.first = element -func PrintList<T : Printable>(list : List<T>*): - var elem = list.first - while elem /= null: - print(elem.val) - elem = elem.next - instance Printable<Foo : Printable> List<Foo>*: - func print(obj : List<Foo>*): - PrintList(obj) + func print(list : List<Foo>*): + var e = list.first + :beginloop + if e == null: + return + print(e.val) + e = e.next + goto beginloop func main() : int: var l : List<String> l.first = null var e1 : ListElement<String> e1.val = "Hallo" var e2 : ListElement<String> e2.val = "Welt" AddToList(&l, &e1) AddToList(&l, &e2) - //PrintList(&l) print(&l) return 0 export main diff --git a/type.c b/type.c index fd1e726..e4ccf00 100644 --- a/type.c +++ b/type.c @@ -1,571 +1,566 @@ #include <config.h> #include "type_t.h" #include "ast_t.h" #include "type_hash.h" #include "adt/error.h" #include "adt/array.h" //#define DEBUG_TYPEVAR_BINDING typedef struct typevar_binding_t typevar_binding_t; struct typevar_binding_t { type_variable_t *type_variable; type_t *old_current_type; }; static typevar_binding_t *typevar_binding_stack = NULL; static struct obstack _type_obst; struct obstack *type_obst = &_type_obst; static type_t type_void_ = { TYPE_VOID, NULL }; static type_t type_invalid_ = { TYPE_INVALID, NULL }; type_t *type_void = &type_void_; type_t *type_invalid = &type_invalid_; +static FILE* out; + void init_type_module() { obstack_init(type_obst); typevar_binding_stack = NEW_ARR_F(typevar_binding_t, 0); + out = stderr; } void exit_type_module() { DEL_ARR_F(typevar_binding_stack); obstack_free(type_obst, NULL); } -static void print_atomic_type(FILE *out, const atomic_type_t *type) +static void print_atomic_type(const atomic_type_t *type) { switch(type->atype) { case ATOMIC_TYPE_INVALID: fputs("INVALIDATOMIC", out); break; case ATOMIC_TYPE_BOOL: fputs("bool", out); break; case ATOMIC_TYPE_BYTE: fputs("byte", out); break; case ATOMIC_TYPE_UBYTE: fputs("unsigned byte", out); break; case ATOMIC_TYPE_INT: fputs("int", out); break; case ATOMIC_TYPE_UINT: fputs("unsigned int", out); break; case ATOMIC_TYPE_SHORT: fputs("short", out); break; case ATOMIC_TYPE_USHORT: fputs("unsigned short", out); break; case ATOMIC_TYPE_LONG: fputs("long", out); break; case ATOMIC_TYPE_ULONG: fputs("unsigned long", out); break; case ATOMIC_TYPE_LONGLONG: fputs("long long", out); break; case ATOMIC_TYPE_ULONGLONG: fputs("unsigned long long", out); break; case ATOMIC_TYPE_FLOAT: fputs("float", out); break; case ATOMIC_TYPE_DOUBLE: fputs("double", out); break; default: fputs("UNKNOWNATOMIC", out); break; } } -static void print_method_type(FILE *out, const method_type_t *type) +static void print_method_type(const method_type_t *type) { fputs("<", out); fputs("func(", out); method_parameter_type_t *param_type = type->parameter_types; int first = 1; while(param_type != NULL) { if(first) { first = 0; } else { fputs(", ", out); } - print_type(out, param_type->type); + print_type(param_type->type); param_type = param_type->next; } fputs(")", out); if(type->result_type != NULL && type->result_type->type != TYPE_VOID) { fputs(" : ", out); - print_type(out, type->result_type); + print_type(type->result_type); } fputs(">", out); } -static void print_pointer_type(FILE *out, const pointer_type_t *type) +static void print_pointer_type(const pointer_type_t *type) { - print_type(out, type->points_to); + print_type(type->points_to); fputs("*", out); } -static void print_array_type(FILE *out, const array_type_t *type) +static void print_array_type(const array_type_t *type) { - print_type(out, type->element_type); + print_type(type->element_type); fprintf(out, "[%lu]", type->size); } -static void print_type_reference(FILE *out, const type_reference_t *type) +static void print_type_reference(const type_reference_t *type) { fprintf(out, "<?%s>", type->symbol->string); } -static void print_type_variable(FILE *out, const type_variable_t *type_variable) +static void print_type_variable(const type_variable_t *type_variable) { if(type_variable->current_type != NULL) { - print_type(out, type_variable->current_type); + print_type(type_variable->current_type); return; } fprintf(out, "%s:", type_variable->declaration.symbol->string); type_constraint_t *constraint = type_variable->constraints; int first = 1; while(constraint != NULL) { if(first) { first = 0; } else { fprintf(out, ", "); } fprintf(out, "%s", constraint->concept_symbol->string); constraint = constraint->next; } } -static void print_type_reference_variable(FILE *out, const type_reference_t *type) +static void print_type_reference_variable(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; - print_type_variable(out, type_variable); + print_type_variable(type_variable); } -static void print_compound_type(FILE *out, const compound_type_t *type) +static void print_compound_type(const compound_type_t *type) { fprintf(out, "%s", type->symbol->string); type_variable_t *type_parameter = type->type_parameters; if(type_parameter != NULL) { fprintf(out, "<"); while(type_parameter != NULL) { if(type_parameter != type->type_parameters) { fprintf(out, ", "); } - print_type_variable(out, type_parameter); + print_type_variable(type_parameter); type_parameter = type_parameter->next; } fprintf(out, ">"); } } -static void print_bind_type_variables(FILE *out, const bind_typevariables_type_t *type) +static void print_bind_type_variables(const bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); - print_type(out, (type_t*) polymorphic_type); + print_type((type_t*) polymorphic_type); pop_type_variable_bindings(old_top); } -void print_type(FILE *out, const type_t *type) +void print_type(const type_t *type) { if(type == NULL) { fputs("nil type", out); return; } switch(type->type) { case TYPE_INVALID: fputs("invalid", out); return; case TYPE_VOID: fputs("void", out); return; case TYPE_ATOMIC: - print_atomic_type(out, (const atomic_type_t*) type); + print_atomic_type((const atomic_type_t*) type); return; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: - print_compound_type(out, (const compound_type_t*) type); + print_compound_type((const compound_type_t*) type); return; case TYPE_METHOD: - print_method_type(out, (const method_type_t*) type); + print_method_type((const method_type_t*) type); return; case TYPE_POINTER: - print_pointer_type(out, (const pointer_type_t*) type); + print_pointer_type((const pointer_type_t*) type); return; case TYPE_ARRAY: - print_array_type(out, (const array_type_t*) type); + print_array_type((const array_type_t*) type); return; case TYPE_REFERENCE: - print_type_reference(out, (const type_reference_t*) type); + print_type_reference((const type_reference_t*) type); return; case TYPE_REFERENCE_TYPE_VARIABLE: - print_type_reference_variable(out, (const type_reference_t*) type); + print_type_reference_variable((const type_reference_t*) type); return; case TYPE_BIND_TYPEVARIABLES: - print_bind_type_variables(out, (const bind_typevariables_type_t*) type); + print_bind_type_variables((const bind_typevariables_type_t*) type); return; } fputs("unknown", out); } int type_valid(const type_t *type) { switch(type->type) { case TYPE_INVALID: case TYPE_REFERENCE: return 0; default: return 1; } } int is_type_int(const type_t *type) { if(type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return 1; default: return 0; } } int is_type_numeric(const type_t *type) { if(type->type != TYPE_ATOMIC) return 0; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return 1; default: return 0; } } type_t* make_atomic_type(atomic_type_type_t atype) { atomic_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *normalized_type = typehash_insert((type_t*) type); if(normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } type_t* make_pointer_type(type_t *points_to) { pointer_type_t *type = obstack_alloc(type_obst, sizeof(type[0])); memset(type, 0, sizeof(type[0])); type->type.type = TYPE_POINTER; type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) type); if(normalized_type != (type_t*) type) { obstack_free(type_obst, type); } return normalized_type; } -static __attribute__((unused)) -void dbg_type(const type_t *type) -{ - print_type(stdout,type); - puts("\n"); - fflush(stdout); -} - static type_t *create_concrete_compound_type(compound_type_t *type) { /* TODO: handle structs with typevars */ return (type_t*) type; } static type_t *create_concrete_method_type(method_type_t *type) { int need_new_type = 0; method_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_METHOD; type_t *result_type = create_concrete_type(type->result_type); if(result_type != type->result_type) need_new_type = 1; new_type->result_type = result_type; method_parameter_type_t *parameter_type = type->parameter_types; method_parameter_type_t *last_parameter_type = NULL; while(parameter_type != NULL) { type_t *param_type = parameter_type->type; type_t *new_param_type = create_concrete_type(param_type); if(new_param_type != param_type) need_new_type = 1; method_parameter_type_t *new_parameter_type = obstack_alloc(type_obst, sizeof(new_parameter_type[0])); memset(new_parameter_type, 0, sizeof(new_parameter_type[0])); new_parameter_type->type = new_param_type; if(last_parameter_type != NULL) { last_parameter_type->next = new_parameter_type; } else { new_type->parameter_types = new_parameter_type; } last_parameter_type = new_parameter_type; parameter_type = parameter_type->next; } if(!need_new_type) { obstack_free(type_obst, new_type); new_type = type; } return (type_t*) new_type; } static type_t *create_concrete_pointer_type(pointer_type_t *type) { type_t *points_to = create_concrete_type(type->points_to); if(points_to == type->points_to) return (type_t*) type; pointer_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_POINTER; new_type->points_to = points_to; type_t *normalized_type = typehash_insert((type_t*) new_type); if(normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_type_variable_reference_type(type_reference_t *type) { type_variable_t *type_variable = type->type_variable; type_t *current_type = type_variable->current_type; if(current_type != NULL) return current_type; return (type_t*) type; } static type_t *create_concrete_array_type(array_type_t *type) { type_t *element_type = create_concrete_type(type->element_type); if(element_type == type->element_type) return (type_t*) type; array_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_ARRAY; new_type->element_type = element_type; new_type->size = type->size; type_t *normalized_type = typehash_insert((type_t*) new_type); if(normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } static type_t *create_concrete_typevar_binding_type(bind_typevariables_type_t *type) { int changed = 0; type_argument_t *new_arguments; type_argument_t *last_argument = NULL; type_argument_t *type_argument = type->type_arguments; while(type_argument != NULL) { type_t *type = type_argument->type; type_t *new_type = create_concrete_type(type); if(new_type != type) { changed = 1; } type_argument_t *new_argument = obstack_alloc(type_obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = new_type; if(last_argument != NULL) { last_argument->next = new_argument; } else { new_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } if(!changed) { assert(new_arguments != NULL); obstack_free(type_obst, new_arguments); return (type_t*) type; } bind_typevariables_type_t *new_type = obstack_alloc(type_obst, sizeof(new_type[0])); memset(new_type, 0, sizeof(new_type[0])); new_type->type.type = TYPE_BIND_TYPEVARIABLES; new_type->polymorphic_type = type->polymorphic_type; new_type->type_arguments = new_arguments; type_t *normalized_type = typehash_insert((type_t*) new_type); if(normalized_type != (type_t*) new_type) { obstack_free(type_obst, new_type); } return normalized_type; } type_t *create_concrete_type(type_t *type) { switch(type->type) { case TYPE_INVALID: return type_invalid; case TYPE_VOID: return type_void; case TYPE_ATOMIC: return type; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return create_concrete_compound_type((compound_type_t*) type); case TYPE_METHOD: return create_concrete_method_type((method_type_t*) type); case TYPE_POINTER: return create_concrete_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return create_concrete_array_type((array_type_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return create_concrete_type_variable_reference_type( (type_reference_t*) type); case TYPE_BIND_TYPEVARIABLES: return create_concrete_typevar_binding_type( (bind_typevariables_type_t*) type); case TYPE_REFERENCE: panic("trying to normalize unresolved type reference"); break; } return type; } int typevar_binding_stack_top() { return ARR_LEN(typevar_binding_stack); } void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments) { type_variable_t *type_parameter; type_argument_t *type_argument; if(type_parameters == NULL || type_arguments == NULL) return; /* we have to take care that all rebinding happens atomically, so we first * create the structures on the binding stack and misuse the * old_current_type value to temporarily save the new! current_type. * We can then walk the list and set the new types */ type_parameter = type_parameters; type_argument = type_arguments; int old_top = typevar_binding_stack_top(); int top = ARR_LEN(typevar_binding_stack) + 1; while(type_parameter != NULL) { type_t *type = type_argument->type; while(type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) type; type_variable_t *var = ref->type_variable; if(var->current_type == NULL) { break; } type = var->current_type; } top = ARR_LEN(typevar_binding_stack) + 1; ARR_RESIZE(typevar_binding_t, typevar_binding_stack, top); typevar_binding_t *binding = & typevar_binding_stack[top-1]; binding->type_variable = type_parameter; binding->old_current_type = type; type_parameter = type_parameter->next; type_argument = type_argument->next; } assert(type_parameter == NULL && type_argument == NULL); for(int i = old_top+1; i <= top; ++i) { typevar_binding_t *binding = & typevar_binding_stack[i-1]; type_variable_t *type_variable = binding->type_variable; type_t *new_type = binding->old_current_type; binding->old_current_type = type_variable->current_type; type_variable->current_type = new_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "binding '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, type_variable->current_type); fprintf(stderr, "\n"); #endif } } void pop_type_variable_bindings(int new_top) { int top = ARR_LEN(typevar_binding_stack) - 1; for(int i = top; i >= new_top; --i) { typevar_binding_t *binding = & typevar_binding_stack[i]; type_variable_t *type_variable = binding->type_variable; type_variable->current_type = binding->old_current_type; #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "reset binding of '%s'(%p) to ", type_variable->symbol->string, type_variable); print_type(stderr, binding->old_current_type); fprintf(stderr, "\n"); #endif } ARR_SHRINKLEN(typevar_binding_stack, new_top); } diff --git a/type.h b/type.h index 37fc00a..4b62217 100644 --- a/type.h +++ b/type.h @@ -1,61 +1,61 @@ #ifndef TYPE_H #define TYPE_H #include <stdio.h> typedef struct type_t type_t; typedef struct atomic_type_t atomic_type_t; typedef struct type_reference_t type_reference_t; typedef struct compound_entry_t compound_entry_t; typedef struct compound_type_t compound_type_t; typedef struct type_constraint_t type_constraint_t; typedef struct type_variable_t type_variable_t; typedef struct type_argument_t type_argument_t; typedef struct bind_typevariables_type_t bind_typevariables_type_t; typedef struct method_parameter_type_t method_parameter_type_t; typedef struct method_type_t method_type_t; typedef struct pointer_type_t pointer_type_t; typedef struct array_type_t array_type_t; extern type_t *type_void; extern type_t *type_invalid; void init_type_module(void); void exit_type_module(void); /** * prints a human readable form of @p type to a stream */ -void print_type(FILE* out, const type_t *type); +void print_type(const type_t *type); /** * returns 1 if type contains integer numbers */ int is_type_int(const type_t *type); /** * returns 1 if type contains numbers (float or int) */ int is_type_numeric(const type_t *type); /** * returns 1 if the type is valid. A type is valid if it contains no unresolved * references anymore and is not of TYPE_INVALID. */ int type_valid(const type_t *type); /** * returns a normalized copy of a type with type variables replaced by their * current type. The given type (and all its hierarchy) is not modified. */ type_t *create_concrete_type(type_t *type); int typevar_binding_stack_top(void); void push_type_variable_bindings(type_variable_t *type_parameters, type_argument_t *type_arguments); void pop_type_variable_bindings(int new_top); #endif
MatzeB/fluffy
ca7f8114a4c7524f0157e0f25373d234acab035c
config.mak shouldn't be in cversion controll
diff --git a/.gitignore b/.gitignore index a1fa5db..0760677 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *.o *.dylib .*.swp a.out +/config.mak diff --git a/config.mak b/config.mak deleted file mode 100644 index f9106b4..0000000 --- a/config.mak +++ /dev/null @@ -1,6 +0,0 @@ -FIRM_HOME = $(HOME)/develop/firm -FIRM_BUILD = $(FIRM_HOME)/build/i686-apple-darwin9.5.0/debug/ -FIRM_CFLAGS = -I$(FIRM_HOME)/libfirm/include -I$(FIRM_HOME)/obstack -I$(FIRM_HOME)/libcore -I$(FIRM_HOME)/libcore/libcore -I$(FIRM_HOME) -FIRM_LIBS = -L$(FIRM_BUILD) -L$(FIRM_BUILD)/libfirm -lfirm -llpp -lcore -lm -lz -ldl -LIBFIRM_FILE = $(FIRM_BUILD)/libfirm/libfirm.a -
MatzeB/fluffy
8ea748a914f0dcd8a1268adb09532f790a0d714f
cleanup, start working on iterators, use bool where possible
diff --git a/.gitignore b/.gitignore index ef866c5..a1fa5db 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.o *.dylib .*.swp +a.out diff --git a/ast.c b/ast.c index c53bcd7..280d347 100644 --- a/ast.c +++ b/ast.c @@ -65,615 +65,617 @@ static void print_call_expression(const call_expression_t *call) static void print_type_arguments(const type_argument_t *type_arguments) { const type_argument_t *argument = type_arguments; int first = 1; while(argument != NULL) { if(first) { fprintf(out, "<$"); first = 0; } else { fprintf(out, ", "); } print_type(out, argument->type); argument = argument->next; } if(type_arguments != NULL) { fprintf(out, ">"); } } static void print_reference_expression(const reference_expression_t *ref) { if(ref->declaration == NULL) { fprintf(out, "?%s", ref->symbol->string); } else { fprintf(out, "%s", ref->declaration->symbol->string); } print_type_arguments(ref->type_arguments); } static void print_select_expression(const select_expression_t *select) { fprintf(out, "("); print_expression(select->compound); fprintf(out, ")."); if(select->compound_entry != NULL) { fputs(select->compound_entry->symbol->string, out); } else { fprintf(out, "?%s", select->symbol->string); } } static void print_array_access_expression(const array_access_expression_t *access) { fprintf(out, "("); print_expression(access->array_ref); fprintf(out, ")["); print_expression(access->index); fprintf(out, "]"); } static void print_sizeof_expression(const sizeof_expression_t *expr) { fprintf(out, "(sizeof<"); print_type(out, expr->type); fprintf(out, ">)"); } static void print_unary_expression(const unary_expression_t *unexpr) { fprintf(out, "("); switch(unexpr->type) { case UNEXPR_CAST: fprintf(out, "cast<"); print_type(out, unexpr->expression.datatype); fprintf(out, "> "); print_expression(unexpr->value); break; default: fprintf(out, "*unexpr %d*", unexpr->type); break; } fprintf(out, ")"); } static void print_binary_expression(const binary_expression_t *binexpr) { fprintf(out, "("); print_expression(binexpr->left); fprintf(out, " "); switch(binexpr->type) { case BINEXPR_INVALID: fprintf(out, "INVOP"); break; case BINEXPR_ASSIGN: fprintf(out, "<-"); break; case BINEXPR_ADD: fprintf(out, "+"); break; case BINEXPR_SUB: fprintf(out, "-"); break; case BINEXPR_MUL: fprintf(out, "*"); break; case BINEXPR_DIV: fprintf(out, "/"); break; case BINEXPR_NOTEQUAL: fprintf(out, "/="); break; case BINEXPR_EQUAL: fprintf(out, "="); break; case BINEXPR_LESS: fprintf(out, "<"); break; case BINEXPR_LESSEQUAL: fprintf(out, "<="); break; case BINEXPR_GREATER: fprintf(out, ">"); break; case BINEXPR_GREATEREQUAL: fprintf(out, ">="); break; default: /* TODO: add missing ops */ fprintf(out, "op%d", binexpr->type); break; } fprintf(out, " "); print_expression(binexpr->right); fprintf(out, ")"); } void print_expression(const expression_t *expression) { if(expression == NULL) { fprintf(out, "*null expression*"); return; } switch(expression->type) { case EXPR_LAST: case EXPR_INVALID: fprintf(out, "*invalid expression*"); break; case EXPR_INT_CONST: print_int_const((const int_const_t*) expression); break; case EXPR_STRING_CONST: print_string_const((const string_const_t*) expression); break; case EXPR_NULL_POINTER: fprintf(out, "null"); break; case EXPR_CALL: print_call_expression((const call_expression_t*) expression); break; case EXPR_BINARY: print_binary_expression((const binary_expression_t*) expression); break; case EXPR_UNARY: print_unary_expression((const unary_expression_t*) expression); break; case EXPR_SELECT: print_select_expression((const select_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: print_array_access_expression( (const array_access_expression_t*) expression); break; case EXPR_SIZEOF: print_sizeof_expression((const sizeof_expression_t*) expression); break; case EXPR_REFERENCE: print_reference_expression((const reference_expression_t*) expression); break; default: /* TODO */ fprintf(out, "some expression of type %d", expression->type); break; } } static void print_indent(void) { for(int i = 0; i < indent; ++i) fprintf(out, "\t"); } static void print_block_statement(const block_statement_t *block) { statement_t *statement = block->statements; while(statement != NULL) { indent++; print_statement(statement); indent--; statement = statement->next; } } static void print_return_statement(const return_statement_t *statement) { fprintf(out, "return "); if(statement->return_value != NULL) print_expression(statement->return_value); } static void print_expression_statement(const expression_statement_t *statement) { print_expression(statement->expression); } static void print_goto_statement(const goto_statement_t *statement) { fprintf(out, "goto "); if(statement->label != NULL) { symbol_t *symbol = statement->label->declaration.symbol; if(symbol == NULL) { fprintf(out, "$%p$", statement->label); } else { fprintf(out, "%s", symbol->string); } } else { fprintf(out, "?%s", statement->label_symbol->string); } } static void print_label_statement(const label_statement_t *statement) { symbol_t *symbol = statement->declaration.declaration.symbol; if(symbol != NULL) { fprintf(out, ":%s", symbol->string); } else { const label_declaration_t *label = &statement->declaration; fprintf(out, ":$%p$", label); } } static void print_if_statement(const if_statement_t *statement) { fprintf(out, "if "); print_expression(statement->condition); fprintf(out, ":\n"); if(statement->true_statement != NULL) print_statement(statement->true_statement); if(statement->false_statement != NULL) { print_indent(); fprintf(out, "else:\n"); print_statement(statement->false_statement); } } static void print_variable_declaration(const variable_declaration_t *var) { fprintf(out, "var"); if(var->type != NULL) { fprintf(out, "<"); print_type(out, var->type); fprintf(out, ">"); } fprintf(out, " %s", var->declaration.symbol->string); } static void print_variable_declaration_statement( const variable_declaration_statement_t *statement) { print_variable_declaration(&statement->declaration); } void print_statement(const statement_t *statement) { print_indent(); switch(statement->type) { case STATEMENT_BLOCK: print_block_statement((const block_statement_t*) statement); break; case STATEMENT_RETURN: print_return_statement((const return_statement_t*) statement); break; case STATEMENT_EXPRESSION: print_expression_statement((const expression_statement_t*) statement); break; case STATEMENT_LABEL: print_label_statement((const label_statement_t*) statement); break; case STATEMENT_GOTO: print_goto_statement((const goto_statement_t*) statement); break; case STATEMENT_IF: print_if_statement((const if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: print_variable_declaration_statement( (const variable_declaration_statement_t*) statement); break; case STATEMENT_LAST: case STATEMENT_INVALID: default: fprintf(out, "*invalid statement*"); break; } fprintf(out, "\n"); } static void print_type_constraint(const type_constraint_t *constraint) { if(constraint->concept == NULL) { fprintf(out, "?%s", constraint->concept_symbol->string); } else { fprintf(out, "%s", constraint->concept->declaration.symbol->string); } } static void print_type_variable(const type_variable_t *type_variable) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { print_type_constraint(constraint); fprintf(out, " "); constraint = constraint->next; } fprintf(out, "%s", type_variable->declaration.symbol->string); } static void print_type_parameters(const type_variable_t *type_parameters) { int first = 1; const type_variable_t *type_parameter = type_parameters; while(type_parameter != NULL) { if(first) { fprintf(out, "<"); first = 0; } else { fprintf(out, ", "); } print_type_variable(type_parameter); type_parameter = type_parameter->next; } if(type_parameters != NULL) fprintf(out, ">"); } static void print_method_parameters(const method_parameter_t *parameters, const method_type_t *method_type) { fprintf(out, "("); int first = 1; const method_parameter_t *parameter = parameters; const method_parameter_type_t *parameter_type = method_type->parameter_types; while(parameter != NULL && parameter_type != NULL) { if(!first) { fprintf(out, ", "); } else { first = 0; } print_type(out, parameter_type->type); fprintf(out, " %s", parameter->declaration.symbol->string); parameter = parameter->next; parameter_type = parameter_type->next; } assert(parameter == NULL && parameter_type == NULL); fprintf(out, ")"); } static void print_method(const method_declaration_t *method_declaration) { const method_t *method = &method_declaration->method; method_type_t *type = method->type; fprintf(out, "func "); if(method->is_extern) { fprintf(out, "extern "); } fprintf(out, " %s", method_declaration->declaration.symbol->string); print_type_parameters(method->type_parameters); print_method_parameters(method->parameters, type); fprintf(out, " : "); print_type(out, type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_method(const concept_method_t *method) { fprintf(out, "\tfunc "); fprintf(out, "%s", method->declaration.symbol->string); print_method_parameters(method->parameters, method->method_type); fprintf(out, " : "); print_type(out, method->method_type->result_type); fprintf(out, "\n\n"); } static void print_concept(const concept_t *concept) { fprintf(out, "concept %s", concept->declaration.symbol->string); print_type_parameters(concept->type_parameters); fprintf(out, ":\n"); concept_method_t *method = concept->methods; while(method != NULL) { print_concept_method(method); method = method->next; } } static void print_concept_method_instance( concept_method_instance_t *method_instance) { fprintf(out, "\tfunc "); const method_t *method = &method_instance->method; if(method_instance->concept_method != NULL) { concept_method_t *method = method_instance->concept_method; fprintf(out, "%s", method->declaration.symbol->string); } else { fprintf(out, "?%s", method_instance->symbol->string); } print_method_parameters(method->parameters, method->type); fprintf(out, " : "); print_type(out, method_instance->method.type->result_type); if(method->statement != NULL) { fprintf(out, ":\n"); print_statement(method->statement); } else { fprintf(out, "\n"); } } static void print_concept_instance(const concept_instance_t *instance) { fprintf(out, "instance "); if(instance->concept != NULL) { fprintf(out, "%s", instance->concept->declaration.symbol->string); } else { fprintf(out, "?%s", instance->concept_symbol->string); } print_type_arguments(instance->type_arguments); fprintf(out, ":\n"); concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { print_concept_method_instance(method_instance); method_instance = method_instance->next; } } static void print_constant(const constant_t *constant) { fprintf(out, "const %s", constant->declaration.symbol->string); if(constant->type != NULL) { fprintf(out, " "); print_type(out, constant->type); } if(constant->expression != NULL) { fprintf(out, " <- "); print_expression(constant->expression); } fprintf(out, "\n"); } static void print_typealias(const typealias_t *alias) { fprintf(out, "typealias %s <- ", alias->declaration.symbol->string); print_type(out, alias->type); fprintf(out, "\n"); } static void print_declaration(const declaration_t *declaration) { print_indent(); switch(declaration->type) { case DECLARATION_METHOD: print_method((const method_declaration_t*) declaration); break; case DECLARATION_CONCEPT: print_concept((const concept_t*) declaration); break; case DECLARATION_VARIABLE: print_variable_declaration((const variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: print_typealias((const typealias_t*) declaration); break; case DECLARATION_CONSTANT: print_constant((const constant_t*) declaration); break; + case DECLARATION_ITERATOR: case DECLARATION_CONCEPT_METHOD: case DECLARATION_METHOD_PARAMETER: - fprintf(out, "some declaration of type %d\n", declaration->type); // TODO + fprintf(out, "some declaration of type %d\n", declaration->type); break; case DECLARATION_TYPE_VARIABLE: case DECLARATION_LABEL: break; case DECLARATION_INVALID: case DECLARATION_LAST: fprintf(out, "invalid namespace declaration (%d)\n", declaration->type); break; } } static void print_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { print_declaration(declaration); declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { print_concept_instance(instance); instance = instance->next; } } void print_ast(FILE *new_out, const namespace_t *namespace) { indent = 0; out = new_out; print_context(&namespace->context); assert(indent == 0); out = NULL; } const char *get_declaration_type_name(declaration_type_t type) { switch(type) { case DECLARATION_LAST: case DECLARATION_INVALID: return "invalid reference"; case DECLARATION_VARIABLE: return "variable"; case DECLARATION_CONSTANT: return "constant"; case DECLARATION_METHOD_PARAMETER: return "method parameter"; case DECLARATION_METHOD: return "method"; + case DECLARATION_ITERATOR: return "iterator"; case DECLARATION_CONCEPT: return "concept"; case DECLARATION_TYPEALIAS: return "type alias"; case DECLARATION_TYPE_VARIABLE: return "type variable"; case DECLARATION_LABEL: return "label"; case DECLARATION_CONCEPT_METHOD: return "concept method"; } panic("invalid environment entry found"); } void init_ast_module(void) { obstack_init(&ast_obstack); } void exit_ast_module(void) { obstack_free(&ast_obstack, NULL); } void* (allocate_ast) (size_t size) { return _allocate_ast(size); } unsigned register_expression() { static unsigned nextid = EXPR_LAST; ++nextid; return nextid; } unsigned register_statement() { static unsigned nextid = STATEMENT_LAST; ++nextid; return nextid; } unsigned register_declaration() { static unsigned nextid = DECLARATION_LAST; ++nextid; return nextid; } unsigned register_attribute() { static unsigned nextid = 0; ++nextid; return nextid; } diff --git a/ast2firm.c b/ast2firm.c index a650585..7c8e509 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -462,1503 +462,1509 @@ static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) variable_declaration_t *variable = (variable_declaration_t*) declaration; ident *ident = new_id_from_str(declaration->symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } declaration = declaration->next; } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if(current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->declaration.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if(type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch(type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_INVALID: break; } if(firm_type == NULL) panic("unknown type found"); if(env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if(method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; const char *string = concept->declaration.symbol->string; size_t len = strlen(string); obstack_printf(&obst, "_tcv%zu%s", len, string); string = concept_method->declaration.symbol->string; len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; while(argument != NULL) { mangle_type(&obst, argument->type); argument = argument->next; } obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *id = new_id_from_str(str); obstack_free(&obst, str); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if(!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } ident *id; if(!is_polymorphic) { //id = new_id_from_str(symbol->string); obstack_printf(&obst, "_%s", symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); id = new_id_from_str(str); obstack_free(&obst, str); } else { const char *string = symbol->string; size_t len = strlen(string); obstack_printf(&obst, "_v%zu%s", len, string); type_variable_t *type_variable = method->type_parameters; while(type_variable != NULL) { mangle_type(&obst, type_variable->current_type); type_variable = type_variable->next; } obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); id = new_id_from_str(str); obstack_free(&obst, str); } /* search for an existing entity */ if(is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for(int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if(get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if(method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if(!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if(is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if(!is_polymorphic) { method->e.entity = entity; } else { if(method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if(cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for(size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if(select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if(variable->entity != NULL) return variable->entity; ir_type *parent_type; if(variable->is_global) { parent_type = get_glob_type(); } else if(variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if(variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if(variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if(variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch(declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: + case DECLARATION_ITERATOR: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; switch(expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if(dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { switch(type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { switch(type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if(compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; switch(unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if(entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if(strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while(type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if(last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if(instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); print_type(stderr, concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if(method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while(argument != NULL) { n_parameters++; argument = argument->next; } if(method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while(argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if(new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if(new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if(result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if(entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); + case DECLARATION_ITERATOR: + // TODO + panic("TODO: iterator to firm"); + break; case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch(expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if(statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if(statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while(statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if(block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if(statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch(statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if(method->is_extern) return; int old_top = typevar_binding_stack_top(); if(is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if(method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if(get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while(label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for(int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if(align > align_all) align_all = align; int misalign = 0; if(align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if(!is_polymorphic_method(method)) { assure_instance(method, declaration->symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; + case DECLARATION_ITERATOR: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: panic("Invalid namespace entry type found"); } declaration = declaration->next; } /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; while(instance != NULL) { create_concept_instance(instance); instance = instance->next; } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while(namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while(!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index aefc828..542c5d7 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,410 +1,413 @@ #ifndef AST_T_H #define AST_T_H +#include <stdbool.h> #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; typedef enum { DECLARATION_INVALID, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, + DECLARATION_ITERATOR, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; - unsigned char export; - unsigned char is_extern; + bool export; + bool is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; struct iterator_declaration_t { - + declaration_t declaration; + method_t method; }; typedef enum { EXPR_INVALID = 0, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; - int value; + bool value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; - unsigned char is_extern; - unsigned char export; - unsigned char is_global; - unsigned char needs_entity; + bool is_extern; + bool export; + bool is_global; + bool needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/parser.c b/parser.c index 75693f1..eeb00bf 100644 --- a/parser.c +++ b/parser.c @@ -1,1113 +1,1109 @@ #include <config.h> #include "parser_t.h" #include <assert.h> #include <stdio.h> #include <stdarg.h> #include "symbol_table_t.h" #include "lexer.h" #include "symbol.h" #include "type_hash.h" #include "ast_t.h" #include "type_t.h" #include "adt/array.h" #include "adt/obst.h" #include "adt/util.h" #include "adt/error.h" //#define ABORT_ON_ERROR -//#define PRINT_TOKENS +//////////////#define PRINT_TOKENS static expression_parse_function_t *expression_parsers = NULL; static parse_statement_function *statement_parsers = NULL; static parse_declaration_function *declaration_parsers = NULL; static parse_attribute_function *attribute_parsers = NULL; static context_t *current_context = NULL; static int error = 0; token_t token; static inline void *allocate_ast_zero(size_t size) { void *res = allocate_ast(size); memset(res, 0, size); return res; } static inline void *allocate_type_zero(size_t size) { void *res = obstack_alloc(type_obst, size); memset(res, 0, size); return res; } void next_token(void) { lexer_next_token(&token); #ifdef PRINT_TOKENS print_token(stderr, &token); fprintf(stderr, "\n"); #endif } static void replace_token_type(token_type_t type) { token.type = type; } static inline void eat(token_type_t type) { assert(token.type == type); next_token(); } static inline void parser_found_error(void) { error = 1; #ifdef ABORT_ON_ERROR abort(); #endif } void parser_print_error_prefix(void) { fputs(source_position.input_name, stderr); fputc(':', stderr); fprintf(stderr, "%d", source_position.linenr); fputs(": error: ", stderr); parser_found_error(); } static void parse_error(const char *message) { parser_print_error_prefix(); fprintf(stderr, "parse error: %s\n", message); } static void parse_error_expected(const char *message, ...) { va_list args; int first = 1; if(message != NULL) { parser_print_error_prefix(); fprintf(stderr, "%s\n", message); } parser_print_error_prefix(); fputs("Parse error: got ", stderr); print_token(stderr, &token); fputs(", expected ", stderr); va_start(args, message); token_type_t token_type = va_arg(args, token_type_t); while(token_type != 0) { if(first == 1) { first = 0; } else { fprintf(stderr, ", "); } print_token_type(stderr, token_type); token_type = va_arg(args, token_type_t); } va_end(args); fprintf(stderr, "\n"); } /** * error recovery: skip a block and all contained sub-blocks */ static void maybe_eat_block(void) { if(token.type != T_INDENT) return; next_token(); unsigned indent = 1; while(indent >= 1) { if(token.type == T_INDENT) { indent++; } else if(token.type == T_DEDENT) { indent--; } else if(token.type == T_EOF) { break; } next_token(); } } /** * error recovery: try to got to the next line. If the current line ends in ':' * then we skip blocks that might follow */ static void eat_until_newline(void) { int prev = -1; while(token.type != T_NEWLINE) { prev = token.type; next_token(); if(token.type == T_EOF) return; } next_token(); if(prev == ':') { maybe_eat_block(); } } #define expect(expected) \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ eat_until_newline(); \ return NULL; \ } \ next_token(); #define expect_void(expected) \ if(UNLIKELY(token.type != (expected))) { \ parse_error_expected(NULL, (expected), 0); \ eat_until_newline(); \ return; \ } \ next_token(); static void parse_method(method_t *method); static statement_t *parse_block(void); static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters); static atomic_type_type_t parse_unsigned_atomic_type(void) { switch(token.type) { case T_byte: next_token(); return ATOMIC_TYPE_UBYTE; case T_short: next_token(); return ATOMIC_TYPE_USHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_ULONGLONG; } return ATOMIC_TYPE_ULONG; case T_int: next_token(); return ATOMIC_TYPE_UINT; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, 0); return ATOMIC_TYPE_INVALID; } } static atomic_type_type_t parse_signed_atomic_type(void) { switch(token.type) { case T_bool: next_token(); return ATOMIC_TYPE_BOOL; case T_byte: next_token(); return ATOMIC_TYPE_BYTE; case T_short: next_token(); return ATOMIC_TYPE_SHORT; case T_long: next_token(); if(token.type == T_long) { next_token(); return ATOMIC_TYPE_LONGLONG; } return ATOMIC_TYPE_LONG; case T_int: next_token(); return ATOMIC_TYPE_INT; case T_float: next_token(); return ATOMIC_TYPE_FLOAT; case T_double: next_token(); return ATOMIC_TYPE_DOUBLE; default: parse_error_expected("couldn't parse type", T_byte, T_short, T_int, T_long, T_float, T_double, 0); return ATOMIC_TYPE_INVALID; } } static type_t *parse_atomic_type(void) { atomic_type_type_t atype; switch(token.type) { case T_unsigned: next_token(); atype = parse_unsigned_atomic_type(); break; case T_signed: next_token(); /* fallthrough */ default: atype = parse_signed_atomic_type(); break; } atomic_type_t *type = allocate_type_zero(sizeof(type[0])); type->type.type = TYPE_ATOMIC; type->atype = atype; type_t *result = typehash_insert((type_t*) type); if(result != (type_t*) type) { obstack_free(type_obst, type); } return result; } static type_argument_t *parse_type_argument(void) { type_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->type = parse_type(); return argument; } static type_argument_t *parse_type_arguments(void) { type_argument_t *first_argument = parse_type_argument(); type_argument_t *last_argument = first_argument; while(token.type == ',') { next_token(); type_argument_t *type_argument = parse_type_argument(); last_argument->next = type_argument; last_argument = type_argument; } return first_argument; } static type_t *parse_type_ref(void) { assert(token.type == T_IDENTIFIER); type_reference_t *type_ref = allocate_type_zero(sizeof(type_ref[0])); type_ref->type.type = TYPE_REFERENCE; type_ref->symbol = token.v.symbol; type_ref->source_position = source_position; next_token(); if(token.type == '<') { next_token(); type_ref->type_arguments = parse_type_arguments(); expect('>'); } return (type_t*) type_ref; } static type_t *parse_method_type(void) { eat(T_func); method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; expect('('); parse_parameter_declaration(method_type, NULL); expect(')'); expect(':'); method_type->result_type = parse_type(); return (type_t*) method_type; } static compound_entry_t *parse_compound_entries(void) { compound_entry_t *result = NULL; compound_entry_t *last_entry = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { compound_entry_t *entry = allocate_ast_zero(sizeof(entry[0])); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound entry", T_IDENTIFIER, 0); eat_until_newline(); continue; } entry->symbol = token.v.symbol; next_token(); expect(':'); entry->type = parse_type(); entry->attributes = parse_attributes(); if(last_entry == NULL) { result = entry; } else { last_entry->next = entry; } last_entry = entry; expect(T_NEWLINE); } return result; } static type_t *parse_union_type(void) { eat(T_union); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->attributes = parse_attributes(); expect(':'); expect(T_NEWLINE); expect(T_INDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (type_t*) compound_type; } static type_t *parse_struct_type(void) { eat(T_struct); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->attributes = parse_attributes(); expect(':'); expect(T_NEWLINE); expect(T_INDENT); compound_type->entries = parse_compound_entries(); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (type_t*) compound_type; } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': next_token(); type = parse_type(); expect(')'); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ array_type_t *array_type; while(1) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); expect(']'); break; } array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; expect(']'); break; } default: return type; } } } static expression_t *parse_string_const(unsigned precedence) { (void) precedence; string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(unsigned precedence) { (void) precedence; int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(unsigned precedence) { (void) precedence; eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(unsigned precedence) { (void) precedence; eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(unsigned precedence) { (void) precedence; eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(unsigned precedence) { (void) precedence; eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); - /* force end of statement */ - assert(token.type == T_DEDENT); - replace_token_type(T_NEWLINE); - return (expression_t*) expression; } static expression_t *parse_reference(unsigned precedence) { (void) precedence; reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); ref->type_arguments = parse_type_arguments(); expect('>'); } return (expression_t*) ref; } static expression_t *parse_sizeof(unsigned precedence) { (void) precedence; eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; expect('<'); expression->type = parse_type(); expect('>'); return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; entry->precedence = precedence; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_brace_expression(unsigned precedence) { (void) precedence; eat('('); expression_t *result = parse_expression(); expect(')'); return result; } static expression_t *parse_cast_expression(unsigned precedence) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<'); unary_expression->expression.datatype = parse_type(); expect('>'); unary_expression->value = parse_sub_expression(precedence); return (expression_t*) unary_expression; } static expression_t *parse_call_expression(unsigned precedence, expression_t *expression) { (void) precedence; call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } expect(')'); return (expression_t*) call; } static expression_t *parse_select_expression(unsigned precedence, expression_t *compound) { (void) precedence; eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(unsigned precedence, expression_t *array_ref) { (void) precedence; eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static \ expression_t *parse_##unexpression_type(unsigned precedence) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(precedence); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER(token_type, binexpression_type) \ static \ expression_t *parse_##binexpression_type(unsigned precedence, \ expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(precedence); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } CREATE_BINEXPR_PARSER('*', BINEXPR_MUL); CREATE_BINEXPR_PARSER('/', BINEXPR_DIV); CREATE_BINEXPR_PARSER('%', BINEXPR_MOD); CREATE_BINEXPR_PARSER('+', BINEXPR_ADD); CREATE_BINEXPR_PARSER('-', BINEXPR_SUB); CREATE_BINEXPR_PARSER('<', BINEXPR_LESS); CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER); CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL); CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN); CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_NOTEQUAL); CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL); CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL); CREATE_BINEXPR_PARSER('&', BINEXPR_AND); CREATE_BINEXPR_PARSER('|', BINEXPR_OR); CREATE_BINEXPR_PARSER('^', BINEXPR_XOR); CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LAZY_AND); CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LAZY_OR); CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT); CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', 16); register_expression_infix_parser(parse_BINEXPR_DIV, '/', 16); register_expression_infix_parser(parse_BINEXPR_MOD, '%', 16); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, 16); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, 16); register_expression_infix_parser(parse_BINEXPR_ADD, '+', 15); register_expression_infix_parser(parse_BINEXPR_SUB, '-', 15); register_expression_infix_parser(parse_BINEXPR_LESS, '<', 14); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', 14); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, 14); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, 14); register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, 13); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, 13); register_expression_infix_parser(parse_BINEXPR_AND, '&', 12); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, 12); register_expression_infix_parser(parse_BINEXPR_XOR, '^', 11); register_expression_infix_parser(parse_BINEXPR_OR, '|', 10); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, 10); register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', 2); register_expression_infix_parser(parse_array_expression, '[', 25); register_expression_infix_parser(parse_call_expression, '(', 30); register_expression_infix_parser(parse_select_expression, '.', 30); register_expression_parser(parse_UNEXPR_NEGATE, '-', 25); register_expression_parser(parse_UNEXPR_NOT, '!', 25); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~', 25); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS, 25); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS, 25); register_expression_parser(parse_UNEXPR_DEREFERENCE, '*', 20); register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&', 20); register_expression_parser(parse_cast_expression, T_cast, 19); register_expression_parser(parse_brace_expression, '(', 1); register_expression_parser(parse_sizeof, T_sizeof, 1); register_expression_parser(parse_int_const, T_INTEGER, 1); register_expression_parser(parse_true, T_true, 1); register_expression_parser(parse_false, T_false, 1); register_expression_parser(parse_string_const, T_STRING_LITERAL, 1); register_expression_parser(parse_null, T_null, 1); register_expression_parser(parse_reference, T_IDENTIFIER, 1); register_expression_parser(parse_func_expression, T_func, 1); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { left = parser->parser(parser->precedence); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; left = parser->infix_parser(parser->infix_precedence, left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE); return (statement_t*) return_statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE); return (statement_t*) goto_statement; } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE); return (statement_t*) label; } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; diff --git a/plugins/plugin_while.fluffy b/plugins/plugin_while.fluffy index 360b576..9ff6b8b 100644 --- a/plugins/plugin_while.fluffy +++ b/plugins/plugin_while.fluffy @@ -1,144 +1,142 @@ struct WhileStatement: statement : Statement loop_control : Expression* loop_body : Statement* loop_step : Statement* var token_while : int var token_continue : int var token_break : int var token_loop : int var token_step : int var while_statement_type : unsigned int var current_loop : WhileStatement* instance AllocateOnAst WhileStatement: func allocate() : WhileStatement*: var res = allocate_zero<$WhileStatement>() res.statement.type = while_statement_type return res func parse_while_statement() : Statement*: var statement = allocate<$WhileStatement>() statement.statement.source_position = source_position assert(token.type == token_while) next_token() statement.loop_control = parse_expression() if token.type == token_step: next_token() var step_statement = allocate<$ExpressionStatement>() step_statement.statement.source_position = source_position step_statement.expression = parse_expression() statement.loop_step = cast<Statement*> step_statement expect(':') var last_current_loop = current_loop current_loop = statement statement.loop_body = parse_statement() current_loop = last_current_loop return cast<Statement*> statement func parse_loop_statement() : Statement*: var statement = allocate<$WhileStatement>() statement.statement.source_position = source_position assert(token.type == token_loop) next_token() statement.loop_control = null expect(':') statement.loop_body = parse_statement() return cast<Statement*> statement func parse_continue_statement() : Statement*: assert(token.type == token_continue) next_token() var statement = allocate<$GotoStatement>() statement.statement.source_position = source_position statement.symbol = symbol_table_insert("__loop_next") return cast<Statement*> statement func parse_break_statement() : Statement*: var statement = allocate<$GotoStatement>() statement.statement.source_position = source_position statement.symbol = symbol_table_insert("__loop_end") assert(token.type == token_break) next_token() return cast<Statement*> statement func lower_while_statement(statement : Statement*) : Statement*: var while_statement = cast<WhileStatement*> statement var loop_body = while_statement.loop_body var label = allocate<$LabelStatement>() label.declaration.declaration.symbol = symbol_table_insert("__loop_begin") var body if while_statement.loop_control /= null: var if_statement = allocate<$IfStatement>() if_statement.statement.source_position \ = while_statement.statement.source_position if_statement.condition = while_statement.loop_control if_statement.true_statement = loop_body body = cast<Statement*> if_statement else: body = loop_body var loop_body_block = cast<BlockStatement*> loop_body var next_label = allocate<$LabelStatement>() next_label.declaration.declaration.symbol \ = symbol_table_insert("__loop_next") block_append(loop_body_block, cast<Statement*> next_label) if while_statement.loop_step /= null: block_append(loop_body_block, while_statement.loop_step) var goto_statement = allocate<$GotoStatement>() goto_statement.statement.source_position \ = loop_body.source_position goto_statement.label = & label.declaration block_append(loop_body_block, cast<Statement*> goto_statement) var endlabel = allocate<$LabelStatement>() endlabel.declaration.declaration.symbol = symbol_table_insert("__loop_end") var block = allocate<$BlockStatement>() block_append(block, cast<Statement*> label) block_append(block, body) block_append(block, cast<Statement*> endlabel) context_append(&block.context, &label.declaration.declaration) context_append(&block.context, &endlabel.declaration.declaration) context_append(&block.context, &next_label.declaration.declaration) return cast<Statement*> block export init_plugin func init_plugin(): - //stderr = _stderrp - token_while = register_new_token("while") token_continue = register_new_token("continue") token_break = register_new_token("break") token_loop = register_new_token("loop") token_step = register_new_token("step") while_statement_type = register_statement() register_statement_parser(parse_while_statement, token_while) register_statement_parser(parse_loop_statement, token_loop) register_statement_parser(parse_continue_statement, token_continue) register_statement_parser(parse_break_statement, token_break) register_statement_lowerer(lower_while_statement, while_statement_type) diff --git a/semantic.c b/semantic.c index ca5afba..d2a4c59 100644 --- a/semantic.c +++ b/semantic.c @@ -1,2538 +1,2549 @@ #include <config.h> #include <stdbool.h> #include "semantic_t.h" #include "ast_t.h" #include "type_t.h" #include "type_hash.h" #include "match_type.h" #include "adt/obst.h" #include "adt/array.h" #include "adt/error.h" //#define DEBUG_TYPEVAR_BINDINGS //#define ABORT_ON_ERRORS //#define DEBUG_ENVIRONMENT typedef struct environment_entry_t environment_entry_t; struct environment_entry_t { symbol_t *symbol; declaration_t *up; const void *up_context; }; static lower_statement_function *statement_lowerers = NULL; static lower_expression_function *expression_lowerers = NULL; static struct obstack symbol_environment_obstack; static environment_entry_t **symbol_stack; static bool found_export; static bool found_errors; static type_t *type_bool = NULL; static type_t *type_byte = NULL; static type_t *type_int = NULL; static type_t *type_uint = NULL; static type_t *type_double = NULL; static type_t *type_byte_ptr = NULL; static type_t *type_void_ptr = NULL; static method_t *current_method = NULL; bool last_statement_was_return = false; static void check_and_push_context(context_t *context); static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position); static void resolve_method_types(method_t *method); void print_error_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: error: ", position.input_name, position.linenr); found_errors = true; #ifdef ABORT_ON_ERRORS abort(); #endif } void print_warning_prefix(const source_position_t position) { fprintf(stderr, "%s:%d: warning: ", position.input_name, position.linenr); } void error_at(const source_position_t position, const char *message) { print_error_prefix(position); fprintf(stderr, "%s\n", message); } /** * pushs an environment_entry on the environment stack and links the * corresponding symbol to the new entry */ static inline void environment_push(declaration_t *declaration, const void *context) { environment_entry_t *entry = obstack_alloc(&symbol_environment_obstack, sizeof(entry[0])); memset(entry, 0, sizeof(entry[0])); int top = ARR_LEN(symbol_stack); ARR_RESIZE(environment_entry_t*, symbol_stack, top + 1); symbol_stack[top] = entry; symbol_t *symbol = declaration->symbol; assert(declaration != symbol->declaration); if(symbol->context == context) { assert(symbol->declaration != NULL); print_error_prefix(declaration->source_position); fprintf(stderr, "multiple definitions for symbol '%s'.\n", symbol->string); print_error_prefix(symbol->declaration->source_position); fprintf(stderr, "this is the location of the previous declaration.\n"); } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Push symbol '%s'\n", symbol->string); #endif entry->up = symbol->declaration; entry->up_context = symbol->context; entry->symbol = symbol; symbol->declaration = declaration; symbol->context = context; } /** * pops symbols from the environment stack until @p new_top is the top element */ static inline void environment_pop_to(size_t new_top) { environment_entry_t *entry = NULL; size_t top = ARR_LEN(symbol_stack); size_t i; if(new_top == top) return; assert(new_top < top); i = top; do { entry = symbol_stack[i - 1]; symbol_t *symbol = entry->symbol; declaration_t *declaration = symbol->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(variable->refs == 0 && !variable->is_extern) { print_warning_prefix(declaration->source_position); fprintf(stderr, "variable '%s' was declared but never read\n", symbol->string); } } #ifdef DEBUG_ENVIRONMENT fprintf(stderr, "Pop symbol '%s'\n", symbol->string); #endif symbol->declaration = entry->up; symbol->context = entry->up_context; --i; } while(i != new_top); obstack_free(&symbol_environment_obstack, entry); ARR_SHRINKLEN(symbol_stack, (int) new_top); } /** * returns the top element of the environment stack */ static inline size_t environment_top(void) { return ARR_LEN(symbol_stack); } static type_t *normalize_type(type_t *type); static void normalize_type_arguments(type_argument_t *type_arguments) { /* normalize type arguments */ type_argument_t *type_argument = type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } } static type_t *resolve_type_reference(type_reference_t *type_ref) { normalize_type_arguments(type_ref->type_arguments); symbol_t *symbol = type_ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "can't resolve type: symbol '%s' is unknown\n", symbol->string); return NULL; } if(declaration->type == DECLARATION_TYPE_VARIABLE) { type_variable_t *type_variable = (type_variable_t*) declaration; if(type_variable->current_type != NULL) { /* not sure if this is really a problem... */ fprintf(stderr, "Debug warning: unresolved type var ref found " "a concrete type...\n"); return type_variable->current_type; } type_ref->type.type = TYPE_REFERENCE_TYPE_VARIABLE; type_ref->type_variable = type_variable; return typehash_insert((type_t*) type_ref); } if(declaration->type != DECLARATION_TYPEALIAS) { print_error_prefix(type_ref->source_position); fprintf(stderr, "expected a type alias, but '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return NULL; } typealias_t *typealias = (typealias_t*) declaration; typealias->type = normalize_type(typealias->type); type_t *type = typealias->type; type_variable_t *type_parameters = NULL; compound_type_t *compound_type = NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) type; type_parameters = compound_type->type_parameters; } /* check that type arguments match type parameters * and normalize the type arguments */ type_argument_t *type_arguments = type_ref->type_arguments; type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = type_arguments; while(type_parameter != NULL) { if(type_argument == NULL) { print_error_prefix(type_ref->source_position); fprintf(stderr, "too few type parameters specified for type "); print_type(stderr, type); fprintf(stderr, "\n"); break; } type_parameter = type_parameter->next; type_argument = type_argument->next; } if(type_argument != NULL) { print_error_prefix(type_ref->source_position); if(type_parameters == NULL) { fprintf(stderr, "type "); } else { fprintf(stderr, "too many type parameters specified for "); } print_type(stderr, type); fprintf(stderr, " takes no type parameters\n"); } if(type_parameters != NULL && type_argument == NULL && type_argument == NULL) { bind_typevariables_type_t *bind_typevariables = obstack_alloc(type_obst, sizeof(bind_typevariables[0])); memset(bind_typevariables, 0, sizeof(bind_typevariables[0])); bind_typevariables->type.type = TYPE_BIND_TYPEVARIABLES; bind_typevariables->type_arguments = type_arguments; assert(compound_type != NULL); bind_typevariables->polymorphic_type = compound_type; type = (type_t*) bind_typevariables; } return type; } static type_t *resolve_type_reference_type_var(type_reference_t *type_ref) { type_variable_t *type_variable = type_ref->type_variable; if(type_variable->current_type != NULL) { return normalize_type(type_variable->current_type); } return typehash_insert((type_t*) type_ref); } static type_t *normalize_pointer_type(pointer_type_t *type) { type->points_to = normalize_type(type->points_to); return typehash_insert((type_t*) type); } static type_t *normalize_array_type(array_type_t *type) { type->element_type = normalize_type(type->element_type); return typehash_insert((type_t*) type); } static type_t *normalize_method_type(method_type_t *method_type) { method_type->result_type = normalize_type(method_type->result_type); method_parameter_type_t *parameter = method_type->parameter_types; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } return typehash_insert((type_t*) method_type); } static void check_compound_type(compound_type_t *type) { int old_top = environment_top(); check_and_push_context(&type->context); compound_entry_t *entry = type->entries; while(entry != NULL) { type_t *type = entry->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS) { compound_type_t *compound_type = (compound_type_t*) type; check_compound_type(compound_type); } entry->type = normalize_type(type); entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if(type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: return type; case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if(type == NULL) return NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if(constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); + case DECLARATION_ITERATOR: + panic("TODO iterator reference"); + break; case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if(!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if(left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if(left->datatype == NULL) { if(right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, - const source_position_t source_position) + const source_position_t source_position, + bool lenient) { if(dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ type_t *from_type = from->datatype; if(from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(stderr, dest_type); fprintf(stderr, "\n"); return NULL; } bool implicit_cast_allowed = true; if(from_type->type == TYPE_POINTER) { if(dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if(p1->points_to != p2->points_to && dest_type != type_void_ptr && from->type != EXPR_NULL_POINTER) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if(dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if(pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if(from_type->type == TYPE_ATOMIC) { if(dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { -#if 0 case ATOMIC_TYPE_BOOL: + if (!lenient) { + implicit_cast_allowed = false; + break; + } implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); -#endif case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; - case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if(!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(stderr, from_type); fprintf(stderr, " to "); print_type(stderr, dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if(lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, - binexpr->expression.source_position); + binexpr->expression.source_position, + false); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if(!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(stderr, left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(stderr, left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(stderr, left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if(left == NULL || right == NULL) return; if(left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, - binexpr->expression.source_position); + binexpr->expression.source_position, + false); } if(right->datatype != righttype) { binexpr->right = make_cast(right, righttype, - binexpr->expression.source_position); + binexpr->expression.source_position, + false); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while(argument != NULL && parameter != NULL) { if(parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } #if 0 if(parameter->current_type != argument->type) { match = false; break; } #endif if (!match_variant_to_concrete_type( argument->type, parameter->current_type, concept->declaration.source_position, false)) { match = false; break; } argument = argument->next; parameter = parameter->next; } if(match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if(match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { if(constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { if(method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while(type_var != NULL) { type_t *current_type = type_var->current_type; if(current_type == NULL) return; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if(!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if(cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if(instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters; while(typevar != NULL) { if(typevar->current_type != NULL) { print_type(stderr, typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if(method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if(concept == NULL) continue; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if(!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->declaration.symbol->string, concept->declaration.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if(instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->declaration.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(stderr, type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->declaration.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if(type == NULL) { return type_int; } switch(type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(stderr, type); fprintf(stderr, ") not supported for function parameters.\n"); return type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(stderr, type); fprintf(stderr, ") not supported for function parameter.\n"); return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(stderr, type); fprintf(stderr, "\n"); return type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if(type == NULL) return; /* determine method type */ if(type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(stderr, type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if(type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(stderr, type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if(method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if(declaration->type == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if(type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while(type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if(type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while(argument != NULL) { if(param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if(param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if(type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if(expression_type != wanted_type) { + /* be a bit lenient for varargs function, to not make using + C printf too much of a pain... */ + bool lenient = param_type == NULL; expression_t *new_expression = make_cast(expression, wanted_type, - expression->source_position); + expression->source_position, lenient); if(new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(stderr, expression->datatype); fprintf(stderr, " should be "); print_type(stderr, wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if(param_type != NULL) param_type = param_type->next; ++i; } if(param_type != NULL) { error_at(call->expression.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while(type_var != NULL) { if(type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->declaration.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->declaration.symbol->string, type_var); print_type(stderr, type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if(type_variables != NULL) { reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if(declaration->type == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->type == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ if(ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while(type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if(last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if(cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if(cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if(value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if(value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if(!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if(value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if(type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(stderr, type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(stderr, type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(unary_expression_t *expression) { expression_t *value = check_expression(expression->value); type_t *type = value->datatype; if(!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); print_type(stderr, type); fprintf(stderr, "\n"); } if(!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if(type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if(atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if(need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.type = EXPR_BINARY; add->expression.datatype = type; if(expression->type == UNEXPR_INCREMENT) { add->type = BINEXPR_ADD; } else { add->type = BINEXPR_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.datatype = type; assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static expression_t *lower_unary_expression(expression_t *expression) { assert(expression->type == EXPR_UNARY); unary_expression_t *unary_expression = (unary_expression_t*) expression; switch(unary_expression->type) { case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: return lower_incdec_expression(unary_expression); default: break; } return expression; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(stderr, type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch(unary_expression->type) { case UNEXPR_CAST: check_cast_expression(unary_expression); return; case UNEXPR_DEREFERENCE: check_dereference_expression(unary_expression); return; case UNEXPR_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case UNEXPR_NOT: check_not_expression(unary_expression); return; case UNEXPR_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case UNEXPR_NEGATE: check_negate_expression(unary_expression); return; case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("increment/decrement not lowered"); case UNEXPR_INVALID: abort(); } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if(datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if(datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if(datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(stderr, datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if(points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(stderr, datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; while(declaration != NULL) { if(declaration->symbol == symbol) break; declaration = declaration->next; } if(declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while(entry != NULL) { if(entry->symbol == symbol) { break; } entry = entry->next; } if(entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); print_type(stderr, (type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if(bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if(type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(stderr, type); fprintf(stderr, "\n"); return; } type_t *result_type; if(type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if(index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(stderr, index->datatype); fprintf(stderr, "\n"); return; } if(index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, - access->expression.source_position); + access->expression.source_position, false); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if(expression == NULL) return NULL; /* try to lower the expression */ if((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; if(lowerer != NULL) { expression = lowerer(expression); } } switch(expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; case EXPR_BINARY: check_binary_expression((binary_expression_t*) expression); break; case EXPR_UNARY: check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_LAST: case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if(return_value != NULL) { if(method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if(return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, - statement->statement.source_position); + statement->statement.source_position, false); statement->return_value = return_value; } } else { if(method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if(condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(stderr, condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if(statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { environment_push(declaration, context); declaration = declaration->next; } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while(statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if(last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if(statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if(expression->datatype == NULL) return; bool may_be_unused = false; if(expression->type == EXPR_BINARY && ((binary_expression_t*) expression)->type == BINEXPR_ASSIGN) { may_be_unused = true; } else if(expression->type == EXPR_UNARY && (((unary_expression_t*) expression)->type == UNEXPR_INCREMENT || ((unary_expression_t*) expression)->type == UNEXPR_DECREMENT)) { may_be_unused = true; } else if(expression->type == EXPR_CALL) { may_be_unused = true; } if(expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if(expression->type == EXPR_BINARY) { binary_expression_t *binexpr = (binary_expression_t*) expression; if(binexpr->type == BINEXPR_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if(goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if(symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if(declaration->type != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_type_name(declaration->type)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if(statement == NULL) return NULL; /* try to lower the statement */ if((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if(lowerer != NULL) { statement = lowerer(statement); } } if(statement == NULL) return NULL; last_statement_was_return = false; switch(statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if(method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while(parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if(method->statement != NULL) { method->statement = check_statement(method->statement); } if(!last_statement_was_return) { type_t *result_type = method->type->result_type; if(result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if(symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if(expression->datatype != constant->type) { expression = make_cast(expression, constant->type, - constant->declaration.source_position); + constant->declaration.source_position, false); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; while(constraint != NULL) { resolve_type_constraint(constraint, type_var->declaration.source_position); constraint = constraint->next; } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while(type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; while(concept_method != NULL) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; concept_method = concept_method->next; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(declaration->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(declaration->source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ size_t n_concept_methods = 0; concept_method_t *method; for (method = concept->methods; method != NULL; method = method->next) { ++n_concept_methods; } bool have_method[n_concept_methods]; memset(&have_method, 0, sizeof(have_method)); concept_method_instance_t *method_instance; for (method_instance = instance->method_instances; method_instance != NULL; method_instance = method_instance->next) { /* find corresponding concept method */ int n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if (method->declaration.symbol == method_instance->symbol) break; } if (method == NULL) { print_warning_prefix(method_instance->source_position); fprintf(stderr, "concept '%s' does not declare a method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } else { method_instance->concept_method = method; method_instance->concept_instance = instance; if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " "in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); } have_method[n] = true; } method_t *imethod = & method_instance->method; if (imethod->type_parameters != NULL) { print_error_prefix(method_instance->source_position); fprintf(stderr, "instance method '%s' must not have type parameters\n", method_instance->symbol->string); } imethod->type = (method_type_t*) normalize_type((type_t*) imethod->type); } size_t n = 0; for (method = concept->methods; method != NULL; method = method->next, ++n) { if(!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_type_name(declaration->type)); return; } found_export = true; } static void check_and_push_context(context_t *context) { variable_declaration_t *variable; method_declaration_t *method; typealias_t *typealias; type_t *type; concept_t *concept; push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->type = normalize_type(variable->type); break; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; resolve_method_types(&method->method); break; case DECLARATION_TYPEALIAS: typealias = (typealias_t*) declaration; type = normalize_type(typealias->type); if(type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } typealias->type = type; break; case DECLARATION_CONCEPT: concept = (concept_t*) declaration; resolve_concept_types(concept); break; default: break; } declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { resolve_concept_instance(instance); instance = instance->next; } /* check semantics in conceptes */ instance = context->concept_instances; while(instance != NULL) { check_concept_instance(instance); instance = instance->next; } /* check semantics in methods */ declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; check_method(&method->method, method->declaration.symbol, method->declaration.source_position); break; case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } declaration = declaration->next; } /* handle export declarations */ export_t *export = context->exports; while(export != NULL) { check_export(export); export = export->next; } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if(statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if(statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if(expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if(expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); namespace_t *namespace = namespaces; while(namespace != NULL) { check_namespace(namespace); namespace = namespace->next; } if(!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_unary_expression, EXPR_UNARY); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); } diff --git a/type_t.h b/type_t.h index 68914ae..4ef2c2c 100644 --- a/type_t.h +++ b/type_t.h @@ -1,130 +1,137 @@ #ifndef TYPE_T_H #define TYPE_T_H +#include <stdbool.h> #include "type.h" #include "symbol.h" #include "lexer.h" #include "ast.h" #include "ast_t.h" #include "adt/obst.h" #include <libfirm/typerep.h> struct obstack *type_obst; typedef enum { TYPE_INVALID, TYPE_VOID, TYPE_ATOMIC, TYPE_COMPOUND_CLASS, TYPE_COMPOUND_STRUCT, TYPE_COMPOUND_UNION, TYPE_METHOD, TYPE_POINTER, TYPE_ARRAY, TYPE_REFERENCE, TYPE_REFERENCE_TYPE_VARIABLE, TYPE_BIND_TYPEVARIABLES } type_type_t; typedef enum { ATOMIC_TYPE_INVALID, ATOMIC_TYPE_BOOL, ATOMIC_TYPE_BYTE, ATOMIC_TYPE_UBYTE, ATOMIC_TYPE_SHORT, ATOMIC_TYPE_USHORT, ATOMIC_TYPE_INT, ATOMIC_TYPE_UINT, ATOMIC_TYPE_LONG, ATOMIC_TYPE_ULONG, ATOMIC_TYPE_LONGLONG, ATOMIC_TYPE_ULONGLONG, ATOMIC_TYPE_FLOAT, ATOMIC_TYPE_DOUBLE, } atomic_type_type_t; struct type_t { type_type_t type; ir_type *firm_type; }; struct atomic_type_t { type_t type; atomic_type_type_t atype; }; struct pointer_type_t { type_t type; type_t *points_to; }; struct array_type_t { type_t type; type_t *element_type; unsigned long size; }; struct type_argument_t { type_t *type; type_argument_t *next; }; struct type_reference_t { type_t type; symbol_t *symbol; source_position_t source_position; type_argument_t *type_arguments; type_variable_t *type_variable; }; struct bind_typevariables_type_t { type_t type; type_argument_t *type_arguments; compound_type_t *polymorphic_type; }; struct method_parameter_type_t { type_t *type; method_parameter_type_t *next; }; struct type_constraint_t { symbol_t *concept_symbol; concept_t *concept; type_constraint_t *next; }; struct method_type_t { type_t type; type_t *result_type; method_parameter_type_t *parameter_types; - int variable_arguments; + bool variable_arguments; +}; + +struct iterator_type_t { + type_t type; + type_t *element_type; + method_parameter_type_t *parameter_types; }; struct compound_entry_t { type_t *type; symbol_t *symbol; compound_entry_t *next; attribute_t *attributes; source_position_t source_position; ir_entity *entity; }; struct compound_type_t { type_t type; compound_entry_t *entries; symbol_t *symbol; attribute_t *attributes; type_variable_t *type_parameters; context_t context; source_position_t source_position; }; type_t *make_atomic_type(atomic_type_type_t type); type_t *make_pointer_type(type_t *type); #endif
MatzeB/fluffy
4d9217b8edea4f5744d99e7ed229c3239ec2508a
add expected test results and script to test fluffy
diff --git a/test/array.fluffy b/test/array.fluffy index 18f494a..ef380a1 100644 --- a/test/array.fluffy +++ b/test/array.fluffy @@ -1,14 +1,15 @@ func extern printf(format : byte*, ...) func extern malloc(size : unsigned int) : void* struct Blo: array : int[10] typealias arr = int[7] func main() : int: var blo = cast<Blo* > malloc(sizeof<Blo>) - printf("Size: %d\n", sizeof<Blo>) blo.array[2] = 5 - return blo.array[2] + blo.array[3] = 0 + printf("Size: %d\n", sizeof<Blo>) + return blo.array[3] export main diff --git a/test/expected_output/array.fluffy.output b/test/expected_output/array.fluffy.output new file mode 100644 index 0000000..35848d9 --- /dev/null +++ b/test/expected_output/array.fluffy.output @@ -0,0 +1 @@ +Size: 40 diff --git a/test/expected_output/bools.fluffy.output b/test/expected_output/bools.fluffy.output new file mode 100644 index 0000000..e78664b --- /dev/null +++ b/test/expected_output/bools.fluffy.output @@ -0,0 +1,13 @@ +im1 +im2 +f1: 1 f2: 0 +im1 +im2 +f1 && f2: 0 +im2 +f2 && f1: 0 +im1 +f1 || f2: 1 +im2 +im1 +f2 || f1: 1 diff --git a/test/expected_output/callbacks.fluffy.output b/test/expected_output/callbacks.fluffy.output new file mode 100644 index 0000000..45698d7 --- /dev/null +++ b/test/expected_output/callbacks.fluffy.output @@ -0,0 +1,8 @@ +pre1 -> I'm impl1 +Result: 42 +pre2 -> I'm impl1 +Result: 42 +pre1: I'm impl2 +Result: 23 +pre4: I'm an anonymous func +Result: 1 diff --git a/test/expected_output/evil.fluffy.output b/test/expected_output/evil.fluffy.output new file mode 100644 index 0000000..98c7ed3 --- /dev/null +++ b/test/expected_output/evil.fluffy.output @@ -0,0 +1,8 @@ +blup +42 +42 +blup +blup +42 +42 +blup diff --git a/test/expected_output/fib.fluffy.output b/test/expected_output/fib.fluffy.output new file mode 100644 index 0000000..a6653bb --- /dev/null +++ b/test/expected_output/fib.fluffy.output @@ -0,0 +1 @@ +fib(10) -> 55 diff --git a/test/expected_output/inference.fluffy.output b/test/expected_output/inference.fluffy.output new file mode 100644 index 0000000..3a2e3f4 --- /dev/null +++ b/test/expected_output/inference.fluffy.output @@ -0,0 +1 @@ +-1 diff --git a/test/expected_output/pointerarith.fluffy.output b/test/expected_output/pointerarith.fluffy.output new file mode 100644 index 0000000..0b15fa8 --- /dev/null +++ b/test/expected_output/pointerarith.fluffy.output @@ -0,0 +1 @@ +Last: ./a.out diff --git a/test/expected_output/polyinstance.fluffy.output b/test/expected_output/polyinstance.fluffy.output new file mode 100644 index 0000000..0b15fa8 --- /dev/null +++ b/test/expected_output/polyinstance.fluffy.output @@ -0,0 +1 @@ +Last: ./a.out diff --git a/test/expected_output/polymorphic.fluffy.output b/test/expected_output/polymorphic.fluffy.output new file mode 100644 index 0000000..2087de4 --- /dev/null +++ b/test/expected_output/polymorphic.fluffy.output @@ -0,0 +1 @@ +sizeof<int>: 4 siyeof<double>: 8 diff --git a/test/expected_output/polystruct.fluffy.output b/test/expected_output/polystruct.fluffy.output new file mode 100644 index 0000000..c127f75 --- /dev/null +++ b/test/expected_output/polystruct.fluffy.output @@ -0,0 +1,4 @@ +Welt +Hallo +13 +42 diff --git a/test/expected_output/simple.fluffy.output b/test/expected_output/simple.fluffy.output new file mode 100644 index 0000000..e69de29 diff --git a/test/expected_output/struct.fluffy.output b/test/expected_output/struct.fluffy.output new file mode 100644 index 0000000..e69de29 diff --git a/test/expected_output/typealias.fluffy.output b/test/expected_output/typealias.fluffy.output new file mode 100644 index 0000000..802992c --- /dev/null +++ b/test/expected_output/typealias.fluffy.output @@ -0,0 +1 @@ +Hello world diff --git a/test/expected_output/typeclass.fluffy.output b/test/expected_output/typeclass.fluffy.output new file mode 100644 index 0000000..1c972b9 --- /dev/null +++ b/test/expected_output/typeclass.fluffy.output @@ -0,0 +1,2 @@ +Eine fünf: +5 diff --git a/test/expected_output/typeclass2.fluffy.output b/test/expected_output/typeclass2.fluffy.output new file mode 100644 index 0000000..c459e9e --- /dev/null +++ b/test/expected_output/typeclass2.fluffy.output @@ -0,0 +1,34 @@ +Initial array: + 20 + 10 + 5 + 89 + 24 + 43 + 13 + 99 + 66 + 5 +Sorted array: + 5 + 5 + 10 + 13 + 20 + 24 + 43 + 66 + 89 + 99 +Initial array: + Eva + Adam + Mr. Fluffy + Peter + Hugo +Sorted array: + Adam + Eva + Hugo + Mr. Fluffy + Peter diff --git a/test/sdl.fluffy b/test/libs/sdl.fluffy similarity index 100% rename from test/sdl.fluffy rename to test/libs/sdl.fluffy diff --git a/test/stdlibtest.fluffy b/test/libs/stdlibtest.fluffy similarity index 100% rename from test/stdlibtest.fluffy rename to test/libs/stdlibtest.fluffy diff --git a/test/enumtest.fluffy b/test/plugins/enumtest.fluffy similarity index 100% rename from test/enumtest.fluffy rename to test/plugins/enumtest.fluffy diff --git a/test/fortest.fluffy b/test/plugins/fortest.fluffy similarity index 100% rename from test/fortest.fluffy rename to test/plugins/fortest.fluffy diff --git a/test/whiletest.fluffy b/test/plugins/whiletest.fluffy similarity index 100% rename from test/whiletest.fluffy rename to test/plugins/whiletest.fluffy diff --git a/test/pointerarith.fluffy b/test/pointerarith.fluffy index 5b27246..eba7e39 100644 --- a/test/pointerarith.fluffy +++ b/test/pointerarith.fluffy @@ -1,6 +1,7 @@ +func extern printf(format : byte*, ...) : int func main(argc : int, argv : byte**) : int: var last = argv + (argc - 1) printf("Last: %s\n", *last) return 0 export main diff --git a/test/polystruct.fluffy b/test/polystruct.fluffy index bd223b6..af022e4 100644 --- a/test/polystruct.fluffy +++ b/test/polystruct.fluffy @@ -1,54 +1,63 @@ typealias String = byte* func extern malloc(size : unsigned int) : void* func extern printf(format : String, ...) : int func extern puts(val : String) func extern strcmp(s1 : String, s2 : String) : int concept Printable<T>: func print(obj : T) instance Printable String: func print(obj : String): puts(obj) instance Printable int: func print(obj : int): printf("%d\n", obj) - struct ListElement<T>: val : T next : ListElement<T>* struct List<T>: first : ListElement<T>* func AddToList<T>(list : List<T>*, element : ListElement<T>*): element.next = list.first list.first = element +func AddMakeElement<T>(list : List<T>*, value : T): + var element = cast<ListElement<T>*> malloc( sizeof<T> ) + element.val = value + AddToList(list, element) + func PrintList<T : Printable>(list : List<T>*): var elem = list.first - while elem /= null: - print(elem.val) - elem = elem.next - -instance Printable<Foo : Printable> List<Foo>*: - func print(obj : List<Foo>*): - PrintList(obj) + :beginloop + if elem == null: + return + print(elem.val) + elem = elem.next + goto beginloop func main() : int: var l : List<String> l.first = null var e1 : ListElement<String> e1.val = "Hallo" var e2 : ListElement<String> e2.val = "Welt" AddToList(&l, &e1) AddToList(&l, &e2) - //PrintList(&l) - print(&l) + PrintList(&l) + + var l2 : List<int> + l2.first = null + AddMakeElement(&l2, 42) + AddMakeElement(&l2, 13) + PrintList(&l2) + return 0 export main diff --git a/test/quicktest.sh b/test/quicktest.sh new file mode 100755 index 0000000..2216c2b --- /dev/null +++ b/test/quicktest.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +TEMPOUT="/tmp/fluffytest.txt" +for i in *.fluffy; do + echo -n "$i..." + ../fluffy $i + ./a.out >& "$TEMPOUT" || echo "(return status != 0)" + if ! diff "$TEMPOUT" "expected_output/$i.output" > /dev/null; then + echo "FAIL" + else + echo "" + fi +done diff --git a/test/wip/polyinstance.fluffy b/test/wip/polyinstance.fluffy new file mode 100644 index 0000000..bd223b6 --- /dev/null +++ b/test/wip/polyinstance.fluffy @@ -0,0 +1,54 @@ +typealias String = byte* + +func extern malloc(size : unsigned int) : void* +func extern printf(format : String, ...) : int +func extern puts(val : String) +func extern strcmp(s1 : String, s2 : String) : int + +concept Printable<T>: + func print(obj : T) + +instance Printable String: + func print(obj : String): + puts(obj) + +instance Printable int: + func print(obj : int): + printf("%d\n", obj) + + +struct ListElement<T>: + val : T + next : ListElement<T>* + +struct List<T>: + first : ListElement<T>* + +func AddToList<T>(list : List<T>*, element : ListElement<T>*): + element.next = list.first + list.first = element + +func PrintList<T : Printable>(list : List<T>*): + var elem = list.first + while elem /= null: + print(elem.val) + elem = elem.next + +instance Printable<Foo : Printable> List<Foo>*: + func print(obj : List<Foo>*): + PrintList(obj) + +func main() : int: + var l : List<String> + l.first = null + var e1 : ListElement<String> + e1.val = "Hallo" + var e2 : ListElement<String> + e2.val = "Welt" + AddToList(&l, &e1) + AddToList(&l, &e2) + //PrintList(&l) + print(&l) + return 0 +export main +
MatzeB/fluffy
e30884d3f17d67a237a43cb9d176e9bd0c7a5d14
change assignment operator to = and equality to ==
diff --git a/TODO b/TODO index 98c5783..f72a452 100644 --- a/TODO +++ b/TODO @@ -1,28 +1,28 @@ This does not describe the goals and visions but short term things that should not be forgotten and are not done yet because I was lazy or did not decide about the right way to do it yet. - semantic should check that structs don't contain themselfes - having the same entry twice in a struct is not detected - correct pointer arithmetic - A typeof operator (resulting in the type of the enclosed expression) - change lexer to build a decision tree for the operators (so we can write <void*> again...) - add possibility to specify default implementations for typeclass functions - add static ifs that can examine const expressions and types at compiletime - fix ++ and -- expressions - forbid same variable names in nested blocks - change firm to pass on debug info on unitialized_variable callback Tasks suitable for contributors, because they don't affect the general design or need only design decision in a very specific part of the compiler and/or because they need no deep understanding of the design. - Add parsing of floating point numbers in lexer - Add option parsing to the compiler, pass options to backend as well - Use more firm optimisations - Create an eccp like wrapper script - Add an alloca operator - create a ++ and -- operator - make lexer accept \r, \r\n and \n as newline -- make lexer unicode aware (so we can read different encodings and utf8) +- make lexer unicode aware (reading utf-8 is enough, for more inputs we could use iconv, but we should recommend utf-8 as default) diff --git a/ast2firm.c b/ast2firm.c index 475f26c..a650585 100644 --- a/ast2firm.c +++ b/ast2firm.c @@ -129,1836 +129,1836 @@ static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type) switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: return mode_Bs; case ATOMIC_TYPE_UBYTE: return mode_Bu; case ATOMIC_TYPE_SHORT: return mode_Hs; case ATOMIC_TYPE_USHORT: return mode_Hu; case ATOMIC_TYPE_INT: return mode_Is; case ATOMIC_TYPE_UINT: return mode_Iu; case ATOMIC_TYPE_LONG: return mode_Ls; case ATOMIC_TYPE_ULONG: return mode_Lu; case ATOMIC_TYPE_LONGLONG: return mode_LLs; case ATOMIC_TYPE_ULONGLONG: return mode_LLu; case ATOMIC_TYPE_FLOAT: return mode_F; case ATOMIC_TYPE_DOUBLE: return mode_D; case ATOMIC_TYPE_BOOL: return mode_b; case ATOMIC_TYPE_INVALID: break; } panic("Encountered unknown atomic type"); } static unsigned get_type_size(type_t *type); static unsigned get_atomic_type_size(const atomic_type_t *type) { switch(type->atype) { case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_BYTE: return 1; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_FLOAT: return 4; case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: return 2; case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_DOUBLE: return 8; case ATOMIC_TYPE_INVALID: break; } panic("Trying to determine size of invalid atomic type"); } static unsigned get_compound_type_size(compound_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_reference_type_var_size(const type_reference_t *type) { type_variable_t *type_variable = type->type_variable; if(type_variable->current_type == NULL) { panic("taking size of unbound type variable"); return 0; } return get_type_size(type_variable->current_type); } static unsigned get_array_type_size(array_type_t *type) { ir_type *irtype = get_ir_type(&type->type); return get_type_size_bytes(irtype); } static unsigned get_type_size(type_t *type) { switch(type->type) { case TYPE_VOID: return 0; case TYPE_ATOMIC: return get_atomic_type_size((const atomic_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return get_compound_type_size((compound_type_t*) type); case TYPE_METHOD: /* just a pointer to the method */ return get_mode_size_bytes(mode_P_code); case TYPE_POINTER: return get_mode_size_bytes(mode_P_data); case TYPE_ARRAY: return get_array_type_size((array_type_t*) type); case TYPE_REFERENCE: panic("Type reference not resolved"); break; case TYPE_REFERENCE_TYPE_VARIABLE: return get_type_reference_type_var_size((type_reference_t*) type); case TYPE_INVALID: break; case TYPE_BIND_TYPEVARIABLES: abort(); } panic("Trying to determine size of invalid type"); } static int count_parameters(const method_type_t *method_type) { int count = 0; method_parameter_type_t *param_type = method_type->parameter_types; while(param_type != NULL) { param_type = param_type->next; count++; } return count; } static ir_type *get_atomic_type(type2firm_env_t *env, const atomic_type_t *type) { (void) env; ir_mode *mode = get_atomic_mode(type); ident *id = get_mode_ident(mode); ir_type *irtype = new_type_primitive(id, mode); return irtype; } static ir_type *get_method_type(type2firm_env_t *env, const method_type_t *method_type) { type_t *result_type = method_type->result_type; ident *id = unique_ident("methodtype"); int n_parameters = count_parameters(method_type); int n_results = result_type->type == TYPE_VOID ? 0 : 1; ir_type *irtype = new_type_method(id, n_parameters, n_results); if(result_type->type != TYPE_VOID) { ir_type *restype = _get_ir_type(env, result_type); set_method_res_type(irtype, 0, restype); } method_parameter_type_t *param_type = method_type->parameter_types; int n = 0; while(param_type != NULL) { ir_type *p_irtype = _get_ir_type(env, param_type->type); set_method_param_type(irtype, n, p_irtype); param_type = param_type->next; n++; } if(method_type->variable_arguments) { set_method_variadicity(irtype, variadicity_variadic); } return irtype; } static ir_type *get_pointer_type(type2firm_env_t *env, pointer_type_t *type) { type_t *points_to = type->points_to; ir_type *ir_points_to; /* Avoid endless recursion if the points_to type contains this poiner type * again (might be a struct). We therefore first create a void* pointer * and then set the real points_to type */ ir_type *ir_type_void = get_ir_type(type_void); ir_type *ir_type = new_type_pointer(unique_ident("pointer"), ir_type_void, mode_P_data); type->type.firm_type = ir_type; ir_points_to = _get_ir_type(env, points_to); set_pointer_points_to_type(ir_type, ir_points_to); return ir_type; } static ir_type *get_array_type(type2firm_env_t *env, array_type_t *type) { type_t *element_type = type->element_type; ir_type *ir_element_type = _get_ir_type(env, element_type); ir_type *ir_type = new_type_array(unique_ident("array"), 1, ir_element_type); set_array_bounds_int(ir_type, 0, 0, type->size); size_t elemsize = get_type_size_bytes(ir_element_type); int align = get_type_alignment_bytes(ir_element_type); if(elemsize % align > 0) { elemsize += align - (elemsize % align); } set_type_size_bytes(ir_type, type->size * elemsize); set_type_alignment_bytes(ir_type, align); set_type_state(ir_type, layout_fixed); return ir_type; } #define INVALID_TYPE ((ir_type_ptr)-1) static ir_type *get_struct_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if(symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_struct"); } ir_type *ir_type = new_type_struct(id); type->type.firm_type = ir_type; int align_all = 1; int offset = 0; compound_entry_t *entry = type->entries; while(entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); int misalign = offset % entry_alignment; offset += misalign; ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); set_entity_offset(entity, offset); add_struct_member(ir_type, entity); entry->entity = entity; offset += entry_size; if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } int misalign = offset % align_all; offset += misalign; set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, offset); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_union_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id; if(symbol != NULL) { id = unique_ident(symbol->string); } else { id = unique_ident("__anonymous_union"); } ir_type *ir_type = new_type_union(id); type->type.firm_type = ir_type; int align_all = 1; int size = 0; compound_entry_t *entry = type->entries; while(entry != NULL) { ident *ident = new_id_from_str(entry->symbol->string); ir_type_ptr entry_ir_type = _get_ir_type(env, entry->type); int entry_size = get_type_size_bytes(entry_ir_type); int entry_alignment = get_type_alignment_bytes(entry_ir_type); ir_entity *entity = new_entity(ir_type, ident, entry_ir_type); add_union_member(ir_type, entity); set_entity_offset(entity, 0); entry->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } entry = entry->next; } set_type_alignment_bytes(ir_type, align_all); set_type_size_bytes(ir_type, size); set_type_state(ir_type, layout_fixed); return ir_type; } static ir_type *get_class_type(type2firm_env_t *env, compound_type_t *type) { symbol_t *symbol = type->symbol; ident *id = unique_ident(symbol->string); ir_type *class_ir_type = new_type_class(id); type->type.firm_type = class_ir_type; int align_all = 1; int size = 0; declaration_t *declaration = type->context.declarations; while(declaration != NULL) { if(declaration->type == DECLARATION_METHOD) { /* TODO */ continue; } if(declaration->type != DECLARATION_VARIABLE) continue; variable_declaration_t *variable = (variable_declaration_t*) declaration; ident *ident = new_id_from_str(declaration->symbol->string); ir_type *var_ir_type = _get_ir_type(env, variable->type); int entry_size = get_type_size_bytes(var_ir_type); int entry_alignment = get_type_alignment_bytes(var_ir_type); ir_entity *entity = new_entity(class_ir_type, ident, var_ir_type); add_class_member(class_ir_type, entity); set_entity_offset(entity, 0); variable->entity = entity; if(entry_size > size) { size = entry_size; } if(entry_alignment > align_all) { if(entry_alignment % align_all != 0) { panic("Uneven alignments not supported yet"); } align_all = entry_alignment; } declaration = declaration->next; } set_type_alignment_bytes(class_ir_type, align_all); set_type_size_bytes(class_ir_type, size); set_type_state(class_ir_type, layout_fixed); return class_ir_type; } static ir_type *get_type_for_type_variable(type2firm_env_t *env, type_reference_t *ref) { assert(ref->type.type == TYPE_REFERENCE_TYPE_VARIABLE); type_variable_t *type_variable = ref->type_variable; type_t *current_type = type_variable->current_type; if(current_type == NULL) { fprintf(stderr, "Panic: trying to transform unbound type variable " "'%s'\n", type_variable->declaration.symbol->string); abort(); } ir_type *ir_type = _get_ir_type(env, current_type); env->can_cache = 0; return ir_type; } static ir_type *get_type_for_bind_typevariables(type2firm_env_t *env, bind_typevariables_type_t *type) { compound_type_t *polymorphic_type = type->polymorphic_type; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(polymorphic_type->type_parameters, type->type_arguments); ir_type *result = _get_ir_type(env, (type_t*) polymorphic_type); pop_type_variable_bindings(old_top); return result; } static ir_type *_get_ir_type(type2firm_env_t *env, type_t *type) { assert(type != NULL); if(type->firm_type != NULL) { assert(type->firm_type != INVALID_TYPE); return type->firm_type; } ir_type *firm_type = NULL; switch(type->type) { case TYPE_ATOMIC: firm_type = get_atomic_type(env, (atomic_type_t*) type); break; case TYPE_METHOD: firm_type = get_method_type(env, (method_type_t*) type); break; case TYPE_POINTER: firm_type = get_pointer_type(env, (pointer_type_t*) type); break; case TYPE_ARRAY: firm_type = get_array_type(env, (array_type_t*) type); break; case TYPE_VOID: /* there is no mode_VOID in firm, use mode_C */ firm_type = new_type_primitive(new_id_from_str("void"), mode_ANY); break; case TYPE_COMPOUND_STRUCT: firm_type = get_struct_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_UNION: firm_type = get_union_type(env, (compound_type_t*) type); break; case TYPE_COMPOUND_CLASS: firm_type = get_class_type(env, (compound_type_t*) type); break; case TYPE_REFERENCE_TYPE_VARIABLE: firm_type = get_type_for_type_variable(env, (type_reference_t*) type); break; case TYPE_BIND_TYPEVARIABLES: firm_type = get_type_for_bind_typevariables(env, (bind_typevariables_type_t*) type); break; case TYPE_REFERENCE: panic("unresolved reference type found"); break; case TYPE_INVALID: break; } if(firm_type == NULL) panic("unknown type found"); if(env->can_cache) { type->firm_type = firm_type; } return firm_type; } static ir_type *get_ir_type(type_t *type) { type2firm_env_t env; env.can_cache = 1; return _get_ir_type(&env, type); } static inline ir_mode *get_ir_mode(type_t *type) { ir_type *irtype = get_ir_type(type); ir_mode *mode = get_type_mode(irtype); assert(mode != NULL); return mode; } static instantiate_method_t *queue_method_instantiation(method_t *method, ir_entity *entity) { instantiate_method_t *instantiate = obstack_alloc(&obst, sizeof(instantiate[0])); memset(instantiate, 0, sizeof(instantiate[0])); instantiate->method = method; instantiate->entity = entity; pdeq_putr(instantiate_methods, instantiate); return instantiate; } static int is_polymorphic_method(const method_t *method) { return method->type_parameters != NULL; } static ir_entity* get_concept_method_instance_entity( concept_method_instance_t *method_instance) { method_t *method = & method_instance->method; if(method->e.entity != NULL) return method->e.entity; method_type_t *method_type = method->type; concept_method_t *concept_method = method_instance->concept_method; concept_t *concept = concept_method->concept; - const char *string + const char *string = concept->declaration.symbol->string; size_t len = strlen(string); obstack_printf(&obst, "_tcv%zu%s", len, string); string = concept_method->declaration.symbol->string; len = strlen(string); obstack_printf(&obst, "%zu%s", len, string); concept_instance_t *instance = method_instance->concept_instance; type_argument_t *argument = instance->type_arguments; while(argument != NULL) { mangle_type(&obst, argument->type); argument = argument->next; } obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *id = new_id_from_str(str); obstack_free(&obst, str); /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); set_entity_visibility(entity, visibility_local); method->e.entity = entity; return entity; } static ir_entity* get_method_entity(method_t *method, symbol_t *symbol) { method_type_t *method_type = method->type; int is_polymorphic = is_polymorphic_method(method); if(!is_polymorphic && method->e.entity != NULL) { return method->e.entity; } ident *id; if(!is_polymorphic) { //id = new_id_from_str(symbol->string); obstack_printf(&obst, "_%s", symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); id = new_id_from_str(str); obstack_free(&obst, str); } else { const char *string = symbol->string; size_t len = strlen(string); obstack_printf(&obst, "_v%zu%s", len, string); type_variable_t *type_variable = method->type_parameters; while(type_variable != NULL) { mangle_type(&obst, type_variable->current_type); type_variable = type_variable->next; } obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); id = new_id_from_str(str); obstack_free(&obst, str); } /* search for an existing entity */ if(is_polymorphic && method->e.entities != NULL) { int len = ARR_LEN(method->e.entities); for(int i = 0; i < len; ++i) { ir_entity *entity = method->e.entities[i]; if(get_entity_ident(entity) == id) { return entity; } } } /* create the entity */ ir_type *global_type = get_glob_type(); ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_entity *entity = new_entity(global_type, id, ir_method_type); set_entity_ld_ident(entity, id); if(method->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else if(!is_polymorphic && method->export) { set_entity_visibility(entity, visibility_external_visible); } else { if(is_polymorphic && method->export) { fprintf(stderr, "Warning: exporting polymorphic methods not " "supported.\n"); } set_entity_visibility(entity, visibility_local); } if(!is_polymorphic) { method->e.entity = entity; } else { if(method->e.entities == NULL) method->e.entities = NEW_ARR_F(ir_entity*, 0); ARR_APP1(ir_entity*, method->e.entities, entity); } return entity; } static dbg_info* get_dbg_info(const source_position_t *pos) { return (dbg_info*) pos; } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos); static ir_node *expression_to_firm(expression_t *expression); static ir_node *int_const_to_firm(const int_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_long(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *float_const_to_firm(const float_const_t *cnst) { ir_mode *mode = get_ir_mode(cnst->expression.datatype); tarval *tv = new_tarval_from_double(cnst->value, mode); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_Const(dbgi, tv); } static ir_node *bool_const_to_firm(const bool_const_t *cnst) { dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); if(cnst->value == 0) { return new_d_Const(dbgi, get_tarval_b_false()); } else { return new_d_Const(dbgi, get_tarval_b_true()); } } static ir_node *string_const_to_firm(const string_const_t* cnst) { ir_type *global_type = get_glob_type(); ir_type *type = new_type_array(unique_ident("bytearray"), 1, byte_ir_type); ir_entity *ent = new_entity(global_type, unique_ident("str"), type); set_entity_variability(ent, variability_constant); set_entity_allocation(ent, allocation_static); set_entity_visibility(ent, visibility_local); ir_type *elem_type = byte_ir_type; ir_mode *mode = get_type_mode(elem_type); const char *string = cnst->value; size_t slen = strlen(string) + 1; set_array_lower_bound_int(type, 0, 0); set_array_upper_bound_int(type, 0, slen); set_type_size_bytes(type, slen); set_type_state(type, layout_fixed); tarval **tvs = xmalloc(slen * sizeof(tvs[0])); for(size_t i = 0; i < slen; ++i) { tvs[i] = new_tarval_from_long(string[i], mode); } set_array_entity_values(ent, tvs, slen); free(tvs); dbg_info *dbgi = get_dbg_info(&cnst->expression.source_position); return new_d_SymConst(dbgi, mode_P, (union symconst_symbol) ent, symconst_addr_ent); } static ir_node *null_pointer_to_firm(void) { ir_mode *mode = get_type_mode(void_ptr_type); tarval *tv = get_tarval_null(mode); return new_Const(tv); } static ir_node *select_expression_addr(const select_expression_t *select) { expression_t *compound_ptr = select->compound; /* make sure the firm type for the struct is constructed */ get_ir_type(compound_ptr->datatype); ir_node *compound_ptr_node = expression_to_firm(compound_ptr); ir_node *nomem = new_NoMem(); ir_entity *entity; if(select->compound_entry != NULL) { entity = select->compound_entry->entity; } else { // TODO } dbg_info *dbgi = get_dbg_info(&select->expression.source_position); ir_node *addr = new_d_simpleSel(dbgi, nomem, compound_ptr_node, entity); return addr; } static ir_node *array_access_expression_addr(const array_access_expression_t* access) { expression_t *array_ref = access->array_ref; expression_t *index = access->index; ir_node *base_addr = expression_to_firm(array_ref); ir_node *index_node = expression_to_firm(index); int elem_size = get_type_size(access->expression.datatype); tarval *elem_size_tv = new_tarval_from_long(elem_size, mode_Is); ir_node *elem_size_const = new_Const(elem_size_tv); dbg_info *dbgi = get_dbg_info(&access->expression.source_position); ir_node *mul = new_d_Mul(dbgi, index_node, elem_size_const, mode_Is); ir_node *add = new_d_Add(dbgi, base_addr, mul, mode_P_data); return add; } static ir_entity *create_variable_entity(variable_declaration_t *variable) { if(variable->entity != NULL) return variable->entity; ir_type *parent_type; if(variable->is_global) { parent_type = get_glob_type(); } else if(variable->needs_entity) { parent_type = get_irg_frame_type(current_ir_graph); } else { return NULL; } obstack_printf(&obst, "_%s", variable->declaration.symbol->string); obstack_1grow(&obst, 0); char *str = obstack_finish(&obst); ident *ident = new_id_from_str(str); obstack_free(&obst, str); type_t *type = variable->type; ir_type *irtype = get_ir_type(type); ir_entity *entity = new_entity(parent_type, ident, irtype); set_entity_ld_ident(entity, ident); set_entity_variability(entity, variability_uninitialized); set_entity_allocation(entity, allocation_static); if(variable->is_extern) { set_entity_visibility(entity, visibility_external_allocated); } else { set_entity_visibility(entity, visibility_local); } variable->entity = entity; return entity; } static ir_node *variable_addr(variable_declaration_t *variable) { ir_entity *entity = create_variable_entity(variable); dbg_info *dbgi = get_dbg_info(&variable->declaration.source_position); ir_node *result; if(variable->is_global) { result = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); } else { assert(variable->needs_entity); ir_node *nomem = new_NoMem(); result = new_d_simpleSel(dbgi, nomem, variable_context, entity); } return result; } static ir_node *variable_to_firm(variable_declaration_t *variable, const source_position_t *source_position) { if(variable->is_global || variable->needs_entity) { ir_node *addr = variable_addr(variable); type_t *type = variable->type; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { return addr; } return load_from_expression_addr(type, addr, source_position); } else { ir_mode *mode = get_ir_mode(variable->type); assert(variable->value_number < get_irg_n_locs(current_ir_graph)); value_numbers[variable->value_number] = variable; dbg_info *dbgi = get_dbg_info(source_position); return get_d_value(dbgi, variable->value_number, mode); } } static ir_node *constant_reference_to_firm(const constant_t *constant) { return expression_to_firm(constant->expression); } static ir_node *declaration_addr(declaration_t *declaration) { switch(declaration->type) { case DECLARATION_VARIABLE: return variable_addr((variable_declaration_t*) declaration); case DECLARATION_INVALID: case DECLARATION_METHOD: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: case DECLARATION_LAST: panic("internal error: trying to create address nodes for non-lvalue"); } panic("Unknown declaration found in reference expression"); } static ir_node *reference_expression_addr(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; return declaration_addr(declaration); } static ir_node *expression_addr(const expression_t *expression) { const unary_expression_t *unexpr; const select_expression_t *select; switch(expression->type) { case EXPR_SELECT: select = (const select_expression_t*) expression; return select_expression_addr(select); case EXPR_ARRAY_ACCESS: return array_access_expression_addr( (const array_access_expression_t*) expression); case EXPR_REFERENCE: return reference_expression_addr( (const reference_expression_t*) expression); case EXPR_UNARY: unexpr = (const unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) { return expression_to_firm(unexpr->value); } break; default: break; } panic("trying to get address from non lvalue construct"); } static void firm_assign(expression_t *dest_expr, ir_node *value, const source_position_t *source_position) { if(dest_expr->type == EXPR_REFERENCE) { const reference_expression_t *ref = (const reference_expression_t*) dest_expr; declaration_t *declaration = ref->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; if(!variable->is_global && !variable->needs_entity) { value_numbers[variable->value_number] = variable; set_value(variable->value_number, value); return; } } } ir_node *addr = expression_addr(dest_expr); ir_node *store = get_store(); dbg_info *dbgi = get_dbg_info(source_position); type_t *type = dest_expr->datatype; ir_node *result; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION) { ir_type *irtype = get_ir_type(type); result = new_d_CopyB(dbgi, store, addr, value, irtype); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_CopyB_M_regular); set_store(mem); } else { result = new_d_Store(dbgi, store, addr, value, cons_none); ir_node *mem = new_d_Proj(dbgi, result, mode_M, pn_Store_M); set_store(mem); } } static ir_node *assign_expression_to_firm(const binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; ir_node *value = expression_to_firm(right); firm_assign(left, value, & assign->expression.source_position); return value; } static ir_op *binexpr_type_to_op(binary_expression_type_t type) { switch(type) { case BINEXPR_ADD: return op_Add; case BINEXPR_SUB: return op_Sub; case BINEXPR_MUL: return op_Mul; case BINEXPR_AND: return op_And; case BINEXPR_OR: return op_Or; case BINEXPR_XOR: return op_Eor; case BINEXPR_SHIFTLEFT: return op_Shl; case BINEXPR_SHIFTRIGHT: return op_Shr; default: return NULL; } } static long binexpr_type_to_cmp_pn(binary_expression_type_t type) { switch(type) { case BINEXPR_EQUAL: return pn_Cmp_Eq; case BINEXPR_NOTEQUAL: return pn_Cmp_Lg; case BINEXPR_LESS: return pn_Cmp_Lt; case BINEXPR_LESSEQUAL: return pn_Cmp_Le; case BINEXPR_GREATER: return pn_Cmp_Gt; case BINEXPR_GREATEREQUAL: return pn_Cmp_Ge; default: return 0; } } static ir_node *create_lazy_op(const binary_expression_t *binary_expression) { int is_or = binary_expression->type == BINEXPR_LAZY_OR; assert(is_or || binary_expression->type == BINEXPR_LAZY_AND); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); ir_node *val1 = expression_to_firm(binary_expression->left); ir_node *cond = new_d_Cond(dbgi, val1); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true case */ ir_node *calc_val2_block = new_immBlock(); if(is_or) { add_immBlock_pred(calc_val2_block, false_proj); } else { add_immBlock_pred(calc_val2_block, true_proj); } mature_immBlock(calc_val2_block); set_cur_block(calc_val2_block); ir_node *val2 = expression_to_firm(binary_expression->right); if(get_cur_block() != NULL) { ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(fallthrough_block, jmp); } /* fallthrough */ ir_node *constb; if(is_or) { constb = new_d_Const(dbgi, get_tarval_b_true()); add_immBlock_pred(fallthrough_block, true_proj); } else { constb = new_d_Const(dbgi, get_tarval_b_false()); add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); ir_node *in[2] = { val2, constb }; ir_node *val = new_d_Phi(dbgi, 2, in, mode_b); return val; } static ir_node *binary_expression_to_firm(const binary_expression_t *binary_expression) { binary_expression_type_t btype = binary_expression->type; switch(btype) { case BINEXPR_ASSIGN: return assign_expression_to_firm(binary_expression); case BINEXPR_LAZY_OR: case BINEXPR_LAZY_AND: return create_lazy_op(binary_expression); default: break; } ir_node *left = expression_to_firm(binary_expression->left); ir_node *right = expression_to_firm(binary_expression->right); dbg_info *dbgi = get_dbg_info(&binary_expression->expression.source_position); if(btype == BINEXPR_DIV) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node, *res; if(mode_is_float(mode)) { node = new_d_Quot(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Quot_M); res = new_d_Proj(dbgi, node, mode, pn_Quot_res); } else { node = new_d_Div(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Div_M); res = new_d_Proj(dbgi, node, mode, pn_Div_res); } set_store(store); return res; } if(btype == BINEXPR_MOD) { ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *store = get_store(); ir_node *node = new_d_Mod(dbgi, store, left, right, mode, op_pin_state_floats); store = new_d_Proj(dbgi, node, mode_M, pn_Mod_M); set_store(store); return new_d_Proj(dbgi, node, mode, pn_Mod_res); } /* an arithmetic binexpression? */ ir_op *irop = binexpr_type_to_op(btype); if(irop != NULL) { ir_node *in[2] = { left, right }; ir_mode *mode = get_ir_mode(binary_expression->expression.datatype); ir_node *block = get_cur_block(); ir_node *node = new_ir_node(dbgi, current_ir_graph, block, irop, mode, 2, in); return node; } /* a comparison expression? */ long compare_pn = binexpr_type_to_cmp_pn(btype); if(compare_pn != 0) { ir_node *cmp = new_d_Cmp(dbgi, left, right); ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, compare_pn); return proj; } panic("found unknown binexpr type"); } static ir_node *cast_expression_to_firm(const unary_expression_t *cast) { type_t *to_type = cast->expression.datatype; ir_node *node = expression_to_firm(cast->value); ir_mode *mode = get_ir_mode(to_type); dbg_info *dbgi = get_dbg_info(&cast->expression.source_position); assert(node != NULL); return new_d_Conv(dbgi, node, mode); } static ir_node *load_from_expression_addr(type_t *type, ir_node *addr, const source_position_t *pos) { dbg_info *dbgi = get_dbg_info(pos); ir_mode *mode = get_ir_mode(type); ir_node *store = get_store(); ir_node *load = new_d_Load(dbgi, store, addr, mode, cons_none); ir_node *mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M); ir_node *val = new_d_Proj(dbgi, load, mode, pn_Load_res); set_store(mem); return val; } typedef ir_node* (*create_unop_node_func) (dbg_info *dbgi, ir_node *value, ir_mode *mode); static ir_node *create_unary_expression_node(const unary_expression_t *expression, create_unop_node_func create_func) { dbg_info *dbgi = get_dbg_info(&expression->expression.source_position); type_t *type = expression->expression.datatype; ir_mode *mode = get_ir_mode(type); ir_node *value = expression_to_firm(expression->value); ir_node *res = create_func(dbgi, value, mode); return res; } static ir_node *unary_expression_to_firm(const unary_expression_t *unary_expression) { ir_node *addr; switch(unary_expression->type) { case UNEXPR_CAST: return cast_expression_to_firm(unary_expression); case UNEXPR_DEREFERENCE: addr = expression_to_firm(unary_expression->value); return load_from_expression_addr(unary_expression->expression.datatype, addr, &unary_expression->expression.source_position); case UNEXPR_TAKE_ADDRESS: return expression_addr(unary_expression->value); case UNEXPR_BITWISE_NOT: case UNEXPR_NOT: return create_unary_expression_node(unary_expression, new_d_Not); case UNEXPR_NEGATE: return create_unary_expression_node(unary_expression, new_d_Minus); case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("inc/dec expression not lowered"); case UNEXPR_INVALID: abort(); } panic("found unknown unary expression"); } static ir_node *select_expression_to_firm(const select_expression_t *select) { ir_node *addr = select_expression_addr(select); type_t *entry_type = select->compound_entry->type; if(entry_type->type == TYPE_COMPOUND_STRUCT || entry_type->type == TYPE_COMPOUND_UNION || entry_type->type == TYPE_ARRAY) return addr; return load_from_expression_addr(select->expression.datatype, addr, &select->expression.source_position); } static ir_entity *assure_instance(method_t *method, symbol_t *symbol, type_argument_t *type_arguments) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(method->type_parameters, type_arguments); ir_entity *entity = get_method_entity(method, symbol); const char *name = get_entity_name(entity); pop_type_variable_bindings(old_top); if(strset_find(&instantiated_methods, name) != NULL) { return entity; } instantiate_method_t *instantiate = queue_method_instantiation(method, entity); type_argument_t *type_argument = type_arguments; type_argument_t *last_argument = NULL; while(type_argument != NULL) { type_t *type = type_argument->type; type_argument_t *new_argument = obstack_alloc(&obst, sizeof(new_argument[0])); memset(new_argument, 0, sizeof(new_argument[0])); new_argument->type = create_concrete_type(type); if(last_argument != NULL) { last_argument->next = new_argument; } else { instantiate->type_arguments = new_argument; } last_argument = new_argument; type_argument = type_argument->next; } strset_insert(&instantiated_methods, name); return entity; } static ir_node *method_reference_to_firm(method_t *method, symbol_t *symbol, type_argument_t *type_arguments, const source_position_t *source_position) { dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = assure_instance(method, symbol, type_arguments); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *concept_method_reference_to_firm(concept_method_t *method, - type_argument_t *type_arguments, + type_argument_t *type_arguments, const source_position_t *source_position) { concept_t *concept = method->concept; int old_top = typevar_binding_stack_top(); push_type_variable_bindings(concept->type_parameters, type_arguments); concept_instance_t *instance = find_concept_instance(concept); if(instance == NULL) { fprintf(stderr, "while looking at method '%s' from '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); print_type(stderr, concept->type_parameters->current_type); panic("no concept instance found in ast2firm phase"); return NULL; } concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, method); if(method_instance == NULL) { fprintf(stderr, "panic: no method '%s' in instance of concept '%s'\n", method->declaration.symbol->string, concept->declaration.symbol->string); panic("panic"); return NULL; } dbg_info *dbgi = get_dbg_info(source_position); ir_entity *entity = get_concept_method_instance_entity(method_instance); ir_node *symconst = new_d_SymConst(dbgi, mode_P, (union symconst_symbol) entity, symconst_addr_ent); pop_type_variable_bindings(old_top); return symconst; } static ir_node *method_parameter_reference_to_firm(method_parameter_t *parameter) { ir_node *args = get_irg_args(current_ir_graph); ir_mode *mode = get_ir_mode(parameter->type); ir_node *block = get_irg_start_block(current_ir_graph); long pn = parameter->num; ir_node *proj = new_r_Proj(current_ir_graph, block, args, mode, pn); return proj; } static ir_node *sizeof_expression_to_firm(const sizeof_expression_t *expression) { ir_mode *mode = get_ir_mode(expression->expression.datatype); unsigned size = get_type_size(expression->type); tarval *tv = new_tarval_from_long(size, mode); ir_node *res = new_Const(tv); return res; } static ir_node *call_expression_to_firm(const call_expression_t *call) { expression_t *method = call->method; ir_node *callee = expression_to_firm(method); assert(method->datatype->type == TYPE_POINTER); pointer_type_t *pointer_type = (pointer_type_t*) method->datatype; type_t *points_to = pointer_type->points_to; assert(points_to->type == TYPE_METHOD); method_type_t *method_type = (method_type_t*) points_to; ir_type *ir_method_type = get_ir_type((type_t*) method_type); ir_type *new_method_type = NULL; int n_parameters = 0; call_argument_t *argument = call->arguments; while(argument != NULL) { n_parameters++; argument = argument->next; } if(method_type->variable_arguments) { /* we need to construct a new method type matching the call * arguments... */ new_method_type = new_type_method(unique_ident("calltype"), n_parameters, get_method_n_ress(ir_method_type)); set_method_calling_convention(new_method_type, get_method_calling_convention(ir_method_type)); set_method_additional_properties(new_method_type, get_method_additional_properties(ir_method_type)); for(int i = 0; i < get_method_n_ress(ir_method_type); ++i) { set_method_res_type(new_method_type, i, get_method_res_type(ir_method_type, i)); } } ir_node *in[n_parameters]; argument = call->arguments; int n = 0; while(argument != NULL) { expression_t *expression = argument->expression; ir_node *arg_node = expression_to_firm(expression); in[n] = arg_node; if(new_method_type != NULL) { ir_type *irtype = get_ir_type(expression->datatype); set_method_param_type(new_method_type, n, irtype); } argument = argument->next; n++; } if(new_method_type != NULL) ir_method_type = new_method_type; dbg_info *dbgi = get_dbg_info(&call->expression.source_position); ir_node *store = get_store(); ir_node *node = new_d_Call(dbgi, store, callee, n_parameters, in, ir_method_type); ir_node *mem = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular); set_store(mem); type_t *result_type = method_type->result_type; ir_node *result = NULL; if(result_type->type != TYPE_VOID) { ir_mode *mode = get_ir_mode(result_type); ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result); result = new_d_Proj(dbgi, resproj, mode, 0); } return result; } static ir_node *func_expression_to_firm(func_expression_t *expression) { method_t *method = & expression->method; ir_entity *entity = method->e.entity; if(entity == NULL) { symbol_t *symbol = unique_symbol("anonfunc"); entity = get_method_entity(method, symbol); } queue_method_instantiation(method, entity); ir_node *symconst = new_SymConst(mode_P, (union symconst_symbol) entity, symconst_addr_ent); return symconst; } static ir_node *declaration_reference_to_firm(declaration_t *declaration, type_argument_t *type_arguments, const source_position_t *source_position) { method_declaration_t *method_declaration; switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; return method_reference_to_firm(&method_declaration->method, declaration->symbol, type_arguments, source_position); case DECLARATION_CONCEPT_METHOD: return concept_method_reference_to_firm( (concept_method_t*) declaration, type_arguments, source_position); case DECLARATION_METHOD_PARAMETER: return method_parameter_reference_to_firm( (method_parameter_t*) declaration); case DECLARATION_CONSTANT: return constant_reference_to_firm((constant_t*) declaration); case DECLARATION_VARIABLE: return variable_to_firm((variable_declaration_t*) declaration, source_position); case DECLARATION_LAST: case DECLARATION_INVALID: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_LABEL: case DECLARATION_TYPE_VARIABLE: panic("internal error: trying to construct node for non-data " "reference"); } panic("unknown declaration type found"); } static ir_node *reference_expression_to_firm(const reference_expression_t *reference) { declaration_t *declaration = reference->declaration; type_argument_t *type_arguments = reference->type_arguments; return declaration_reference_to_firm(declaration, type_arguments, &reference->expression.source_position); } static ir_node *expression_to_firm(expression_t *expression) { ir_node *addr; switch(expression->type) { case EXPR_INT_CONST: return int_const_to_firm((const int_const_t*) expression); case EXPR_FLOAT_CONST: return float_const_to_firm((const float_const_t*) expression); case EXPR_STRING_CONST: return string_const_to_firm((const string_const_t*) expression); case EXPR_BOOL_CONST: return bool_const_to_firm((const bool_const_t*) expression); case EXPR_NULL_POINTER: return null_pointer_to_firm(); case EXPR_REFERENCE: return reference_expression_to_firm( (const reference_expression_t*) expression); case EXPR_BINARY: return binary_expression_to_firm( (const binary_expression_t*) expression); case EXPR_UNARY: return unary_expression_to_firm( (const unary_expression_t*) expression); case EXPR_SELECT: return select_expression_to_firm( (const select_expression_t*) expression); case EXPR_ARRAY_ACCESS: addr = expression_addr(expression); return load_from_expression_addr(expression->datatype, addr, &expression->source_position); case EXPR_CALL: return call_expression_to_firm((const call_expression_t*) expression); case EXPR_SIZEOF: return sizeof_expression_to_firm( (const sizeof_expression_t*) expression); case EXPR_FUNC: return func_expression_to_firm( (func_expression_t*) expression); case EXPR_LAST: case EXPR_INVALID: break; } abort(); return NULL; } static void statement_to_firm(statement_t *statement); static void return_statement_to_firm(const return_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *ret; if(statement->return_value != NULL) { ir_node *retval = expression_to_firm(statement->return_value); ir_node *in[1]; in[0] = retval; ret = new_d_Return(dbgi, get_store(), 1, in); } else { ret = new_d_Return(dbgi, get_store(), 0, NULL); } ir_node *end_block = get_irg_end_block(current_ir_graph); add_immBlock_pred(end_block, ret); set_cur_block(NULL); } static void if_statement_to_firm(const if_statement_t *statement) { dbg_info *dbgi = get_dbg_info(&statement->statement.source_position); ir_node *condition = expression_to_firm(statement->condition); assert(condition != NULL); ir_node *cond = new_d_Cond(dbgi, condition); ir_node *true_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true); ir_node *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false); ir_node *fallthrough_block = new_immBlock(); /* the true (blocks) */ ir_node *true_block = new_immBlock(); add_immBlock_pred(true_block, true_proj); mature_immBlock(true_block); set_cur_block(true_block); statement_to_firm(statement->true_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } /* the false (blocks) */ if(statement->false_statement != NULL) { ir_node *false_block = new_immBlock(); add_immBlock_pred(false_block, false_proj); mature_immBlock(false_block); set_cur_block(false_block); statement_to_firm(statement->false_statement); if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(fallthrough_block, jmp); } } else { add_immBlock_pred(fallthrough_block, false_proj); } mature_immBlock(fallthrough_block); set_cur_block(fallthrough_block); } static void expression_statement_to_firm(const expression_statement_t *statement) { expression_to_firm(statement->expression); } static void block_statement_to_firm(const block_statement_t *block) { context2firm(&block->context); statement_t *statement = block->statements; while(statement != NULL) { statement_to_firm(statement); statement = statement->next; } } static void goto_statement_to_firm(goto_statement_t *goto_statement) { dbg_info *dbgi = get_dbg_info(&goto_statement->statement.source_position); label_declaration_t *label = goto_statement->label; ir_node *block = label->block; if (block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } ir_node *jmp = new_d_Jmp(dbgi); add_immBlock_pred(block, jmp); set_cur_block(NULL); } static void label_statement_to_firm(label_statement_t *label_statement) { label_declaration_t *label = &label_statement->declaration; ir_node *block = label->block; if(block == NULL) { block = new_immBlock(); label->block = block; label->next = labels; labels = label; } if(get_cur_block() != NULL) { ir_node *jmp = new_Jmp(); add_immBlock_pred(block, jmp); } set_cur_block(block); } static void statement_to_firm(statement_t *statement) { if(statement->type != STATEMENT_LABEL && get_cur_block() == NULL) { fprintf(stderr, "Warning: unreachable code detected\n"); return; } switch(statement->type) { case STATEMENT_BLOCK: block_statement_to_firm((block_statement_t*) statement); return; case STATEMENT_RETURN: return_statement_to_firm((return_statement_t*) statement); return; case STATEMENT_IF: if_statement_to_firm((if_statement_t*) statement); return; case STATEMENT_VARIABLE_DECLARATION: /* nothing to do */ break; case STATEMENT_EXPRESSION: expression_statement_to_firm((expression_statement_t*) statement); break; case STATEMENT_LABEL: label_statement_to_firm((label_statement_t*) statement); break; case STATEMENT_GOTO: goto_statement_to_firm((goto_statement_t*) statement); break; default: abort(); } } static void create_method(method_t *method, ir_entity *entity, type_argument_t *type_arguments) { if(method->is_extern) return; int old_top = typevar_binding_stack_top(); if(is_polymorphic_method(method)) { assert(type_arguments != NULL); push_type_variable_bindings(method->type_parameters, type_arguments); } ir_graph *irg = new_ir_graph(entity, method->n_local_vars); assert(variable_context == NULL); variable_context = get_irg_frame(irg); assert(value_numbers == NULL); value_numbers = xmalloc(method->n_local_vars * sizeof(value_numbers[0])); context2firm(&method->context); ir_node *firstblock = get_cur_block(); if(method->statement) statement_to_firm(method->statement); /* no return statement seen yet? */ ir_node *end_block = get_irg_end_block(irg); if(get_cur_block() != NULL) { ir_node *ret = new_Return(get_store(), 0, NULL); add_immBlock_pred(end_block, ret); } mature_immBlock(firstblock); mature_immBlock(end_block); label_declaration_t *label = labels; while(label != NULL) { mature_immBlock(label->block); label->block = NULL; label = label->next; } labels = NULL; irg_finalize_cons(irg); /* finalize the frame type */ ir_type *frame_type = get_irg_frame_type(irg); int n = get_compound_n_members(frame_type); int align_all = 4; int offset = 0; for(int i = 0; i < n; ++i) { ir_entity *entity = get_compound_member(frame_type, i); ir_type *entity_type = get_entity_type(entity); int align = get_type_alignment_bytes(entity_type); if(align > align_all) align_all = align; int misalign = 0; if(align > 0) { misalign = offset % align; offset += misalign; } set_entity_offset(entity, offset); offset += get_type_size_bytes(entity_type); } set_type_size_bytes(frame_type, offset); set_type_alignment_bytes(frame_type, align_all); set_type_state(frame_type, layout_fixed); irg_vrfy(irg); free(value_numbers); value_numbers = NULL; variable_context = NULL; pop_type_variable_bindings(old_top); } static void create_concept_instance(concept_instance_t *instance) { if (instance->type_parameters != NULL) return; concept_method_instance_t *method_instance = instance->method_instances; for ( ; method_instance != NULL; method_instance = method_instance->next) { /* we have to construct this instance lazily TODO: construct all instances lazily might be a good idea */ method_t *method = & method_instance->method; /* make sure the method entity is set */ ir_entity *entity = get_concept_method_instance_entity(method_instance); /* we can emit it like a normal method */ queue_method_instantiation(method, entity); } } static void context2firm(const context_t *context) { method_declaration_t *method_declaration; method_t *method; /* scan context for functions */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method_declaration = (method_declaration_t*) declaration; method = &method_declaration->method; if(!is_polymorphic_method(method)) { assure_instance(method, declaration->symbol, NULL); } break; case DECLARATION_VARIABLE: create_variable_entity((variable_declaration_t*) declaration); break; case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_CONSTANT: case DECLARATION_LABEL: case DECLARATION_METHOD_PARAMETER: case DECLARATION_CONCEPT_METHOD: case DECLARATION_TYPE_VARIABLE: break; case DECLARATION_LAST: case DECLARATION_INVALID: panic("Invalid namespace entry type found"); } declaration = declaration->next; } - /* TODO: create these lazily? */ + /* TODO: create these always lazily? */ concept_instance_t *instance = context->concept_instances; while(instance != NULL) { create_concept_instance(instance); instance = instance->next; } } static void namespace2firm(namespace_t *namespace) { context2firm(& namespace->context); } /** * Build a firm representation of the program */ void ast2firm(void) { obstack_init(&obst); strset_init(&instantiated_methods); instantiate_methods = new_pdeq(); assert(typevar_binding_stack_top() == 0); namespace_t *namespace = namespaces; while(namespace != NULL) { namespace2firm(namespace); namespace = namespace->next; } while(!pdeq_empty(instantiate_methods)) { instantiate_method_t *instantiate_method = pdeq_getl(instantiate_methods); assert(typevar_binding_stack_top() == 0); create_method(instantiate_method->method, instantiate_method->entity, instantiate_method->type_arguments); } assert(typevar_binding_stack_top() == 0); del_pdeq(instantiate_methods); obstack_free(&obst, NULL); strset_destroy(&instantiated_methods); } diff --git a/ast_t.h b/ast_t.h index 1e6d99a..aefc828 100644 --- a/ast_t.h +++ b/ast_t.h @@ -1,406 +1,410 @@ #ifndef AST_T_H #define AST_T_H #include "ast.h" #include "ast2firm.h" #include "symbol.h" #include "semantic.h" #include "lexer.h" #include "type.h" #include "adt/obst.h" #include <libfirm/typerep.h> extern struct obstack ast_obstack; extern namespace_t *namespaces; typedef enum { DECLARATION_INVALID, DECLARATION_METHOD, DECLARATION_METHOD_PARAMETER, DECLARATION_VARIABLE, DECLARATION_CONSTANT, DECLARATION_TYPE_VARIABLE, DECLARATION_TYPEALIAS, DECLARATION_CONCEPT, DECLARATION_CONCEPT_METHOD, DECLARATION_LABEL, DECLARATION_LAST } declaration_type_t; /** * base struct for a declaration */ struct declaration_t { declaration_type_t type; symbol_t *symbol; declaration_t *next; source_position_t source_position; }; struct export_t { symbol_t *symbol; export_t *next; source_position_t source_position; }; /** * a naming context. Containts a list of declarations valid in this context * (note that contexts are hierarchic, declarations from parent contexts are * not explicitely included) */ struct context_t { declaration_t *declarations; concept_instance_t *concept_instances; export_t *exports; }; /** * base structure for attributes (meta-data which can be attached to several * language elements) */ struct attribute_t { unsigned type; source_position_t source_position; attribute_t *next; }; struct type_variable_t { declaration_t declaration; type_constraint_t *constraints; type_variable_t *next; type_t *current_type; }; struct method_t { method_type_t *type; type_variable_t *type_parameters; method_parameter_t *parameters; unsigned char export; unsigned char is_extern; context_t context; statement_t *statement; union { ir_entity *entity; ir_entity **entities; } e; int n_local_vars; }; struct method_declaration_t { declaration_t declaration; method_t method; }; +struct iterator_declaration_t { + +}; + typedef enum { EXPR_INVALID = 0, EXPR_INT_CONST, EXPR_FLOAT_CONST, EXPR_BOOL_CONST, EXPR_STRING_CONST, EXPR_NULL_POINTER, EXPR_REFERENCE, EXPR_CALL, EXPR_UNARY, EXPR_BINARY, EXPR_SELECT, EXPR_ARRAY_ACCESS, EXPR_SIZEOF, EXPR_FUNC, EXPR_LAST } expresion_type_t; /** * base structure for expressions */ struct expression_t { expresion_type_t type; type_t *datatype; source_position_t source_position; }; struct bool_const_t { expression_t expression; int value; }; struct int_const_t { expression_t expression; int value; }; struct float_const_t { expression_t expression; double value; }; struct string_const_t { expression_t expression; const char *value; }; struct null_pointer_t { expression_t expression; }; struct func_expression_t { expression_t expression; method_t method; }; struct reference_expression_t { expression_t expression; symbol_t *symbol; declaration_t *declaration; type_argument_t *type_arguments; }; struct call_argument_t { expression_t *expression; call_argument_t *next; }; struct call_expression_t { expression_t expression; expression_t *method; call_argument_t *arguments; }; typedef enum { UNEXPR_INVALID = 0, UNEXPR_NEGATE, UNEXPR_NOT, UNEXPR_BITWISE_NOT, UNEXPR_DEREFERENCE, UNEXPR_TAKE_ADDRESS, UNEXPR_CAST, UNEXPR_INCREMENT, UNEXPR_DECREMENT } unary_expression_type_t; struct unary_expression_t { expression_t expression; unary_expression_type_t type; expression_t *value; }; typedef enum { BINEXPR_INVALID = 0, BINEXPR_ASSIGN, BINEXPR_ADD, BINEXPR_SUB, BINEXPR_MUL, BINEXPR_DIV, BINEXPR_MOD, BINEXPR_EQUAL, BINEXPR_NOTEQUAL, BINEXPR_LESS, BINEXPR_LESSEQUAL, BINEXPR_GREATER, BINEXPR_GREATEREQUAL, BINEXPR_LAZY_AND, BINEXPR_LAZY_OR, BINEXPR_AND, BINEXPR_OR, BINEXPR_XOR, BINEXPR_SHIFTLEFT, BINEXPR_SHIFTRIGHT, } binary_expression_type_t; struct binary_expression_t { expression_t expression; binary_expression_type_t type; expression_t *left; expression_t *right; }; struct select_expression_t { expression_t expression; expression_t *compound; symbol_t *symbol; compound_entry_t *compound_entry; declaration_t *declaration; }; struct array_access_expression_t { expression_t expression; expression_t *array_ref; expression_t *index; }; struct sizeof_expression_t { expression_t expression; type_t *type; }; typedef enum { STATEMENT_INVALID, STATEMENT_BLOCK, STATEMENT_RETURN, STATEMENT_VARIABLE_DECLARATION, STATEMENT_IF, STATEMENT_EXPRESSION, STATEMENT_GOTO, STATEMENT_LABEL, STATEMENT_LAST } statement_type_t; struct statement_t { statement_type_t type; statement_t *next; source_position_t source_position; }; struct return_statement_t { statement_t statement; expression_t *return_value; }; struct block_statement_t { statement_t statement; statement_t *statements; source_position_t end_position; context_t context; }; struct variable_declaration_t { declaration_t declaration; type_t *type; unsigned char is_extern; unsigned char export; unsigned char is_global; unsigned char needs_entity; int refs; /**< temporarily used by semantic phase */ ir_entity *entity; int value_number; }; struct variable_declaration_statement_t { statement_t statement; variable_declaration_t declaration; }; struct if_statement_t { statement_t statement; expression_t *condition; statement_t *true_statement; statement_t *false_statement; }; struct label_declaration_t { declaration_t declaration; ir_node *block; label_declaration_t *next; }; struct goto_statement_t { statement_t statement; symbol_t *label_symbol; label_declaration_t *label; }; struct label_statement_t { statement_t statement; label_declaration_t declaration; }; struct expression_statement_t { statement_t statement; expression_t *expression; }; struct method_parameter_t { declaration_t declaration; method_parameter_t *next; type_t *type; int num; }; struct constant_t { declaration_t declaration; type_t *type; expression_t *expression; }; struct typealias_t { declaration_t declaration; type_t *type; }; struct concept_method_instance_t { method_t method; symbol_t *symbol; source_position_t source_position; concept_method_instance_t *next; concept_method_t *concept_method; concept_instance_t *concept_instance; }; struct concept_instance_t { symbol_t *concept_symbol; source_position_t source_position; concept_t *concept; type_argument_t *type_arguments; concept_method_instance_t *method_instances; concept_instance_t *next; concept_instance_t *next_in_concept; context_t context; type_variable_t *type_parameters; }; struct concept_method_t { declaration_t declaration; method_type_t *method_type; method_parameter_t *parameters; concept_t *concept; concept_method_t *next; }; struct concept_t { declaration_t declaration; type_variable_t *type_parameters; concept_method_t *methods; concept_instance_t *instances; context_t context; }; struct namespace_t { symbol_t *symbol; const char *filename; context_t context; namespace_t *next; }; static inline void *_allocate_ast(size_t size) { return obstack_alloc(&ast_obstack, size); } #define allocate_ast(size) _allocate_ast(size) const char *get_declaration_type_name(declaration_type_t type); /* ----- helpers for plugins ------ */ unsigned register_expression(void); unsigned register_statement(void); unsigned register_declaration(void); unsigned register_attribute(void); #endif diff --git a/benchmarks/fib.fluffy b/benchmarks/fib.fluffy index 5ef5ce7..538f0ee 100644 --- a/benchmarks/fib.fluffy +++ b/benchmarks/fib.fluffy @@ -1,17 +1,17 @@ func fib(n : unsigned int) : unsigned int: - if n = 0: + if n == 0: return 0 - if n = 1: + if n == 1: return 1 return fib(n-1) + fib(n-2) func main(argc : int, argv : byte* *) : int: - var n <- cast<unsigned int> 8 + var n = cast<unsigned int> 8 if argc > 1: - n <- cast<unsigned int> atoi(argv[1]) + n = cast<unsigned int> atoi(argv[1]) printf("Fib %u: %u\n", n, fib(n)) return 0 export main diff --git a/benchmarks/queens.fluffy b/benchmarks/queens.fluffy index 1c5b5c1..a9373c9 100644 --- a/benchmarks/queens.fluffy +++ b/benchmarks/queens.fluffy @@ -1,49 +1,49 @@ var row : int* func myabs(i : int) : int: if i < 0: return -i return i func place_ok(i : int) : bool: - var j <- 0 + var j = 0 while j < i: - if row[j] = row[i] || myabs(row[i]-row[j]) = (i-j): + if row[j] == row[i] || myabs(row[i]-row[j]) == (i-j): return false - j <- j + 1 + j = j + 1 return true func solve(n : int) : int: - var c <- 0 - var res <- 0 + var c = 0 + var res = 0 - row <- cast<int* > malloc(sizeof<int> * n) - row[0] <- -1 + row = cast<int* > malloc(sizeof<int> * n) + row[0] = -1 while c >= 0: - row[c] <- row[c] + 1 + row[c] = row[c] + 1 while (row[c] < n) && (!place_ok(c)): - row[c] <- row[c] + 1 + row[c] = row[c] + 1 if row[c] < n: - if c = n-1: - res <- res + 1 + if c == n-1: + res = res + 1 else: - c <- c + 1 - row[c] <- -1 + c = c + 1 + row[c] = -1 else: - c <- c - 1 + c = c - 1 free(row) return res export main func main(argc : int, argv : byte* *) : int: - var n <- 8 + var n = 8 if argc > 1: - n <- atoi(argv[1]) + n = atoi(argv[1]) printf("The %d-queens problem has %d solutions.\n", n, solve(n)) return 0 diff --git a/match_type.c b/match_type.c index c4a4a35..f34febf 100644 --- a/match_type.c +++ b/match_type.c @@ -1,227 +1,228 @@ #include <config.h> #include "match_type.h" #include <assert.h> #include "type_t.h" #include "ast_t.h" #include "semantic_t.h" #include "type_hash.h" #include "adt/error.h" static inline void match_error(type_t *variant, type_t *concrete, const source_position_t source_position) { print_error_prefix(source_position); fprintf(stderr, "can't match variant type "); print_type(stderr, variant); fprintf(stderr, " against "); print_type(stderr, concrete); fprintf(stderr, "\n"); } static bool matched_type_variable(type_variable_t *type_variable, type_t *type, const source_position_t source_position, bool report_errors) { type_t *current_type = type_variable->current_type; if(current_type != NULL && current_type != type) { if (report_errors) { print_error_prefix(source_position); fprintf(stderr, "ambiguous matches found for type variable '%s': ", type_variable->declaration.symbol->string); print_type(stderr, current_type); fprintf(stderr, ", "); print_type(stderr, type); fprintf(stderr, "\n"); } /* are both types normalized? */ assert(typehash_contains(current_type)); assert(typehash_contains(type)); return false; } type_variable->current_type = type; return true; } static bool match_compound_type(compound_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_variable_t *type_parameters = variant_type->type_parameters; if(type_parameters == NULL) { if(concrete_type != (type_t*) variant_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } + return true; } if(concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if(polymorphic_type != variant_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_variable_t *type_parameter = type_parameters; type_argument_t *type_argument = bind_typevariables->type_arguments; bool result = true; while(type_parameter != NULL) { assert(type_argument != NULL); if(!matched_type_variable(type_parameter, type_argument->type, source_position, true)) result = false; type_parameter = type_parameter->next; type_argument = type_argument->next; } return result; } static bool match_bind_typevariables(bind_typevariables_type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { if(concrete_type->type != TYPE_BIND_TYPEVARIABLES) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } bind_typevariables_type_t *bind_typevariables = (bind_typevariables_type_t*) concrete_type; compound_type_t *polymorphic_type = bind_typevariables->polymorphic_type; if(polymorphic_type != variant_type->polymorphic_type) { if(report_errors) match_error((type_t*) variant_type, concrete_type, source_position); return false; } type_argument_t *argument1 = variant_type->type_arguments; type_argument_t *argument2 = bind_typevariables->type_arguments; bool result = true; while(argument1 != NULL) { assert(argument2 != NULL); if(!match_variant_to_concrete_type(argument1->type, argument2->type, source_position, report_errors)) result = false; argument1 = argument1->next; argument2 = argument2->next; } assert(argument2 == NULL); return result; } bool match_variant_to_concrete_type(type_t *variant_type, type_t *concrete_type, const source_position_t source_position, bool report_errors) { type_reference_t *type_ref; type_variable_t *type_var; pointer_type_t *pointer_type_1; pointer_type_t *pointer_type_2; method_type_t *method_type_1; method_type_t *method_type_2; assert(type_valid(variant_type)); assert(type_valid(concrete_type)); switch(variant_type->type) { case TYPE_REFERENCE_TYPE_VARIABLE: type_ref = (type_reference_t*) variant_type; type_var = type_ref->type_variable; return matched_type_variable(type_var, concrete_type, source_position, report_errors); case TYPE_VOID: case TYPE_ATOMIC: if(concrete_type != variant_type) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } return true; case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: return match_compound_type((compound_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_POINTER: if(concrete_type->type != TYPE_POINTER) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } pointer_type_1 = (pointer_type_t*) variant_type; pointer_type_2 = (pointer_type_t*) concrete_type; return match_variant_to_concrete_type(pointer_type_1->points_to, pointer_type_2->points_to, source_position, report_errors); case TYPE_METHOD: if(concrete_type->type != TYPE_METHOD) { if(report_errors) match_error(variant_type, concrete_type, source_position); return false; } method_type_1 = (method_type_t*) variant_type; method_type_2 = (method_type_t*) concrete_type; bool result = match_variant_to_concrete_type(method_type_1->result_type, method_type_2->result_type, source_position, report_errors); method_parameter_type_t *param1 = method_type_1->parameter_types; method_parameter_type_t *param2 = method_type_2->parameter_types; while(param1 != NULL && param2 != NULL) { if(!match_variant_to_concrete_type(param1->type, param2->type, source_position, report_errors)) result = false; param1 = param1->next; param2 = param2->next; } if(param1 != NULL || param2 != NULL) { if (report_errors) match_error(variant_type, concrete_type, source_position); return false; } return result; case TYPE_BIND_TYPEVARIABLES: return match_bind_typevariables( (bind_typevariables_type_t*) variant_type, concrete_type, source_position, report_errors); case TYPE_ARRAY: panic("TODO"); case TYPE_REFERENCE: panic("type reference not resolved in match variant to concrete type"); case TYPE_INVALID: panic("invalid type in match variant to concrete type"); } panic("unknown type in match variant to concrete type"); } diff --git a/parser.c b/parser.c index c0510f9..75693f1 100644 --- a/parser.c +++ b/parser.c @@ -417,1765 +417,1762 @@ static type_t *parse_struct_type(void) } static type_t *make_pointer_type_no_hash(type_t *type) { pointer_type_t *pointer_type = allocate_type_zero(sizeof(pointer_type[0])); pointer_type->type.type = TYPE_POINTER; pointer_type->points_to = type; return (type_t*) pointer_type; } type_t *parse_type(void) { type_t *type; switch(token.type) { case T_unsigned: case T_signed: case T_bool: case T_int: case T_long: case T_byte: case T_short: case T_float: case T_double: type = parse_atomic_type(); break; case T_IDENTIFIER: type = parse_type_ref(); break; case T_void: type = type_void; next_token(); break; case T_union: type = parse_union_type(); break; case T_struct: type = parse_struct_type(); break; case T_func: type = parse_method_type(); break; case '(': next_token(); type = parse_type(); expect(')'); break; default: parser_print_error_prefix(); fprintf(stderr, "Token "); print_token(stderr, &token); fprintf(stderr, " doesn't start a type\n"); type = type_invalid; break; } /* parse type modifiers */ array_type_t *array_type; while(1) { switch(token.type) { case '*': { next_token(); type = make_pointer_type_no_hash(type); break; } case '[': { next_token(); if(token.type != T_INTEGER) { parse_error_expected("problem while parsing array type", T_INTEGER, 0); break; } int size = token.v.intvalue; next_token(); if(size < 0) { parse_error("negative array size not allowed"); expect(']'); break; } array_type = allocate_type_zero(sizeof(array_type[0])); array_type->type.type = TYPE_ARRAY; array_type->element_type = type; array_type->size = size; type = (type_t*) array_type; expect(']'); break; } default: return type; } } } static expression_t *parse_string_const(unsigned precedence) { (void) precedence; string_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_STRING_CONST; cnst->value = token.v.string; next_token(); return (expression_t*) cnst; } static expression_t *parse_int_const(unsigned precedence) { (void) precedence; int_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_INT_CONST; cnst->value = token.v.intvalue; next_token(); return (expression_t*) cnst; } static expression_t *parse_true(unsigned precedence) { (void) precedence; eat(T_true); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 1; return (expression_t*) cnst; } static expression_t *parse_false(unsigned precedence) { (void) precedence; eat(T_false); bool_const_t *cnst = allocate_ast_zero(sizeof(cnst[0])); cnst->expression.type = EXPR_BOOL_CONST; cnst->value = 0; return (expression_t*) cnst; } static expression_t *parse_null(unsigned precedence) { (void) precedence; eat(T_null); null_pointer_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_NULL_POINTER; expression->expression.datatype = make_pointer_type(type_void); return (expression_t*) expression; } static expression_t *parse_func_expression(unsigned precedence) { (void) precedence; eat(T_func); func_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_FUNC; parse_method(&expression->method); /* force end of statement */ assert(token.type == T_DEDENT); replace_token_type(T_NEWLINE); return (expression_t*) expression; } static expression_t *parse_reference(unsigned precedence) { (void) precedence; reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = token.v.symbol; next_token(); if(token.type == T_TYPESTART) { next_token(); ref->type_arguments = parse_type_arguments(); expect('>'); } return (expression_t*) ref; } static expression_t *parse_sizeof(unsigned precedence) { (void) precedence; eat(T_sizeof); sizeof_expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->expression.type = EXPR_SIZEOF; expect('<'); expression->type = parse_type(); expect('>'); return (expression_t*) expression; } void register_statement_parser(parse_statement_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(statement_parsers); if(token_type >= len) { ARR_RESIZE(parse_statement_function, statement_parsers, token_type + 1); memset(& statement_parsers[len], 0, (token_type - len + 1) * sizeof(statement_parsers[0])); } if(statement_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("Trying to register multiple statement parsers for 1 token"); } statement_parsers[token_type] = parser; } void register_declaration_parser(parse_declaration_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(declaration_parsers); if(token_type >= len) { ARR_RESIZE(parse_declaration_function, declaration_parsers, token_type + 1); memset(& declaration_parsers[len], 0, (token_type - len + 1) * sizeof(declaration_parsers[0])); } if(declaration_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } declaration_parsers[token_type] = parser; } void register_attribute_parser(parse_attribute_function parser, int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(attribute_parsers); if(token_type >= len) { ARR_RESIZE(parse_attribute_function, attribute_parsers, token_type + 1); memset(& attribute_parsers[len], 0, (token_type - len + 1) * sizeof(attribute_parsers[0])); } if(attribute_parsers[token_type] != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple namespace parsers for 1 token"); } attribute_parsers[token_type] = parser; } static expression_parse_function_t *get_expression_parser_entry(int token_type) { if(token_type < 0) panic("can't register parser for negative token"); int len = ARR_LEN(expression_parsers); if(token_type >= len) { ARR_RESIZE(expression_parse_function_t, expression_parsers, token_type + 1); memset(& expression_parsers[len], 0, (token_type - len + 1) * sizeof(expression_parsers[0])); } return &expression_parsers[token_type]; } void register_expression_parser(parse_expression_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple expression parsers for a token"); } entry->parser = parser; entry->precedence = precedence; } void register_expression_infix_parser(parse_expression_infix_function parser, int token_type, unsigned precedence) { expression_parse_function_t *entry = get_expression_parser_entry(token_type); if(entry->infix_parser != NULL) { fprintf(stderr, "for token "); print_token_type(stderr, token_type); fprintf(stderr, "\n"); panic("trying to register multiple infix expression parsers for a " "token"); } entry->infix_parser = parser; entry->infix_precedence = precedence; } static expression_t *expected_expression_error(void) { parser_print_error_prefix(); fprintf(stderr, "expected expression, got token "); print_token(stderr, & token); fprintf(stderr, "\n"); expression_t *expression = allocate_ast_zero(sizeof(expression[0])); expression->type = EXPR_INVALID; next_token(); return expression; } static expression_t *parse_brace_expression(unsigned precedence) { (void) precedence; eat('('); expression_t *result = parse_expression(); expect(')'); return result; } static expression_t *parse_cast_expression(unsigned precedence) { eat(T_cast); unary_expression_t *unary_expression = allocate_ast_zero(sizeof(unary_expression[0])); unary_expression->expression.type = EXPR_UNARY; unary_expression->type = UNEXPR_CAST; expect('<'); unary_expression->expression.datatype = parse_type(); expect('>'); unary_expression->value = parse_sub_expression(precedence); return (expression_t*) unary_expression; } static expression_t *parse_call_expression(unsigned precedence, expression_t *expression) { (void) precedence; call_expression_t *call = allocate_ast_zero(sizeof(call[0])); call->expression.type = EXPR_CALL; call->method = expression; /* parse arguments */ eat('('); if(token.type != ')') { call_argument_t *last_argument = NULL; while(1) { call_argument_t *argument = allocate_ast_zero(sizeof(argument[0])); argument->expression = parse_expression(); if(last_argument == NULL) { call->arguments = argument; } else { last_argument->next = argument; } last_argument = argument; if(token.type != ',') break; next_token(); } } expect(')'); return (expression_t*) call; } static expression_t *parse_select_expression(unsigned precedence, expression_t *compound) { (void) precedence; eat('.'); select_expression_t *select = allocate_ast_zero(sizeof(select[0])); select->expression.type = EXPR_SELECT; select->compound = compound; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing compound select", T_IDENTIFIER, 0); return NULL; } select->symbol = token.v.symbol; next_token(); return (expression_t*) select; } static expression_t *parse_array_expression(unsigned precedence, expression_t *array_ref) { (void) precedence; eat('['); array_access_expression_t *array_access = allocate_ast_zero(sizeof(array_access[0])); array_access->expression.type = EXPR_ARRAY_ACCESS; array_access->array_ref = array_ref; array_access->index = parse_expression(); if(token.type != ']') { parse_error_expected("Problem while parsing array access", ']', 0); return NULL; } next_token(); return (expression_t*) array_access; } #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type) \ static \ expression_t *parse_##unexpression_type(unsigned precedence) \ { \ eat(token_type); \ \ unary_expression_t *unary_expression \ = allocate_ast_zero(sizeof(unary_expression[0])); \ unary_expression->expression.type = EXPR_UNARY; \ unary_expression->type = unexpression_type; \ unary_expression->value = parse_sub_expression(precedence); \ \ return (expression_t*) unary_expression; \ } CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE) CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT) CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NOT) CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE) CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS) CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, UNEXPR_INCREMENT) CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_DECREMENT) #define CREATE_BINEXPR_PARSER(token_type, binexpression_type) \ static \ expression_t *parse_##binexpression_type(unsigned precedence, \ expression_t *left) \ { \ eat(token_type); \ \ expression_t *right = parse_sub_expression(precedence); \ \ binary_expression_t *binexpr \ = allocate_ast_zero(sizeof(binexpr[0])); \ binexpr->expression.type = EXPR_BINARY; \ binexpr->type = binexpression_type; \ binexpr->left = left; \ binexpr->right = right; \ \ return (expression_t*) binexpr; \ } CREATE_BINEXPR_PARSER('*', BINEXPR_MUL); CREATE_BINEXPR_PARSER('/', BINEXPR_DIV); CREATE_BINEXPR_PARSER('%', BINEXPR_MOD); CREATE_BINEXPR_PARSER('+', BINEXPR_ADD); CREATE_BINEXPR_PARSER('-', BINEXPR_SUB); CREATE_BINEXPR_PARSER('<', BINEXPR_LESS); CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER); -CREATE_BINEXPR_PARSER('=', BINEXPR_EQUAL); -CREATE_BINEXPR_PARSER(T_ASSIGN, BINEXPR_ASSIGN); +CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL); +CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN); CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_NOTEQUAL); CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL); CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL); CREATE_BINEXPR_PARSER('&', BINEXPR_AND); CREATE_BINEXPR_PARSER('|', BINEXPR_OR); CREATE_BINEXPR_PARSER('^', BINEXPR_XOR); CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LAZY_AND); CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LAZY_OR); CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT); CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT); static void register_expression_parsers(void) { register_expression_infix_parser(parse_BINEXPR_MUL, '*', 16); register_expression_infix_parser(parse_BINEXPR_DIV, '/', 16); register_expression_infix_parser(parse_BINEXPR_MOD, '%', 16); register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT, T_LESSLESS, 16); register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT, T_GREATERGREATER, 16); register_expression_infix_parser(parse_BINEXPR_ADD, '+', 15); register_expression_infix_parser(parse_BINEXPR_SUB, '-', 15); register_expression_infix_parser(parse_BINEXPR_LESS, '<', 14); register_expression_infix_parser(parse_BINEXPR_GREATER, '>', 14); register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL, 14); register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL, T_GREATEREQUAL, 14); - register_expression_infix_parser(parse_BINEXPR_EQUAL, '=', 13); + register_expression_infix_parser(parse_BINEXPR_EQUAL, T_EQUALEQUAL, 13); register_expression_infix_parser(parse_BINEXPR_NOTEQUAL, T_SLASHEQUAL, 13); register_expression_infix_parser(parse_BINEXPR_AND, '&', 12); register_expression_infix_parser(parse_BINEXPR_LAZY_AND, T_ANDAND, 12); register_expression_infix_parser(parse_BINEXPR_XOR, '^', 11); register_expression_infix_parser(parse_BINEXPR_OR, '|', 10); register_expression_infix_parser(parse_BINEXPR_LAZY_OR, T_PIPEPIPE, 10); - register_expression_infix_parser(parse_BINEXPR_ASSIGN, T_ASSIGN, 2); + register_expression_infix_parser(parse_BINEXPR_ASSIGN, '=', 2); register_expression_infix_parser(parse_array_expression, '[', 25); register_expression_infix_parser(parse_call_expression, '(', 30); register_expression_infix_parser(parse_select_expression, '.', 30); register_expression_parser(parse_UNEXPR_NEGATE, '-', 25); register_expression_parser(parse_UNEXPR_NOT, '!', 25); register_expression_parser(parse_UNEXPR_BITWISE_NOT, '~', 25); register_expression_parser(parse_UNEXPR_INCREMENT, T_PLUSPLUS, 25); register_expression_parser(parse_UNEXPR_DECREMENT, T_MINUSMINUS, 25); register_expression_parser(parse_UNEXPR_DEREFERENCE, '*', 20); register_expression_parser(parse_UNEXPR_TAKE_ADDRESS, '&', 20); register_expression_parser(parse_cast_expression, T_cast, 19); register_expression_parser(parse_brace_expression, '(', 1); register_expression_parser(parse_sizeof, T_sizeof, 1); register_expression_parser(parse_int_const, T_INTEGER, 1); register_expression_parser(parse_true, T_true, 1); register_expression_parser(parse_false, T_false, 1); register_expression_parser(parse_string_const, T_STRING_LITERAL, 1); register_expression_parser(parse_null, T_null, 1); register_expression_parser(parse_reference, T_IDENTIFIER, 1); register_expression_parser(parse_func_expression, T_func, 1); } expression_t *parse_sub_expression(unsigned precedence) { if(token.type < 0) { return expected_expression_error(); } expression_parse_function_t *parser = & expression_parsers[token.type]; source_position_t start = source_position; expression_t *left; if(parser->parser != NULL) { left = parser->parser(parser->precedence); } else { left = expected_expression_error(); } assert(left != NULL); left->source_position = start; while(1) { if(token.type < 0) { return expected_expression_error(); } parser = &expression_parsers[token.type]; if(parser->infix_parser == NULL) break; if(parser->infix_precedence < precedence) break; left = parser->infix_parser(parser->infix_precedence, left); assert(left != NULL); left->source_position = start; } return left; } expression_t *parse_expression(void) { return parse_sub_expression(1); } static statement_t *parse_return_statement(void) { return_statement_t *return_statement = allocate_ast_zero(sizeof(return_statement[0])); return_statement->statement.type = STATEMENT_RETURN; next_token(); if(token.type != T_NEWLINE) { return_statement->return_value = parse_expression(); } expect(T_NEWLINE); return (statement_t*) return_statement; } static statement_t *parse_goto_statement(void) { eat(T_goto); goto_statement_t *goto_statement = allocate_ast_zero(sizeof(goto_statement[0])); goto_statement->statement.type = STATEMENT_GOTO; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing goto statement", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } goto_statement->label_symbol = token.v.symbol; next_token(); expect(T_NEWLINE); return (statement_t*) goto_statement; } static statement_t *parse_label_statement(void) { eat(':'); label_statement_t *label = allocate_ast_zero(sizeof(label[0])); label->statement.type = STATEMENT_LABEL; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing label", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } label->declaration.declaration.type = DECLARATION_LABEL; label->declaration.declaration.source_position = source_position; label->declaration.declaration.symbol = token.v.symbol; next_token(); add_declaration((declaration_t*) &label->declaration); expect(T_NEWLINE); return (statement_t*) label; } static statement_t *parse_sub_block(void) { if(token.type != T_NEWLINE) { return parse_statement(); } eat(T_NEWLINE); if(token.type != T_INDENT) { /* create an empty block */ block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; return (statement_t*) block; } return parse_block(); } static statement_t *parse_if_statement(void) { eat(T_if); expression_t *condition = parse_expression(); expect(':'); statement_t *true_statement = parse_sub_block(); statement_t *false_statement = NULL; if(token.type == T_else) { next_token(); if(token.type == ':') next_token(); false_statement = parse_sub_block(); } if_statement_t *if_statement = allocate_ast_zero(sizeof(if_statement[0])); if_statement->statement.type = STATEMENT_IF; if_statement->condition = condition; if_statement->true_statement = true_statement; if_statement->false_statement = false_statement; return (statement_t*) if_statement; } static statement_t *parse_initial_assignment(symbol_t *symbol) { reference_expression_t *ref = allocate_ast_zero(sizeof(ref[0])); ref->expression.type = EXPR_REFERENCE; ref->symbol = symbol; binary_expression_t *assign = allocate_ast_zero(sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.source_position = source_position; assign->type = BINEXPR_ASSIGN; assign->left = (expression_t*) ref; assign->right = parse_expression(); expression_statement_t *expr_statement = allocate_ast_zero(sizeof(expr_statement[0])); expr_statement->statement.type = STATEMENT_EXPRESSION; expr_statement->expression = (expression_t*) assign; return (statement_t*) expr_statement; } static statement_t *parse_variable_declaration(void) { statement_t *first_statement = NULL; statement_t *last_statement = NULL; eat(T_var); while(1) { if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing variable declaration", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } variable_declaration_statement_t *declaration_statement = allocate_ast_zero(sizeof(declaration_statement[0])); declaration_statement->statement.type = STATEMENT_VARIABLE_DECLARATION; declaration_t *declaration = &declaration_statement->declaration.declaration; declaration->type = DECLARATION_VARIABLE; declaration->source_position = source_position; declaration->symbol = token.v.symbol; next_token(); add_declaration(declaration); variable_declaration_t *variable_declaration = &declaration_statement->declaration; if(token.type == ':') { next_token(); variable_declaration->type = parse_type(); } /* append multiple variable declarations */ if(last_statement != NULL) { last_statement->next = (statement_t*) declaration_statement; } else { first_statement = (statement_t*) declaration_statement; } last_statement = (statement_t*) declaration_statement; /* do we have an assignment expression? */ - if(token.type == T_ASSIGN) { + if(token.type == '=') { next_token(); statement_t *assign = parse_initial_assignment(declaration->symbol); last_statement->next = assign; last_statement = assign; - } else if(token.type == '=') { - next_token(); - parse_error("found '=' after variable declaration, did you mean '<-'?"); } /* check if we have more declared symbols separated by ',' */ if(token.type != ',') break; next_token(); } expect(T_NEWLINE); return first_statement; } static statement_t *parse_expression_statement(void) { expression_statement_t *expression_statement = allocate_ast_zero(sizeof(expression_statement[0])); expression_statement->statement.type = STATEMENT_EXPRESSION; expression_statement->expression = parse_expression(); expect(T_NEWLINE); return (statement_t*) expression_statement; } static statement_t *parse_newline(void) { eat(T_NEWLINE); if(token.type == T_INDENT) return parse_block(); return NULL; } static void register_statement_parsers(void) { register_statement_parser(parse_return_statement, T_return); register_statement_parser(parse_if_statement, T_if); register_statement_parser(parse_block, T_INDENT); register_statement_parser(parse_variable_declaration, T_var); register_statement_parser(parse_label_statement, ':'); register_statement_parser(parse_goto_statement, T_goto); register_statement_parser(parse_newline, T_NEWLINE); } statement_t *parse_statement(void) { statement_t *statement = NULL; source_position_t start = source_position; if(token.type < 0) { /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing statement", T_DEDENT, 0); return NULL; } parse_statement_function parser = NULL; if(token.type < ARR_LEN(statement_parsers)) parser = statement_parsers[token.type]; if(parser != NULL) { statement = parser(); } else { parse_declaration_function declaration_parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) declaration_parser = declaration_parsers[token.type]; if(declaration_parser != NULL) { declaration_parser(); } else { statement = parse_expression_statement(); } } if(statement == NULL) return NULL; statement->source_position = start; statement_t *next = statement->next; while(next != NULL) { next->source_position = start; next = next->next; } return statement; } static statement_t *parse_block(void) { eat(T_INDENT); block_statement_t *block = allocate_ast_zero(sizeof(block[0])); block->statement.type = STATEMENT_BLOCK; context_t *last_context = current_context; current_context = &block->context; statement_t *last_statement = NULL; while(token.type != T_DEDENT && token.type != T_EOF) { /* parse statement */ statement_t *statement = parse_statement(); if(statement == NULL) continue; if(last_statement != NULL) { last_statement->next = statement; } else { block->statements = statement; } last_statement = statement; /* the parse rule might have produced multiple statements */ while(last_statement->next != NULL) last_statement = last_statement->next; } assert(current_context == &block->context); current_context = last_context; block->end_position = source_position; expect(T_DEDENT); return (statement_t*) block; } static void parse_parameter_declaration(method_type_t *method_type, method_parameter_t **parameters) { assert(method_type != NULL); if(token.type == ')') return; method_parameter_type_t *last_type = NULL; method_parameter_t *last_param = NULL; if(parameters != NULL) *parameters = NULL; while(1) { if(token.type == T_DOTDOTDOT) { method_type->variable_arguments = 1; next_token(); if(token.type == ',') { parse_error("'...' has to be the last argument in a function " "parameter list"); eat_until_newline(); return; } break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing parameter", T_IDENTIFIER, 0); eat_until_newline(); return; } symbol_t *symbol = token.v.symbol; next_token(); expect_void(':'); method_parameter_type_t *param_type = allocate_ast_zero(sizeof(param_type[0])); param_type->type = parse_type(); if(last_type != NULL) { last_type->next = param_type; } else { method_type->parameter_types = param_type; } last_type = param_type; if(parameters != NULL) { method_parameter_t *method_param = allocate_ast_zero(sizeof(method_param[0])); method_param->declaration.type = DECLARATION_METHOD_PARAMETER; method_param->declaration.symbol = symbol; method_param->declaration.source_position = source_position; method_param->type = param_type->type; if(last_param != NULL) { last_param->next = method_param; } else { *parameters = method_param; } last_param = method_param; } if(token.type != ',') break; next_token(); } } static type_constraint_t *parse_type_constraints(void) { type_constraint_t *first_constraint = NULL; type_constraint_t *last_constraint = NULL; while(token.type == T_IDENTIFIER) { type_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0])); constraint->concept_symbol = token.v.symbol; next_token(); if(last_constraint == NULL) { first_constraint = constraint; } else { last_constraint->next = constraint; } last_constraint = constraint; } return first_constraint; } static type_variable_t *parse_type_parameter(void) { type_variable_t *type_variable = allocate_ast_zero(sizeof(type_variable[0])); type_variable->declaration.type = DECLARATION_TYPE_VARIABLE; if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing type parameter", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } type_variable->declaration.source_position = source_position; type_variable->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); type_variable->constraints = parse_type_constraints(); } return type_variable; } static type_variable_t *parse_type_parameters(context_t *context) { type_variable_t *first_variable = NULL; type_variable_t *last_variable = NULL; while(1) { type_variable_t *type_variable = parse_type_parameter(); if(last_variable != NULL) { last_variable->next = type_variable; } else { first_variable = type_variable; } last_variable = type_variable; if(context != NULL) { declaration_t *declaration = & type_variable->declaration; declaration->next = context->declarations; context->declarations = declaration; } if(token.type != ',') break; next_token(); } return first_variable; } void add_declaration(declaration_t *declaration) { assert(declaration != NULL); assert(declaration->source_position.input_name != NULL); assert(current_context != NULL); declaration->next = current_context->declarations; current_context->declarations = declaration; } static void parse_method(method_t *method) { method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; context_t *last_context = current_context; current_context = &method->context; if(token.type == '<') { next_token(); method->type_parameters = parse_type_parameters(current_context); expect_void('>'); } expect_void('('); parse_parameter_declaration(method_type, &method->parameters); method->type = method_type; /* add parameters to context */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { declaration_t *declaration = (declaration_t*) parameter; declaration->next = current_context->declarations; current_context->declarations = declaration; parameter = parameter->next; } expect_void(')'); method_type->result_type = type_void; if(token.type == ':') { next_token(); if(token.type == T_NEWLINE) { method->statement = parse_sub_block(); goto method_parser_end; } method_type->result_type = parse_type(); if(token.type == ':') { next_token(); method->statement = parse_sub_block(); goto method_parser_end; } } expect_void(T_NEWLINE); method_parser_end: assert(current_context == &method->context); current_context = last_context; } static void parse_method_declaration(void) { eat(T_func); method_declaration_t *method_declaration = allocate_ast_zero(sizeof(method_declaration[0])); method_declaration->declaration.type = DECLARATION_METHOD; if(token.type == T_extern) { method_declaration->method.is_extern = 1; next_token(); } if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing function", T_IDENTIFIER, 0); eat_until_newline(); return; } method_declaration->declaration.source_position = source_position; method_declaration->declaration.symbol = token.v.symbol; next_token(); parse_method(&method_declaration->method); add_declaration((declaration_t*) method_declaration); } static void parse_global_variable(void) { eat(T_var); variable_declaration_t *variable = allocate_ast_zero(sizeof(variable[0])); variable->declaration.type = DECLARATION_VARIABLE; variable->is_global = 1; if(token.type == T_extern) { next_token(); variable->is_extern = 1; } if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing global variable", T_IDENTIFIER, 0); eat_until_newline(); return; } variable->declaration.source_position = source_position; variable->declaration.symbol = token.v.symbol; next_token(); if(token.type != ':') { parse_error_expected("global variables must have a type specified", ':', 0); eat_until_newline(); } else { next_token(); variable->type = parse_type(); expect_void(T_NEWLINE); } add_declaration((declaration_t*) variable); } static void parse_constant(void) { eat(T_const); constant_t *constant = allocate_ast_zero(sizeof(constant[0])); constant->declaration.type = DECLARATION_CONSTANT; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing constant", T_IDENTIFIER, 0); eat_until_newline(); return; } constant->declaration.source_position = source_position; constant->declaration.symbol = token.v.symbol; next_token(); if(token.type == ':') { next_token(); constant->type = parse_type(); } - expect_void(T_ASSIGN); + expect_void('='); constant->expression = parse_expression(); expect_void(T_NEWLINE); add_declaration((declaration_t*) constant); } static void parse_typealias(void) { eat(T_typealias); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing typealias", T_IDENTIFIER, 0); eat_until_newline(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); - expect_void(T_ASSIGN); + expect_void('='); typealias->type = parse_type(); expect_void(T_NEWLINE); add_declaration((declaration_t*) typealias); } static attribute_t *parse_attribute(void) { eat('$'); attribute_t *attribute = NULL; if(token.type < 0) { parse_error("problem while parsing attribute"); return NULL; } parse_attribute_function parser = NULL; if(token.type < ARR_LEN(attribute_parsers)) parser = attribute_parsers[token.type]; if(parser == NULL) { parser_print_error_prefix(); print_token(stderr, &token); fprintf(stderr, " doesn't start a known attribute type\n"); return NULL; } if(parser != NULL) { attribute = parser(); } return attribute; } attribute_t *parse_attributes(void) { attribute_t *last = NULL; while(token.type == '$') { attribute_t *attribute = parse_attribute(); if(attribute != NULL) { attribute->next = last; last = attribute; } } return last; } static void parse_class(void) { eat(T_class); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing class", T_IDENTIFIER, 0); eat_until_newline(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_CLASS; compound_type->symbol = typealias->declaration.symbol; compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; expect_void(':'); expect_void(T_NEWLINE); if(token.type == T_INDENT) { next_token(); context_t *last_context = current_context; current_context = &compound_type->context; while(token.type != T_EOF && token.type != T_DEDENT) { parse_declaration(); } next_token(); assert(current_context == &compound_type->context); current_context = last_context; } add_declaration((declaration_t*) typealias); } static void parse_struct(void) { eat(T_struct); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing struct", T_IDENTIFIER, 0); eat_until_newline(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_STRUCT; compound_type->symbol = typealias->declaration.symbol; if(token.type == '<') { next_token(); compound_type->type_parameters = parse_type_parameters(&compound_type->context); expect_void('>'); } compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; expect_void(':'); expect_void(T_NEWLINE); if(token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration((declaration_t*) typealias); } static void parse_union(void) { eat(T_union); typealias_t *typealias = allocate_ast_zero(sizeof(typealias[0])); typealias->declaration.type = DECLARATION_TYPEALIAS; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing union", T_IDENTIFIER, 0); eat_until_newline(); return; } typealias->declaration.source_position = source_position; typealias->declaration.symbol = token.v.symbol; next_token(); compound_type_t *compound_type = allocate_ast_zero(sizeof(compound_type[0])); compound_type->type.type = TYPE_COMPOUND_UNION; compound_type->symbol = typealias->declaration.symbol; compound_type->attributes = parse_attributes(); typealias->type = (type_t*) compound_type; expect_void(':'); expect_void(T_NEWLINE); if(token.type == T_INDENT) { next_token(); compound_type->entries = parse_compound_entries(); eat(T_DEDENT); } add_declaration((declaration_t*) typealias); } static concept_method_t *parse_concept_method(void) { expect(T_func); concept_method_t *method = allocate_ast_zero(sizeof(method[0])); method->declaration.type = DECLARATION_CONCEPT_METHOD; method_type_t *method_type = allocate_type_zero(sizeof(method_type[0])); memset(method_type, 0, sizeof(method_type[0])); method_type->type.type = TYPE_METHOD; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } method->declaration.source_position = source_position; method->declaration.symbol = token.v.symbol; next_token(); expect('('); parse_parameter_declaration(method_type, &method->parameters); expect(')'); if(token.type == ':') { next_token(); method_type->result_type = parse_type(); } else { method_type->result_type = type_void; } expect(T_NEWLINE); method->method_type = method_type; add_declaration((declaration_t*) method); return method; } static void parse_concept(void) { eat(T_concept); concept_t *concept = allocate_ast_zero(sizeof(concept[0])); concept->declaration.type = DECLARATION_CONCEPT; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept", T_IDENTIFIER, 0); eat_until_newline(); return; } concept->declaration.source_position = source_position; concept->declaration.symbol = token.v.symbol; next_token(); if(token.type == '<') { next_token(); context_t *context = &concept->context; concept->type_parameters = parse_type_parameters(context); expect_void('>'); } expect_void(':'); expect_void(T_NEWLINE); if(token.type != T_INDENT) { goto end_of_parse_concept; } next_token(); concept_method_t *last_method = NULL; while(token.type != T_DEDENT) { if(token.type == T_EOF) { parse_error("EOF while parsing concept"); goto end_of_parse_concept; } concept_method_t *method = parse_concept_method(); method->concept = concept; if(last_method != NULL) { last_method->next = method; } else { concept->methods = method; } last_method = method; } next_token(); end_of_parse_concept: add_declaration((declaration_t*) concept); } static concept_method_instance_t *parse_concept_method_instance(void) { concept_method_instance_t *method_instance = allocate_ast_zero(sizeof(method_instance[0])); expect(T_func); if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept method " "instance", T_IDENTIFIER, 0); eat_until_newline(); return NULL; } method_instance->source_position = source_position; method_instance->symbol = token.v.symbol; next_token(); parse_method(& method_instance->method); return method_instance; } static void parse_concept_instance(void) { eat(T_instance); concept_instance_t *instance = allocate_ast_zero(sizeof(instance[0])); instance->source_position = source_position; if(token.type != T_IDENTIFIER) { parse_error_expected("Problem while parsing concept instance", T_IDENTIFIER, 0); eat_until_newline(); return; } instance->concept_symbol = token.v.symbol; next_token(); if(token.type == '<') { next_token(); instance->type_parameters = parse_type_parameters(&instance->context); expect_void('>'); } instance->type_arguments = parse_type_arguments(); expect_void(':'); expect_void(T_NEWLINE); if(token.type != T_INDENT) { goto add_instance; } eat(T_INDENT); concept_method_instance_t *last_method = NULL; while(token.type != T_DEDENT) { if(token.type == T_EOF) { parse_error("EOF while parsing concept instance"); return; } if(token.type == T_NEWLINE) { next_token(); continue; } concept_method_instance_t *method = parse_concept_method_instance(); if(method == NULL) continue; if(last_method != NULL) { last_method->next = method; } else { instance->method_instances = method; } last_method = method; } eat(T_DEDENT); add_instance: assert(current_context != NULL); instance->next = current_context->concept_instances; current_context->concept_instances = instance; } static void skip_declaration(void) { next_token(); } static void parse_export(void) { eat(T_export); while(1) { if(token.type == T_NEWLINE) { break; } if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing export declaration", T_IDENTIFIER, 0); eat_until_newline(); return; } export_t *export = allocate_ast_zero(sizeof(export[0])); export->symbol = token.v.symbol; export->source_position = source_position; next_token(); assert(current_context != NULL); export->next = current_context->exports; current_context->exports = export; if(token.type != ',') { break; } next_token(); } expect_void(T_NEWLINE); } void parse_declaration(void) { if(token.type < 0) { if(token.type == T_EOF) return; /* this shouldn't happen if the lexer is correct... */ parse_error_expected("problem while parsing declaration", T_DEDENT, 0); return; } parse_declaration_function parser = NULL; if(token.type < ARR_LEN(declaration_parsers)) parser = declaration_parsers[token.type]; if(parser == NULL) { parse_error_expected("Couldn't parse declaration", T_func, T_var, T_extern, T_struct, T_concept, T_instance, 0); eat_until_newline(); return; } if(parser != NULL) { parser(); } } static namespace_t *get_namespace(symbol_t *symbol) { /* search for an existing namespace */ namespace_t *namespace = namespaces; while(namespace != NULL) { if(namespace->symbol == symbol) return namespace; namespace = namespace->next; } namespace = allocate_ast_zero(sizeof(namespace[0])); namespace->symbol = symbol; namespace->next = namespaces; namespaces = namespace; return namespace; } static namespace_t *parse_namespace(void) { symbol_t *namespace_symbol = NULL; /* parse namespace name */ if(token.type == T_namespace) { next_token(); if(token.type != T_IDENTIFIER) { parse_error_expected("problem while parsing namespace", T_IDENTIFIER, 0); eat_until_newline(); } namespace_symbol = token.v.symbol; next_token(); if(token.type != T_NEWLINE) { parse_error("extra tokens after namespace definition"); eat_until_newline(); } else { next_token(); } } namespace_t *namespace = get_namespace(namespace_symbol); assert(current_context == NULL); current_context = &namespace->context; /* parse namespace entries */ while(token.type != T_EOF) { parse_declaration(); } assert(current_context == &namespace->context); current_context = NULL; return namespace; } static void register_declaration_parsers(void) { register_declaration_parser(parse_method_declaration, T_func); register_declaration_parser(parse_global_variable, T_var); register_declaration_parser(parse_constant, T_const); register_declaration_parser(parse_class, T_class); register_declaration_parser(parse_struct, T_struct); register_declaration_parser(parse_union, T_union); register_declaration_parser(parse_typealias, T_typealias); register_declaration_parser(parse_concept, T_concept); register_declaration_parser(parse_concept_instance, T_instance); register_declaration_parser(parse_export, T_export); register_declaration_parser(skip_declaration, T_NEWLINE); } namespace_t *parse(FILE *in, const char *input_name) { lexer_init(in, input_name); next_token(); namespace_t *namespace = parse_namespace(); namespace->filename = input_name; lexer_destroy(); if(error) { fprintf(stderr, "syntax errors found...\n"); return NULL; } diff --git a/plugins/api.fluffy b/plugins/api.fluffy index bc7f621..a7a7da7 100644 --- a/plugins/api.fluffy +++ b/plugins/api.fluffy @@ -1,376 +1,376 @@ struct SourcePosition: input_name : byte* linenr : unsigned int struct Symbol: string : byte* id : unsigned int thing : EnvironmentEntry* label : EnvironmentEntry* struct Token: type : int v : V union V: symbol : Symbol* intvalue : int string : String struct Type: type : unsigned int firm_type : IrType* struct Attribute: type : unsigned int source_position : SourcePosition next : Attribute* struct CompoundEntry: type : Type* symbol : Symbol* next : CompoundEntry* attributes : Attribute* source_position : SourcePosition entity : IrEntity* struct CompoundType: type : Type entries : CompoundEntry* symbol : Symbol* attributes : Attribute type_parameters : TypeVariable* context : Context* source_position : SourcePosition struct TypeConstraint: concept_symbol : Symbol* type_class : TypeClass* next : TypeConstraint* struct Declaration: type : unsigned int symbol : Symbol* next : Declaration* source_position : SourcePosition struct Export: symbol : Symbol next : Export* source_position : SourcePosition struct Context: declarations : Declaration* concept_instances : TypeClassInstance* exports : Export* struct TypeVariable: declaration : Declaration constraints : TypeConstraint* next : TypeVariable* current_type : Type* struct Constant: declaration : Declaration type : Type* expression : Expression* struct Statement: type : unsigned int next : Statement* source_position : SourcePosition struct Expression: type : unsigned int datatype : Type* source_position : SourcePosition struct IntConst: expression : Expression value : int struct BinaryExpression: expression : Expression type : int left : Expression* right : Expression* struct BlockStatement: statement : Statement statements : Statement* end_position : SourcePosition context : Context struct ExpressionStatement: statement : Statement expression : Expression* struct LabelDeclaration: declaration : Declaration block : IrNode* next : LabelDeclaration* struct LabelStatement: statement : Statement declaration : LabelDeclaration struct GotoStatement: statement : Statement symbol : Symbol* label : LabelDeclaration* struct IfStatement: statement : Statement condition : Expression* true_statement : Statement* false_statement : Statement* struct TypeClass: declaration : Declaration* type_parameters : TypeVariable* methods : TypeClassMethod* instances : TypeClassInstance* context : Context struct TypeClassMethod: // TODO struct TypeClassInstance: // TODO struct Lexer: c : int source_position : SourcePosition input : FILE* // more stuff... -const STATEMENT_INAVLID <- 0 -const STATEMENT_BLOCK <- 1 -const STATEMENT_RETURN <- 2 -const STATEMENT_VARIABLE_DECLARATION <- 3 -const STATEMENT_IF <- 4 -const STATEMENT_EXPRESSION <- 5 -const STATEMENT_GOTO <- 6 -const STATEMENT_LABEL <- 7 - -const TYPE_INVALID <- 0 -const TYPE_VOID <- 1 -const TYPE_ATOMIC <- 2 -const TYPE_COMPOUND_STRUCT <- 3 -const TYPE_COMPOUND_UNION <- 4 -const TYPE_METHOD <- 5 -const TYPE_POINTER <- 6 -const TYPE_ARRAY <- 7 -const TYPE_REFERENCE <- 8 -const TYPE_REFERENCE_TYPE_VARIABLE <- 9 - -const DECLARATION_INVALID <- 0 -const DECLARATION_METHOD <- 1 -const DECLARATION_METHOD_PARAMETER <- 2 -const DECLARATION_VARIABLE <- 3 -const DECLARATION_CONSTANT <- 4 -const DECLARATION_TYPE_VARIABLE <- 5 -const DECLARATION_TYPEALIAS <- 6 -const DECLARATION_TYPECLASS <- 7 -const DECLARATION_TYPECLASS_METHOD <- 8 -const DECLARATION_LABEL <- 9 - -const ATOMIC_TYPE_INVALID <- 0 -const ATOMIC_TYPE_BOOL <- 1 -const ATOMIC_TYPE_BYTE <- 2 -const ATOMIC_TYPE_UBYTE <- 3 -const ATOMIC_TYPE_SHORT <- 4 -const ATOMIC_TYPE_USHORT <- 5 -const ATOMIC_TYPE_INT <- 6 -const ATOMIC_TYPE_UINT <- 7 -const ATOMIC_TYPE_LONG <- 8 -const ATOMIC_TYPE_ULONG <- 9 - -const EXPR_INVALID <- 0 -const EXPR_INT_CONST <- 1 -const EXPR_FLOAT_CONST <- 2 -const EXPR_BOOL_CONST <- 3 -const EXPR_STRING_CONST <- 4 -const EXPR_NULL_POINTER <- 5 -const EXPR_REFERENCE <- 6 -const EXPR_CALL <- 7 -const EXPR_UNARY <- 8 -const EXPR_BINARY <- 9 - -const BINEXPR_INVALID <- 0 -const BINEXPR_ASSIGN <- 1 -const BINEXPR_ADD <- 2 - -const T_EOF <- -1 -const T_NEWLINE <- 256 -const T_INDENT <- 257 -const T_DEDENT <- 258 -const T_IDENTIFIER <- 259 -const T_INTEGER <- 260 -const T_STRING_LITERAL <- 261 -const T_ASSIGN <- 296 - -typealias FILE <- void -typealias EnvironmentEntry <- void -typealias IrNode <- void -typealias IrType <- void -typealias IrEntity <- void -typealias ParseStatementFunction <- func () : Statement* -typealias ParseAttributeFunction <- func () : Attribute* -typealias ParseExpressionFunction <- func (precedence : unsigned int) : Expression* -typealias ParseExpressionInfixFunction <- func (precedence : unsigned int, \ +const STATEMENT_INAVLID = 0 +const STATEMENT_BLOCK = 1 +const STATEMENT_RETURN = 2 +const STATEMENT_VARIABLE_DECLARATION = 3 +const STATEMENT_IF = 4 +const STATEMENT_EXPRESSION = 5 +const STATEMENT_GOTO = 6 +const STATEMENT_LABEL = 7 + +const TYPE_INVALID = 0 +const TYPE_VOID = 1 +const TYPE_ATOMIC = 2 +const TYPE_COMPOUND_STRUCT = 3 +const TYPE_COMPOUND_UNION = 4 +const TYPE_METHOD = 5 +const TYPE_POINTER = 6 +const TYPE_ARRAY = 7 +const TYPE_REFERENCE = 8 +const TYPE_REFERENCE_TYPE_VARIABLE = 9 + +const DECLARATION_INVALID = 0 +const DECLARATION_METHOD = 1 +const DECLARATION_METHOD_PARAMETER = 2 +const DECLARATION_VARIABLE = 3 +const DECLARATION_CONSTANT = 4 +const DECLARATION_TYPE_VARIABLE = 5 +const DECLARATION_TYPEALIAS = 6 +const DECLARATION_TYPECLASS = 7 +const DECLARATION_TYPECLASS_METHOD = 8 +const DECLARATION_LABEL = 9 + +const ATOMIC_TYPE_INVALID = 0 +const ATOMIC_TYPE_BOOL = 1 +const ATOMIC_TYPE_BYTE = 2 +const ATOMIC_TYPE_UBYTE = 3 +const ATOMIC_TYPE_SHORT = 4 +const ATOMIC_TYPE_USHORT = 5 +const ATOMIC_TYPE_INT = 6 +const ATOMIC_TYPE_UINT = 7 +const ATOMIC_TYPE_LONG = 8 +const ATOMIC_TYPE_ULONG = 9 + +const EXPR_INVALID = 0 +const EXPR_INT_CONST = 1 +const EXPR_FLOAT_CONST = 2 +const EXPR_BOOL_CONST = 3 +const EXPR_STRING_CONST = 4 +const EXPR_NULL_POINTER = 5 +const EXPR_REFERENCE = 6 +const EXPR_CALL = 7 +const EXPR_UNARY = 8 +const EXPR_BINARY = 9 + +const BINEXPR_INVALID = 0 +const BINEXPR_ASSIGN = 1 +const BINEXPR_ADD = 2 + +const T_EOF = -1 +const T_NEWLINE = 256 +const T_INDENT = 257 +const T_DEDENT = 258 +const T_IDENTIFIER = 259 +const T_INTEGER = 260 +const T_STRING_LITERAL = 261 +const T_ASSIGN = 296 + +typealias FILE = void +typealias EnvironmentEntry = void +typealias IrNode = void +typealias IrType = void +typealias IrEntity = void +typealias ParseStatementFunction = func () : Statement* +typealias ParseAttributeFunction = func () : Attribute* +typealias ParseExpressionFunction = func (precedence : unsigned int) : Expression* +typealias ParseExpressionInfixFunction = func (precedence : unsigned int, \ left : Expression*) : Expression* -typealias LowerStatementFunction <- func (statement : Statement*) : Statement* -typealias LowerExpressionFunction <- func (expression : Expression*) : Expression* -typealias ParseDeclarationFunction <- func() : void -typealias String <- byte* +typealias LowerStatementFunction = func (statement : Statement*) : Statement* +typealias LowerExpressionFunction = func (expression : Expression*) : Expression* +typealias ParseDeclarationFunction = func() : void +typealias String = byte* func extern register_new_token(token : String) : unsigned int func extern register_statement() : unsigned int func extern register_expression() : unsigned int func extern register_declaration() : unsigned int func extern register_attribute() : unsigned int func extern puts(string : String) : int func extern fputs(string : String, stream : FILE*) : int func extern printf(string : String, ptr : void*) func extern abort() func extern memset(ptr : void*, c : int, size : unsigned int) func extern register_statement_parser(parser : ParseStatementFunction*, \ token_type : int) func extern register_attribute_parser(parser : ParseAttributeFunction*, \ token_type : int) func extern register_expression_parser(parser : ParseExpressionFunction*, \ token_type : int, \ precedence : unsigned int) func extern register_expression_infix_parser( \ parser : ParseExpressionInfixFunction, token_type : int, \ precedence : unsigned int) func extern register_declaration_parser(parser : ParseDeclarationFunction*, \ token_type : int) func extern print_token(out : FILE*, token : Token*) func extern lexer_next_token(token : Token*) func extern allocate_ast(size : unsigned int) : void* func extern parser_print_error_prefix() func extern next_token() func extern add_declaration(declaration : Declaration*) func extern parse_sub_expression(precedence : unsigned int) : Expression* func extern parse_expression() : Expression* func extern parse_statement() : Statement* func extern parse_type() : Type* func extern print_error_prefix(position : SourcePosition) func extern print_warning_preifx(position : SourcePosition) func extern check_statement(statement : Statement*) : Statement* func extern check_expression(expression : Expression*) : Expression* func extern register_statement_lowerer(function : LowerStatementFunction*, \ statement_type : unsigned int) func extern register_expression_lowerer(function : LowerExpressionFunction*, \ expression_type : unsigned int) func extern make_atomic_type(type : int) : Type* func extern make_pointer_type(type : Type*) : Type* func extern symbol_table_insert(string : String) : Symbol* var extern stdout : FILE* var stderr : FILE* var extern __stderrp : FILE* var extern token : Token var extern source_position : SourcePosition concept AllocateOnAst<T>: func allocate() : T* func allocate_zero<T>() : T*: - var res <- cast<T* > allocate_ast(sizeof<T>) + var res = cast<T* > allocate_ast(sizeof<T>) memset(res, 0, sizeof<T>) return res instance AllocateOnAst BlockStatement: func allocate() : BlockStatement*: - var res <- allocate_zero<$BlockStatement>() - res.statement.type <- STATEMENT_BLOCK + var res = allocate_zero<$BlockStatement>() + res.statement.type = STATEMENT_BLOCK return res instance AllocateOnAst IfStatement: func allocate() : IfStatement*: - var res <- allocate_zero<$IfStatement>() - res.statement.type <- STATEMENT_IF + var res = allocate_zero<$IfStatement>() + res.statement.type = STATEMENT_IF return res instance AllocateOnAst ExpressionStatement: func allocate() : ExpressionStatement*: - var res <- allocate_zero<$ExpressionStatement>() - res.statement.type <- STATEMENT_EXPRESSION + var res = allocate_zero<$ExpressionStatement>() + res.statement.type = STATEMENT_EXPRESSION return res instance AllocateOnAst GotoStatement: func allocate() : GotoStatement*: - var res <- allocate_zero<$GotoStatement>() - res.statement.type <- STATEMENT_GOTO + var res = allocate_zero<$GotoStatement>() + res.statement.type = STATEMENT_GOTO return res instance AllocateOnAst LabelStatement: func allocate() : LabelStatement*: - var res <- allocate_zero<$LabelStatement>() - res.statement.type <- STATEMENT_LABEL - res.declaration.declaration.type <- DECLARATION_LABEL + var res = allocate_zero<$LabelStatement>() + res.statement.type = STATEMENT_LABEL + res.declaration.declaration.type = DECLARATION_LABEL return res instance AllocateOnAst Constant: func allocate() : Constant*: - var res <- allocate_zero<$Constant>() - res.declaration.type <- DECLARATION_CONSTANT + var res = allocate_zero<$Constant>() + res.declaration.type = DECLARATION_CONSTANT return res instance AllocateOnAst BinaryExpression: func allocate() : BinaryExpression*: - var res <- allocate_zero<$BinaryExpression>() - res.expression.type <- EXPR_BINARY + var res = allocate_zero<$BinaryExpression>() + res.expression.type = EXPR_BINARY return res instance AllocateOnAst IntConst: func allocate() : IntConst*: - var res <- allocate_zero<$IntConst>() - res.expression.type <- EXPR_INT_CONST + var res = allocate_zero<$IntConst>() + res.expression.type = EXPR_INT_CONST return res func api_init(): - stderr <- __stderrp + stderr = __stderrp func expect(token_type : int): if token.type /= token_type: parser_print_error_prefix() fputs("Parse error expected another token\n", stderr) abort() next_token() func assert(expr : bool): if !expr: fputs("Assert failed\n", stderr) abort() func context_append(context : Context*, declaration : Declaration*): - declaration.next <- context.declarations - context.declarations <- declaration + declaration.next = context.declarations + context.declarations = declaration func block_append(block : BlockStatement*, append : Statement*): - var statement <- block.statements + var statement = block.statements - if block.statements = null: - block.statements <- append + if block.statements == null: + block.statements = append return :label - if statement.next = null: - statement.next <- append + if statement.next == null: + statement.next = append return - statement <- statement.next + statement = statement.next goto label diff --git a/plugins/plugin_enum.fluffy b/plugins/plugin_enum.fluffy index 933684f..c07cf9b 100644 --- a/plugins/plugin_enum.fluffy +++ b/plugins/plugin_enum.fluffy @@ -1,56 +1,56 @@ var token_enum : int var type_int : Type* func parse_enum(): - assert(token.type = token_enum) + assert(token.type == token_enum) next_token() expect(T_IDENTIFIER) expect(':') expect(T_NEWLINE) if token.type /= T_INDENT: return next_token() - var idx <- 0 - var last_expression <- cast<Expression* > null + var idx = 0 + var last_expression = cast<Expression* > null while token.type /= T_DEDENT && token.type /= T_EOF: - assert(token.type = T_IDENTIFIER) + assert(token.type == T_IDENTIFIER) - var constant <- allocate<$Constant>() - constant.declaration.symbol <- token.v.symbol - constant.declaration.source_position <- source_position - constant.type <- type_int + var constant = allocate<$Constant>() + constant.declaration.symbol = token.v.symbol + constant.declaration.source_position = source_position + constant.type = type_int next_token() - if token.type = T_ASSIGN: + if token.type == T_ASSIGN: next_token() - var expression <- parse_expression() - last_expression <- expression - idx <- 0 - constant.expression <- expression + var expression = parse_expression() + last_expression = expression + idx = 0 + constant.expression = expression else: if last_expression /= null: - var expression <- allocate<$BinaryExpression>() - var intconst <- allocate<$IntConst>() - intconst.value <- idx - expression.type <- BINEXPR_ADD - expression.left <- last_expression - expression.right <- cast<Expression* > intconst - constant.expression <- cast<Expression* > expression + var expression = allocate<$BinaryExpression>() + var intconst = allocate<$IntConst>() + intconst.value = idx + expression.type = BINEXPR_ADD + expression.left = last_expression + expression.right = cast<Expression* > intconst + constant.expression = cast<Expression* > expression else: - var expression <- allocate<$IntConst>() - expression.value <- idx - constant.expression <- cast<Expression* > expression + var expression = allocate<$IntConst>() + expression.value = idx + constant.expression = cast<Expression* > expression add_declaration(cast<Declaration* > constant) expect(T_NEWLINE) - idx <- idx + 1 + idx = idx + 1 next_token() func init_plugin(): - token_enum <- register_new_token("enum") - type_int <- make_atomic_type(ATOMIC_TYPE_INT) + token_enum = register_new_token("enum") + type_int = make_atomic_type(ATOMIC_TYPE_INT) register_declaration_parser(parse_enum, token_enum) export init_plugin diff --git a/plugins/plugin_for.fluffy b/plugins/plugin_for.fluffy index e7fca1a..e393c8c 100644 --- a/plugins/plugin_for.fluffy +++ b/plugins/plugin_for.fluffy @@ -1,82 +1,82 @@ struct ForStatement: statement : Statement pre_expression : Expression* loop_control : Expression* step_expression : Expression* loop_body : Statement* var token_for : int var for_statement : unsigned int instance AllocateOnAst ForStatement: func allocate() : ForStatement*: - var res <- allocate_zero<$ForStatement>() - res.statement.type <- for_statement + var res = allocate_zero<$ForStatement>() + res.statement.type = for_statement return res func parse_for_statement() : Statement*: - var statement <- allocate<$ForStatement>() - statement.statement.source_position <- source_position + var statement = allocate<$ForStatement>() + statement.statement.source_position = source_position - assert(token.type = token_for) + assert(token.type == token_for) next_token() expect('(') if token.type /= ';': - statement.pre_expression <- parse_expression() + statement.pre_expression = parse_expression() expect(';') - statement.loop_control <- parse_expression() + statement.loop_control = parse_expression() expect(';') if token.type /= ')': - statement.step_expression <- parse_expression() + statement.step_expression = parse_expression() expect(')') expect(':') - statement.loop_body <- parse_statement() + statement.loop_body = parse_statement() return cast<Statement* > statement func lower_for_statement(statement : Statement*) : Statement*: - var for_statement <- cast<ForStatement* > statement - var loop_body <- for_statement.loop_body + var for_statement = cast<ForStatement* > statement + var loop_body = for_statement.loop_body - var expression <- allocate<$ExpressionStatement>() - expression.expression <- for_statement.pre_expression + var expression = allocate<$ExpressionStatement>() + expression.expression = for_statement.pre_expression - var label <- allocate<$LabelStatement>() - label.declaration.declaration.symbol <- symbol_table_insert("__loop_begin") + var label = allocate<$LabelStatement>() + label.declaration.declaration.symbol = symbol_table_insert("__loop_begin") - var if_statement <- allocate<$IfStatement>() - if_statement.condition <- for_statement.loop_control - if_statement.true_statement <- loop_body + var if_statement = allocate<$IfStatement>() + if_statement.condition = for_statement.loop_control + if_statement.true_statement = loop_body - var loop_body_block <- cast<BlockStatement*> loop_body + var loop_body_block = cast<BlockStatement*> loop_body - var step_expression <- allocate<$ExpressionStatement>() - step_expression.expression <- for_statement.step_expression + var step_expression = allocate<$ExpressionStatement>() + step_expression.expression = for_statement.step_expression block_append(loop_body_block, cast<Statement*> step_expression) - var goto_statement <- allocate<$GotoStatement>() - goto_statement.label <- & label.declaration + var goto_statement = allocate<$GotoStatement>() + goto_statement.label = & label.declaration block_append(loop_body_block, cast<Statement*> goto_statement) - var endlabel <- allocate<$LabelStatement>() - endlabel.declaration.declaration.symbol <- symbol_table_insert("__loop_end") + var endlabel = allocate<$LabelStatement>() + endlabel.declaration.declaration.symbol = symbol_table_insert("__loop_end") - var block <- allocate<$BlockStatement>() + var block = allocate<$BlockStatement>() block_append(block, cast<Statement*> expression) block_append(block, cast<Statement*> label) block_append(block, cast<Statement*> if_statement) block_append(block, cast<Statement*> endlabel) context_append(&block.context, &label.declaration.declaration) context_append(&block.context, &endlabel.declaration.declaration) return cast<Statement* > block export init_plugin func init_plugin(): - token_for <- register_new_token("for") - for_statement <- register_statement() + token_for = register_new_token("for") + for_statement = register_statement() register_statement_parser(parse_for_statement, token_for) register_statement_lowerer(lower_for_statement, for_statement) diff --git a/plugins/plugin_while.fluffy b/plugins/plugin_while.fluffy index 65734fe..360b576 100644 --- a/plugins/plugin_while.fluffy +++ b/plugins/plugin_while.fluffy @@ -1,144 +1,144 @@ struct WhileStatement: statement : Statement loop_control : Expression* loop_body : Statement* loop_step : Statement* var token_while : int var token_continue : int var token_break : int var token_loop : int var token_step : int var while_statement_type : unsigned int var current_loop : WhileStatement* instance AllocateOnAst WhileStatement: func allocate() : WhileStatement*: - var res <- allocate_zero<$WhileStatement>() - res.statement.type <- while_statement_type + var res = allocate_zero<$WhileStatement>() + res.statement.type = while_statement_type return res func parse_while_statement() : Statement*: - var statement <- allocate<$WhileStatement>() - statement.statement.source_position <- source_position + var statement = allocate<$WhileStatement>() + statement.statement.source_position = source_position - assert(token.type = token_while) + assert(token.type == token_while) next_token() - statement.loop_control <- parse_expression() + statement.loop_control = parse_expression() - if token.type = token_step: + if token.type == token_step: next_token() - var step_statement <- allocate<$ExpressionStatement>() - step_statement.statement.source_position <- source_position - step_statement.expression <- parse_expression() - statement.loop_step <- cast<Statement*> step_statement + var step_statement = allocate<$ExpressionStatement>() + step_statement.statement.source_position = source_position + step_statement.expression = parse_expression() + statement.loop_step = cast<Statement*> step_statement expect(':') - var last_current_loop <- current_loop - current_loop <- statement + var last_current_loop = current_loop + current_loop = statement - statement.loop_body <- parse_statement() + statement.loop_body = parse_statement() - current_loop <- last_current_loop + current_loop = last_current_loop return cast<Statement*> statement func parse_loop_statement() : Statement*: - var statement <- allocate<$WhileStatement>() - statement.statement.source_position <- source_position + var statement = allocate<$WhileStatement>() + statement.statement.source_position = source_position - assert(token.type = token_loop) + assert(token.type == token_loop) next_token() - statement.loop_control <- null + statement.loop_control = null expect(':') - statement.loop_body <- parse_statement() + statement.loop_body = parse_statement() return cast<Statement*> statement func parse_continue_statement() : Statement*: - assert(token.type = token_continue) + assert(token.type == token_continue) next_token() - var statement <- allocate<$GotoStatement>() - statement.statement.source_position <- source_position - statement.symbol <- symbol_table_insert("__loop_next") + var statement = allocate<$GotoStatement>() + statement.statement.source_position = source_position + statement.symbol = symbol_table_insert("__loop_next") return cast<Statement*> statement func parse_break_statement() : Statement*: - var statement <- allocate<$GotoStatement>() - statement.statement.source_position <- source_position - statement.symbol <- symbol_table_insert("__loop_end") + var statement = allocate<$GotoStatement>() + statement.statement.source_position = source_position + statement.symbol = symbol_table_insert("__loop_end") - assert(token.type = token_break) + assert(token.type == token_break) next_token() return cast<Statement*> statement func lower_while_statement(statement : Statement*) : Statement*: - var while_statement <- cast<WhileStatement*> statement - var loop_body <- while_statement.loop_body + var while_statement = cast<WhileStatement*> statement + var loop_body = while_statement.loop_body - var label <- allocate<$LabelStatement>() - label.declaration.declaration.symbol <- symbol_table_insert("__loop_begin") + var label = allocate<$LabelStatement>() + label.declaration.declaration.symbol = symbol_table_insert("__loop_begin") var body if while_statement.loop_control /= null: - var if_statement <- allocate<$IfStatement>() + var if_statement = allocate<$IfStatement>() if_statement.statement.source_position \ - <- while_statement.statement.source_position - if_statement.condition <- while_statement.loop_control - if_statement.true_statement <- loop_body - body <- cast<Statement*> if_statement + = while_statement.statement.source_position + if_statement.condition = while_statement.loop_control + if_statement.true_statement = loop_body + body = cast<Statement*> if_statement else: - body <- loop_body + body = loop_body - var loop_body_block <- cast<BlockStatement*> loop_body + var loop_body_block = cast<BlockStatement*> loop_body - var next_label <- allocate<$LabelStatement>() + var next_label = allocate<$LabelStatement>() next_label.declaration.declaration.symbol \ - <- symbol_table_insert("__loop_next") + = symbol_table_insert("__loop_next") block_append(loop_body_block, cast<Statement*> next_label) if while_statement.loop_step /= null: block_append(loop_body_block, while_statement.loop_step) - var goto_statement <- allocate<$GotoStatement>() + var goto_statement = allocate<$GotoStatement>() goto_statement.statement.source_position \ - <- loop_body.source_position - goto_statement.label <- & label.declaration + = loop_body.source_position + goto_statement.label = & label.declaration block_append(loop_body_block, cast<Statement*> goto_statement) - var endlabel <- allocate<$LabelStatement>() - endlabel.declaration.declaration.symbol <- symbol_table_insert("__loop_end") + var endlabel = allocate<$LabelStatement>() + endlabel.declaration.declaration.symbol = symbol_table_insert("__loop_end") - var block <- allocate<$BlockStatement>() + var block = allocate<$BlockStatement>() block_append(block, cast<Statement*> label) block_append(block, body) block_append(block, cast<Statement*> endlabel) context_append(&block.context, &label.declaration.declaration) context_append(&block.context, &endlabel.declaration.declaration) context_append(&block.context, &next_label.declaration.declaration) return cast<Statement*> block export init_plugin func init_plugin(): - //stderr <- _stderrp - - token_while <- register_new_token("while") - token_continue <- register_new_token("continue") - token_break <- register_new_token("break") - token_loop <- register_new_token("loop") - token_step <- register_new_token("step") - while_statement_type <- register_statement() + //stderr = _stderrp + + token_while = register_new_token("while") + token_continue = register_new_token("continue") + token_break = register_new_token("break") + token_loop = register_new_token("loop") + token_step = register_new_token("step") + while_statement_type = register_statement() register_statement_parser(parse_while_statement, token_while) register_statement_parser(parse_loop_statement, token_loop) register_statement_parser(parse_continue_statement, token_continue) register_statement_parser(parse_break_statement, token_break) register_statement_lowerer(lower_while_statement, while_statement_type) diff --git a/stdlib/construct.fluffy b/stdlib/construct.fluffy index 63866db..a6631ad 100644 --- a/stdlib/construct.fluffy +++ b/stdlib/construct.fluffy @@ -1,15 +1,15 @@ concept Construct<T>: func construct(object : T*) func destruct(object : T*) func new<T : Construct>() : T*: - var result <- cast<T* > malloc(sizeof<T>) + var result = cast<T* > malloc(sizeof<T>) construct(result) return result func delete<T : Construct>(obj : T*): destruct(obj) free(obj) func allocate<T>() : T*: return cast<T*> malloc(sizeof<T>) diff --git a/stdlib/cstdio.fluffy b/stdlib/cstdio.fluffy index 3372f60..af7a489 100644 --- a/stdlib/cstdio.fluffy +++ b/stdlib/cstdio.fluffy @@ -1,24 +1,24 @@ -typealias FILE <- void +typealias FILE = void var extern stdout : FILE* var extern stderr : FILE* var extern stdin : FILE* func extern fputc(c : int, stream : FILE* ) : int func extern fputs(s : String, stream : FILE* ) : int func extern fopen(path : String, mode : String) : FILE* func extern fclose(stream : FILE* ) : int func extern fflush(stream : FILE* ) : int func extern fread(ptr : void*, size : size_t, nmemb : size_t, stream : FILE*) : size_t func extern fwrite(ptr : void*, size : size_t, nmemb : size_t, stream : FILE*) : size_t func extern ungetc(c : int, stream : FILE*) : int func extern puts(s : String) : int func extern putchar(c : int) : int func extern printf(format : String, ...) : int func extern fprintf(stream : FILE*, format : String, ...) : int func extern sprintf(str : String, format : String, ...) : int func extern snprintf(std : String, size : size_t, format : String, ...) : int -const EOF <- -1 +const EOF = -1 diff --git a/stdlib/ctime.fluffy b/stdlib/ctime.fluffy index 5bfbc25..1c723e0 100644 --- a/stdlib/ctime.fluffy +++ b/stdlib/ctime.fluffy @@ -1,6 +1,6 @@ -typealias time_t <- int +typealias time_t = int func extern time(timer : time_t*) : time_t func extern difftime(time1 : time_t, time0 : time_t) : double func extern ctime(timer : time_t*) : byte* diff --git a/stdlib/ctypes.fluffy b/stdlib/ctypes.fluffy index f177349..eba75e8 100644 --- a/stdlib/ctypes.fluffy +++ b/stdlib/ctypes.fluffy @@ -1,3 +1,3 @@ -typealias size_t <- unsigned int -typealias String <- byte* +typealias size_t = unsigned int +typealias String = byte* diff --git a/stdlib/flexarray.fluffy b/stdlib/flexarray.fluffy index e67a7c0..2a58e2e 100644 --- a/stdlib/flexarray.fluffy +++ b/stdlib/flexarray.fluffy @@ -1,38 +1,38 @@ struct FlexibleArray: buffer : byte* len : size_t size : size_t instance Construct FlexibleArray: func construct(array : FlexibleArray*): - array.buffer <- null - array.len <- 0 - array.size <- 0 + array.buffer = null + array.len = 0 + array.size = 0 func destruct(array : FlexibleArray*): free(array.buffer) func flexarray_resize(array : FlexibleArray*, new_len : size_t): if new_len > array.size: - var new_size <- array.size + 1 + var new_size = array.size + 1 while new_size < new_len: - new_size <- new_size * 2 + new_size = new_size * 2 - array.buffer <- cast<byte* > realloc(array.buffer, new_size) - array.size <- new_size + array.buffer = cast<byte* > realloc(array.buffer, new_size) + array.size = new_size - array.len <- new_len + array.len = new_len func flexarray_append_char(array : FlexibleArray*, c : byte): flexarray_resize(array, array.len + 1) - array.buffer[array.len - 1] <- c + array.buffer[array.len - 1] = c func flexarray_append(array : FlexibleArray*, buffer : byte*, buffer_len : size_t): - var old_len <- array.len + var old_len = array.len flexarray_resize(array, array.len + buffer_len) memcpy(array.buffer + cast<byte* > old_len, buffer, buffer_len) func flexarray_append_string(array : FlexibleArray*, string : String): - var len <- strlen(string) + var len = strlen(string) flexarray_append(array, string, len) diff --git a/test/array.fluffy b/test/array.fluffy index 561fd3e..18f494a 100644 --- a/test/array.fluffy +++ b/test/array.fluffy @@ -1,14 +1,14 @@ func extern printf(format : byte*, ...) func extern malloc(size : unsigned int) : void* struct Blo: array : int[10] -typealias arr <- int[7] +typealias arr = int[7] func main() : int: - var blo <- cast<Blo* > malloc(sizeof<Blo>) + var blo = cast<Blo* > malloc(sizeof<Blo>) printf("Size: %d\n", sizeof<Blo>) - blo.array[2] <- 5 + blo.array[2] = 5 return blo.array[2] export main diff --git a/test/callbacks.fluffy b/test/callbacks.fluffy index a1e3266..d191bca 100644 --- a/test/callbacks.fluffy +++ b/test/callbacks.fluffy @@ -1,30 +1,30 @@ -typealias String <- byte* +typealias String = byte* func extern printf(format : String, ...) : int var callback : (func(prefix : String) : int)* func callit(prefix : String): - var res <- callback(prefix) + var res = callback(prefix) printf("Result: %d\n", res) func impl1(prefix : String) : int: printf("%s -> I'm impl1\n", prefix) return 42 func impl2(prefix : String) : int: printf("%s: I'm impl2\n", prefix) return 23 func main() : int: - callback <- impl1 + callback = impl1 callit("pre1") callit("pre2") - callback <- impl2 + callback = impl2 callit("pre1") - callback <- func(prefix : String) : int: + callback = func(prefix : String) : int: printf("%s: I'm an anonymous func\n", prefix) return 1 callit("pre4") return 0 export main diff --git a/test/enumtest.fluffy b/test/enumtest.fluffy index 93e2702..8c24af6 100644 --- a/test/enumtest.fluffy +++ b/test/enumtest.fluffy @@ -1,15 +1,15 @@ func extern printf(format : byte*, ...) : int enum Blup: DECLARATION_INVALID DECLARATION_METHOD DECLARATION_METHOD_PARAMETER - DECLARATION_CONSTANT <- 34*2 + DECLARATION_CONSTANT = 34*2 DECLARATION_CONSTANT_2 DECLARATION_CONSTANT_3 func main() : int: printf("Result: %d %d %d %d\n", DECLARATION_INVALID, DECLARATION_METHOD, \ DECLARATION_CONSTANT, DECLARATION_CONSTANT_3) return 0 export main diff --git a/test/evil.fluffy b/test/evil.fluffy index 64a6c87..89b4d0a 100644 --- a/test/evil.fluffy +++ b/test/evil.fluffy @@ -1,29 +1,29 @@ func extern printf(format : byte*, ...) : int func extern malloc(size : unsigned int) : void* func extern puts(string : byte*) : int concept Print<T>: func print(object : T) instance Print int: func print(object : int): printf("%d\n", object) instance Print byte*: func print(object : byte*): puts(object) func swap<ST : Print, ST2 : Print>(obj1 : ST, obj2 : ST2, marker : int) : void: if marker <= 0: return print(obj1) print(obj2) swap(obj2, obj1, marker-1) func callit(): - swap("blup", 1, 4) + swap("blup", 42, 4) func main() : int: callit() return 0 export main diff --git a/test/fib.fluffy b/test/fib.fluffy index 238cf66..a9994e0 100644 --- a/test/fib.fluffy +++ b/test/fib.fluffy @@ -1,22 +1,22 @@ func extern atoi(string : byte* ) : int func extern printf(string : byte*, ...) : int func main(argc : int, argv : byte* * ) : int: - var number <- 10 + var number = 10 if argc > 1: - number <- atoi(argv[1]) + number = atoi(argv[1]) - var result <- fib(number) + var result = fib(number) printf("fib(%d) -> %d\n", number, result) return 0 func fib(n : int) : int: - if n = 0: + if n == 0: return 0 - if n = 1: + if n == 1: return 1 return fib(n-1) + fib(n-2) export main diff --git a/test/fortest.fluffy b/test/fortest.fluffy index 1563aef..fcbfea7 100644 --- a/test/fortest.fluffy +++ b/test/fortest.fluffy @@ -1,9 +1,9 @@ func extern printf(format : byte*, ...) : int export main func main() : int: - var i <- 0 - for(i <- 23; i < 42; ++i): + var i = 0 + for(i = 23; i < 42; ++i): printf("%d\n", i) return 0 diff --git a/test/inference.fluffy b/test/inference.fluffy index df484fa..ce17df0 100644 --- a/test/inference.fluffy +++ b/test/inference.fluffy @@ -1,7 +1,7 @@ func extern printf(format : byte*, ...) : int func main() : int: - var v <- cast<short> 0xffffffff + var v = cast<short> 0xffffffff printf("%d\n", v) return 0 export main diff --git a/test/pointerarith.fluffy b/test/pointerarith.fluffy index 6ca4a05..5b27246 100644 --- a/test/pointerarith.fluffy +++ b/test/pointerarith.fluffy @@ -1,6 +1,6 @@ func main(argc : int, argv : byte**) : int: - var last <- argv + (argc - 1) + var last = argv + (argc - 1) printf("Last: %s\n", *last) return 0 export main diff --git a/test/polystruct.fluffy b/test/polystruct.fluffy index 7612db4..bd223b6 100644 --- a/test/polystruct.fluffy +++ b/test/polystruct.fluffy @@ -1,53 +1,54 @@ -typealias String <- byte* +typealias String = byte* func extern malloc(size : unsigned int) : void* func extern printf(format : String, ...) : int func extern puts(val : String) func extern strcmp(s1 : String, s2 : String) : int concept Printable<T>: func print(obj : T) instance Printable String: func print(obj : String): puts(obj) instance Printable int: func print(obj : int): printf("%d\n", obj) struct ListElement<T>: val : T next : ListElement<T>* struct List<T>: first : ListElement<T>* func AddToList<T>(list : List<T>*, element : ListElement<T>*): - element.next <- list.first - list.first <- element + element.next = list.first + list.first = element func PrintList<T : Printable>(list : List<T>*): - var elem <- list.first + var elem = list.first while elem /= null: print(elem.val) - elem <- elem.next + elem = elem.next instance Printable<Foo : Printable> List<Foo>*: func print(obj : List<Foo>*): PrintList(obj) func main() : int: var l : List<String> - l.first <- null + l.first = null var e1 : ListElement<String> - e1.val <- "Hallo" + e1.val = "Hallo" var e2 : ListElement<String> - e2.val <- "Welt" + e2.val = "Welt" AddToList(&l, &e1) AddToList(&l, &e2) - PrintList(&l) + //PrintList(&l) + print(&l) return 0 export main diff --git a/test/sdl.fluffy b/test/sdl.fluffy index d375ab9..37638b0 100644 --- a/test/sdl.fluffy +++ b/test/sdl.fluffy @@ -1,92 +1,92 @@ struct PixelFormat: struct Palette: ncolors : int colors : Color struct Color: r : byte g : byte b : byte a : byte struct Surface: flags : unsigned int format : PixelFormat* w : int h : int pitch : unsigned short pixels : void* offset : int hwdata : void* clip_rect : Rect unused1 : unsigned int locked : unsigned int map : void* format_version : unsigned int refcount : int struct Rect: x : short y : short w : unsigned short h : unsigned short func extern SDL_Init(flags : unsigned int) : int func extern SDL_Quit() : void func extern SDL_GetError() : byte* func extern SDL_SetVideoMode(width : int, height : int, bpp : int, flags : int) : Surface* func extern SDL_UpperBlit(src : Surface*, srcrect : Rect*, dest : Surface*, destrect : Rect*) : int func extern SDL_FillRect(dest : Surface*, destrect : Rect*, color : unsigned int) : int func extern IMG_Load(filename : byte*) : Surface* func extern SDL_FreeSurface(surface : Surface*) func extern SDL_Delay(ms : unsigned int) func extern SDL_Flip(screen : Surface*) func extern malloc(size : unsigned int) : void* func extern free(ptr : void*) func extern printf(format : byte*, ...) : int func main(argc : int, argv : byte * * ) : int: SDL_Init(cast<unsigned int> 0x0000FFFF) - var image_count <- argc - 1 - var screen <- SDL_SetVideoMode(640, 480, 0, 0) - var filename <- argv + cast<byte * * > 4 - var i <- 0 - var rect <- cast<Rect* > (malloc(cast<unsigned int> 8)) + var image_count = argc - 1 + var screen = SDL_SetVideoMode(640, 480, 0, 0) + var filename = argv + cast<byte * * > 4 + var i = 0 + var rect = cast<Rect* > (malloc(cast<unsigned int> 8)) printf("Screen: %dx%d\n", screen.w, screen.h) :loop if i >= image_count: goto end printf("Loading file: %s\n", *filename) - var image <- IMG_Load(*filename) - if image = null: + var image = IMG_Load(*filename) + if image == null: return 1 SDL_FillRect(screen, null, cast<unsigned int> 0) - rect.x <- (screen.w - image.w) >> 1 - rect.y <- (screen.h - image.h) >> 1 + rect.x = (screen.w - image.w) >> 1 + rect.y = (screen.h - image.h) >> 1 SDL_UpperBlit(image, null, screen, rect) SDL_Flip(screen) SDL_Delay(cast<unsigned int> 1500) - i <- i + 1 - filename <- filename + cast<byte * * > 4 + i = i + 1 + filename = filename + cast<byte * * > 4 goto loop :end free(rect) SDL_Quit() return 0 export main diff --git a/test/stdlibtest.fluffy b/test/stdlibtest.fluffy index f5dc857..635ff7f 100644 --- a/test/stdlibtest.fluffy +++ b/test/stdlibtest.fluffy @@ -1,13 +1,13 @@ func main(): - var array <- new<$FlexibleArray>() + var array = new<$FlexibleArray>() flexarray_append_string(array, "<html>\n") flexarray_append_string(array, "\t<body>\n") flexarray_append_string(array, "\t\t<h1>Hello ") flexarray_append_string(array, "Welt</h1>\n") flexarray_append_string(array, "\t</body>\n") flexarray_append_string(array, "</html>") puts(array.buffer) delete(array) printf("Jo: %d\n", 42) export main diff --git a/test/typealias.fluffy b/test/typealias.fluffy index d25807b..2481d09 100644 --- a/test/typealias.fluffy +++ b/test/typealias.fluffy @@ -1,8 +1,8 @@ -typealias string <- byte* +typealias string = byte* func extern puts(blo : string) : int func main() : int: puts("Hello world") return 0 export main diff --git a/test/typeclass2.fluffy b/test/typeclass2.fluffy index b5e868f..b6d16ce 100644 --- a/test/typeclass2.fluffy +++ b/test/typeclass2.fluffy @@ -1,102 +1,102 @@ -typealias String <- byte* +typealias String = byte* func extern malloc(size : unsigned int) : void* func extern printf(format : String, ...) : int func extern puts(val : String) func extern strcmp(s1 : String, s2 : String) : int concept Ordered<T>: func less(obj1 : T, obj2 : T) : bool instance Ordered int: func less(obj1 : int, obj2 : int) : bool: return obj1 < obj2 instance Ordered String: func less(obj1 : String, obj2 : String) : bool: return strcmp(obj1, obj2) < 0 concept Printable<T>: func print(obj : T) instance Printable String: func print(obj : String): puts(obj) instance Printable int: func print(obj : int): printf("%d\n", obj) func bubblesort<T : Ordered> (array : T*, len : int): - var sorted <- 1 + var sorted = 1 - var i <- 0 + var i = 0 :loop_begin if i >= len - 1: if sorted /= 1: bubblesort(array, len) return if less(array[i+1], array[i]): - var temp <- array[i] - array[i] <- array[i+1] - array[i+1] <- temp - sorted <- 0 + var temp = array[i] + array[i] = array[i+1] + array[i+1] = temp + sorted = 0 - i <- i + 1 + i = i + 1 goto loop_begin func print_array<T : Printable>(array : T*, len : int): - var i <- 0 + var i = 0 :loop_begin if i >= len: return printf("\t") print(array[i]) - i <- i + 1 + i = i + 1 goto loop_begin func main() : int: - typealias arr_type <- int* - var array <- cast<arr_type> malloc( cast<unsigned int> 10 * sizeof<int>) - array[0] <- 20 - array[1] <- 10 - array[2] <- 5 - array[3] <- 89 - array[4] <- 24 - array[5] <- 43 - array[6] <- 13 - array[7] <- 99 - array[8] <- 66 - array[9] <- 5 - - var sarray <- cast<String* > malloc(cast<unsigned int> 5 * sizeof<String>) - sarray[0] <- "Eva" - sarray[1] <- "Adam" - sarray[2] <- "Mr. Fluffy" - sarray[3] <- "Peter" - sarray[4] <- "Hugo" + typealias arr_type = int* + var array = cast<arr_type> malloc( cast<unsigned int> 10 * sizeof<int>) + array[0] = 20 + array[1] = 10 + array[2] = 5 + array[3] = 89 + array[4] = 24 + array[5] = 43 + array[6] = 13 + array[7] = 99 + array[8] = 66 + array[9] = 5 + + var sarray = cast<String* > malloc(cast<unsigned int> 5 * sizeof<String>) + sarray[0] = "Eva" + sarray[1] = "Adam" + sarray[2] = "Mr. Fluffy" + sarray[3] = "Peter" + sarray[4] = "Hugo" print("Initial array:") print_array(array, 10) bubblesort(array, 10) print("Sorted array:") print_array(array, 10) print("Initial array:") print_array(sarray, 5) bubblesort(sarray, 5) print("Sorted array:") print_array(sarray, 5) return 0 export main diff --git a/test/whiletest.fluffy b/test/whiletest.fluffy index a2728d2..f7ab70f 100644 --- a/test/whiletest.fluffy +++ b/test/whiletest.fluffy @@ -1,23 +1,23 @@ func extern printf(string : byte*, ...) : int func extern srand(seed : int) func extern rand() : int func main() : int: srand(12345) - var i <- 23 + var i = 23 while i < 42: printf("%d\n", i) - if rand() % 5 = 2: + if rand() % 5 == 2: continue - i <- i + 1 + i = i + 1 - i <- 23 + i = 23 while i < 42: printf("%d\n", i) - if rand() % 7 = 4: + if rand() % 7 == 4: break - i <- i + 1 + i = i + 1 return 0 export main diff --git a/tokens.inc b/tokens.inc index 775088d..1f1d20c 100644 --- a/tokens.inc +++ b/tokens.inc @@ -1,81 +1,81 @@ #ifndef TS #define TS(x,str,val) #endif TS(NEWLINE, "newline", = 256) TS(INDENT, "indent",) TS(DEDENT, "dedent",) TS(IDENTIFIER, "identifier",) TS(INTEGER, "integer number",) TS(STRING_LITERAL, "string literal",) #define Keyword(x) T(x,#x,) Keyword(bool) Keyword(byte) Keyword(cast) Keyword(class) Keyword(const) Keyword(double) Keyword(else) Keyword(export) Keyword(extern) Keyword(false) Keyword(float) Keyword(func) Keyword(goto) Keyword(if) Keyword(instance) Keyword(int) Keyword(long) Keyword(namespace) Keyword(null) Keyword(return) Keyword(short) Keyword(signed) Keyword(static) Keyword(struct) Keyword(true) Keyword(typealias) Keyword(concept) Keyword(union) Keyword(unsigned) Keyword(var) Keyword(void) Keyword(sizeof) #undef S T(DOTDOT, "..",) T(DOTDOTDOT, "...",) -T(ASSIGN, "<-",) +T(EQUALEQUAL, "==",) T(TYPESTART, "<$",) T(SLASHEQUAL, "/=",) T(LESSEQUAL, "<=",) T(LESSLESS, "<<",) T(GREATEREQUAL, ">=",) T(GREATERGREATER, ">>",) T(PIPEPIPE, "||",) T(ANDAND, "&&",) T(PLUSPLUS, "++",) T(MINUSMINUS, "--",) T(MULTILINE_COMMENT_BEGIN, "/*",) T(MULTILINE_COMMENT_END, "*/",) T(SINGLELINE_COMMENT, "//",) #define T_LAST_TOKEN (T_SINGLELINE_COMMENT+1) T(PLUS, "+", = '+') T(MINUS, "-", = '-') T(MULT, "*", = '*') T(DIV, "/", = '/') T(MOD, "%", = '%') T(EQUAL, "=", = '=') T(LESS, "<", = '<') T(GREATER, ">", = '>') T(DOT, ".", = '.') T(CARET, "^", = '^') T(EXCLAMATION, "!", = '!') T(QUESTION, "?", = '?') T(AND, "&", = '&') T(TILDE, "~", = '~') T(PIPE, "|", = '|') T(DOLLAR, "$", = '$')
MatzeB/fluffy
24beca7882497bca7bab557e4ac199382c5286ad
more work towards generic concept instances
diff --git a/semantic.c b/semantic.c index ab9223c..ca5afba 100644 --- a/semantic.c +++ b/semantic.c @@ -325,2191 +325,2214 @@ static void check_compound_type(compound_type_t *type) entry = entry->next; } environment_pop_to(old_top); } static type_t *normalize_compound_type(compound_type_t *type) { type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_bind_typevariables(bind_typevariables_type_t *type) { type_t *polymorphic_type = (type_t*) type->polymorphic_type; polymorphic_type = normalize_type(polymorphic_type); assert(polymorphic_type->type == TYPE_COMPOUND_STRUCT || polymorphic_type->type == TYPE_COMPOUND_UNION || polymorphic_type->type == TYPE_COMPOUND_CLASS); type->polymorphic_type = (compound_type_t*) polymorphic_type; type_t *result = typehash_insert((type_t*) type); return result; } static type_t *normalize_type(type_t *type) { /* happens sometimes on semantic errors */ if(type == NULL) return NULL; switch(type->type) { case TYPE_INVALID: case TYPE_VOID: case TYPE_ATOMIC: return type; case TYPE_REFERENCE: return resolve_type_reference((type_reference_t*) type); case TYPE_REFERENCE_TYPE_VARIABLE: return resolve_type_reference_type_var((type_reference_t*) type); case TYPE_POINTER: return normalize_pointer_type((pointer_type_t*) type); case TYPE_ARRAY: return normalize_array_type((array_type_t*) type); case TYPE_METHOD: return normalize_method_type((method_type_t*) type); case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_UNION: case TYPE_COMPOUND_STRUCT: return normalize_compound_type((compound_type_t*) type); case TYPE_BIND_TYPEVARIABLES: return normalize_bind_typevariables((bind_typevariables_type_t*) type); } panic("Unknown type found"); } static type_t *check_reference(declaration_t *declaration, const source_position_t source_position) { variable_declaration_t *variable; method_declaration_t *method; method_parameter_t *method_parameter; constant_t *constant; concept_method_t *concept_method; type_t *type; switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->refs++; type = variable->type; if(type == NULL) return NULL; if(type->type == TYPE_COMPOUND_STRUCT || type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_CLASS || type->type == TYPE_BIND_TYPEVARIABLES || type->type == TYPE_ARRAY) { variable->needs_entity = 1; } return type; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; return make_pointer_type((type_t*) method->method.type); case DECLARATION_CONSTANT: constant = (constant_t*) declaration; /* do type inference for the constant if needed */ if(constant->type == NULL) { constant->expression = check_expression(constant->expression); constant->type = constant->expression->datatype; } return constant->type; case DECLARATION_METHOD_PARAMETER: method_parameter = (method_parameter_t*) declaration; assert(method_parameter->type != NULL); return method_parameter->type; case DECLARATION_CONCEPT_METHOD: concept_method = (concept_method_t*) declaration; return make_pointer_type((type_t*) concept_method->method_type); case DECLARATION_LABEL: case DECLARATION_TYPEALIAS: case DECLARATION_CONCEPT: case DECLARATION_TYPE_VARIABLE: print_error_prefix(source_position); fprintf(stderr, "'%s' (a '%s') can't be used as expression\n", declaration->symbol->string, get_declaration_type_name(declaration->type)); return NULL; case DECLARATION_LAST: case DECLARATION_INVALID: panic("reference to invalid declaration type encountered"); return NULL; } panic("reference to unknown declaration type encountered"); return NULL; } static void check_reference_expression(reference_expression_t *ref) { symbol_t *symbol = ref->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(ref->expression.source_position); fprintf(stderr, "no known definition for '%s'\n", symbol->string); return; } normalize_type_arguments(ref->type_arguments); ref->declaration = declaration; type_t *type = check_reference(declaration, ref->expression.source_position); ref->expression.datatype = type; } static bool is_lvalue(const expression_t *expression) { unary_expression_t *unexpr; reference_expression_t *reference; declaration_t *declaration; switch(expression->type) { case EXPR_REFERENCE: reference = (reference_expression_t*) expression; declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { return true; } break; case EXPR_ARRAY_ACCESS: return true; case EXPR_SELECT: return true; case EXPR_UNARY: unexpr = (unary_expression_t*) expression; if(unexpr->type == UNEXPR_DEREFERENCE) return true; break; default: break; } return false; } static void check_assign_expression(binary_expression_t *assign) { expression_t *left = assign->left; expression_t *right = assign->right; if(!is_lvalue(left)) { error_at(assign->expression.source_position, "left side of assign is not an lvalue.\n"); return; } if(left->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) left; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; symbol_t *symbol = variable->declaration.symbol; /* do type inference if needed */ if(left->datatype == NULL) { if(right->datatype == NULL) { print_error_prefix(assign->expression.source_position); fprintf(stderr, "can't infer type for '%s'\n", symbol->string); return; } variable->type = right->datatype; left->datatype = right->datatype; } /* the reference expression increased the ref pointer, but * making an assignment is not reading the value */ variable->refs--; } } } /** * creates an implicit cast if possible or reports an error */ static expression_t *make_cast(expression_t *from, type_t *dest_type, const source_position_t source_position) { if(dest_type == NULL || from->datatype == dest_type) return from; /* TODO: - test which types can be implicitely casted... * - improve error reporting (want to know the context of the cast) * ("can't implicitely cast for argument 2 of method call...") */ type_t *from_type = from->datatype; if(from_type == NULL) { print_error_prefix(from->source_position); fprintf(stderr, "can't implicitely cast from unknown type to "); print_type(stderr, dest_type); fprintf(stderr, "\n"); return NULL; } bool implicit_cast_allowed = true; if(from_type->type == TYPE_POINTER) { if(dest_type->type == TYPE_POINTER) { pointer_type_t *p1 = (pointer_type_t*) from_type; pointer_type_t *p2 = (pointer_type_t*) dest_type; /* you can implicitely cast any pointer to void* and * it is allowed to cast 'null' to any pointer */ if(p1->points_to != p2->points_to && dest_type != type_void_ptr && from->type != EXPR_NULL_POINTER) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(from_type->type == TYPE_ARRAY) { array_type_t *array_type = (array_type_t*) from_type; if(dest_type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) dest_type; /* we can cast to pointer of same type and void* */ if(pointer_type->points_to != array_type->element_type && dest_type != type_void_ptr) { implicit_cast_allowed = false; } } else { implicit_cast_allowed = false; } } else if(dest_type->type == TYPE_POINTER) { implicit_cast_allowed = false; } else if(from_type->type == TYPE_ATOMIC) { if(dest_type->type != TYPE_ATOMIC) { implicit_cast_allowed = false; } else { atomic_type_t *from_type_atomic = (atomic_type_t*) from_type; atomic_type_type_t from_atype = from_type_atomic->atype; atomic_type_t *dest_type_atomic = (atomic_type_t*) dest_type; atomic_type_type_t dest_atype = dest_type_atomic->atype; switch(from_atype) { #if 0 case ATOMIC_TYPE_BOOL: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_BYTE) || (dest_atype == ATOMIC_TYPE_UBYTE); #endif case ATOMIC_TYPE_UBYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_USHORT) || (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_USHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_UINT) || (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_UINT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONG) || (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_ULONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_ULONGLONG) || (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_BYTE: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_SHORT); case ATOMIC_TYPE_SHORT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_INT); case ATOMIC_TYPE_INT: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONG); case ATOMIC_TYPE_LONG: implicit_cast_allowed |= (dest_atype == ATOMIC_TYPE_LONGLONG); break; case ATOMIC_TYPE_FLOAT: implicit_cast_allowed = (dest_atype == ATOMIC_TYPE_DOUBLE); break; case ATOMIC_TYPE_BOOL: case ATOMIC_TYPE_DOUBLE: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_INVALID: implicit_cast_allowed = false; break; } } } if(!implicit_cast_allowed) { print_error_prefix(source_position); fprintf(stderr, "can't implicitely cast "); print_type(stderr, from_type); fprintf(stderr, " to "); print_type(stderr, dest_type); fprintf(stderr, "\n"); return NULL; } unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = dest_type; cast->value = from; return (expression_t*) cast; } static void check_binary_expression(binary_expression_t *binexpr) { binexpr->left = check_expression(binexpr->left); binexpr->right = check_expression(binexpr->right); expression_t *left = binexpr->left; expression_t *right = binexpr->right; type_t *exprtype; type_t *lefttype, *righttype; binary_expression_type_t binexpr_type = binexpr->type; switch(binexpr_type) { case BINEXPR_ASSIGN: check_assign_expression(binexpr); exprtype = left->datatype; lefttype = exprtype; righttype = exprtype; break; case BINEXPR_ADD: case BINEXPR_SUB: exprtype = left->datatype; lefttype = exprtype; righttype = right->datatype; /* implement address arithmetic */ if(lefttype->type == TYPE_POINTER && is_type_int(righttype)) { pointer_type_t *pointer_type = (pointer_type_t*) lefttype; sizeof_expression_t *sizeof_expr = allocate_ast(sizeof(sizeof_expr[0])); memset(sizeof_expr, 0, sizeof(sizeof_expr[0])); sizeof_expr->expression.type = EXPR_SIZEOF; sizeof_expr->expression.datatype = type_uint; sizeof_expr->type = pointer_type->points_to; binary_expression_t *mulexpr = allocate_ast(sizeof(mulexpr[0])); memset(mulexpr, 0, sizeof(mulexpr[0])); mulexpr->expression.type = EXPR_BINARY; mulexpr->expression.datatype = type_uint; mulexpr->type = BINEXPR_MUL; mulexpr->left = make_cast(right, type_uint, binexpr->expression.source_position); mulexpr->right = (expression_t*) sizeof_expr; unary_expression_t *cast = allocate_ast(sizeof(cast[0])); memset(cast, 0, sizeof(cast[0])); cast->expression.type = EXPR_UNARY; cast->expression.source_position = binexpr->expression.source_position; cast->type = UNEXPR_CAST; cast->expression.datatype = lefttype; cast->value = (expression_t*) mulexpr; right = (expression_t*) cast; binexpr->right = right; } righttype = lefttype; break; case BINEXPR_MUL: case BINEXPR_MOD: case BINEXPR_DIV: if(!is_type_numeric(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "Mul/Mod/Div expressions need a numeric type but " "type "); print_type(stderr, left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = lefttype; break; case BINEXPR_AND: case BINEXPR_OR: case BINEXPR_XOR: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "And/Or/Xor expressions need an integer type " "but type "); print_type(stderr, left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = left->datatype; break; case BINEXPR_SHIFTLEFT: case BINEXPR_SHIFTRIGHT: if(!is_type_int(left->datatype)) { print_error_prefix(binexpr->expression.source_position); fprintf(stderr, "ShiftLeft/ShiftRight expressions need an integer " "type, but type "); print_type(stderr, left->datatype); fprintf(stderr, "is given\n"); } exprtype = left->datatype; lefttype = exprtype; righttype = type_uint; break; /* comparison operation */ case BINEXPR_EQUAL: case BINEXPR_NOTEQUAL: case BINEXPR_LESS: case BINEXPR_LESSEQUAL: case BINEXPR_GREATER: case BINEXPR_GREATEREQUAL: exprtype = type_bool; /* TODO find out greatest common type... */ lefttype = left->datatype; righttype = left->datatype; break; case BINEXPR_LAZY_AND: case BINEXPR_LAZY_OR: exprtype = type_bool; lefttype = type_bool; righttype = type_bool; break; case BINEXPR_INVALID: abort(); } if(left == NULL || right == NULL) return; if(left->datatype != lefttype) { binexpr->left = make_cast(left, lefttype, binexpr->expression.source_position); } if(right->datatype != righttype) { binexpr->right = make_cast(right, righttype, binexpr->expression.source_position); } binexpr->expression.datatype = exprtype; } /** * find a concept instance matching the current type_variable configuration */ static concept_instance_t *_find_concept_instance(concept_t *concept, const source_position_t *pos) { concept_instance_t *instance; for ( instance = concept->instances; instance != NULL; instance = instance->next_in_concept) { assert(instance->concept == concept); type_argument_t *argument = instance->type_arguments; type_variable_t *parameter = concept->type_parameters; bool match = true; while(argument != NULL && parameter != NULL) { if(parameter->current_type == NULL) { print_error_prefix(*pos); panic("type variable has no type set while searching " "concept instance"); } +#if 0 if(parameter->current_type != argument->type) { match = false; break; } +#endif + if (!match_variant_to_concrete_type( + argument->type, parameter->current_type, + concept->declaration.source_position, false)) { + match = false; + break; + } argument = argument->next; parameter = parameter->next; } if(match && (argument != NULL || parameter != NULL)) { print_error_prefix(instance->source_position); panic("type argument count of concept instance doesn't match " "type parameter count of concept"); } if(match) break; } return instance; } concept_instance_t *find_concept_instance(concept_t *concept) { return _find_concept_instance(concept, NULL); } /** tests whether a type variable has a concept as constraint */ static bool type_variable_has_constraint(const type_variable_t *type_variable, const concept_t *concept) { type_constraint_t *constraint = type_variable->constraints; while(constraint != NULL) { if(constraint->concept == concept) return true; constraint = constraint->next; } return false; } concept_method_instance_t *get_method_from_concept_instance( concept_instance_t *instance, concept_method_t *method) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { if(method_instance->concept_method == method) { return method_instance; } method_instance = method_instance->next; } return NULL; } static void resolve_concept_method_instance(reference_expression_t *reference) { declaration_t *declaration = reference->declaration; assert(declaration->type == DECLARATION_CONCEPT_METHOD); concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; /* test whether 1 of the type variables points to another type variable. * this can happen when concept methods are invoked inside polymorphic * methods. We can't resolve the method right now, but we have to check * the constraints of the type variable */ bool cant_resolve = false; type_variable_t *type_var = concept->type_parameters; while(type_var != NULL) { type_t *current_type = type_var->current_type; if(current_type == NULL) return; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *type_ref = (type_reference_t*) current_type; type_variable_t *type_variable = type_ref->type_variable; if(!type_variable_has_constraint(type_variable, concept)) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "type variable '%s' needs a constraint for " "concept '%s' when using method '%s'.\n", type_variable->declaration.symbol->string, concept->declaration.symbol->string, concept_method->declaration.symbol->string); return; } cant_resolve = true; } type_var = type_var->next; } /* we have to defer the resolving for the ast2firm phase */ if(cant_resolve) { return; } /* we assume that all typevars have current_type set */ const source_position_t *pos = &reference->expression.source_position; concept_instance_t *instance = _find_concept_instance(concept, pos); if(instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "there's no instance of concept '%s' for type ", concept->declaration.symbol->string); type_variable_t *typevar = concept->type_parameters; while(typevar != NULL) { if(typevar->current_type != NULL) { print_type(stderr, typevar->current_type); fprintf(stderr, " "); } typevar = typevar->next; } fprintf(stderr, "\n"); return; } #if 0 concept_method_instance_t *method_instance = get_method_from_concept_instance(instance, concept_method); if(method_instance == NULL) { print_error_prefix(reference->expression.source_position); fprintf(stderr, "no instance of method '%s' found in concept " "instance?\n", concept_method->declaration.symbol->string); panic("panic"); } type_t *type = (type_t*) method_instance->method.type; type_t *pointer_type = make_pointer_type(type); reference->expression.datatype = pointer_type; reference->declaration = (declaration_t*) &method_instance->method; #endif } static void check_type_constraints(type_variable_t *type_variables, const source_position_t source_position) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; type_t *current_type = type_var->current_type; for( ;constraint != NULL; constraint = constraint->next) { concept_t *concept = constraint->concept; if(concept == NULL) continue; if(current_type->type == TYPE_REFERENCE_TYPE_VARIABLE) { type_reference_t *ref = (type_reference_t*) current_type; type_variable_t *type_var = ref->type_variable; if(!type_variable_has_constraint(type_var, concept)) { print_error_prefix(source_position); fprintf(stderr, "type variable '%s' needs constraint " "'%s'\n", type_var->declaration.symbol->string, concept->declaration.symbol->string); } continue; } /* set typevariable values for the concept * This currently only works for conceptes with 1 parameter */ concept->type_parameters->current_type = type_var->current_type; concept_instance_t *instance = _find_concept_instance(concept, & source_position); if(instance == NULL) { print_error_prefix(source_position); fprintf(stderr, "concrete type for type variable '%s' of " "method doesn't match type constraints:\n", type_var->declaration.symbol->string); print_error_prefix(source_position); fprintf(stderr, "type "); print_type(stderr, type_var->current_type); fprintf(stderr, " is no instance of concept '%s'\n", concept->declaration.symbol->string); } /* reset typevar binding */ concept->type_parameters->current_type = NULL; } type_var = type_var->next; } } /** * For variable argument functions, the last arguments are promoted as in the * C language: all integer types get INT, all pointers to void*, float becomes * double */ static type_t *get_default_param_type(type_t *type, source_position_t source_position) { atomic_type_t *atomic_type; if(type == NULL) { return type_int; } switch(type->type) { case TYPE_ATOMIC: atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type.\n"); return type; case ATOMIC_TYPE_BOOL: return type_uint; case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: return type_int; case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return type_double; } break; case TYPE_ARRAY: case TYPE_POINTER: return type_void_ptr; case TYPE_METHOD: print_error_prefix(source_position); fprintf(stderr, "method type ("); print_type(stderr, type); fprintf(stderr, ") not supported for function parameters.\n"); return type; case TYPE_BIND_TYPEVARIABLES: case TYPE_COMPOUND_CLASS: case TYPE_COMPOUND_STRUCT: case TYPE_COMPOUND_UNION: print_error_prefix(source_position); fprintf(stderr, "compound type ("); print_type(stderr, type); fprintf(stderr, ") not supported for function parameter.\n"); return type; case TYPE_REFERENCE: case TYPE_REFERENCE_TYPE_VARIABLE: case TYPE_VOID: case TYPE_INVALID: print_error_prefix(source_position); fprintf(stderr, "function argument has invalid type "); print_type(stderr, type); fprintf(stderr, "\n"); return type; } print_error_prefix(source_position); panic("invalid type for function argument"); } static void check_call_expression(call_expression_t *call) { call->method = check_expression(call->method); expression_t *method = call->method; type_t *type = method->datatype; type_argument_t *type_arguments = NULL; /* can happen if we had a deeper semantic error */ if(type == NULL) return; /* determine method type */ if(type->type != TYPE_POINTER) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call non-pointer type "); print_type(stderr, type); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) type; type = pointer_type->points_to; if(type->type != TYPE_METHOD) { print_error_prefix(call->expression.source_position); fprintf(stderr, "trying to call a non-method value of type"); print_type(stderr, type); fprintf(stderr, "\n"); return; } method_type_t *method_type = (method_type_t*) type; /* match parameter types against type variables */ type_variable_t *type_variables = NULL; if(method->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) method; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_CONCEPT_METHOD) { concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_variables = concept->type_parameters; type_arguments = reference->type_arguments; } else if(declaration->type == DECLARATION_METHOD) { method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_variables = method_declaration->method.type_parameters; type_arguments = reference->type_arguments; } } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; type_var = type_var->next; } } /* apply type arguments */ if(type_arguments != NULL) { type_variable_t *type_var = type_variables; type_argument_t *type_argument = type_arguments; while(type_argument != NULL && type_var != NULL) { type_var->current_type = type_argument->type; type_var = type_var->next; type_argument = type_argument->next; } if(type_argument != NULL || type_var != NULL) { error_at(method->source_position, "wrong number of type arguments on method reference"); } } /* check call arguments, match argument types against expected types * and try to determine type variable configuration */ call_argument_t *argument = call->arguments; method_parameter_type_t *param_type = method_type->parameter_types; int i = 0; while(argument != NULL) { if(param_type == NULL && !method_type->variable_arguments) { error_at(call->expression.source_position, "too much arguments for method call\n"); break; } argument->expression = check_expression(argument->expression); expression_t *expression = argument->expression; type_t *wanted_type; type_t *expression_type = expression->datatype; if(param_type != NULL) { wanted_type = param_type->type; } else { wanted_type = get_default_param_type(expression_type, argument->expression->source_position); } /* match type of argument against type variables */ if(type_variables != NULL && type_arguments == NULL) { match_variant_to_concrete_type(wanted_type, expression_type, expression->source_position, true); } else if(expression_type != wanted_type) { expression_t *new_expression = make_cast(expression, wanted_type, expression->source_position); if(new_expression == NULL) { print_error_prefix(expression->source_position); fprintf(stderr, "invalid type for argument %d of call: ", i); print_type(stderr, expression->datatype); fprintf(stderr, " should be "); print_type(stderr, wanted_type); fprintf(stderr, "\n"); } else { expression = new_expression; } } argument->expression = expression; argument = argument->next; if(param_type != NULL) param_type = param_type->next; ++i; } if(param_type != NULL) { error_at(call->expression.source_position, "too few arguments for method call\n"); } /* test whether we could determine the concrete types for all type * variables */ type_variable_t *type_var = type_variables; while(type_var != NULL) { if(type_var->current_type == NULL) { print_error_prefix(call->expression.source_position); fprintf(stderr, "Couldn't determine concrete type for type " "variable '%s' in call expression\n", type_var->declaration.symbol->string); } #ifdef DEBUG_TYPEVAR_BINDING fprintf(stderr, "TypeVar '%s'(%p) bound to ", type_var->declaration.symbol->string, type_var); print_type(stderr, type_var->current_type); fprintf(stderr, "\n"); #endif type_var = type_var->next; } /* normalize result type, as we know the concrete types for the typevars */ type_t *result_type = method_type->result_type; if(type_variables != NULL) { - bool set_type_arguments = true; reference_expression_t *ref = (reference_expression_t*) method; declaration_t *declaration = ref->declaration; type_variable_t *type_parameters; result_type = create_concrete_type(result_type); if(declaration->type == DECLARATION_CONCEPT_METHOD) { /* we might be able to resolve the concept_method_instance now */ resolve_concept_method_instance(ref); -#if 0 - if(ref->declaration->type == DECLARATION_METHOD) - set_type_arguments = false; -#endif concept_method_t *concept_method = (concept_method_t*) declaration; concept_t *concept = concept_method->concept; type_parameters = concept->type_parameters; } else { /* check type constraints */ assert(declaration->type == DECLARATION_METHOD); check_type_constraints(type_variables, call->expression.source_position); method_declaration_t *method_declaration = (method_declaration_t*) declaration; type_parameters = method_declaration->method.type_parameters; } /* set type arguments on the reference expression */ - if(set_type_arguments && ref->type_arguments == NULL) { + if(ref->type_arguments == NULL) { type_variable_t *type_var = type_parameters; type_argument_t *last_argument = NULL; while(type_var != NULL) { type_argument_t *argument = allocate_ast(sizeof(argument[0])); memset(argument, 0, sizeof(argument[0])); type_t *current_type = type_var->current_type; argument->type = current_type; if(last_argument != NULL) { last_argument->next = argument; } else { ref->type_arguments = argument; } last_argument = argument; type_var = type_var->next; } } ref->expression.datatype = create_concrete_type(ref->expression.datatype); } /* clear typevariable configuration */ if(type_variables != NULL) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_var->current_type = NULL; #ifdef DEBUG_TYPEVAR_BINDINGS fprintf(stderr, "Unbind %s(%p)\n", type_var->declaration.symbol->string, type_var); #endif type_var = type_var->next; } } call->expression.datatype = result_type; } static void check_cast_expression(unary_expression_t *cast) { if(cast->expression.datatype == NULL) { panic("Cast expression needs a datatype!"); } cast->expression.datatype = normalize_type(cast->expression.datatype); cast->value = check_expression(cast->value); if(cast->value->datatype == type_void) { error_at(cast->expression.source_position, "can't cast void type to anything\n"); } } static void check_dereference_expression(unary_expression_t *dereference) { dereference->value = check_expression(dereference->value); expression_t *value = dereference->value; if(value->datatype == NULL) { error_at(dereference->expression.source_position, "can't derefence expression with unknown datatype\n"); return; } if(value->datatype->type != TYPE_POINTER) { error_at(dereference->expression.source_position, "can only dereference expressions with pointer type\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) value->datatype; type_t *dereferenced_type = pointer_type->points_to; dereference->expression.datatype = dereferenced_type; } static void check_take_address_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; type_t *result_type = make_pointer_type(type); expression_t *value = expression->value; if(!is_lvalue(value)) { /* TODO use another word than lvalue to explain this to the user... */ error_at(expression->expression.source_position, "can only take address of l-values\n"); return; } if(value->type == EXPR_REFERENCE) { reference_expression_t *reference = (reference_expression_t*) value; declaration_t *declaration = reference->declaration; if(declaration->type == DECLARATION_VARIABLE) { variable_declaration_t *variable = (variable_declaration_t*) declaration; variable->needs_entity = 1; } } expression->expression.datatype = result_type; } static bool is_arithmetic_type(type_t *type) { if(type->type != TYPE_ATOMIC) return false; atomic_type_t *atomic_type = (atomic_type_t*) type; switch(atomic_type->atype) { case ATOMIC_TYPE_BYTE: case ATOMIC_TYPE_UBYTE: case ATOMIC_TYPE_INT: case ATOMIC_TYPE_UINT: case ATOMIC_TYPE_SHORT: case ATOMIC_TYPE_USHORT: case ATOMIC_TYPE_LONG: case ATOMIC_TYPE_ULONG: case ATOMIC_TYPE_LONGLONG: case ATOMIC_TYPE_ULONGLONG: case ATOMIC_TYPE_FLOAT: case ATOMIC_TYPE_DOUBLE: return true; case ATOMIC_TYPE_INVALID: case ATOMIC_TYPE_BOOL: return false; } return false; } static void check_negate_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_arithmetic_type(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "negate expression only valid for arithmetic types, " "but argument has type "); print_type(stderr, type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_bitwise_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type == NULL) return; if(!is_type_int(type)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for integer types, " "but argument has type "); print_type(stderr, type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static expression_t *lower_incdec_expression(unary_expression_t *expression) { expression_t *value = check_expression(expression->value); type_t *type = value->datatype; if(!is_type_numeric(type) && type->type != TYPE_POINTER) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression only valid for numeric or pointer types " "but argument has type ", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); print_type(stderr, type); fprintf(stderr, "\n"); } if(!is_lvalue(value)) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "%s expression needs an lvalue\n", expression->type == UNEXPR_INCREMENT ? "increment" : "decrement" ); } bool need_int_const = true; if(type->type == TYPE_ATOMIC) { atomic_type_t *atomic_type = (atomic_type_t*) type; if(atomic_type->atype == ATOMIC_TYPE_FLOAT || atomic_type->atype == ATOMIC_TYPE_DOUBLE) { need_int_const = false; } } expression_t *constant; if(need_int_const) { int_const_t *iconst = allocate_ast(sizeof(iconst[0])); memset(iconst, 0, sizeof(iconst[0])); iconst->expression.type = EXPR_INT_CONST; iconst->expression.datatype = type; iconst->value = 1; constant = (expression_t*) iconst; } else { float_const_t *fconst = allocate_ast(sizeof(fconst[0])); memset(fconst, 0, sizeof(fconst[0])); fconst->expression.type = EXPR_FLOAT_CONST; fconst->expression.datatype = type; fconst->value = 1.0; constant = (expression_t*) fconst; } binary_expression_t *add = allocate_ast(sizeof(add[0])); memset(add, 0, sizeof(add[0])); add->expression.type = EXPR_BINARY; add->expression.datatype = type; if(expression->type == UNEXPR_INCREMENT) { add->type = BINEXPR_ADD; } else { add->type = BINEXPR_SUB; } add->left = value; add->right = constant; binary_expression_t *assign = allocate_ast(sizeof(assign[0])); memset(assign, 0, sizeof(assign[0])); assign->expression.type = EXPR_BINARY; assign->expression.datatype = type; assign->type = BINEXPR_ASSIGN; assign->left = value; assign->right = (expression_t*) add; return (expression_t*) assign; } static expression_t *lower_unary_expression(expression_t *expression) { assert(expression->type == EXPR_UNARY); unary_expression_t *unary_expression = (unary_expression_t*) expression; switch(unary_expression->type) { case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: return lower_incdec_expression(unary_expression); default: break; } return expression; } static void check_not_expression(unary_expression_t *expression) { expression->value = check_expression(expression->value); type_t *type = expression->value->datatype; if(type != type_bool) { print_error_prefix(expression->expression.source_position); fprintf(stderr, "not expression only valid for bool type, " "but argument has type "); print_type(stderr, type); fprintf(stderr, "\n"); } expression->expression.datatype = type; } static void check_unary_expression(unary_expression_t *unary_expression) { switch(unary_expression->type) { case UNEXPR_CAST: check_cast_expression(unary_expression); return; case UNEXPR_DEREFERENCE: check_dereference_expression(unary_expression); return; case UNEXPR_TAKE_ADDRESS: check_take_address_expression(unary_expression); return; case UNEXPR_NOT: check_not_expression(unary_expression); return; case UNEXPR_BITWISE_NOT: check_bitwise_not_expression(unary_expression); return; case UNEXPR_NEGATE: check_negate_expression(unary_expression); return; case UNEXPR_INCREMENT: case UNEXPR_DECREMENT: panic("increment/decrement not lowered"); case UNEXPR_INVALID: abort(); } panic("Unknown unary expression found"); } static void check_select_expression(select_expression_t *select) { select->compound = check_expression(select->compound); expression_t *compound = select->compound; type_t *datatype = compound->datatype; if(datatype == NULL) return; bind_typevariables_type_t *bind_typevariables = NULL; compound_type_t *compound_type; if(datatype->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) datatype; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(datatype->type == TYPE_COMPOUND_STRUCT || datatype->type == TYPE_COMPOUND_UNION || datatype->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) datatype; } else { if(datatype->type != TYPE_POINTER) { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a compound type (or pointer) but " "found type "); print_type(stderr, datatype); fprintf(stderr, "\n"); return; } pointer_type_t *pointer_type = (pointer_type_t*) datatype; type_t *points_to = pointer_type->points_to; if(points_to->type == TYPE_BIND_TYPEVARIABLES) { bind_typevariables = (bind_typevariables_type_t*) points_to; compound_type = (compound_type_t*) bind_typevariables->polymorphic_type; } else if(points_to->type == TYPE_COMPOUND_STRUCT || points_to->type == TYPE_COMPOUND_UNION || points_to->type == TYPE_COMPOUND_CLASS) { compound_type = (compound_type_t*) points_to; } else { print_error_prefix(select->expression.source_position); fprintf(stderr, "select needs a pointer to compound type but found " "type "); print_type(stderr, datatype); fprintf(stderr, "\n"); return; } } symbol_t *symbol = select->symbol; /* try to find a matching declaration */ declaration_t *declaration = compound_type->context.declarations; while(declaration != NULL) { if(declaration->symbol == symbol) break; declaration = declaration->next; } if(declaration != NULL) { type_t *type = check_reference(declaration, select->expression.source_position); select->expression.datatype = type; select->declaration = declaration; return; } compound_entry_t *entry = compound_type->entries; while(entry != NULL) { if(entry->symbol == symbol) { break; } entry = entry->next; } if(entry == NULL) { print_error_prefix(select->expression.source_position); fprintf(stderr, "compound type "); print_type(stderr, (type_t*) compound_type); fprintf(stderr, " does not have a member '%s'\n", symbol->string); return; } type_t *result_type = entry->type; /* resolve type varible bindings if needed */ if(bind_typevariables != NULL) { int old_top = typevar_binding_stack_top(); push_type_variable_bindings(compound_type->type_parameters, bind_typevariables->type_arguments); result_type = create_concrete_type(entry->type); pop_type_variable_bindings(old_top); } select->compound_entry = entry; select->expression.datatype = result_type; } static void check_array_access_expression(array_access_expression_t *access) { access->array_ref = check_expression(access->array_ref); access->index = check_expression(access->index); expression_t *array_ref = access->array_ref; expression_t *index = access->index; type_t *type = array_ref->datatype; if(type == NULL || (type->type != TYPE_POINTER && type->type != TYPE_ARRAY)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected pointer or array type for array access, " "got "); print_type(stderr, type); fprintf(stderr, "\n"); return; } type_t *result_type; if(type->type == TYPE_POINTER) { pointer_type_t *pointer_type = (pointer_type_t*) type; result_type = pointer_type->points_to; } else { assert(type->type == TYPE_ARRAY); array_type_t *array_type = (array_type_t*) type; result_type = array_type->element_type; /* TODO We could issue a warning if we have a constant index expression * that exceeds the array size */ } access->expression.datatype = result_type; if(index->datatype == NULL || !is_type_int(index->datatype)) { print_error_prefix(access->expression.source_position); fprintf(stderr, "expected integer type for array index, got "); print_type(stderr, index->datatype); fprintf(stderr, "\n"); return; } if(index->datatype != NULL && index->datatype != type_int) { access->index = make_cast(index, type_int, access->expression.source_position); } } static void check_sizeof_expression(sizeof_expression_t *expression) { expression->type = normalize_type(expression->type); expression->expression.datatype = type_uint; } static void check_func_expression(func_expression_t *expression) { method_t *method = & expression->method; resolve_method_types(method); check_method(method, NULL, expression->expression.source_position); expression->expression.datatype = make_pointer_type((type_t*) method->type); } WARN_UNUSED expression_t *check_expression(expression_t *expression) { if(expression == NULL) return NULL; /* try to lower the expression */ if((unsigned) expression->type < (unsigned) ARR_LEN(expression_lowerers)) { lower_expression_function lowerer = expression_lowerers[expression->type]; if(lowerer != NULL) { expression = lowerer(expression); } } switch(expression->type) { case EXPR_INT_CONST: expression->datatype = type_int; break; case EXPR_FLOAT_CONST: expression->datatype = type_double; break; case EXPR_BOOL_CONST: expression->datatype = type_bool; break; case EXPR_STRING_CONST: expression->datatype = type_byte_ptr; break; case EXPR_NULL_POINTER: expression->datatype = type_void_ptr; break; case EXPR_FUNC: check_func_expression((func_expression_t*) expression); break; case EXPR_REFERENCE: check_reference_expression((reference_expression_t*) expression); break; case EXPR_SIZEOF: check_sizeof_expression((sizeof_expression_t*) expression); break; case EXPR_BINARY: check_binary_expression((binary_expression_t*) expression); break; case EXPR_UNARY: check_unary_expression((unary_expression_t*) expression); break; case EXPR_SELECT: check_select_expression((select_expression_t*) expression); break; case EXPR_CALL: check_call_expression((call_expression_t*) expression); break; case EXPR_ARRAY_ACCESS: check_array_access_expression((array_access_expression_t*) expression); break; case EXPR_LAST: case EXPR_INVALID: panic("Invalid expression encountered"); } return expression; } static void check_return_statement(return_statement_t *statement) { method_t *method = current_method; type_t *method_result_type = method->type->result_type; statement->return_value = check_expression(statement->return_value); expression_t *return_value = statement->return_value; last_statement_was_return = true; if(return_value != NULL) { if(method_result_type == type_void && return_value->datatype != type_void) { error_at(statement->statement.source_position, "return with value in void method\n"); return; } /* do we need a cast ?*/ if(return_value->datatype != method_result_type) { return_value = make_cast(return_value, method_result_type, statement->statement.source_position); statement->return_value = return_value; } } else { if(method_result_type != type_void) { error_at(statement->statement.source_position, "missing return value in non-void method\n"); return; } } } static void check_if_statement(if_statement_t *statement) { statement->condition = check_expression(statement->condition); expression_t *condition = statement->condition; assert(condition != NULL); if(condition->datatype != type_bool) { error_at(statement->statement.source_position, "if condition needs to be boolean but has type "); print_type(stderr, condition->datatype); fprintf(stderr, "\n"); return; } statement->true_statement = check_statement(statement->true_statement); if(statement->false_statement != NULL) { statement->false_statement = check_statement(statement->false_statement); } } static void push_context(const context_t *context) { declaration_t *declaration = context->declarations; while(declaration != NULL) { environment_push(declaration, context); declaration = declaration->next; } } static void check_block_statement(block_statement_t *block) { int old_top = environment_top(); check_and_push_context(& block->context); statement_t *statement = block->statements; statement_t *last = NULL; while(statement != NULL) { statement_t *next = statement->next; statement = check_statement(statement); assert(statement->next == next || statement->next == NULL); statement->next = next; if(last != NULL) { last->next = statement; } else { block->statements = statement; } last = statement; statement = next; } environment_pop_to(old_top); } static void check_variable_declaration(variable_declaration_statement_t *statement) { method_t *method = current_method; assert(method != NULL); statement->declaration.value_number = method->n_local_vars; method->n_local_vars++; /* TODO: try to catch cases where a variable is used before it is defined * (Note: Adding the variable just here to the environment is not a good * idea the case were a variable is used earlier indicates an error * typically) */ statement->declaration.refs = 0; if(statement->declaration.type != NULL) { statement->declaration.type = normalize_type(statement->declaration.type); } } static void check_expression_statement(expression_statement_t *statement) { statement->expression = check_expression(statement->expression); expression_t *expression = statement->expression; /* can happen on semantic errors */ if(expression->datatype == NULL) return; bool may_be_unused = false; if(expression->type == EXPR_BINARY && ((binary_expression_t*) expression)->type == BINEXPR_ASSIGN) { may_be_unused = true; } else if(expression->type == EXPR_UNARY && (((unary_expression_t*) expression)->type == UNEXPR_INCREMENT || ((unary_expression_t*) expression)->type == UNEXPR_DECREMENT)) { may_be_unused = true; } else if(expression->type == EXPR_CALL) { may_be_unused = true; } if(expression->datatype != type_void && !may_be_unused) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "result of expression is unused\n"); if(expression->type == EXPR_BINARY) { binary_expression_t *binexpr = (binary_expression_t*) expression; if(binexpr->type == BINEXPR_EQUAL) { print_warning_prefix(statement->statement.source_position); fprintf(stderr, "Did you mean '<-' instead of '='?\n"); } } print_warning_prefix(statement->statement.source_position); fprintf(stderr, "note: cast expression to void to avoid this " "warning\n"); } } static void check_label_statement(label_statement_t *label) { (void) label; /* nothing to do */ } static void check_goto_statement(goto_statement_t *goto_statement) { /* already resolved? */ if(goto_statement->label != NULL) return; symbol_t *symbol = goto_statement->label_symbol; if(symbol == NULL) { error_at(goto_statement->statement.source_position, "unresolved anonymous goto\n"); return; } declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' is an unknown symbol.\n", symbol->string); return; } if(declaration->type != DECLARATION_LABEL) { print_error_prefix(goto_statement->statement.source_position); fprintf(stderr, "goto argument '%s' should be a label but is a '%s'.\n", symbol->string, get_declaration_type_name(declaration->type)); return; } label_declaration_t *label = (label_declaration_t*) declaration; goto_statement->label = label; } WARN_UNUSED statement_t *check_statement(statement_t *statement) { if(statement == NULL) return NULL; /* try to lower the statement */ if((int) statement->type < (int) ARR_LEN(statement_lowerers)) { lower_statement_function lowerer = statement_lowerers[statement->type]; if(lowerer != NULL) { statement = lowerer(statement); } } if(statement == NULL) return NULL; last_statement_was_return = false; switch(statement->type) { case STATEMENT_INVALID: panic("encountered invalid statement"); break; case STATEMENT_BLOCK: check_block_statement((block_statement_t*) statement); break; case STATEMENT_RETURN: check_return_statement((return_statement_t*) statement); break; case STATEMENT_GOTO: check_goto_statement((goto_statement_t*) statement); break; case STATEMENT_LABEL: check_label_statement((label_statement_t*) statement); break; case STATEMENT_IF: check_if_statement((if_statement_t*) statement); break; case STATEMENT_VARIABLE_DECLARATION: check_variable_declaration((variable_declaration_statement_t*) statement); break; case STATEMENT_EXPRESSION: check_expression_statement((expression_statement_t*) statement); break; default: panic("Unknown statement found"); break; } return statement; } static void check_method(method_t *method, symbol_t *symbol, const source_position_t source_position) { if(method->is_extern) return; int old_top = environment_top(); push_context(&method->context); method_t *last_method = current_method; current_method = method; /* set method parameter numbers */ method_parameter_t *parameter = method->parameters; int n = 0; while(parameter != NULL) { parameter->num = n; n++; parameter = parameter->next; } bool last_last_statement_was_return = last_statement_was_return; last_statement_was_return = false; if(method->statement != NULL) { method->statement = check_statement(method->statement); } if(!last_statement_was_return) { type_t *result_type = method->type->result_type; if(result_type != type_void) { /* TODO: report end-position of block-statement? */ print_error_prefix(source_position); if(symbol != NULL) { fprintf(stderr, "missing return statement at end of function " "'%s'\n", symbol->string); } else { fprintf(stderr, "missing return statement at end of anonymous " "function\n"); } return; } } current_method = last_method; last_statement_was_return = last_last_statement_was_return; environment_pop_to(old_top); } static void check_constant(constant_t *constant) { expression_t *expression = constant->expression; expression = check_expression(expression); if(expression->datatype != constant->type) { expression = make_cast(expression, constant->type, constant->declaration.source_position); } constant->expression = expression; } static void resolve_type_constraint(type_constraint_t *constraint, const source_position_t source_position) { symbol_t *symbol = constraint->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(source_position); fprintf(stderr, "nothing known about symbol '%s'\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } constraint->concept = (concept_t*) declaration; } static void resolve_type_variable_constraints(type_variable_t *type_variables) { type_variable_t *type_var = type_variables; while(type_var != NULL) { type_constraint_t *constraint = type_var->constraints; while(constraint != NULL) { resolve_type_constraint(constraint, type_var->declaration.source_position); constraint = constraint->next; } type_var = type_var->next; } } static void resolve_method_types(method_t *method) { int old_top = environment_top(); /* push type variables */ push_context(&method->context); resolve_type_variable_constraints(method->type_parameters); /* normalize parameter types */ method_parameter_t *parameter = method->parameters; while(parameter != NULL) { parameter->type = normalize_type(parameter->type); parameter = parameter->next; } method->type = (method_type_t*) normalize_type((type_t*) method->type); environment_pop_to(old_top); } static void check_concept_instance(concept_instance_t *instance) { concept_method_instance_t *method_instance = instance->method_instances; while(method_instance != NULL) { method_t *method = &method_instance->method; resolve_method_types(method); check_method(method, method_instance->symbol, method_instance->source_position); method_instance = method_instance->next; } } static void resolve_concept_types(concept_t *concept) { int old_top = environment_top(); /* push type variables */ type_variable_t *type_parameter = concept->type_parameters; while(type_parameter != NULL) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, concept); type_parameter = type_parameter->next; } resolve_type_variable_constraints(concept->type_parameters); /* normalize method types */ concept_method_t *concept_method = concept->methods; while(concept_method != NULL) { type_t *normalized_type = normalize_type((type_t*) concept_method->method_type); assert(normalized_type->type == TYPE_METHOD); concept_method->method_type = (method_type_t*) normalized_type; concept_method = concept_method->next; } environment_pop_to(old_top); } static void resolve_concept_instance(concept_instance_t *instance) { symbol_t *symbol = instance->concept_symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(declaration->source_position); fprintf(stderr, "symbol '%s' is unknown\n", symbol->string); return; } if(declaration->type != DECLARATION_CONCEPT) { print_error_prefix(declaration->source_position); fprintf(stderr, "expected a concept but symbol '%s' is a '%s'\n", symbol->string, get_declaration_type_name(declaration->type)); return; } concept_t *concept = (concept_t*) declaration; instance->concept = concept; instance->next_in_concept = concept->instances; concept->instances = instance; int old_top = environment_top(); /* push type variables */ resolve_type_variable_constraints(instance->type_parameters); type_variable_t *type_parameter = instance->type_parameters; for ( ; type_parameter != NULL; type_parameter = type_parameter->next) { declaration_t *declaration = (declaration_t*) type_parameter; environment_push(declaration, instance); } /* normalize argument types */ type_argument_t *type_argument = instance->type_arguments; while(type_argument != NULL) { type_argument->type = normalize_type(type_argument->type); type_argument = type_argument->next; } /* link methods and normalize their types */ - concept_method_t *method = concept->methods; - while(method != NULL) { - bool found_instance = false; - concept_method_instance_t *method_instance - = instance->method_instances; - - while(method_instance != NULL) { - method_t *imethod = & method_instance->method; + size_t n_concept_methods = 0; + concept_method_t *method; + for (method = concept->methods; method != NULL; method = method->next) { + ++n_concept_methods; + } + bool have_method[n_concept_methods]; + memset(&have_method, 0, sizeof(have_method)); + + concept_method_instance_t *method_instance; + for (method_instance = instance->method_instances; method_instance != NULL; + method_instance = method_instance->next) { + + /* find corresponding concept method */ + int n = 0; + for (method = concept->methods; method != NULL; + method = method->next, ++n) { + if (method->declaration.symbol == method_instance->symbol) + break; + } - if(method_instance->symbol != method->declaration.symbol) { - method_instance = method_instance->next; - continue; - } - - if(found_instance) { + if (method == NULL) { + print_warning_prefix(method_instance->source_position); + fprintf(stderr, "concept '%s' does not declare a method '%s'\n", + concept->declaration.symbol->string, + method->declaration.symbol->string); + } else { + method_instance->concept_method = method; + method_instance->concept_instance = instance; + if (have_method[n]) { print_error_prefix(method_instance->source_position); fprintf(stderr, "multiple implementations of method '%s' found " - "in instance of concept '%s'\n", - method->declaration.symbol->string, - concept->declaration.symbol->string); - } else { - found_instance = true; - method_instance->concept_method = method; - method_instance->concept_instance = instance; + "in instance of concept '%s'\n", + method->declaration.symbol->string, + concept->declaration.symbol->string); } + have_method[n] = true; + } + method_t *imethod = & method_instance->method; - imethod->type - = (method_type_t*) normalize_type((type_t*) imethod->type); - method_instance = method_instance->next; + if (imethod->type_parameters != NULL) { + print_error_prefix(method_instance->source_position); + fprintf(stderr, "instance method '%s' must not have type parameters\n", + method_instance->symbol->string); } - if(!found_instance) { + + imethod->type + = (method_type_t*) normalize_type((type_t*) imethod->type); + } + + size_t n = 0; + for (method = concept->methods; method != NULL; + method = method->next, ++n) { + if(!have_method[n]) { print_error_prefix(instance->source_position); fprintf(stderr, "instance of concept '%s' does not implement " "method '%s'\n", concept->declaration.symbol->string, method->declaration.symbol->string); } - - method = method->next; } environment_pop_to(old_top); } static void check_export(const export_t *export) { method_declaration_t *method; variable_declaration_t *variable; symbol_t *symbol = export->symbol; declaration_t *declaration = symbol->declaration; if(declaration == NULL) { print_error_prefix(export->source_position); fprintf(stderr, "Exported symbol '%s' is unknown\n", symbol->string); return; } switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; method->method.export = 1; break; case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->export = 1; break; default: print_error_prefix(export->source_position); fprintf(stderr, "Can only export functions and variables but '%s' " "is a %s\n", symbol->string, get_declaration_type_name(declaration->type)); return; } found_export = true; } static void check_and_push_context(context_t *context) { variable_declaration_t *variable; method_declaration_t *method; typealias_t *typealias; type_t *type; concept_t *concept; push_context(context); /* normalize types, resolve concept instance references */ declaration_t *declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_VARIABLE: variable = (variable_declaration_t*) declaration; variable->type = normalize_type(variable->type); break; case DECLARATION_METHOD: method = (method_declaration_t*) declaration; resolve_method_types(&method->method); break; case DECLARATION_TYPEALIAS: typealias = (typealias_t*) declaration; type = normalize_type(typealias->type); if(type->type == TYPE_COMPOUND_UNION || type->type == TYPE_COMPOUND_STRUCT) { check_compound_type((compound_type_t*) type); } typealias->type = type; break; case DECLARATION_CONCEPT: concept = (concept_t*) declaration; resolve_concept_types(concept); break; default: break; } declaration = declaration->next; } concept_instance_t *instance = context->concept_instances; while(instance != NULL) { resolve_concept_instance(instance); instance = instance->next; } + /* check semantics in conceptes */ + instance = context->concept_instances; + while(instance != NULL) { + check_concept_instance(instance); + instance = instance->next; + } /* check semantics in methods */ declaration = context->declarations; while(declaration != NULL) { switch(declaration->type) { case DECLARATION_METHOD: method = (method_declaration_t*) declaration; check_method(&method->method, method->declaration.symbol, method->declaration.source_position); break; case DECLARATION_CONSTANT: check_constant((constant_t*) declaration); break; default: break; } declaration = declaration->next; } - /* check semantics in conceptes */ - instance = context->concept_instances; - while(instance != NULL) { - check_concept_instance(instance); - instance = instance->next; - } /* handle export declarations */ export_t *export = context->exports; while(export != NULL) { check_export(export); export = export->next; } } static void check_namespace(namespace_t *namespace) { int old_top = environment_top(); check_and_push_context(&namespace->context); environment_pop_to(old_top); } void register_statement_lowerer(lower_statement_function function, unsigned int statement_type) { unsigned int len = ARR_LEN(statement_lowerers); if(statement_type >= len) { ARR_RESIZE(lower_statement_function, statement_lowerers, statement_type + 1); memset(&statement_lowerers[len], 0, (statement_type - len + 1) * sizeof(statement_lowerers[0])); } if(statement_lowerers[statement_type] != NULL) { panic("Trying to register multiple lowerers for a statement type"); } statement_lowerers[statement_type] = function; } void register_expression_lowerer(lower_expression_function function, unsigned int expression_type) { unsigned int len = ARR_LEN(expression_lowerers); if(expression_type >= len) { ARR_RESIZE(lower_expression_function, expression_lowerers, expression_type + 1); memset(&expression_lowerers[len], 0, (expression_type - len + 1) * sizeof(expression_lowerers[0])); } if(expression_lowerers[expression_type] != NULL) { panic("Trying to register multiple lowerers for a expression type"); } expression_lowerers[expression_type] = function; } int check_static_semantic(void) { obstack_init(&symbol_environment_obstack); symbol_stack = NEW_ARR_F(environment_entry_t*, 0); found_errors = false; found_export = false; type_bool = make_atomic_type(ATOMIC_TYPE_BOOL); type_byte = make_atomic_type(ATOMIC_TYPE_BYTE); type_int = make_atomic_type(ATOMIC_TYPE_INT); type_uint = make_atomic_type(ATOMIC_TYPE_UINT); type_double = make_atomic_type(ATOMIC_TYPE_DOUBLE); type_void_ptr = make_pointer_type(type_void); type_byte_ptr = make_pointer_type(type_byte); namespace_t *namespace = namespaces; while(namespace != NULL) { check_namespace(namespace); namespace = namespace->next; } if(!found_export) { fprintf(stderr, "error: no symbol exported\n"); found_errors = true; } DEL_ARR_F(symbol_stack); obstack_free(&symbol_environment_obstack, NULL); return !found_errors; } void init_semantic_module(void) { statement_lowerers = NEW_ARR_F(lower_statement_function, 0); expression_lowerers = NEW_ARR_F(lower_expression_function, 0); register_expression_lowerer(lower_unary_expression, EXPR_UNARY); } void exit_semantic_module(void) { DEL_ARR_F(expression_lowerers); DEL_ARR_F(statement_lowerers); }
antoine-levitt/ACCQUAREL
78f533f56473dd5e3edfc52d31d080248a7ace4d
energy diff
diff --git a/src/common.f90 b/src/common.f90 index efe15ce..13963fb 100644 --- a/src/common.f90 +++ b/src/common.f90 @@ -1,252 +1,272 @@ MODULE debug ! This module contains a logical flag to perform various checks in the computation of ESA's THETA function. ! LOGICAL,PARAMETER :: THETA_CHECK=.TRUE. - LOGICAL,PARAMETER :: THETA_CHECK=.FALSE. + LOGICAL :: THETA_CHECK=.TRUE. END MODULE MODULE metric_relativistic ! This module contains pointers assigned to the tensors relative to the metric (as we work in a nonorthogonal basis), which are the overlap matrix S, its inverse S^-{1}, its square root S^{1/2}, the inverse of its square root S^{-1/2} and the matrix of its Cholesky factorization (for the solution of the generalized eigenproblem), all stored in packed form. DOUBLE COMPLEX,POINTER,DIMENSION(:) :: PS,PIS,PSRS,PISRS,PCFS END MODULE MODULE metric_nonrelativistic ! This module contains pointers assigned to the tensors relative to the metric (as we work in a nonorthogonal basis), which are the overlap matrix S, its inverse S^-{1}, its square root S^{1/2}, the inverse of its square root S^{-1/2} and the matrix of its Cholesky factorization (for the solution of the generalized eigenproblem), all stored in packed form. DOUBLE PRECISION,POINTER,DIMENSION(:) :: PS,PIS,PSRS,PISRS,PCFS END MODULE MODULE common_functions INTERFACE ENERGY MODULE PROCEDURE ENERGY_relativistic,ENERGY_AOCOSDHF,ENERGY_RHF,ENERGY_UHF END INTERFACE INTERFACE ELECTRONIC_ENERGY MODULE PROCEDURE ELECTRONIC_ENERGY_relativistic,ELECTRONIC_ENERGY_AOCOSDHF,ELECTRONIC_ENERGY_RHF,ELECTRONIC_ENERGY_UHF END INTERFACE CONTAINS FUNCTION ENERGY_relativistic(POEFM,PTEFM,PDM,N) RESULT(ETOT) ! Function that computes the Dirac-Fock total energy associated to a density matrix (whose upper triangular part is stored in packed form in PDM) of a given molecular system, POEFM and PTEFM containing respectively the core hamiltonian matrix and the two-electron part of the Fock matrix (both stored similarly). USE data_parameters IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION :: ETOT ETOT=ELECTRONIC_ENERGY_relativistic(POEFM,PTEFM,PDM,N)+INTERNUCLEAR_ENERGY END FUNCTION ENERGY_relativistic FUNCTION ENERGY_AOCOSDHF(POEFM,PTEFMC,PTEFMO,PDMC,PDMO,N) RESULT(ETOT) USE data_parameters IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFMC,PTEFMO,PDMC,PDMO DOUBLE PRECISION :: ETOT ETOT=ELECTRONIC_ENERGY_AOCOSDHF(POEFM,PTEFMC,PTEFMO,PDMC,PDMO,N)+INTERNUCLEAR_ENERGY END FUNCTION ENERGY_AOCOSDHF FUNCTION ENERGY_RHF(POEFM,PTEFM,PDM,N) RESULT(ETOT) ! Function that computes the restricted closed-shell Hartree-Fock total energy associated to a density matrix (whose upper triangular parts are stored in packed form) of a given molecular system, POEFM and PTEFM containing respectively the core hamiltonian matrix and the two-electron part of the Fock matrix (both stored similarly). USE data_parameters IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION :: ETOT ETOT=ELECTRONIC_ENERGY_RHF(POEFM,PTEFM,PDM,N)+INTERNUCLEAR_ENERGY END FUNCTION ENERGY_RHF FUNCTION ENERGY_UHF(POEFM,PTEFM,PEMS,PTDM,PSDM,N) RESULT(ETOT) ! Function that computes the unrestricted open-shell Hartree-Fock total energy associated to the total and spin density matrices (whose upper triangular part is stored in packed form in PDM) of a given molecular system, POEFM, PTEFM and PEMS containing respectively the core hamiltonian matrix, the two-electron part of the Fock matrix associated to the total density matrix and the exchange matrix associated to the spin density matrix (all stored similarly). USE data_parameters IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PEMS,PTDM,PSDM DOUBLE PRECISION :: ETOT ETOT=ELECTRONIC_ENERGY_UHF(POEFM,PTEFM,PEMS,PTDM,PSDM,N)+INTERNUCLEAR_ENERGY END FUNCTION ENERGY_UHF FUNCTION ENERGY_RGHF(POEFM,PTEFM,PDM,N) RESULT(ETOT) ! Function that computes the real general Hartree-Fock total energy associated to a density matrix (whose upper triangular parts are stored in packed form) of a given molecular system, POEFM and PTEFM containing respectively the core hamiltonian matrix and the two-electron part of the Fock matrix (both stored similarly). USE data_parameters IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION :: ETOT ETOT=ELECTRONIC_ENERGY_HF(POEFM,PTEFM,PDM,N)+INTERNUCLEAR_ENERGY END FUNCTION ENERGY_RGHF +FUNCTION ENERGY_DIFF_RGHF(POEFM,PDM1,PDM2,PHI,N) RESULT(ETOT) + ! computes the energy difference between PDM1 and PDM2. + USE case_parameters ; USE data_parameters ; USE basis_parameters + IMPLICIT NONE + INTEGER,INTENT(IN) :: N + DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PDM1,PDM2 + DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PTEFM1,PTEFM2p1 + DOUBLE PRECISION :: ETOT + TYPE(gaussianbasisfunction),DIMENSION(:) :: PHI + + CALL BUILDTEFM_RGHF(PTEFM1,N,PHI,PDM1) + CALL BUILDTEFM_RGHF(PTEFM2p1,N,PHI,PDM1+PDM2) + + ETOT = ENERGY_RGHF(POEFM,PTEFM2p1,PDM2-PDM1,N) + ! ETOT = ETOT + ENERGY_RGHF(0*POEFM,PTEFM2m1,PDM2,N) + + + ETOT = ENERGY_RHF(POEFM,PTEFM2p1,PDM2-PDM1,N) +END FUNCTION ENERGY_DIFF_RGHF + FUNCTION ELECTRONIC_ENERGY_relativistic(POEFM,PTEFM,PDM,N) RESULT(ENERGY) ! Function that computes the Dirac-Fock electronic energy associated to a density matrix (whose upper triangular part is stored in packed form in PDM) of a given molecular system, POEFM and PTEFM containing respectively the core hamiltonian matrix and the two-electron part of the Fock matrix (both stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION :: ENERGY INTEGER :: I,J,IJ DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PEM PEM=POEFM+0.5D0*PTEFM ENERGY=0.D0 IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 IF (I.NE.J) THEN ENERGY=ENERGY+REAL(PEM(IJ)*CONJG(PDM(IJ))+CONJG(PEM(IJ))*PDM(IJ)) ELSE ENERGY=ENERGY+REAL(PEM(IJ)*PDM(IJ)) END IF END DO END DO END FUNCTION ELECTRONIC_ENERGY_relativistic FUNCTION ELECTRONIC_ENERGY_AOCOSDHF(POEFM,PTEFMC,PTEFMO,PDMC,PDMO,N) RESULT(ENERGY) ! Function that computes average-of-configuration Dirac-Hartree-Fock electronic energy associated the closed- and open-shell density matrices (whose upper triangular parts are stored in packed form). USE data_parameters IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFMC,PTEFMO,PDMC,PDMO DOUBLE PRECISION :: ENERGY INTEGER :: I,J,IJ DOUBLE PRECISION :: a DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PEMC,PEMO a=REAL(NBOOS*(NBEOS-1))/REAL(NBEOS*(NBOOS-1)) PEMC=POEFM+0.5D0*PTEFMC+PTEFMO ; PEMO=POEFM+0.5D0*a*PTEFMO ENERGY=0.D0 IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 IF (I.NE.J) THEN ENERGY=ENERGY+REAL(PEMC(IJ)*CONJG(PDMC(IJ))+CONJG(PEMC(IJ))*PDMC(IJ) & & +PEMO(IJ)*CONJG(PDMO(IJ))+CONJG(PEMO(IJ))*PDMO(IJ)) ELSE ENERGY=ENERGY+REAL(PEMC(IJ)*PDMC(IJ)+PEMO(IJ)*PDMO(IJ)) END IF END DO END DO END FUNCTION ELECTRONIC_ENERGY_AOCOSDHF FUNCTION ELECTRONIC_ENERGY_HF(POEFM,PTEFM,PDM,N) RESULT(ENERGY) ! Function that computes the Hartree-Fock energy associated to a density matrix (whose upper triangular part is stored in packed form in PDM) of a given system, POEFM and PTEFM containing respectively the (core hamiltonian) matrix and the (two-electron) part of the Fock matrix (both stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION :: ENERGY INTEGER :: I,J,IJ DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PEM PEM=POEFM+0.5D0*PTEFM ENERGY=0.D0 IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 IF (I.NE.J) THEN ENERGY=ENERGY+2.D0*PEM(IJ)*PDM(IJ) ELSE ENERGY=ENERGY+PEM(IJ)*PDM(IJ) END IF END DO END DO END FUNCTION ELECTRONIC_ENERGY_HF FUNCTION ELECTRONIC_ENERGY_RHF(POEFM,PTEFM,PDM,N) RESULT(ENERGY) ! Function that computes the restricted closed-shell Hartree-Fock electronic energy associated to a density matrix (whose upper triangular part is stored in packed form in PDM) of a given molecular system, POEFM and PTEFM containing respectively the core hamiltonian matrix and the two-electron part of the Fock matrix (both stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION :: ENERGY INTEGER :: I,J,IJ DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PEM PEM=2.D0*POEFM+PTEFM ENERGY=0.D0 IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 IF (I.NE.J) THEN ENERGY=ENERGY+2.D0*PEM(IJ)*PDM(IJ) ELSE ENERGY=ENERGY+PEM(IJ)*PDM(IJ) END IF END DO END DO END FUNCTION ELECTRONIC_ENERGY_RHF FUNCTION ELECTRONIC_ENERGY_UHF(POEFM,PTEFM,PEMS,PTDM,PSDM,N) RESULT(ENERGY) ! Function that computes the unrestricted open-shell Hartree-Fock electronic energy associated to the total and spin density matrices (whose upper triangular parts are stored in packed form) of a given molecular system, POEFM, PTEFM and PEMS containing respectively the core hamiltonian matrix, the two-electron part of the Fock matrix associated to the total density matrix and the exchange matrix associated to the spin density matrix (all stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PEMS,PTDM,PSDM DOUBLE PRECISION :: ENERGY INTEGER :: I,J,IJ DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PM PM=POEFM+0.25D0*PTEFM ENERGY=0.D0 IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 IF (I.NE.J) THEN ENERGY=ENERGY+2.D0*(PM(IJ)*PTDM(IJ)-0.25D0*PEMS(IJ)*PSDM(IJ)) ELSE ENERGY=ENERGY+PM(IJ)*PTDM(IJ)-0.25D0*PEMS(IJ)*PSDM(IJ) END IF END DO END DO END FUNCTION ELECTRONIC_ENERGY_UHF FUNCTION FREEENERGY_HF(POEFM,PTEFM,PDM,N,TEMPERATURE,FUNC) RESULT(ENRG) ! Function that computes the free energy (of a Hartree(-Fock) model with temperature) associated to a density matrix (whose upper triangular part is stored in packed form in PDM) of a given system, POEFM and PTEFM containing respectively the (core hamiltonian) matrix and the (two-electron) part of the Fock matrix (both stored similarly). USE matrix_tools ; USE metric_nonrelativistic IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: POEFM,PTEFM,PDM DOUBLE PRECISION,INTENT(IN) :: TEMPERATURE INTERFACE DOUBLE PRECISION FUNCTION FUNC(X) DOUBLE PRECISION,INTENT(IN) :: X END FUNCTION END INTERFACE DOUBLE PRECISION :: ENRG INTEGER :: I,J,IJ,INFO DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PTMP DOUBLE PRECISION,DIMENSION(N) :: W DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N,N) :: Z,TMP PTMP=PDM CALL DSPEV('V','U',N,PTMP,W,Z,N,WORK,INFO) IF (INFO/=0) GO TO 1 TMP=0.D0 DO I=1,N TMP(I,I)=FUNC(W(I)) END DO PTMP=PACK(MATMUL(Z,MATMUL(TMP,TRANSPOSE(Z))),N) ENRG=ELECTRONIC_ENERGY_HF(POEFM,PTEFM,PDM,N)+TEMPERATURE*TRACEOFPRODUCT(PTMP,PS,N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function FREEENERGY)' STOP END FUNCTION FREEENERGY_HF END MODULE
antoine-levitt/ACCQUAREL
264ac103c9189074eb84f5393578015e5af61228
gradient RGHF
diff --git a/src/drivers.f90 b/src/drivers.f90 index bf6ed5d..1ffb849 100644 --- a/src/drivers.f90 +++ b/src/drivers.f90 @@ -1,607 +1,607 @@ SUBROUTINE DRIVER_relativistic USE case_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools USE metric_relativistic ; USE scf_algorithms IMPLICIT NONE INTEGER :: NBAST TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF INTEGER,DIMENSION(2) :: NGBF INTEGER :: TYPENMBR(3),INFO,I DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC ! Computation of the discretization basis CALL FORMBASIS(PHI,NBAS,GBF,NGBF) NBAST=SUM(NBAS) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM IF (INFO/=0) GOTO 1 ! Condition number WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1') ! Computation and assembly of the core hamiltonian matrix WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS) ! Creation of the list of nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR) IF (DIRECT) THEN IF (.NOT.USEDISK) THEN ! storage of the list of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4)) OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:) END DO CLOSE(LUNIT,STATUS='DELETE') END IF ELSE IF (.NOT.DIRECT) THEN ! Precomputation of the bielectronic integrals is preferred to "on the fly" computation ! Precomputation of the bielectronic integrals involving gaussian basis functions WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF' CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) IF (SEMIDIRECT) THEN IF (.NOT.USEDISK) THEN ! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR)) OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:),BITYPE(I) END DO CLOSE(LUNIT,STATUS='DELETE') END IF ELSE WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions' IF (USEDISK) THEN ! storage of the list and values of nonzero bielectronic integrals on disk ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1)) OPEN(LUNIT,access='STREAM') ; OPEN(BIUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(1,:),BITYPE(1) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1)) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) DEALLOCATE(BILIST,BITYPE) ELSE ! storage of the list and values of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR)) OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:),BITYPE(1) CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1)) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO CLOSE(LUNIT,STATUS='DELETE') DEALLOCATE(BITYPE) END IF CALL DEALLOCATE_INTEGRALS END IF END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) IF(RESUME) THEN OPEN(100,FILE='eig.txt') READ(100,*) EIG OPEN(101,FILE='eigvec_r.txt') OPEN(102,FILE='eigvec_i.txt') CALL READMATRIX(EIGVEC,NBAST,101,102) CLOSE(100) CLOSE(101) CLOSE(102) END IF DO I=1,NBALG SELECT CASE (ALG(I)) CASE (1) WRITE(*,'(/,a)')' Roothaan''s algorithm' SELECT CASE (MODEL) CASE (1) CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR) CASE (2) CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR) CASE (3) CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (2) WRITE(*,'(/,a)')' level-shifting algorithm' CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (3) WRITE(*,'(/,a)')' DIIS algorithm' CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (5) WRITE(*,'(/,a)')' Eric Sere''s algorithm' CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (6) WRITE(*,'(/,a)')' Roothaan/Gradient algorithm' CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT END DO IF (DIRECT) THEN IF (USEDISK) THEN OPEN(LUNIT,access='STREAM') ; CLOSE(LUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST) END IF ELSE IF (SEMIDIRECT) THEN IF (USEDISK) THEN OPEN(LUNIT,access='STREAM') ; CLOSE(LUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,BITYPE) END IF CALL DEALLOCATE_INTEGRALS ELSE IF (USEDISK) THEN OPEN(BIUNIT,access='STREAM') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,CBIVALUES) END IF END IF END IF OPEN(100,FILE='eig.txt') WRITE(100,*) EIG OPEN(101,FILE='eigvec_r.txt') OPEN(102,FILE='eigvec_i.txt') CALL PRINTMATRIX(EIGVEC,NBAST,101,102) CLOSE(100) CLOSE(101) CLOSE(102) DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF WRITE(*,*)'(called from subroutine DRIVER)' STOP END SUBROUTINE DRIVER_relativistic SUBROUTINE DRIVER_nonrelativistic USE case_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic USE scf_algorithms IMPLICIT NONE INTEGER :: NBAST TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS INTEGER :: INFO,I DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC ! Computation of the discretization basis IF(MODEL == 4) THEN CALL FORMBASIS_RGHF(PHI,NBAS) ELSE CALL FORMBASIS(PHI,NBAS) END IF NBAST=SUM(NBAS) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) IF(MODEL == 4) THEN CALL BUILDOM_RGHF(POM,PHI,NBAST) ELSE CALL BUILDOM(POM,PHI,NBAST) END IF PS=>POM ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM IF (INFO/=0) GOTO 1 ! Condition number WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1') ! Computation and assembly of the matrix of the free hamiltonian WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) IF(MODEL == 4) THEN CALL BUILDOEFM_RGHF(POEFM,PHI,NBAST) ELSE CALL BUILDOEFM(POEFM,PHI,NBAST) END IF ! Creation of the list of the nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAST,BINMBR) IF (DIRECT) THEN ! Computation of the bielectronic integrals will be done "on the fly" ! storage of the list of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4)) OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:) END DO CLOSE(LUNIT,STATUS='DELETE') ELSE ! Precomputation of the bielectronic integrals WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions' IF (USEDISK) THEN ALLOCATE(BILIST(1:1,1:4)) OPEN(LUNIT,access='STREAM') ; OPEN(BIUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(1,:) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO DEALLOCATE(BILIST) CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) ELSE ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR)) OPEN(LUNIT,access='STREAM') !$OMP PARALLEL DO SCHEDULE(STATIC,1) DO I=1,BINMBR READ(LUNIT)BILIST(I,:) RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO !$OMP END PARALLEL DO CLOSE(LUNIT,STATUS='DELETE') END IF END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) IF(RESUME) THEN OPEN(100,FILE='eig.txt') READ(100,*) EIG OPEN(101,FILE='eigvec.txt') CALL READMATRIX(EIGVEC,NBAST,101) CLOSE(100) CLOSE(101) END IF DO I=1,NBALG SELECT CASE (ALG(I)) CASE (1) WRITE(*,'(/,a)')' Roothaan''s algorithm' SELECT CASE (MODEL) CASE (1) CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL ROOTHAAN_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (2) WRITE(*,'(/,a)')' level-shifting algorithm' SELECT CASE (MODEL) CASE (1) CALL LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL LEVELSHIFTING_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (3) WRITE(*,'(/,a)')' DIIS algorithm' SELECT CASE (MODEL) CASE (1) CALL DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL DIIS_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (4) WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)' SELECT CASE (MODEL) CASE (1) CALL ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL ODA_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE(6) WRITE(*,*)' Roothaan/Gradient algorithm' SELECT CASE (MODEL) CASE (1) CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) - WRITE(*,*)' Not implemented yet!' + CALL GRADIENT_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT END SELECT END DO OPEN(100,FILE='eig.txt') WRITE(100,*) EIG OPEN(101,FILE='eigvec.txt') CALL PRINTMATRIX(EIGVEC,NBAST,101) CLOSE(100) CLOSE(101) IF (DIRECT) THEN DEALLOCATE(BILIST) ELSE IF (USEDISK) THEN OPEN(BIUNIT,access='STREAM') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,RBIVALUES) END IF END IF DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF WRITE(*,*)'(called from subroutine DRIVER)' STOP END SUBROUTINE DRIVER_nonrelativistic SUBROUTINE DRIVER_boson_star ! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants IMPLICIT NONE INTEGER :: NBAST,ITER,I,J,INFO INTEGER,TARGET :: RANK INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI LOGICAL :: NUMCONV ! boucle sur la temperature INTEGER :: K ! test ! DOUBLE PRECISION :: RCOND ! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK ! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0 ! Computation of the discretization basis CALL FORMBASIS(PHI,NBAS) NBAST=NBAS(1) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM ! tests ! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST)) ! PA=POM ! CALL DSPTRF('U',NBAST,PA,IPIV,INFO) ! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO) ! DEALLOCATE(PA,WORK,IPIV,IWORK) ! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND ! tests ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM IF (INFO/=0) GO TO 5 ! Computation and assembly of the matrix of the free hamiltonian WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) CALL BUILDKPFM(POEFM,PHI,NBAST) ! Creation of the list of nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAST,BINMBR) ! Computation of the Coulomb integrals WRITE(*,'(a)')'* Computation of the bielectronic integrals' IF (USEDISK) THEN ALLOCATE(BILIST(1:1,1:4)) OPEN(LUNIT,access='STREAM') ; OPEN(BIUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(1,:) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO DEALLOCATE(BILIST) CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) ELSE ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR)) OPEN(LUNIT,access='STREAM') !$OMP PARALLEL DO SCHEDULE(STATIC, 1) DO I=1,BINMBR READ(LUNIT)BILIST(I,:) RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO !$OMP END PARALLEL DO CLOSE(LUNIT,STATUS='DELETE') END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2)) ALLOCATE(LAMBDA(1:NBAST)) ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ! Initialisation CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 6 OPEN(33) DO I=1,NBAST write(33,*)EIG(I) END DO CLOSE(33) RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM PDM1=0.D0 LAMBDA=0.D0 ; ! IF (TEMPERATURE==0) LAMBDA(1)=MASS LAMBDA(1)=MASS ETOT1=0.D0 CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM) PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI) DO K=0,1000 ! TEMPERATURE LOOP TEMPERATURE=DBLE(K)*0.0001 ITER=0 ! ROOTHAAN'S ALGORITHM LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the density matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 6 IF (TEMPERATURE>0.D0) THEN ! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix MU_I=>EIG ; RANK_P=>RANK MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16) WRITE(*,*)'mu=',MU WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU) ! Computation of the updated occupation numbers DO I=1,NBAST IF (MU-EIG(I)>0.D0) THEN LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE) RANK=I ELSE LAMBDA(I)=0.D0 END IF ! WRITE(*,*)'lambda_',I,'=',LAMBDA(I) END DO write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA) END IF ! Assembly of the density matrix PDM1=PDM ; PDM=0.D0 DO I=1,RANK CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM) END DO ! Computation of the energy associated to the density matrix CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM) PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI) ETOT=ELECTRONIC_ENERGY_HF(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) WRITE(33,*)TEMPERATURE,ETOT,MU,RANK ! plot of the eigenfunction associated a pure state IF (RANK==1) THEN WRITE(*,*)' ' WRITE(*,*)'The minimizer is achieved by a pure state.' OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE') DO J=1,NBAST WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\' DO I=1,NBAST IF (EIGVEC(I,J)>=0.D0) THEN WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\' ELSE WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\' END IF END DO WRITE(9,*)')' END DO CLOSE(9) ELSE IF (RANK>1) THEN WRITE(*,*)' ' WRITE(*,*)'The minimizer is achieved by a mixed state.' END IF GO TO 4 3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) ! GO TO 4 4 CONTINUE END DO DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1) DEALLOCATE(PTTEFM,PTDM,PDMDIF) IF (USEDISK) THEN OPEN(BIUNIT,access='STREAM') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,RBIVALUES) END IF GO TO 7 RETURN 5 IF (INFO<0) THEN WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF 6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)' 7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI) END SUBROUTINE DRIVER_boson_star
antoine-levitt/ACCQUAREL
0ecf180d5e01ddf15542743e10cf8af3109853a4
modifs sur algo gradient
diff --git a/src/gradient.f90 b/src/gradient.f90 index 9ef0f81..d5b4404 100644 --- a/src/gradient.f90 +++ b/src/gradient.f90 @@ -1,381 +1,638 @@ MODULE gradient_mod USE basis_parameters - DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG - DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG - TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG + DOUBLE PRECISION,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG + DOUBLE PRECISION,POINTER,DIMENSION(:,:) :: CMT_PG + TYPE(gaussianbasisfunction),POINTER,DIMENSION(:) :: PHI_PG INTEGER,POINTER :: NBAST_PG CONTAINS FUNCTION OBJECTIVE(EPS) - USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions + USE esa_mod ; USE metric_nonrelativistic ; USE matrix_tools ; USE common_functions USE matrices - DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM + DOUBLE PRECISION,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM DOUBLE PRECISION :: OBJECTIVE DOUBLE PRECISION, INTENT(IN) :: EPS PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),& &UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG) - PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D') - CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW) - OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG) + CALL BUILDTEFM_RGHF(PTEFM,NBAST_PG,PHI_PG,PDMNEW) + OBJECTIVE=ENERGY_RGHF(POEFM_PG,PTEFM,PDMNEW,NBAST_PG) END FUNCTION OBJECTIVE - FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW) + FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI,INITEPS) RESULT(PDMNEW) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions - USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output + USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output USE esa_mod ; USE optimization_tools IMPLICIT NONE INTEGER :: INFO,LOON INTEGER,INTENT(IN),TARGET :: NBAST DOUBLE PRECISION,DIMENSION(NBAST) :: EIG - DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC - DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc - DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM - DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT - TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI - DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW + DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC + DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc,INITEPS + DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM + DOUBLE PRECISION,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT + TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI + DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST - E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS) - write(*,*) EPS + E = golden(0.D0,INITEPS,INITEPS*2,OBJECTIVE,0.01D0,EPS) + write(*,*) 'Chose eps = ',EPS + write(*,*) 'Had initeps = ',INITEPS PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) - PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') END FUNCTION LINESEARCH_golden ! performs a linesearch about PDM FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions - USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output + USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output USE esa_mod IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST) :: EIG - DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC - DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM - DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT - TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI + DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC + DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM + DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT + TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,INFO,LOON DOUBLE PRECISION :: E,EAFTER,EBEFORE,FIRST_DER,SECOND_DER,EPS,DER_AFTER - DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW - INTEGER,PARAMETER :: N_POINTS = 20 + DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW + INTEGER,PARAMETER :: N_POINTS = 50 DOUBLE PRECISION, DIMENSION(N_POINTS) :: ENERGIES - DOUBLE PRECISION, PARAMETER :: EPS_MIN = 0D0 - DOUBLE PRECISION, PARAMETER :: EPS_MAX = 10D0 + DOUBLE PRECISION, PARAMETER :: EPS_MIN = 0.001D0 + DOUBLE PRECISION, PARAMETER :: EPS_MAX = 0.1D0 CHARACTER(1),PARAMETER :: ALGORITHM = 'E' CHARACTER(1),PARAMETER :: SEARCH_SPACE = 'L' ! compute EPS IF(ALGORITHM == 'F') THEN ! fixed EPS = 0.1 ELSEIF(ALGORITHM == 'E') THEN ! exhaustive search ! energy at PDM PDMNEW=PDM CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) E=ENERGY(POEFM,PTEFM,PDMNEW,NBAST) do I=1,N_POINTS if(SEARCH_SPACE == 'L') THEN eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) ELSE eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) eps = 10**eps END if ! energy at PDM + eps PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) - PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) ENERGIES(I)=ENERGY(POEFM,PTEFM,PDMNEW,NBAST) end do I = MINLOC(ENERGIES,1) if(SEARCH_SPACE == 'L') THEN eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) ELSE eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) eps = 10**eps END if - write(*,*) eps + write(*,*) 'Chose eps',eps END IF PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) - PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') ! uncomment for a roothaan step ! ! Assembly and diagonalization of the Fock matrix ! CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) ! CALL EIGENSOLVER(POEFM+PTEFM,PCFS,NBAST,EIG,EIGVEC,INFO) ! ! Assembly of the density matrix according to the aufbau principle ! CALL CHECKORB(EIG,NBAST,LOON) ! CALL FORMDM(PDMNEW,EIGVEC,NBAST,LOON,LOON+NBE-1) END FUNCTION LINESEARCH END MODULE gradient_mod SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism). ! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output USE esa_mod ; USE gradient_mod IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,LOON,INFO,I DOUBLE PRECISION :: ETOT,ETOT1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM LOGICAL :: NUMCONV ! INITIALIZATION AND PRELIMINARIES ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ALLOCATE(PPM(1:NBAST*(NBAST+1)/2)) ITER=0 PDM=(0.D0,0.D0) PTEFM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) PDM1=PDM CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 5 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 6 4 WRITE(*,*)'(called from subroutine ROOTHAAN)' 5 DEALLOCATE(PDM,PDM1,PTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) STOP ! Gradient algorithm 6 WRITE(*,*) ' ' WRITE(*,*) 'Switching to gradient algorithm' WRITE(*,*) ' ' PDM = THETA(PDM,POEFM,NBAST,PHI,'D') ITER = 0 7 ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! computation of the commutator ! CMT in ON basis = DF - Sm1 F D S CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - & MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) PDM1 = PDM ! PDM by line search - PDM = LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) + ! PDM = LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) GO TO 2 ELSE IF (ITER==200*MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 5 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 7 END IF END SUBROUTINE GRADIENT_relativistic SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism). ! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions - USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output + USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output ; USE gradient_mod IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,INFO,I DOUBLE PRECISION :: ETOT,ETOT1,EPS - DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1 + DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PDM2 LOGICAL :: NUMCONV ! INITIALIZATION AND PRELIMINARIES - ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) + ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PDM2(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ITER=0 PDM=(0.D0,0.D0) PTEFM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! Assembly of the density matrix according to the aufbau principle PDM1 = PDM CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 5 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 6 4 WRITE(*,*)'(called from subroutine ROOTHAAN)' 5 DEALLOCATE(PDM,PDM1,PTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) STOP ! Gradient algorithm 6 WRITE(*,*) ' ' WRITE(*,*) 'Switching to gradient algorithm' WRITE(*,*) ' ' ITER = 0 7 ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! computation of the commutator - EPS = .05 + EPS = 0.15 + + WRITE(*,*) 'HI' + write(142,*) NORM(PDM-PDM1,NBAST,'F') + + PDM2 = PDM1 PDM1 = PDM ! CMT in ON basis = DF - Sm1 F D S CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - & MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) - + + ! PDM = LINESEARCH(CMT,PDM,NBAST,POEFM,PFM,PHI) + ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) + if(ITER > 20) THEN + WRITE(*,*)'nu', 1 - NORM(PDM-PDM1,NBAST,'F')/NORM(PDM1-PDM2,NBAST,'F') + END IF ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) GO TO 2 - ELSE IF (ITER==1000*MAXITR+200) THEN + ELSE IF (ITER==1000) THEN ! Maximum number of iterations reached without convergence GO TO 5 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 7 END IF END SUBROUTINE + +SUBROUTINE GRADIENT_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) +! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism). +! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951. + USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions + USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output ; USE gradient_mod + USE random ; USE setup_tools + IMPLICIT NONE + INTEGER,INTENT(IN) :: NBAST + DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG + DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC + DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM + DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT,CMTCMTCMT,ISRS,CMT1 + TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI + DOUBLE PRECISION,INTENT(IN) :: TRSHLD + INTEGER,INTENT(IN) :: MAXITR + LOGICAL,INTENT(IN) :: RESUME + + INTEGER :: ITER,INFO,I + DOUBLE PRECISION :: ETOT,ETOT1,EPS,DER2,GRAD_STEPSIZE + DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PDM2 + LOGICAL :: NUMCONV + + +! INITIALIZATION AND PRELIMINARIES + ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PDM2(1:NBAST*(NBAST+1)/2)) + ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) + + OPEN(100,FILE=SETUP_FILE) + REWIND(100) + CALL LOOKFOR(100,'GRADIENT STEPSIZE',INFO) + !READ(100,'(/,f16.8)')GRAD_STEPSIZE + READ(100,'(/,f16.8)')GRAD_STEPSIZE + WRITE(*,*) GRAD_STEPSIZE + CLOSE(100) + + ITER=0 + PDM=(0.D0,0.D0) + PTEFM=(0.D0,0.D0) + ETOT1=0.D0 + OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write') + OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write') + OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write') + +! LOOP +1 CONTINUE + ITER=ITER+1 + WRITE(*,'(a)')' ' + WRITE(*,'(a,i3)')'# ITER = ',ITER + + + CALL INIT_RANDOM_SEED + CALL RANDOM_NUMBER(EIGVEC) + + ! Assembly and diagonalization of the Fock matrix + PFM=POEFM+PTEFM + IF(.NOT.(RESUME .AND. ITER == 1)) THEN + CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) + IF (INFO/=0) GO TO 4 + END IF +! Assembly of the density matrix according to the aufbau principle + PDM1 = PDM + CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE) +! Computation of the energy associated to the density matrix + CALL BUILDTEFM_RGHF(PTEFM,NBAST,PHI,PDM) + ETOT=ENERGY_RGHF(POEFM,PTEFM,PDM,NBAST) + WRITE(*,*)'E(D_n)=',ETOT +! Numerical convergence check + CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) + IF (NUMCONV) THEN +! Convergence reached + GO TO 2 + ELSE IF (ITER==MAXITR) THEN +! Maximum number of iterations reached without convergence + GO TO 3 + ELSE +! Convergence not reached, increment + ETOT1=ETOT + GO TO 1 + END IF +! MESSAGES +2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).' + OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') + DO I=1,NBAST + WRITE(9,'(i4,e22.14)')I,EIG(I) + END DO + CLOSE(9) + GO TO 5 +3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).' + OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') + DO I=1,NBAST + WRITE(9,'(i4,e22.14)')I,EIG(I) + END DO + CLOSE(9) + GO TO 6 +4 WRITE(*,*)'(called from subroutine ROOTHAAN)' +5 DEALLOCATE(PDM,PDM1,PTEFM,PFM) + CLOSE(16) ; CLOSE(17) ; CLOSE(18) + STOP + + ! Gradient algorithm +6 WRITE(*,*) ' ' + WRITE(*,*) 'Switching to gradient algorithm' + WRITE(*,*) ' ' + ITER = 0 +7 ITER=ITER+1 + WRITE(*,'(a)')' ' + WRITE(*,'(a,i3)')'# ITER = ',ITER + +! Assembly and diagonalization of the Fock matrix + PFM=POEFM+PTEFM + CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) + IF (INFO/=0) GO TO 4 + + ! computation of the commutator + ! CMT in ON basis = DF - Sm1 F D S + CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - & + MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) + CMTCMT = MATMUL(MATMUL(CMT,UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) - & + &MATMUL(MATMUL(UNPACK(PDM,NBAST),UNPACK(PS,NBAST)),CMT) + CMTCMTCMT = MATMUL(CMT,CMTCMT) - MATMUL(CMTCMT,CMT) + + CALL BUILDTEFM_RGHF(PTEFM,NBAST,PHI,PACK(MATMUL(CMTCMT,UNPACK(PIS,NBAST)),NBAST)) + DER2 = traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),CMTCMTCMT,NBAST) + DER2 = DER2 + traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(PTEFM,NBAST)),CMTCMT,NBAST) + WRITE(*,*) 'der21', traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),CMTCMTCMT,NBAST) + WRITE(*,*) 'der22', traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(PTEFM,NBAST)),CMTCMT,NBAST) + + IF(ITER < 10000) THEN + EPS = NORM(CMT,NBAST,'F')*NORM(CMT,NBAST,'F') / DER2 / 10 + ! IF(EPS > .1) THEN + ! EPS = .1 + ! END IF + ELSE + ! EPS = 0.01 + END IF + write(*,*) GRAD_STEPSIZE + IF(GRAD_STEPSIZE /= 0.D0) THEN + EPS = GRAD_STEPSIZE + END IF + write(*,*) EPS + + + PDM2 = PDM1 + PDM1 = PDM + PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& + UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) + + ! PDM = LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI,EPS) + +! Computation of the energy associated to the density matrix + CALL BUILDTEFM_RGHF(PTEFM,NBAST,PHI,PDM) + ETOT=ENERGY_RGHF(POEFM,PTEFM,PDM,NBAST) + WRITE(*,*)'E(D_n)=',ETOT + ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) + PFM = POEFM+PTEFM + CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - & + MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) + CMTCMT = MATMUL(MATMUL(CMT,UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) - & + &MATMUL(MATMUL(UNPACK(PDM,NBAST),UNPACK(PS,NBAST)),CMT) + WRITE(100,*) ETOT - (-198.46810301852636D0) + WRITE(101,*) NORM(CMTCMT,NBAST,'F') + WRITE(102,*) NORM(PDM-PDM1,NBAST,'F') + FLUSH(100) + FLUSH(101) + WRITE(*,*)'Norm(PDM-PDM1)/Norm(PDM1-PDM2)', NORM(PDM-PDM1,NBAST,'F')/NORM(PDM1-PDM2,NBAST,'F') + WRITE(*,*)'NU', 1.D0 - NORM(PDM-PDM1,NBAST,'F')/NORM(PDM1-PDM2,NBAST,'F') + WRITE(*,*)'CMT', NORM(CMT,NBAST,'F') / NORM(CMT1,NBAST,'F') + CMT1= CMT + + write(*,*) 'Delta E', ENERGY_DIFF_RGHF(POEFM,PDM1,PDM,PHI,NBAST) +! Numerical convergence check + CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) + IF (NUMCONV) THEN +! Convergence reached + ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) + GO TO 2 + ELSE IF (ITER==200) THEN +! Maximum number of iterations reached without convergence + GO TO 5 + ELSE +! Convergence not reached, increment + ETOT1=ETOT + GO TO 7 + END IF +END SUBROUTINE + + +! debug code +FUNCTION DEBUG(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW) + USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions + USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output + USE esa_mod + IMPLICIT NONE + INTEGER,INTENT(IN) :: NBAST + DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM + DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT + TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI + INTEGER :: I + DOUBLE PRECISION :: E,EAFTER,EBEFORE,FIRST_DER,SECOND_DER,EPS,DER_AFTER + DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW + + DOUBLE PRECISION :: EPS_FINDIFF = 1e-0 + + do + ! quadratic model + ! energy at PDM + PDMNEW=PDM + CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) + E=ENERGY(POEFM,PTEFM,PDMNEW,NBAST) + ! energy at PDM + epsilon + PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS_FINDIFF,CMT,NBAST),UNPACK(PDM,NBAST)),& + &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS_FINDIFF,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) + PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') + CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) + EAFTER=ENERGY(POEFM,PTEFM,PDMNEW,NBAST) + + + ! ! CMT*D - D*CMT + CMTCMT = MATMUL(MATMUL(CMT,UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) - & + &MATMUL(MATMUL(UNPACK(PDM,NBAST),UNPACK(PS,NBAST)),CMT) + write(*,*) 'Derivative really equal to CMTCMT?',& + &norm(MATMUL(UNPACK(PDMNEW-PDM,NBAST),UNPACK(PS,NBAST))/EPS_FINDIFF - CMTCMT,NBAST,'F') + write(*,*) 'Tr(F dDds)',REAL(traceofproduct(PFM,(PDMNEW-PDM)/EPS_FINDIFF,NBAST)) + write(*,*) 'Tr(F CMTCMT)',real(traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),CMTCMT,NBAST)) + write(*,*) 'Tr(CMT^2)',REAL(traceofproduct(CMT,CMT,NBAST)) + write(*,*) '(En - En-1)/eps',(EAFTER - E)/EPS_FINDIFF + write(*,*) (EAFTER - E)/EPS_FINDIFF - REAL(traceofproduct(CMT,CMT,NBAST)) + + der_after = real(traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(POEFM+PTEFM,NBAST)),CMTCMT,NBAST)) + first_der = real(traceofproduct(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),CMTCMT,NBAST)) + write(*,*) first_der, der_after + + SECOND_DER = (der_after - first_der)/EPS_FINDIFF + + EPS = - FIRST_DER/SECOND_DER + ! EPS = MAX(EPS,1.D0) + ! write(*,*) 'E = ', E, 'after = ', EAFTER-E, 'before = ', EBEFORE-E + write(*,*) 'First derivative = ', first_der, 'second derivative = ', second_der, 'eps = ',eps + ! write(*,*) first_der + ! write(*,*) -REAL(traceofproduct(CMT,CMT,NBAST)) + ! write(*,*) second_der + ! write(*,*) eps + if(eps_findiff < 1e-10) STOP + write(42,*)eps_findiff, abs((EAFTER - E)/EPS_FINDIFF -& + &REAL(traceofproduct(CMT,CMT,NBAST))),norm(MATMUL(UNPACK(PDMNEW-PDM,NBAST),& + &UNPACK(PS,NBAST))/EPS_FINDIFF - CMTCMT,NBAST,'F') + eps_findiff = eps_findiff / 1.1 + end do +END FUNCTION
antoine-levitt/ACCQUAREL
5932ca29fbb3609799fb422d59d067013bf1c6f4
trace, getenv
diff --git a/src/tools.f90 b/src/tools.f90 index 2105899..d8fe64a 100644 --- a/src/tools.f90 +++ b/src/tools.f90 @@ -83,985 +83,1009 @@ END INTERFACE EXPONENTIAL INTERFACE TRACE MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian END INTERFACE INTERFACE TRACEOFPRODUCT MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian END INTERFACE INTERFACE EIGENSOLVER MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized END INTERFACE INTERFACE COMMUTATOR MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian END INTERFACE INTERFACE PRINTMATRIX MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian,PRINTMATRIX_complex,PRINTMATRIX_real END INTERFACE INTERFACE READMATRIX MODULE PROCEDURE READMATRIX_complex,READMATRIX_real END INTERFACE READMATRIX CONTAINS ! handling of symmetric and hermitian matrices stored in packed form. FUNCTION PACK_symmetric(A,N) RESULT (PA) ! Function that stores the upper triangular part of a symmetric matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=(A(I,J)+A(J,I))/2.D0 END DO END DO END FUNCTION PACK_symmetric FUNCTION PACK_hermitian(A,N) RESULT (PA) ! Function that stores the upper triangular part of a hermitian matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=A(I,J) PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0 END DO END DO END FUNCTION PACK_hermitian FUNCTION UNPACK_symmetric(PA,N) RESULT (A) ! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=PA(1+J:I-1+J) END DO END FUNCTION UNPACK_symmetric FUNCTION UNPACK_hermitian(PA,N) RESULT (A) ! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=CONJG(PA(1+J:I-1+J)) END DO END FUNCTION UNPACK_hermitian FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO END DO END DO END FUNCTION ABA_symmetric FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2)) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO END DO END DO DO I=1,N PC(I*(I+1)/2) = REAL(PC(I*(I+1)/2)) END DO END FUNCTION ABA_hermitian FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N) END FUNCTION ABCBA_symmetric FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD PD=ABA(PA,ABA(PB,PC,N),N) END FUNCTION ABCBA_hermitian FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_symmetric FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_hermitian SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric(PB,PA,N) ! Subroutine that forms the block-diagonal symmetric matrix B of order 2N from a symmetric matrix A of size N, both of which have their upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION, DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION, DIMENSION(N*2*(N*2+1)/2),INTENT(OUT) :: PB DOUBLE PRECISION, DIMENSION(2*N,2*N) :: B B=0.D0 B(1:N,1:N)=UNPACK(PA,N) ; B(N+1:2*N,N+1:2*N)=B(1:N,1:N) PB=PACK(B,2*N) END SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric ! diverse linear algebra routines FUNCTION INVERSE_real(A,N) RESULT(INVA) ! Function that computes the inverse of a square real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N) :: A DOUBLE PRECISION,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK INVA=A CALL DGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_real FUNCTION INVERSE_complex(A,N) RESULT(INVA) ! Function that computes the inverse of a square complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK INVA=A CALL ZGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_complex FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA) ! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK PINVA=PA CALL DSPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_symmetric FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA) ! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK PINVA=PA CALL ZHPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_hermitian FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA) ! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_symmetric FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA) ! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_hermitian FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine DGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_real FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine ZGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_complex +FUNCTION TRACE_real(A,N) RESULT (TRACE) + ! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format. + INTEGER,INTENT(IN) :: N + DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A + DOUBLE PRECISION :: TRACE + + INTEGER :: I + + TRACE=0.D0 + DO I=1,N + TRACE=TRACE+A(I,I) + END DO +END FUNCTION TRACE_real + FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE) ! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION :: TRACE INTEGER :: I TRACE=0.D0 DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_symmetric FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE) ! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX :: TRACE INTEGER :: I TRACE=(0.D0,0.D0) DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_hermitian FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: TRACE INTEGER :: I,J TRACE=0.D0 DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_real FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square complex matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: TRACE INTEGER :: I,J TRACE=(0.D0,0.D0) DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_complex FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION :: TRACE INTEGER :: I,J,IJ,JI TRACE=0.D0 DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*PB(IJ) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+PA(JI)*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_symmetric FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX :: TRACE INTEGER :: I,J,IJ,JI TRACE=(0.D0,0.D0) DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*CONJG(PB(IJ)) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+CONJG(PA(JI))*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_hermitian FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: FIP INTEGER :: I,J FIP=0.D0 DO I=1,N DO J=1,N FIP=FIP+A(I,J)*B(I,J) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_real FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: FIP INTEGER :: I,J FIP=(0.D0,0.D0) DO I=1,N DO J=1,N FIP=FIP+A(I,J)*CONJG(B(I,J)) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_complex SUBROUTINE NORM_check_norm(CHAR) CHARACTER(1),INTENT(IN) :: CHAR IF((CHAR /= 'F') .AND. & &(CHAR /= 'I') .AND. & &(CHAR /= '1') .AND. & &(CHAR /= 'M')) THEN WRITE(*,*) 'Invalid norm' STOP END IF END SUBROUTINE NORM_check_norm FUNCTION NORM_real(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANGE CALL NORM_check_norm(CHAR) NORM = DLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_real FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANGE CALL NORM_check_norm(CHAR) NORM = ZLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_complex FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANSP CALL NORM_check_norm(CHAR) NORM = DLANSP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_symmetric FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANHP CALL NORM_check_norm(CHAR) NORM = ZLANHP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_hermitian SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's DSPGV subroutine. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC INTEGER,INTENT(OUT) :: INFO INTEGER :: I,NEIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP AP=PA ; BP=PCFB ! Transform problem to standard eigenvalue problem and solve CALL DSPGST(1,'U',N,AP,BP,INFO) IF (INFO/=0) GO TO 1 CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GO TO 2 ! Backtransform eigenvectors to the original problem NEIG=N IF (INFO>0) NEIG=INFO-1 DO I=1,NEIG CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1) END DO RETURN ! MESSAGES 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF 3 WRITE(*,*)'(called from subroutine EIGENSOLVER)' RETURN END SUBROUTINE EIGENSOLVER_symmetric_prefactorized SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's ZHPGV subroutine. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC INTEGER,INTENT(OUT) :: INFO INTEGER :: I,NEIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP AP=PA ; BP=PCFB ! Transform problem to standard eigenvalue problem and solve CALL ZHPGST(1,'U',N,AP,BP,INFO) IF (INFO/=0) GO TO 1 CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GO TO 2 ! Backtransform eigenvectors to the original problem NEIG=N IF (INFO>0) NEIG=INFO-1 DO I=1,NEIG CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1) END DO RETURN ! MESSAGES 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF 3 WRITE(*,*)'(called from subroutine EIGENSOLVER)' RETURN END SUBROUTINE EIGENSOLVER_hermitian_prefactorized FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C) ! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS DOUBLE PRECISION,DIMENSION(N,N) :: C DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N) C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A)) END FUNCTION COMMUTATOR_symmetric FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C) ! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS DOUBLE COMPLEX,DIMENSION(N,N) :: C DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N) C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A)) END FUNCTION COMMUTATOR_hermitian ! input/output routines for matrices SUBROUTINE READMATRIX_real(MAT,N,LOGUNIT) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: MAT INTEGER :: I DOUBLE PRECISION,DIMENSION(N) :: LINE DO I=1,N READ(LOGUNIT,*)LINE MAT(I,:)=LINE END DO END SUBROUTINE READMATRIX_REAL SUBROUTINE READMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: MAT DOUBLE PRECISION,DIMENSION(N,N) :: R,I CALL READMATRIX_real(R,N,LOGUNIT_REAL) CALL READMATRIX_real(I,N,LOGUNIT_IMAG) MAT=DCMPLX(R,I) END SUBROUTINE READMATRIX_complex SUBROUTINE PRINTMATRIX_real(MAT,N,LOGUNIT) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: MAT INTEGER :: I DO I=1,N WRITE(LOGUNIT,*)MAT(I,:) END DO END SUBROUTINE PRINTMATRIX_real SUBROUTINE PRINTMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: MAT INTEGER :: I DO I=1,N IF (LOGUNIT_REAL==LOGUNIT_IMAG) THEN WRITE(LOGUNIT_REAL,*)MAT(I,:) ELSE WRITE(LOGUNIT_REAL,*)REAL(MAT(I,:)) WRITE(LOGUNIT_IMAG,*)AIMAG(MAT(I,:)) END IF END DO END SUBROUTINE PRINTMATRIX_complex SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT CALL PRINTMATRIX_real(UNPACK(PMAT,N),N,LOGUNIT) END SUBROUTINE PRINTMATRIX_symmetric SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT CALL PRINTMATRIX_complex(UNPACK(PMAT,N),N,LOGUNIT_REAL,LOGUNIT_IMAG) END SUBROUTINE PRINTMATRIX_hermitian END MODULE matrix_tools MODULE mathematical_functions INTERFACE DFACT MODULE PROCEDURE DOUBLE_FACTORIAL END INTERFACE CONTAINS FUNCTION FACTORIAL(N) RESULT(FACT) IMPLICIT NONE INTEGER,INTENT(IN) :: N INTEGER :: FACT INTEGER :: I IF (N<0) THEN STOP'Function FACTORIAL: the factorial is undefined for negative integers.' ELSE FACT=1 IF (N>1) THEN DO I=2,N FACT=FACT*I END DO END IF END IF END FUNCTION FACTORIAL FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT) IMPLICIT NONE INTEGER,INTENT(IN) :: N INTEGER :: DFACT INTEGER :: I IF (N<-1) THEN STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.' ELSE DFACT=1 IF (N>1) THEN I=N DO WHILE (I>1) DFACT=DFACT*I I=I-2 END DO END IF END IF END FUNCTION DOUBLE_FACTORIAL END MODULE MODULE setup_tools ! name of the setup file CHARACTER(100) :: SETUP_FILE CONTAINS SUBROUTINE SETUP_FILENAME ! Subroutine that retrieves the name of the setup file CALL GETARG(1,SETUP_FILE) IF (SETUP_FILE=='') SETUP_FILE='setup' END SUBROUTINE SETUP_FILENAME SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO) ! Subroutine that looks for a given text string in an open unit. IMPLICIT NONE INTEGER,INTENT(IN) :: NUNIT INTEGER,INTENT(OUT) :: INFO CHARACTER(*),INTENT(IN) :: SUBSTRING CHARACTER(80) :: STRING INFO=0 1 READ(100,'(a)',ERR=2,END=2) STRING IF (INDEX(STRING,SUBSTRING)==0) GOTO 1 RETURN 2 INFO=1 END SUBROUTINE LOOKFOR + + +FUNCTION GETENV(STR) RESULT(RES) + CHARACTER(*),INTENT(IN) :: STR + CHARACTER(40) :: RESSTR + DOUBLE PRECISION :: RES + CALL GET_ENVIRONMENT_VARIABLE(STR,RESSTR) + READ(RESSTR,*), RES +END FUNCTION GETENV + END MODULE
antoine-levitt/ACCQUAREL
659ea9fa2ad1c696004054148c1e1f798419eab2
Added commentaries about the implementation of the DIIS scheme (nothing is changed in the code)
diff --git a/src/diis.f90 b/src/diis.f90 index 0847383..82b8409 100644 --- a/src/diis.f90 +++ b/src/diis.f90 @@ -1,454 +1,457 @@ SUBROUTINE DIIS_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! DIIS (Direct Inversion in the Iterative Subspace) algorithm (relativistic case) ! Reference: P. Pulay, Convergence acceleration of iterative sequences. The case of SCF iteration, Chem. Phys. Lett., 73(2), 393-398, 1980. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,LOON,INFO,I,J,IJ,K INTEGER :: MXSET,MSET,MM INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV DOUBLE PRECISION :: ETOT,ETOT1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PTDM,PBM,DIISV DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: PDMSET,TMP,ISRS DOUBLE COMPLEX,DIMENSION(:,:,:),ALLOCATABLE :: ERRSET LOGICAL :: NUMCONV ! INITIALIZATIONS AND PRELIMINARIES ! Reading of the maximum dimension of the density matrix simplex OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) READ(100,'(/,i2)')MXSET CLOSE(100) ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ALLOCATE(ERRSET(1:MXSET,1:NBAST,1:NBAST),PDMSET(1:MXSET,1:NBAST*(NBAST+1)/2)) ALLOCATE(ISRS(1:NBAST,1:NBAST),TMP(1:NBAST,1:NBAST)) ISRS=UNPACK(PISRS,NBAST) ITER=0 MSET=0 ; PDMSET=(0.D0,0.D0) IF (RESUME) THEN CALL CHECKORB(EIG,NBAST,LOON) CALL FORMDM(PTDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ELSE PTDM=(0.D0,0.D0) ETOT1=0.D0 END IF OPEN(16,FILE='plots/diisenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/diiscrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/diiscrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the total energy CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check IF (ITER==1) THEN CALL CHECKNUMCONV(PDM,PDMSET(1,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) ELSE CALL CHECKNUMCONV(PDM,PDMSET(MSET,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) END IF IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT ! Storage of the current density matrix, computation and storage of a new DIIS error vector IF (MSET==MXSET) THEN ! we have reached the maximum allowed dimension for the simplex PDMSET=EOSHIFT(PDMSET,SHIFT=1) ! elimination of the oldest stored density matrix ERRSET=EOSHIFT(ERRSET,SHIFT=1) ! elimination of the oldest stored error vector ELSE MSET=MSET+1 ! the current dimension of the simplex is increased by one END IF PDMSET(MSET,:)=PDM ERRSET(MSET,:,:)=COMMUTATOR(POEFM+PTEFM,PDMSET(MSET,:),PS,NBAST) IF (ITER==1) THEN PTDM=PDM ELSE -! TO DO: check LINEAR DEPENDENCE??? WRITE(*,*)'Dimension of the density matrix simplex =',MSET ! Computation of the new pseudo-density matrix ! assembly and solving of the linear system associated to the DIIS equations MM=(MSET+1)*(MSET+2)/2 ALLOCATE(PBM(1:MM)) PBM=(0.D0,0.D0) ; PBM(MM-MSET:MM-1)=(-1.D0,0.D0) IJ=0 DO J=1,MSET DO I=1,J IJ=IJ+1 ; PBM(IJ)=& &FINNERPRODUCT(MATMUL(ISRS,MATMUL(ERRSET(J,:,:),ISRS)),MATMUL(ISRS,MATMUL(ERRSET(I,:,:),ISRS)),NBAST) END DO END DO ALLOCATE(DIISV(1:MSET+1)) DIISV(1:MSET)=(0.D0,0.D0) ; DIISV(MSET+1)=(-1.D0,0.D0) ALLOCATE(IPIV(1:MSET+1)) CALL ZHPSV('U',MSET+1,1,PBM,IPIV,DIISV,MSET+1,INFO) DEALLOCATE(IPIV,PBM) IF (INFO/=0) GO TO 4 +! TO DO: If the procedure fails, the data from the oldest iterations should be thrown out until the system of equations becomes solvable. ! assembly of the pseudo-density matrix PTDM=(0.D0,0.D0) DO I=1,MSET PTDM=PTDM+DIISV(I)*PDMSET(I,:) END DO DEALLOCATE(DIISV) +! Note that, sometimes, some of the coefficients are negative, so that the extrapolated density matrix does not belong to the convex set. However, there seems to be no benefit of constraining coefficients over a convex set within the DIIS scheme (see Kudin, Scuseria, Cancès 2002). END IF GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: no convergence after',MAXITR,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) GO TO 6 4 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPSV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPSV: the factorization has been completed, but the block diagonal matrix is & &exactly singular, so the solution could not be computed' END IF GO TO 5 5 WRITE(*,*)'(called from subroutine DIIS)' 6 DEALLOCATE(PDM,PTDM,PDMSET,PTEFM,PFM,TMP,ISRS,ERRSET) CLOSE(16) ; CLOSE(17) ; CLOSE(18) END SUBROUTINE DIIS_relativistic SUBROUTINE DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! DIIS (Direct Inversion in the Iterative Subspace) algorithm (restricted closed-shell Hartree-Fock formalism) ! Reference: P. Pulay, Convergence acceleration of iterative sequences. The case of SCF iteration, Chem. Phys. Lett., 73(2), 393-398, 1980. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE setup_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,INFO,I,J,IJ,K INTEGER :: MXSET,MSET,MM INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV DOUBLE PRECISION :: ETOT,ETOT1 DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PTDM,PBM,DIISV DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ERRSET,PDMSET,TMP LOGICAL :: NUMCONV ! INITIALIZATIONS AND PRELIMINARIES ! Reading of the maximum dimension of the density matrix simplex OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) READ(100,'(/,i2)')MXSET CLOSE(100) ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ALLOCATE(ERRSET(1:MXSET,1:NBAST*NBAST),PDMSET(1:MXSET,1:NBAST*(NBAST+1)/2),TMP(1:NBAST,1:NBAST)) ITER=0 MSET=0 ; PDMSET=0.D0 PTDM=0.D0 ETOT1=0.D0 OPEN(16,FILE='plots/diisenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/diiscrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/diiscrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTEFM IF(.NOT.(RESUME .AND. ITER == 1)) THEN CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 END IF ! Assembly of the density matrix according to the aufbau principle CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2) ! Computation of the total energy CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'Total energy =',ETOT ! Numerical convergence check IF (ITER==1) THEN CALL CHECKNUMCONV(PDM,PDMSET(1,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) ELSE CALL CHECKNUMCONV(PDM,PDMSET(MSET,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) END IF IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT ! Storage of the current density matrix, computation and storage of a new DIIS error vector IF (MSET==MXSET) THEN ! we have reached the maximum allowed dimension for the simplex PDMSET=EOSHIFT(PDMSET,SHIFT=1) ! elimination of the oldest stored density matrix ERRSET=EOSHIFT(ERRSET,SHIFT=1) ! elimination of the oldest stored error vector ELSE MSET=MSET+1 ! the current dimension of the simplex is increased by one END IF PDMSET(MSET,:)=PDM TMP=COMMUTATOR(POEFM+PTEFM,PDMSET(MSET,:),PS,NBAST) IJ=0 DO I=1,NBAST DO J=1,NBAST IJ=IJ+1 ERRSET(MSET,IJ)=TMP(I,J) END DO END DO IF (ITER==1) THEN PTDM=PDM ELSE -! TO DO: check LINEAR DEPENDENCE by computing a Gram determinant?? WRITE(*,*)'Dimension of the density matrix simplex =',MSET ! Computation of the new pseudo-density matrix ! assembly and solving of the linear system associated to the DIIS equations MM=(MSET+1)*(MSET+2)/2 ALLOCATE(PBM(1:MM)) PBM=0.D0 ; PBM(MM-MSET:MM-1)=-1.D0 IJ=0 DO J=1,MSET DO I=1,J IJ=IJ+1 ; PBM(IJ)=PBM(IJ)+DOT_PRODUCT(ERRSET(J,:),ERRSET(I,:)) END DO END DO ALLOCATE(DIISV(1:MSET+1)) DIISV(1:MSET)=0.D0 ; DIISV(MSET+1)=-1.D0 ALLOCATE(IPIV(1:MSET+1)) CALL DSPSV('U',MSET+1,1,PBM,IPIV,DIISV,MSET+1,INFO) DEALLOCATE(IPIV,PBM) IF (INFO/=0) GO TO 4 +! TO DO: If the procedure fails, the data from the oldest iterations should be thrown out until the system of equations becomes solvable. ! assembly of the pseudo-density matrix PTDM=0.D0 DO I=1,MSET PTDM=PTDM+DIISV(I)*PDMSET(I,:) END DO DEALLOCATE(DIISV) +! Note: sometimes, some of the coefficients are negative, so that the extrapolated density matrix does not belong to the convex set. However, there seems to be no benefit of constraining coefficients over a convex set within the DIIS scheme (see Kudin, Scuseria, Cancès 2002). END IF GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: no convergence after',MAXITR,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) GO TO 6 4 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPSV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPSV: the factorization has been completed, but the block diagonal matrix is & &exactly singular, so the solution could not be computed' END IF GO TO 5 5 WRITE(*,*)'(called from subroutine DIIS)' 6 DEALLOCATE(PDM,PTDM,PDMSET,PTEFM,PFM,TMP,ERRSET) CLOSE(16) ; CLOSE(17) ; CLOSE(18) END SUBROUTINE DIIS_RHF SUBROUTINE DIIS_RGHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! DIIS (Direct Inversion in the Iterative Subspace) algorithm (real general Hartree-Fock formalism) ! Reference: P. Pulay, Convergence acceleration of iterative sequences. The case of SCF iteration, Chem. Phys. Lett., 73(2), 393-398, 1980. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE setup_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,INFO,I,J,IJ,K INTEGER :: MXSET,MSET,MM INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV DOUBLE PRECISION :: ETOT,ETOT1 DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PTDM,PBM,DIISV DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: ERRSET,PDMSET,TMP LOGICAL :: NUMCONV ! INITIALIZATIONS AND PRELIMINARIES ! Reading of the maximum dimension of the density matrix simplex OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) READ(100,'(/,i2)')MXSET CLOSE(100) ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ALLOCATE(ERRSET(1:MXSET,1:NBAST*NBAST),PDMSET(1:MXSET,1:NBAST*(NBAST+1)/2),TMP(1:NBAST,1:NBAST)) ITER=0 MSET=0 ; PDMSET=0.D0 PTDM=0.D0 ETOT1=0.D0 OPEN(16,FILE='plots/diisenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/diiscrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/diiscrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix CALL BUILDTEFM_RGHF(PTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTEFM IF(.NOT.(RESUME .AND. ITER == 1)) THEN CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 END IF ! Assembly of the density matrix according to the aufbau principle CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE) ! Computation of the total energy CALL BUILDTEFM_RGHF(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY_RGHF(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'Total energy =',ETOT ! Numerical convergence check IF (ITER==1) THEN CALL CHECKNUMCONV(PDM,PDMSET(1,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) ELSE CALL CHECKNUMCONV(PDM,PDMSET(MSET,:),POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) END IF IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT ! Storage of the current density matrix, computation and storage of a new DIIS error vector IF (MSET==MXSET) THEN ! we have reached the maximum allowed dimension for the simplex PDMSET=EOSHIFT(PDMSET,SHIFT=1) ! elimination of the oldest stored density matrix ERRSET=EOSHIFT(ERRSET,SHIFT=1) ! elimination of the oldest stored error vector ELSE MSET=MSET+1 ! the current dimension of the simplex is increased by one END IF PDMSET(MSET,:)=PDM TMP=COMMUTATOR(POEFM+PTEFM,PDMSET(MSET,:),PS,NBAST) IJ=0 DO I=1,NBAST DO J=1,NBAST IJ=IJ+1 ERRSET(MSET,IJ)=TMP(I,J) END DO END DO IF (ITER==1) THEN PTDM=PDM ELSE -! TO DO: check LINEAR DEPENDENCE by computing a Gram determinant?? WRITE(*,*)'Dimension of the density matrix simplex =',MSET ! Computation of the new pseudo-density matrix ! assembly and solving of the linear system associated to the DIIS equations MM=(MSET+1)*(MSET+2)/2 ALLOCATE(PBM(1:MM)) PBM=0.D0 ; PBM(MM-MSET:MM-1)=-1.D0 IJ=0 DO J=1,MSET DO I=1,J IJ=IJ+1 ; PBM(IJ)=PBM(IJ)+DOT_PRODUCT(ERRSET(J,:),ERRSET(I,:)) END DO END DO ALLOCATE(DIISV(1:MSET+1)) DIISV(1:MSET)=0.D0 ; DIISV(MSET+1)=-1.D0 ALLOCATE(IPIV(1:MSET+1)) CALL DSPSV('U',MSET+1,1,PBM,IPIV,DIISV,MSET+1,INFO) DEALLOCATE(IPIV,PBM) IF (INFO/=0) GO TO 4 +! TO DO: If the procedure fails, the data from the oldest iterations should be thrown out until the system of equations becomes solvable. ! assembly of the pseudo-density matrix PTDM=0.D0 DO I=1,MSET PTDM=PTDM+DIISV(I)*PDMSET(I,:) END DO DEALLOCATE(DIISV) +! Note: sometimes, some of the coefficients are negative, so that the extrapolated density matrix does not belong to the convex set. However, there seems to be no benefit of constraining coefficients over a convex set within the DIIS scheme (see Kudin, Scuseria, Cancès 2002). END IF GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine DIIS: no convergence after',MAXITR,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) GO TO 6 4 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPSV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPSV: the factorization has been completed, but the block diagonal matrix is & &exactly singular, so the solution could not be computed' END IF GO TO 5 5 WRITE(*,*)'(called from subroutine DIIS)' 6 DEALLOCATE(PDM,PTDM,PDMSET,PTEFM,PFM,TMP,ERRSET) CLOSE(16) ; CLOSE(17) ; CLOSE(18) END SUBROUTINE DIIS_RGHF
antoine-levitt/ACCQUAREL
4b6cdf9d8651c2c62a86ee08de1f880aa297b0f1
moved matrix sign function to the matrix_tools module and added reference
diff --git a/src/esa.f90 b/src/esa.f90 index 0e2d952..5651152 100644 --- a/src/esa.f90 +++ b/src/esa.f90 @@ -1,294 +1,264 @@ MODULE esa_mod USE basis_parameters INTEGER,POINTER :: NBAST_P DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_P,PTDM_P,PDMDIF_P TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_P CHARACTER,POINTER :: METHOD_P CONTAINS FUNCTION THETA(PDM,POEFM,N,PHI,METHOD) RESULT (PDMNEW) ! Function that computes the value of $\Theta(D)$ (with $D$ a hermitian matrix of size N, which upper triangular part is stored in packed form in PDM) with precision TOL (if the (geometrical) convergence of the fixed-point iterative sequence is attained), \Theta being the function defined in: A new definition of the Dirac-Fock ground state, Eric Séré, preprint (2009). USE case_parameters ; USE basis_parameters ; USE matrices USE matrix_tools ; USE metric_relativistic USE debug IMPLICIT NONE CHARACTER,INTENT(IN) :: METHOD INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDM,POEFM TYPE(twospinor),DIMENSION(N),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDMNEW INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-8 INTEGER :: ITER,INFO,LOON DOUBLE PRECISION :: RESIDUAL DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PTEFM,PFM,PDMOLD,PPROJM - DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF + DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF,TMP,ISRS IF (METHOD=='N') THEN PDMNEW = PDM RETURN END IF ITER=0 PDMOLD=PDM IF (THETA_CHECK) THEN WRITE(13,*)'tr(SD)=',REAL(TRACEOFPRODUCT(PS,PDM,N)) ! PTMP=PDM ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF ! Fixed-point iterative sequence DO ITER=ITER+1 ! Projection of the current density matrix CALL BUILDTEFM(PTEFM,N,PHI,PDMOLD) PFM=POEFM+PTEFM IF (METHOD=='D') THEN ! computation of the "positive" spectral projector associated to the Fock matrix based on the current density matrix via diagonalization CALL EIGENSOLVER(PFM,PCFS,N,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 1 CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-C*C)) PDMNEW=ABCBA(PPROJM,PS,PDMOLD,N) ELSEIF(METHOD=='S') THEN ! OR -! computation of the "positive" spectral projector via the sign function obtained by polynomial recursion - DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+C*C*PS,N) +! computation of the "positive" spectral projector via the sign function + DM=UNPACK(PDMOLD,N) ; TMP=UNPACK(PFM+C*C*PS,N) ; ISRS=UNPACK(PISRS,N) + SF=SIGN_FUNCTION(MATMUL(UNPACK(PIS,N),TMP)/NORM(MATMUL(ISRS,MATMUL(TMP,ISRS)),N,'F'),N) TSF=TRANSPOSE(CONJG(SF)) PDMNEW=PACK((DM+MATMUL(DM,TSF)+MATMUL(SF,DM+MATMUL(DM,TSF)))/4.D0,N) END IF IF (THETA_CHECK) THEN WRITE(13,*)'Iter #',ITER WRITE(13,*)'tr(SPSDSP)=',REAL(TRACEOFPRODUCT(PS,PDMNEW,N)) ! PTMP=PDMNEW ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF IF (THETA_CHECK) WRITE(13,*)'Residual =',NORM(ABA(PSRS,PDMNEW-PDMOLD,N),N,'I') RESIDUAL=NORM(PDMNEW-PDMOLD,N,'I') IF (RESIDUAL<TOL) THEN IF (THETA_CHECK) THEN WRITE(13,'(a,i3,a)')' Function THETA: convergence after ',ITER,' iteration(s).' WRITE(13,*)ITER,RESIDUAL END IF RETURN ELSE IF (ITER>=ITERMAX) THEN WRITE(*,*)'Warning in function THETA: no convergence after ',ITER,' iteration(s) (the residual is ',RESIDUAL,').' IF (THETA_CHECK) THEN WRITE(13,*)'Function THETA: no convergence after ',ITER,' iteration(s).' WRITE(13,*)'Residual =',RESIDUAL END IF RETURN END IF PDMOLD=PDMNEW END DO 1 WRITE(*,*)'(called from subroutine THETA)' END FUNCTION THETA - -FUNCTION SIGN(PA,N) RESULT (SA) -! Function that computes the sign function of the hermitian matrix of a selfadjoint operator, which upper triangular part is stored in packed form, using a polynomial recursion (PINVS contains the inverse of the overlap matrix, which upper triangular part is stored in packed form). -! Note: the result is an unpacked matrix due to subsequent use. - USE matrix_tools ; USE metric_relativistic - IMPLICIT NONE - INTEGER,INTENT(IN) :: N - DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA - DOUBLE COMPLEX,DIMENSION(N,N) :: SA - - DOUBLE COMPLEX,DIMENSION(N,N) :: A,ISRS - - INTEGER,PARAMETER :: ITERMAX=50 - DOUBLE PRECISION,PARAMETER :: TOL=1.D-15 - INTEGER :: I,ITER - - A=UNPACK(PA,N) ; ISRS=UNPACK(PISRS,N) - SA=MATMUL(UNPACK(PIS,N),A)/NORM(MATMUL(ISRS,MATMUL(A,ISRS)),N,'F') - ITER=0 - DO - ITER=ITER+1 - A=SA - SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0 - IF (NORM(SA-A,N,'F')<TOL) THEN - RETURN - ELSE IF (ITER==ITERMAX) THEN - WRITE(*,*)'Function SIGN: no convergence after ',ITER,' iteration(s).' - STOP - END IF - END DO -END FUNCTION SIGN END MODULE FUNCTION DFE(LAMBDA) RESULT (ETOT) USE common_functions ; USE matrices ; USE matrix_tools ; USE esa_mod IMPLICIT NONE DOUBLE PRECISION,INTENT(IN) :: LAMBDA DOUBLE PRECISION :: ETOT DOUBLE COMPLEX,DIMENSION(NBAST_P*(NBAST_P+1)/2) :: PDM,PTEFM,PTMP PDM=THETA(PTDM_P+LAMBDA*PDMDIF_P,POEFM_P,NBAST_P,PHI_P,METHOD_P) CALL BUILDTEFM(PTEFM,NBAST_P,PHI_P,PDM) ETOT=ENERGY(POEFM_P,PTEFM,PDM,NBAST_P) END FUNCTION DFE SUBROUTINE ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Eric Séré's Algorithm USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools USE optimization_tools ; USE esa_mod USE debug IMPLICIT NONE INTEGER,INTENT(IN),TARGET :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME CHARACTER,TARGET :: METHOD INTEGER :: ITER,LOON,INFO,I,NUM DOUBLE PRECISION :: ALPHA,BETA,LAMBDA DOUBLE PRECISION :: DPDUMMY,TOL DOUBLE PRECISION :: ETOT,ETOT1,ETTOT,PDMDIFNORM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: PTDM,PDMDIF LOGICAL :: NUMCONV INTERFACE DOUBLE PRECISION FUNCTION DFE(LAMBDA) DOUBLE PRECISION,INTENT(IN) :: LAMBDA END FUNCTION END INTERFACE ! INITIALIZATIONS AND PRELIMINARIES OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) READ(100,'(/,a)')METHOD CLOSE(100) IF (METHOD=='D') THEN WRITE(*,*)'Function $Theta$ computed using diagonalization' ELSEIF(METHOD=='S') THEN - WRITE(*,*)'Function $Theta$ computed using polynomial recursion' + WRITE(*,*)'Function $Theta$ computed using matrix sign function' ELSE WRITE(*,*)'Function $Theta$ ignored' END IF ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ! Pointer assignments NBAST_P=>NBAST ; POEFM_P=>POEFM ; PTDM_P=>PTDM ; PDMDIF_P=>PDMDIF ; PHI_P=>PHI ; METHOD_P=>METHOD ITER=0 TOL=1.D-4 PDM=(0.D0,0.D0) ; PTDM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/esaenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/esacrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/esacrit2.txt',STATUS='unknown',ACTION='write') OPEN(19,FILE='plots/esaenrgyt.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) PDM1=PDM CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! test ERIC ! PFM=POEFM+PTEFM ! CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) ! CALL CHECKORB(EIG,NBAST,LOON) ! computation of the positive spectral projector associated to PFM ! CALL FORMDM(PTMP,EIGVEC,NBAST,LOON,NBAST) ! infinity norm of the commutator between PFM and its positive spectral projector ! WRITE(44,*)ITER,NORM(COMMUTATOR(POEFM+PTEFM,PTMP,PS,NBAST),NBAST,'I') ! fin test ERIC ! Computation of the pseudo density matrix IF (THETA_CHECK) WRITE(13,*)'theta(D-~D)' PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD) PDMDIFNORM=NORM(ABA(PSRS,PDMDIF,NBAST),NBAST,'I') WRITE(*,*)'Infinity norm of the difference D_{n-1}-~D_{n-2}=',PDMDIFNORM IF (PDMDIFNORM<=TRSHLD) GO TO 2 BETA=REAL(TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)) write(*,*)'beta=',beta IF (BETA>0.D0) THEN WRITE(*,*)'Warning: internal computation error (beta>0).' GO TO 4 ELSE CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF) ALPHA=REAL(TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)) write(*,*)'alpha=',alpha IF (ALPHA>0.D0) THEN LAMBDA=-BETA/ALPHA IF (LAMBDA<1.D0) THEN WRITE(*,*)'lambda=',LAMBDA ! on peut raffiner avec la methode de la section doree (la fonction n'etant a priori pas quadratique), voir comment optimiser un peu cela... ! WRITE(*,*)'refinement using golden section search (',0.D0,',',LAMBDA,',',1.D0,')' ! DPDUMMY=GOLDEN(0.D0,LAMBDA,1.D0,DFE,TOL,LAMBDA) IF (THETA_CHECK) WRITE(13,*)'theta(~D+s(D-~D))' PTDM=THETA(PTDM+LAMBDA*PDMDIF,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) END IF ELSE IF (ALPHA<0.D0) THEN WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'Warning: internal computation error (alpha=0).' GO TO 4 END IF END IF ! Trace of the pseudo density matrix WRITE(*,*)'tr(tilde{D}_n)=',REAL(TRACE(ABA(PSRS,PTDM,NBAST),NBAST)) ! Energy associated to the pseudo density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST) WRITE(19,*)ETTOT WRITE(*,*)'E(tilde{D}_n)=',ETTOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: convergence after',ITER,'iteration(s).' GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: no convergence after',ITER,'iteration(s).' GO TO 6 4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: computation stopped after',ITER,'iteration(s).' GO TO 6 5 WRITE(*,*)'(called from subroutine ESA)' GO TO 7 6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) 7 NULLIFY(NBAST_P,POEFM_P,PTDM_P,PDMDIF_P,PHI_P) DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) ; CLOSE(19) END SUBROUTINE ESA diff --git a/src/tools.f90 b/src/tools.f90 index 2105899..c32f932 100644 --- a/src/tools.f90 +++ b/src/tools.f90 @@ -1,1003 +1,1033 @@ MODULE constants DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0 ! speed of light in the vacuum in atomic units (for the relativistic case) ! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006. DOUBLE PRECISION,PARAMETER :: SPEED_OF_LIGHT=137.035999967994D0 END MODULE MODULE random CONTAINS SUBROUTINE INIT_RANDOM_SEED() ! Initialization of the seed of the pseudorandom number generator used by RANDOM_NUMBER based on the system's time (this routine must be called once). IMPLICIT NONE INTEGER :: I,N,CLOCK INTEGER,DIMENSION(:),ALLOCATABLE :: SEED CALL RANDOM_SEED(SIZE=N) ALLOCATE(SEED(N)) CALL SYSTEM_CLOCK(COUNT=CLOCK) SEED=CLOCK+37*(/(I-1,I=1,N)/) CALL RANDOM_SEED(PUT=SEED) DEALLOCATE(SEED) END SUBROUTINE INIT_RANDOM_SEED FUNCTION GET_RANDOM(N) RESULT(RANDOM_ARRAY) ! Function that returns an array of random numbers of size N in (0, 1) IMPLICIT NONE INTEGER,INTENT(IN) :: N REAL,DIMENSION(N) :: RANDOM_ARRAY CALL RANDOM_NUMBER(RANDOM_ARRAY) END FUNCTION GET_RANDOM END MODULE random MODULE matrix_tools INTERFACE PACK MODULE PROCEDURE PACK_symmetric,PACK_hermitian END INTERFACE INTERFACE UNPACK MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian END INTERFACE INTERFACE ABA MODULE PROCEDURE ABA_symmetric,ABA_hermitian END INTERFACE INTERFACE ABCBA MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian END INTERFACE INTERFACE ABC_CBA MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian END INTERFACE INTERFACE BUILD_BLOCK_DIAGONAL MODULE PROCEDURE BUILD_BLOCK_DIAGONAL_symmetric END INTERFACE BUILD_BLOCK_DIAGONAL INTERFACE FINNERPRODUCT MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex END INTERFACE INTERFACE NORM MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian END INTERFACE INTERFACE INVERSE MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian END INTERFACE +INTERFACE SIGN_FUNCTION + MODULE PROCEDURE SIGN_FUNCTION_complex +END INTERFACE + INTERFACE SQUARE_ROOT MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian END INTERFACE INTERFACE EXPONENTIAL MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex END INTERFACE EXPONENTIAL INTERFACE TRACE MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian END INTERFACE INTERFACE TRACEOFPRODUCT MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian END INTERFACE INTERFACE EIGENSOLVER MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized END INTERFACE INTERFACE COMMUTATOR MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian END INTERFACE INTERFACE PRINTMATRIX MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian,PRINTMATRIX_complex,PRINTMATRIX_real END INTERFACE INTERFACE READMATRIX MODULE PROCEDURE READMATRIX_complex,READMATRIX_real END INTERFACE READMATRIX CONTAINS ! handling of symmetric and hermitian matrices stored in packed form. FUNCTION PACK_symmetric(A,N) RESULT (PA) ! Function that stores the upper triangular part of a symmetric matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=(A(I,J)+A(J,I))/2.D0 END DO END DO END FUNCTION PACK_symmetric FUNCTION PACK_hermitian(A,N) RESULT (PA) ! Function that stores the upper triangular part of a hermitian matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=A(I,J) PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0 END DO END DO END FUNCTION PACK_hermitian FUNCTION UNPACK_symmetric(PA,N) RESULT (A) ! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=PA(1+J:I-1+J) END DO END FUNCTION UNPACK_symmetric FUNCTION UNPACK_hermitian(PA,N) RESULT (A) ! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=CONJG(PA(1+J:I-1+J)) END DO END FUNCTION UNPACK_hermitian FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO END DO END DO END FUNCTION ABA_symmetric FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2)) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO END DO END DO DO I=1,N PC(I*(I+1)/2) = REAL(PC(I*(I+1)/2)) END DO END FUNCTION ABA_hermitian FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N) END FUNCTION ABCBA_symmetric FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD PD=ABA(PA,ABA(PB,PC,N),N) END FUNCTION ABCBA_hermitian FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_symmetric FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_hermitian SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric(PB,PA,N) ! Subroutine that forms the block-diagonal symmetric matrix B of order 2N from a symmetric matrix A of size N, both of which have their upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION, DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION, DIMENSION(N*2*(N*2+1)/2),INTENT(OUT) :: PB DOUBLE PRECISION, DIMENSION(2*N,2*N) :: B B=0.D0 B(1:N,1:N)=UNPACK(PA,N) ; B(N+1:2*N,N+1:2*N)=B(1:N,1:N) PB=PACK(B,2*N) END SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric ! diverse linear algebra routines FUNCTION INVERSE_real(A,N) RESULT(INVA) ! Function that computes the inverse of a square real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N) :: A DOUBLE PRECISION,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK INVA=A CALL DGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_real FUNCTION INVERSE_complex(A,N) RESULT(INVA) ! Function that computes the inverse of a square complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK INVA=A CALL ZGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_complex FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA) ! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK PINVA=PA CALL DSPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_symmetric FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA) ! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK PINVA=PA CALL ZHPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_hermitian +FUNCTION SIGN_FUNCTION_complex(A,N) RESULT (SA) +! Function that computes the sign function of a complex square matrix, which is supposed to have no eigenvalues on the imaginary axis (so that the function is defined), by the Newton--Schulz iteration. +! Reference: Günther Schulz, Iterative Berechnung der reziproken Matrix, Z. Angew. Math. Mech., 13, 57-59, 1933. + IMPLICIT NONE + INTEGER,INTENT(IN) :: N + DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A + DOUBLE COMPLEX,DIMENSION(N,N) :: SA + + INTEGER,PARAMETER :: ITERMAX=50 + DOUBLE PRECISION,PARAMETER :: TOL=1.D-15 + INTEGER :: I,ITER + DOUBLE COMPLEX,DIMENSION(N,N) :: OLDSA + + ITER=0 ; SA=A + DO + ITER=ITER+1 ; OLDSA=SA + SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0 + IF (NORM(SA-OLDSA,N,'F')<TOL) THEN + RETURN + ELSE IF (ITER==ITERMAX) THEN + WRITE(*,*)'Function SIGN_FUNCTION: no convergence after ',ITER,' iteration(s).' + STOP + END IF + END DO +END FUNCTION SIGN_FUNCTION_complex + FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA) ! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_symmetric FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA) ! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_hermitian FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine DGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_real FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine ZGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_complex FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE) ! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION :: TRACE INTEGER :: I TRACE=0.D0 DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_symmetric FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE) ! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX :: TRACE INTEGER :: I TRACE=(0.D0,0.D0) DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_hermitian FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: TRACE INTEGER :: I,J TRACE=0.D0 DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_real FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square complex matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: TRACE INTEGER :: I,J TRACE=(0.D0,0.D0) DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_complex FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION :: TRACE INTEGER :: I,J,IJ,JI TRACE=0.D0 DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*PB(IJ) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+PA(JI)*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_symmetric FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX :: TRACE INTEGER :: I,J,IJ,JI TRACE=(0.D0,0.D0) DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*CONJG(PB(IJ)) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+CONJG(PA(JI))*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_hermitian FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: FIP INTEGER :: I,J FIP=0.D0 DO I=1,N DO J=1,N FIP=FIP+A(I,J)*B(I,J) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_real FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: FIP INTEGER :: I,J FIP=(0.D0,0.D0) DO I=1,N DO J=1,N FIP=FIP+A(I,J)*CONJG(B(I,J)) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_complex SUBROUTINE NORM_check_norm(CHAR) CHARACTER(1),INTENT(IN) :: CHAR IF((CHAR /= 'F') .AND. & &(CHAR /= 'I') .AND. & &(CHAR /= '1') .AND. & &(CHAR /= 'M')) THEN WRITE(*,*) 'Invalid norm' STOP END IF END SUBROUTINE NORM_check_norm FUNCTION NORM_real(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANGE CALL NORM_check_norm(CHAR) NORM = DLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_real FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANGE CALL NORM_check_norm(CHAR) NORM = ZLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_complex FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANSP CALL NORM_check_norm(CHAR) NORM = DLANSP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_symmetric FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANHP CALL NORM_check_norm(CHAR) NORM = ZLANHP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_hermitian SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's DSPGV subroutine. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC INTEGER,INTENT(OUT) :: INFO INTEGER :: I,NEIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP AP=PA ; BP=PCFB ! Transform problem to standard eigenvalue problem and solve CALL DSPGST(1,'U',N,AP,BP,INFO) IF (INFO/=0) GO TO 1 CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GO TO 2 ! Backtransform eigenvectors to the original problem NEIG=N IF (INFO>0) NEIG=INFO-1 DO I=1,NEIG CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1) END DO RETURN ! MESSAGES 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF 3 WRITE(*,*)'(called from subroutine EIGENSOLVER)' RETURN END SUBROUTINE EIGENSOLVER_symmetric_prefactorized SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's ZHPGV subroutine. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC INTEGER,INTENT(OUT) :: INFO INTEGER :: I,NEIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP AP=PA ; BP=PCFB ! Transform problem to standard eigenvalue problem and solve CALL ZHPGST(1,'U',N,AP,BP,INFO) IF (INFO/=0) GO TO 1 CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GO TO 2 ! Backtransform eigenvectors to the original problem NEIG=N IF (INFO>0) NEIG=INFO-1 DO I=1,NEIG CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1) END DO RETURN ! MESSAGES 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF 3 WRITE(*,*)'(called from subroutine EIGENSOLVER)' RETURN END SUBROUTINE EIGENSOLVER_hermitian_prefactorized FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C) ! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS DOUBLE PRECISION,DIMENSION(N,N) :: C DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N) C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A)) END FUNCTION COMMUTATOR_symmetric FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C) ! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS DOUBLE COMPLEX,DIMENSION(N,N) :: C DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N) C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A)) END FUNCTION COMMUTATOR_hermitian ! input/output routines for matrices SUBROUTINE READMATRIX_real(MAT,N,LOGUNIT) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: MAT INTEGER :: I DOUBLE PRECISION,DIMENSION(N) :: LINE DO I=1,N READ(LOGUNIT,*)LINE MAT(I,:)=LINE END DO END SUBROUTINE READMATRIX_REAL SUBROUTINE READMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: MAT DOUBLE PRECISION,DIMENSION(N,N) :: R,I CALL READMATRIX_real(R,N,LOGUNIT_REAL) CALL READMATRIX_real(I,N,LOGUNIT_IMAG) MAT=DCMPLX(R,I) END SUBROUTINE READMATRIX_complex SUBROUTINE PRINTMATRIX_real(MAT,N,LOGUNIT) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: MAT INTEGER :: I DO I=1,N WRITE(LOGUNIT,*)MAT(I,:) END DO END SUBROUTINE PRINTMATRIX_real SUBROUTINE PRINTMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: MAT INTEGER :: I DO I=1,N IF (LOGUNIT_REAL==LOGUNIT_IMAG) THEN WRITE(LOGUNIT_REAL,*)MAT(I,:) ELSE WRITE(LOGUNIT_REAL,*)REAL(MAT(I,:)) WRITE(LOGUNIT_IMAG,*)AIMAG(MAT(I,:)) END IF END DO END SUBROUTINE PRINTMATRIX_complex SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT CALL PRINTMATRIX_real(UNPACK(PMAT,N),N,LOGUNIT) END SUBROUTINE PRINTMATRIX_symmetric SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) IMPLICIT NONE INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT CALL PRINTMATRIX_complex(UNPACK(PMAT,N),N,LOGUNIT_REAL,LOGUNIT_IMAG) END SUBROUTINE PRINTMATRIX_hermitian END MODULE matrix_tools MODULE mathematical_functions INTERFACE DFACT MODULE PROCEDURE DOUBLE_FACTORIAL END INTERFACE CONTAINS FUNCTION FACTORIAL(N) RESULT(FACT) IMPLICIT NONE INTEGER,INTENT(IN) :: N INTEGER :: FACT
antoine-levitt/ACCQUAREL
b6c01c4fba776e357a93e360650b88afb03777f3
minor correction of the hamiltonian in the CGHF case
diff --git a/src/matrices.F90 b/src/matrices.F90 index 3e6a529..1be9982 100644 --- a/src/matrices.F90 +++ b/src/matrices.F90 @@ -1,712 +1,712 @@ SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PDM=(0.D0,0.D0) DO I=LOON,HOON CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_relativistic SUBROUTINE FORMDM_nonrelativistic_nonorthogonal(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). Same as FORMDM_nonrelativistic, but does not expect orthogonal eigenvectors USE metric_nonrelativistic ; USE matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC_GS,S INTEGER :: I,J EIGVEC_GS=EIGVEC S=UNPACK(PS,NBAST) PDM=0.D0 DO I=LOON,HOON DO J=LOON,I-1 EIGVEC_GS(:,I)=EIGVEC_GS(:,I) - dot_product(EIGVEC_GS(:,J),MATMUL(S,EIGVEC_GS(:,I))) * EIGVEC_GS(:,J) END DO EIGVEC_GS(:,I) = EIGVEC_GS(:,I) / SQRT(dot_product(EIGVEC_GS(:,I),MATMUL(S,EIGVEC_GS(:,I)))) CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_nonrelativistic_nonorthogonal SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PDM=0.D0 DO I=LOON,HOON CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_nonrelativistic SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON) ! Assembly of the matrix of the projector on the "positive" space (i.e., the electronic states) associated to a Dirac-Fock Hamiltonian (only the upper triangular part of the matrix is stored in packed format). IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST,LOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PPROJM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PPROJM=(0.D0,0.D0) DO I=0,NBAST-LOON CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM) END DO END SUBROUTINE FORMPROJ SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS) ! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE POM=(0.D0,0.D0) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO POM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO POM(I+(J-1)*J/2)=VALUE END DO END DO END SUBROUTINE BUILDOM_relativistic SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST) ! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format), for the RHF, ROHF or UHF models. USE basis_parameters ; USE integrals IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J DO J=1,NBAST DO I=1,J POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J)) END DO END DO END SUBROUTINE BUILDOM_nonrelativistic SUBROUTINE BUILDOM_RGHF(POM,PHI,NBAST) ! Computation and assembly of the block-diagonal overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format), in the real general Hartree-Fock formalism. USE basis_parameters ; USE integrals ; USE matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2) CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2) END SUBROUTINE BUILDOM_RGHF SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST) ! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J,N DOUBLE PRECISION :: VALUE DO J=1,NBAST DO I=1,J PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0 END DO END DO END SUBROUTINE BUILDKPFM_nonrelativistic SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: I,J,K,L,M,N DOUBLE COMPLEX :: TMP,VALUE POEFM=(0.D0,0.D0) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) DO N=1,NBN VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N)) END DO END DO END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO IF(MODEL==3) THEN ! CGHF model: Schrodinger kinetic energy DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) - VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L) & - & *KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2.D0 + VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & + & *KINETICVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L))/2.D0 END DO END DO END DO POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2)+VALUE END DO END DO ELSE DO J=NBAS(1)+1,SUM(NBAS) DO I=1,NBAS(1) VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), & & DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), & & DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3)) END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) DO N=1,NBN TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N)) END DO VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP END DO END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO END IF END SUBROUTINE BUILDOEFM_relativistic SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE data_parameters ; USE basis_parameters ; USE integrals IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J,N DOUBLE PRECISION :: VALUE POEFM=0.D0 DO J=1,NBAST DO I=1,J VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0 DO N=1,NBN VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N)) END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO END SUBROUTINE BUILDOEFM_nonrelativistic SUBROUTINE BUILDOEFM_RGHF(POEFM,PHI,NBAST) ! Computation and assembly of the monoelectronic part of the block-diagonal Fock matrix in the real general Hartree-Fock formalism (only the upper triangular part of the matrix is stored in packed format). USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2) CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2) END SUBROUTINE BUILDOEFM_RGHF SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER(smallint) :: I,J,K,L INTEGER :: N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM TEFM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF ! IF ((I==J).AND.(I==K).AND.(I==L)) THEN ! NO CONTRIBUTION ! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K)) ! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN ! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN ! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I)) ! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN ! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K)) ! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I)) ELSE TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_relativistic SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM INTEGER(smallint) :: I,J,K,L INTEGER :: N DOUBLE PRECISION :: INTGRL TEFM=0.D0 DM=UNPACK(PDM,NBAST) IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the values of the bielectronic integrals are computed "on the fly" I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (USEDISK) THEN ! the list and values of the bielectronic integrals are read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE ! the list and values of the bielectronic integrals are read in memory I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=RBIVALUES(N) END IF END IF ! 1 value for the 4 indices IF ((I==J).AND.(J==K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I) ! 2 distinct values for the 4 indices ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I)) ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L)) ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I) ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I) TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J) TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I) ! 3 distinct values for the 4 indices ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J)) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I) ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I)) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J) ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I)) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J) ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K) ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I) ! 4 distinct values for the 4 indices ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) & .OR.((I>K).AND.(K>J).AND.(J>L)) & .OR.((I>K).AND.(K>L).AND.(L>J))) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K) END IF END DO IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_RHF SUBROUTINE BUILDTEFM_RGHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the real general Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) PTEFM=PCM-PEM END SUBROUTINE BUILDTEFM_RGHF SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER(smallint) :: I,J,K,L INTEGER :: N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM CM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN CM(I,J)=CM(I,J)+INTGRL*DM(I,J) ELSE CM(I,J)=CM(I,J)+INTGRL*DM(K,L) CM(K,L)=CM(K,L)+INTGRL*DM(I,J) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_relativistic SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM INTEGER(smallint) :: I,J,K,L INTEGER :: N DOUBLE PRECISION :: INTGRL CM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) CM(I,J)=CM(I,J)+INTGRL*DM(K,L) #include "forall.f90" #undef ACTION PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_nonrelativistic SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER(smallint) :: I,J,K,L INTEGER :: N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM EM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN EM(I,J)=EM(I,J)+INTGRL*DM(J,I) ELSE EM(I,L)=EM(I,L)+INTGRL*DM(J,K) EM(K,J)=EM(K,J)+INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_relativistic SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM INTEGER(smallint) :: I,J,K,L INTEGER :: N DOUBLE PRECISION :: INTGRL EM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) EM(I,K)=EM(I,K)+INTGRL*DM(L,J) #include "forall.f90" #undef ACTION PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_nonrelativistic SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE PSAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO
antoine-levitt/ACCQUAREL
f7fc516bc297fc02ce7614e4e85f86d165557d50
Use small integers
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index 1f20580..0d3d2b3 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,562 +1,564 @@ MODULE integrals + ! size of bielectronic indices. 1 for 8-bits (255), 2 for 16-bits(65535), 4 for 32-bits (2^32), 8 for 64-bits (2^64). Only used when writing/reading data on disk. Should be bigger than two times the total number of basis functions (signedness issues). 2 is default, set it to 1 to reduce disk usage. Use in code with INTEGER(smallint) + INTEGER, parameter :: smallint = 2 ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) - INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST + INTEGER(smallint),DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic FUNCTION APRIORI_ZERO(PHI1,PHI2,PHI3,PHI4) RESULT(VALUE) ! Function that checks whether a given bielectronic integral can a priori be predicted to be zero USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI1,PHI2,PHI3,PHI4 LOGICAL :: SC,VALUE INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree ! If all functions have the same center and any monomial is odd, integral is zero SC=((PHI1%center_id==PHI2%center_id).AND.(PHI2%center_id==PHI3%center_id).AND.(PHI3%center_id==PHI4%center_id)) IF(SC) THEN IF(ANY(MOD(GLOBALMONOMIALDEGREE,2)==1)) THEN VALUE = .TRUE. RETURN END IF END IF ! Plane symmetries IF((SYM_SX .AND. MOD(GLOBALMONOMIALDEGREE(1),2) == 1).OR.& &(SYM_SY .AND. MOD(GLOBALMONOMIALDEGREE(2),2) == 1).OR.& &(SYM_SZ .AND. MOD(GLOBALMONOMIALDEGREE(3),2) == 1)) THEN VALUE = .TRUE. RETURN END IF VALUE = .FALSE. END FUNCTION APRIORI_ZERO SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE - INTEGER :: I,J,K,L + INTEGER(smallint) :: I,J,K,L LOGICAL :: SS = .TRUE. OPEN(LUNIT,access='STREAM') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(PHI(I),PHI(J),PHI(K),PHI(L))) THEN IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) IF(SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) - INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 + INTEGER(smallint) :: I,J,K,L,I1,I2,I3,I4,I5,I6 OPEN(LUNIT,access='STREAM') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! LLSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SL' SUBSIZE(2)=SUBSIZE(2)+1 GO TO 2 END IF END DO END DO END DO END DO END DO END DO 2 CONTINUE END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O NBF=NGBF ! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=1,NGBF(1) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-1)*(I)*(I+1)*(I+2)/24 N=(I-2)*(I-1)*(I)*(I+1)/24 O=(I-3)*(I-2)*(I-1)*(I)/24 DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO IF (SLINTEGRALS) THEN ! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(N,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN ! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE diff --git a/src/matrices.F90 b/src/matrices.F90 index 85f8898..89449eb 100644 --- a/src/matrices.F90 +++ b/src/matrices.F90 @@ -1,1110 +1,1118 @@ SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PDM=(0.D0,0.D0) DO I=LOON,HOON CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_relativistic SUBROUTINE FORMDM_nonrelativistic_nonorthogonal(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). Same as FORMDM_nonrelativistic, but does not expect orthogonal eigenvectors USE metric_nonrelativistic ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC_GS,S INTEGER :: I,J EIGVEC_GS = EIGVEC S = UNPACK(PS,NBAST) PDM=0.D0 DO I=LOON,HOON DO J=LOON,I-1 EIGVEC_GS(:,I) = EIGVEC_GS(:,I) - dot_product(EIGVEC_GS(:,J),MATMUL(S,EIGVEC_GS(:,I))) * EIGVEC_GS(:,J) END DO EIGVEC_GS(:,I) = EIGVEC_GS(:,I) / SQRT(dot_product(EIGVEC_GS(:,I),MATMUL(S,EIGVEC_GS(:,I)))) CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_nonrelativistic_nonorthogonal SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PDM=0.D0 DO I=LOON,HOON CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_nonrelativistic SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON) ! Assembly of the matrix of the projector on the "positive" space (i.e., the electronic states) associated to a Dirac-Fock Hamiltonian (only the upper triangular part of the matrix is stored in packed format). INTEGER,INTENT(IN) :: NBAST,LOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PPROJM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PPROJM=(0.D0,0.D0) DO I=0,NBAST-LOON CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM) END DO END SUBROUTINE FORMPROJ SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS) ! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE POM=(0.D0,0.D0) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO POM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO POM(I+(J-1)*J/2)=VALUE END DO END DO END SUBROUTINE BUILDOM_relativistic SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST) ! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J DO J=1,NBAST DO I=1,J POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J)) END DO END DO END SUBROUTINE BUILDOM_nonrelativistic SUBROUTINE BUILDOM_GHF(POM,PHI,NBAST) ! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI ! matrix is block-diagonal CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2) CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2) END SUBROUTINE BUILDOM_GHF SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST) ! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J,N DOUBLE PRECISION :: VALUE DO J=1,NBAST DO I=1,J PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0 END DO END DO END SUBROUTINE BUILDKPFM_nonrelativistic SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: I,J,K,L,M,N DOUBLE COMPLEX :: TMP,VALUE POEFM=(0.D0,0.D0) ! potential energy for L spinors DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) DO N=1,NBN VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N)) END DO END DO END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO IF(MODEL == 3) THEN ! schrodinger kinetic energy DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L)*& &KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2 END DO END DO END DO POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2) + VALUE END DO END DO ELSE ! kinetic energy alpha.p DO J=NBAS(1)+1,SUM(NBAS) DO I=1,NBAS(1) VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), & & DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), & & DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3)) END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO !potential energy for S spinors DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) DO N=1,NBN TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N)) END DO VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP END DO END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO END IF END SUBROUTINE BUILDOEFM_relativistic SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE data_parameters ; USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J,N DOUBLE PRECISION :: VALUE POEFM=0.D0 DO J=1,NBAST DO I=1,J VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0 DO N=1,NBN VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N)) END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO END SUBROUTINE BUILDOEFM_nonrelativistic SUBROUTINE BUILDOEFM_GHF(POEFM,PHI,NBAST) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI ! the one-electron Fock operator does not couple spins, matrix is block-diagonal CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2) CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2) END SUBROUTINE BUILDOEFM_GHF SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM - INTEGER :: I,J,K,L,N + INTEGER(smallint) :: I,J,K,L + INTEGER :: N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM TEFM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF ! IF ((I==J).AND.(I==K).AND.(I==L)) THEN ! NO CONTRIBUTION ! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K)) ! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN ! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN ! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I)) ! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN ! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K)) ! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I)) ELSE TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_relativistic SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM - INTEGER :: I,J,K,L,N + INTEGER(smallint) :: I,J,K,L + INTEGER :: N DOUBLE PRECISION :: INTGRL TEFM=0.D0 DM=UNPACK(PDM,NBAST) IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the values of the bielectronic integrals are computed "on the fly" I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (USEDISK) THEN ! the list and values of the bielectronic integrals are read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE ! the list and values of the bielectronic integrals are read in memory I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=RBIVALUES(N) END IF END IF ! 1 value for the 4 indices IF ((I==J).AND.(J==K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I) ! 2 distinct values for the 4 indices ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I)) ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L)) ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I) ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I) TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J) TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I) ! 3 distinct values for the 4 indices ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J)) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I) ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I)) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J) ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I)) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J) ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K) ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I) ! 4 distinct values for the 4 indices ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) & .OR.((I>K).AND.(K>J).AND.(J>L)) & .OR.((I>K).AND.(K>L).AND.(L>J))) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K) END IF END DO IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_RHF SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) PTEFM=PCM-PEM END SUBROUTINE BUILDTEFM_GHF SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM - INTEGER :: I,J,K,L,N + INTEGER(smallint) :: I,J,K,L + INTEGER :: N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM CM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN CM(I,J)=CM(I,J)+INTGRL*DM(I,J) ELSE CM(I,J)=CM(I,J)+INTGRL*DM(K,L) CM(K,L)=CM(K,L)+INTGRL*DM(I,J) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_relativistic SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is CM(I,J) = sum over k,l of (IJ|KL) D(I,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM - INTEGER :: I,J,K,L,N + INTEGER(smallint) :: I,J,K,L + INTEGER :: N DOUBLE PRECISION :: INTGRL CM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) CM(I,J) = CM(I,J) + INTGRL*DM(K,L) #include "forall.f90" #undef ACTION PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_nonrelativistic SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM - INTEGER :: I,J,K,L,N + INTEGER(smallint) :: I,J,K,L + INTEGER :: N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM EM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN EM(I,J)=EM(I,J)+INTGRL*DM(J,I) ELSE EM(I,L)=EM(I,L)+INTGRL*DM(J,K) EM(K,J)=EM(K,J)+INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_relativistic SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM - INTEGER :: I,J,K,L,N + INTEGER(smallint) :: I,J,K,L + INTEGER :: N DOUBLE PRECISION :: INTGRL EM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) EM(I,K) = EM(I,K) + INTGRL*DM(L,J) #include "forall.f90" #undef ACTION PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_nonrelativistic SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE PSAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (2) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (3) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO END SELECT END SUBROUTINE BUILDSAMCM SUBROUTINE BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the orbital angular momentum operator L=x^p (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE POAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (2) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (3) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO END SELECT END SUBROUTINE BUILDOAMCM SUBROUTINE BUILDTAMCM(PTAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the total angular momentum operator J=L+S (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PSAMCM,POAMCM CALL BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) CALL BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT) PTAMCM=PSAMCM+POAMCM END SUBROUTINE BUILDTAMCM SUBROUTINE BUILDA(PA,NBAST,NBO,PHI,EIGVEC,EIG) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools USE case_parameters ; USE data_parameters ; USE basis_parameters INTEGER,INTENT(IN) :: NBAST,NBO DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO),NBO*(NBAST-NBO)) :: A DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO)*(NBO*(NBAST-NBO)+1)/2) :: PA TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM - INTEGER :: I,J,K,L,N,OI,OJ,VA,VB + INTEGER(smallint) :: I,J,K,L + INTEGER :: N,OI,OJ,VA,VB DOUBLE PRECISION :: INTGRL A = 0 DO OI=1,NBO DO VA=1,NBAST-NBO A((OI-1)*(NBAST-NBO)+VA,(OI-1)*(NBAST-NBO)+VA)=(EIG(NBO+VA)-EIG(OI)) END DO END DO #define ACTION(I,J,K,L) \ DO OI=1,NBO ;\ DO VA=1,NBAST-NBO ;\ DO OJ=1,NBO ;\ DO VB=1,NBAST-NBO ;\ A((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)=A((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)+INTGRL*(EIGVEC(J,OI)*EIGVEC(I,NBO+VA)*EIGVEC(K,OJ)*EIGVEC(L,NBO+VB) -EIGVEC(L,OI)*EIGVEC(I,NBO+VA)*EIGVEC(K,OJ)*EIGVEC(J,NBO+VB));\ END DO ;\ END DO ;\ END DO ;\ END DO #include "forall.f90" #undef ACTION PA = PACK(A,(NBAST-NBO)*NBO) END SUBROUTINE BUILDA SUBROUTINE BUILDB(PB,NBAST,NBO,PHI,EIGVEC,EIG) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools USE case_parameters ; USE data_parameters ; USE basis_parameters INTEGER,INTENT(IN) :: NBAST,NBO DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO),NBO*(NBAST-NBO)) :: B DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO)*(NBO*(NBAST-NBO)+1)/2) :: PB TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM - INTEGER :: I,J,K,L,N,OI,OJ,VA,VB + INTEGER(smallint) :: I,J,K,L + INTEGER :: N,OI,OJ,VA,VB DOUBLE PRECISION :: INTGRL #define ACTION(I,J,K,L) \ DO OI=1,NBO ;\ DO VA=1,NBAST-NBO ;\ DO OJ=1,NBO ;\ DO VB=1,NBAST-NBO ;\ B((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)=B((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)+INTGRL*(EIGVEC(J,OI)*EIGVEC(I,NBO+VA)*EIGVEC(L,OJ)*EIGVEC(K,NBO+VB) -EIGVEC(L,OI)*EIGVEC(I,NBO+VA)*EIGVEC(J,OJ)*EIGVEC(K,NBO+VB));\ END DO ;\ END DO ;\ END DO ;\ END DO #include "forall.f90" #undef ACTION PB = PACK(B,NBO*(NBAST-NBO)) END SUBROUTINE BUILDB MODULE matrices INTERFACE FORMDM SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON) INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC END SUBROUTINE SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON) INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC END SUBROUTINE END INTERFACE INTERFACE BUILDOM SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS END SUBROUTINE SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDKPFM SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDOEFM SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS END SUBROUTINE SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDTEFM SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE INTERFACE BUILDCOULOMB SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE INTERFACE BUILDEXCHANGE SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE END MODULE
antoine-levitt/ACCQUAREL
04fac7851bb6317697b132552cfccf9c5a449873
Use access='STREAM' to write LUNIT and BIUNIT
diff --git a/src/drivers.f90 b/src/drivers.f90 index cdf8688..fa1bfb2 100644 --- a/src/drivers.f90 +++ b/src/drivers.f90 @@ -1,606 +1,606 @@ SUBROUTINE DRIVER_relativistic USE case_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools USE metric_relativistic ; USE scf_algorithms IMPLICIT NONE INTEGER :: NBAST TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF INTEGER,DIMENSION(2) :: NGBF INTEGER :: TYPENMBR(3),INFO,I DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC ! Computation of the discretization basis CALL FORMBASIS(PHI,NBAS,GBF,NGBF) NBAST=SUM(NBAS) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM IF (INFO/=0) GOTO 1 ! Condition number WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1') ! Computation and assembly of the core hamiltonian matrix WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS) ! Creation of the list of nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR) IF (DIRECT) THEN IF (.NOT.USEDISK) THEN ! storage of the list of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4)) - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:) END DO CLOSE(LUNIT,STATUS='DELETE') END IF ELSE IF (.NOT.DIRECT) THEN ! Precomputation of the bielectronic integrals is preferred to "on the fly" computation ! Precomputation of the bielectronic integrals involving gaussian basis functions WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF' CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) IF (SEMIDIRECT) THEN IF (.NOT.USEDISK) THEN ! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR)) - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:),BITYPE(I) END DO CLOSE(LUNIT,STATUS='DELETE') END IF ELSE WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions' IF (USEDISK) THEN ! storage of the list and values of nonzero bielectronic integrals on disk ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1)) - OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') ; OPEN(BIUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(1,:),BITYPE(1) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1)) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) DEALLOCATE(BILIST,BITYPE) ELSE ! storage of the list and values of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR)) - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:),BITYPE(1) CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1)) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO CLOSE(LUNIT,STATUS='DELETE') DEALLOCATE(BITYPE) END IF CALL DEALLOCATE_INTEGRALS END IF END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) IF(RESUME) THEN OPEN(100,FILE='eig.txt') READ(100,*) EIG OPEN(101,FILE='eigvec_r.txt') OPEN(102,FILE='eigvec_i.txt') CALL READMATRIX(EIGVEC,NBAST,101,102) CLOSE(100) CLOSE(101) CLOSE(102) END IF DO I=1,NBALG SELECT CASE (ALG(I)) CASE (1) WRITE(*,'(/,a)')' Roothaan''s algorithm' SELECT CASE (MODEL) CASE (1) CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR) CASE (2) CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR) CASE (3) CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (2) WRITE(*,'(/,a)')' level-shifting algorithm' CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (3) WRITE(*,'(/,a)')' DIIS algorithm' CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (5) WRITE(*,'(/,a)')' Eric Sere''s algorithm' CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (6) WRITE(*,'(/,a)')' Roothaan/Gradient algorithm' CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT END DO IF (DIRECT) THEN IF (USEDISK) THEN - OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE') + OPEN(LUNIT,access='STREAM') ; CLOSE(LUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST) END IF ELSE IF (SEMIDIRECT) THEN IF (USEDISK) THEN - OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE') + OPEN(LUNIT,access='STREAM') ; CLOSE(LUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,BITYPE) END IF CALL DEALLOCATE_INTEGRALS ELSE IF (USEDISK) THEN - OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE') + OPEN(BIUNIT,access='STREAM') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,CBIVALUES) END IF END IF END IF OPEN(100,FILE='eig.txt') WRITE(100,*) EIG OPEN(101,FILE='eigvec_r.txt') OPEN(102,FILE='eigvec_i.txt') CALL PRINTMATRIX(EIGVEC,NBAST,101,102) CLOSE(100) CLOSE(101) CLOSE(102) DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF WRITE(*,*)'(called from subroutine DRIVER)' STOP END SUBROUTINE DRIVER_relativistic SUBROUTINE DRIVER_nonrelativistic USE case_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic USE scf_algorithms IMPLICIT NONE INTEGER :: NBAST TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS INTEGER :: INFO,I DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC ! Computation of the discretization basis IF(MODEL == 4) THEN CALL FORMBASIS_GHF(PHI,NBAS) ELSE CALL FORMBASIS(PHI,NBAS) END IF NBAST=SUM(NBAS) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) IF(MODEL == 4) THEN CALL BUILDOM_GHF(POM,PHI,NBAST) ELSE CALL BUILDOM(POM,PHI,NBAST) END IF PS=>POM ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM IF (INFO/=0) GOTO 1 ! Condition number WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1') ! Computation and assembly of the matrix of the free hamiltonian WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) IF(MODEL == 4) THEN CALL BUILDOEFM_GHF(POEFM,PHI,NBAST) ELSE CALL BUILDOEFM(POEFM,PHI,NBAST) END IF ! Creation of the list of the nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAST,BINMBR) IF (DIRECT) THEN ! Computation of the bielectronic integrals will be done "on the fly" ! storage of the list of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4)) - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(I,:) END DO CLOSE(LUNIT,STATUS='DELETE') ELSE ! Precomputation of the bielectronic integrals WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions' IF (USEDISK) THEN ALLOCATE(BILIST(1:1,1:4)) - OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') ; OPEN(BIUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(1,:) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO DEALLOCATE(BILIST) CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) ELSE ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR)) - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') !$OMP PARALLEL DO SCHEDULE(STATIC,1) DO I=1,BINMBR READ(LUNIT)BILIST(I,:) RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO !$OMP END PARALLEL DO CLOSE(LUNIT,STATUS='DELETE') END IF END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) IF(RESUME) THEN OPEN(100,FILE='eig.txt') READ(100,*) EIG OPEN(101,FILE='eigvec.txt') CALL READMATRIX(EIGVEC,NBAST,101) CLOSE(100) CLOSE(101) END IF DO I=1,NBALG SELECT CASE (ALG(I)) CASE (1) WRITE(*,'(/,a)')' Roothaan''s algorithm' SELECT CASE (MODEL) CASE (1) CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (2) WRITE(*,'(/,a)')' level-shifting algorithm' SELECT CASE (MODEL) CASE (1) CALL LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL LEVELSHIFTING_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (3) WRITE(*,'(/,a)')' DIIS algorithm' SELECT CASE (MODEL) CASE (1) CALL DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL DIIS_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (4) WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)' SELECT CASE (MODEL) CASE (1) CALL ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE(6) WRITE(*,*)' Roothaan/Gradient algorithm' SELECT CASE (MODEL) CASE (1) CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) WRITE(*,*)' Not implemented yet!' END SELECT END SELECT END DO OPEN(100,FILE='eig.txt') WRITE(100,*) EIG OPEN(101,FILE='eigvec.txt') CALL PRINTMATRIX(EIGVEC,NBAST,101) CLOSE(100) CLOSE(101) IF (DIRECT) THEN DEALLOCATE(BILIST) ELSE IF (USEDISK) THEN - OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE') + OPEN(BIUNIT,access='STREAM') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,RBIVALUES) END IF END IF DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF WRITE(*,*)'(called from subroutine DRIVER)' STOP END SUBROUTINE DRIVER_nonrelativistic SUBROUTINE DRIVER_boson_star ! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants INTEGER :: NBAST,ITER,I,J,INFO INTEGER,TARGET :: RANK INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI LOGICAL :: NUMCONV ! boucle sur la temperature INTEGER :: K ! test ! DOUBLE PRECISION :: RCOND ! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK ! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0 ! Computation of the discretization basis CALL FORMBASIS(PHI,NBAS) NBAST=NBAS(1) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM ! tests ! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST)) ! PA=POM ! CALL DSPTRF('U',NBAST,PA,IPIV,INFO) ! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO) ! DEALLOCATE(PA,WORK,IPIV,IWORK) ! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND ! tests ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM IF (INFO/=0) GO TO 5 ! Computation and assembly of the matrix of the free hamiltonian WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) CALL BUILDKPFM(POEFM,PHI,NBAST) ! Creation of the list of nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAST,BINMBR) ! Computation of the Coulomb integrals WRITE(*,'(a)')'* Computation of the bielectronic integrals' IF (USEDISK) THEN ALLOCATE(BILIST(1:1,1:4)) - OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') ; OPEN(BIUNIT,access='STREAM') DO I=1,BINMBR READ(LUNIT)BILIST(1,:) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO DEALLOCATE(BILIST) CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) ELSE ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR)) - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') !$OMP PARALLEL DO SCHEDULE(STATIC, 1) DO I=1,BINMBR READ(LUNIT)BILIST(I,:) RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO !$OMP END PARALLEL DO CLOSE(LUNIT,STATUS='DELETE') END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2)) ALLOCATE(LAMBDA(1:NBAST)) ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ! Initialisation CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 6 OPEN(33) DO I=1,NBAST write(33,*)EIG(I) END DO CLOSE(33) RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM PDM1=0.D0 LAMBDA=0.D0 ; ! IF (TEMPERATURE==0) LAMBDA(1)=MASS LAMBDA(1)=MASS ETOT1=0.D0 CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM) PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI) DO K=0,1000 ! TEMPERATURE LOOP TEMPERATURE=DBLE(K)*0.0001 ITER=0 ! ROOTHAAN'S ALGORITHM LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the density matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 6 IF (TEMPERATURE>0.D0) THEN ! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix MU_I=>EIG ; RANK_P=>RANK MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16) WRITE(*,*)'mu=',MU WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU) ! Computation of the updated occupation numbers DO I=1,NBAST IF (MU-EIG(I)>0.D0) THEN LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE) RANK=I ELSE LAMBDA(I)=0.D0 END IF ! WRITE(*,*)'lambda_',I,'=',LAMBDA(I) END DO write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA) END IF ! Assembly of the density matrix PDM1=PDM ; PDM=0.D0 DO I=1,RANK CALL DSPR('U',NBAST,LAMBDA(I),EIGVEC(:,I),1,PDM) END DO ! Computation of the energy associated to the density matrix CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM) PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI) ETOT=ENERGY_HF(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Convergence after',ITER,'iterations.' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) WRITE(33,*)TEMPERATURE,ETOT,MU,RANK ! plot of the eigenfunction associated a pure state IF (RANK==1) THEN WRITE(*,*)' ' WRITE(*,*)'The minimizer is achieved by a pure state.' OPEN(9,FILE='gnuplot.batch',STATUS='UNKNOWN',ACTION='WRITE') DO J=1,NBAST WRITE(9,*)'psi',J-1,'(x)=',SCALING**2,'*(\' DO I=1,NBAST IF (EIGVEC(I,J)>=0.D0) THEN WRITE(9,*)'+',EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\' ELSE WRITE(9,*)EIGVEC(I,J),'*exp(-',FIRST_TERM*COMMON_RATIO**(I-1),'*(',SCALING,'*x)**2)\' END IF END DO WRITE(9,*)')' END DO CLOSE(9) ELSE IF (RANK>1) THEN WRITE(*,*)' ' WRITE(*,*)'The minimizer is achieved by a mixed state.' END IF GO TO 4 3 WRITE(*,*)' ' ; WRITE(*,*)'No convergence after',ITER,'iterations.' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,*)I,EIG(I) END DO CLOSE(9) ! GO TO 4 4 CONTINUE END DO DEALLOCATE(LAMBDA,EIG,EIGVEC,POEFM,PTEFM,PFM,PDM,PDM1) DEALLOCATE(PTTEFM,PTDM,PDMDIF) IF (USEDISK) THEN - OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE') + OPEN(BIUNIT,access='STREAM') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,RBIVALUES) END IF GO TO 7 RETURN 5 IF (INFO<0) THEN WRITE(*,*)'Subroutine DPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF 6 WRITE(*,*)'(called from subroutine DRIVER_boson_star)' 7 DEALLOCATE(POM,PIOM,PSROM,PISROM,NBAS,PHI) END SUBROUTINE DRIVER_boson_star diff --git a/src/forall.f90 b/src/forall.f90 index 8c84c32..6b993e8 100644 --- a/src/forall.f90 +++ b/src/forall.f90 @@ -1,104 +1,104 @@ - IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') + IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the values of the bielectronic integrals are computed "on the fly" I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (USEDISK) THEN ! the list and values of the bielectronic integrals are read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE ! the list and values of the bielectronic integrals are read in memory I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=RBIVALUES(N) END IF END IF ! 1 value for the 4 indices IF ((I==J).AND.(J==K).AND.(K==L)) THEN ACTION(I,I,I,I) ! 2 distinct values for the 4 indices ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN ACTION(I,J,J,J) ACTION(J,J,I,J) ACTION(J,J,J,I) ACTION(J,I,J,J) ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN ACTION(L,I,I,I) ACTION(I,I,L,I) ACTION(I,I,I,L) ACTION(I,L,I,I) ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN ACTION(I,I,K,K) ACTION(K,K,I,I) ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN ACTION(I,J,I,J) ACTION(J,I,J,I) ACTION(J,I,I,J) ACTION(I,J,J,I) ! 3 distinct values for the 4 indices ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN ACTION(I,J,I,L) ACTION(J,I,I,L) ACTION(I,J,L,I) ACTION(J,I,L,I) ACTION(I,L,I,J) ACTION(L,I,I,J) ACTION(I,L,J,I) ACTION(L,I,J,I) ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN ACTION(I,J,J,L) ACTION(J,I,J,L) ACTION(I,J,L,J) ACTION(J,I,L,J) ACTION(J,L,I,J) ACTION(L,J,I,J) ACTION(J,L,J,I) ACTION(L,J,J,I) ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN ACTION(I,J,K,J) ACTION(J,I,K,J) ACTION(I,J,J,K) ACTION(J,I,J,K) ACTION(K,J,I,J) ACTION(J,K,I,J) ACTION(K,J,J,I) ACTION(J,K,J,I) ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN ACTION(I,J,K,K) ACTION(J,I,K,K) ACTION(K,K,I,J) ACTION(K,K,J,I) ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN ACTION(I,I,K,L) ACTION(I,I,L,K) ACTION(K,L,I,I) ACTION(L,K,I,I) ! 4 distinct values for the 4 indices ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) & .OR.((I>K).AND.(K>J).AND.(J>L)) & .OR.((I>K).AND.(K>L).AND.(L>J))) THEN ACTION(I,J,K,L) ACTION(J,I,K,L) ACTION(I,J,L,K) ACTION(J,I,L,K) ACTION(K,L,I,J) ACTION(L,K,I,J) ACTION(K,L,J,I) ACTION(L,K,J,I) END IF END DO IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT) diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index 8129e18..1f20580 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,562 +1,562 @@ MODULE integrals ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic FUNCTION APRIORI_ZERO(PHI1,PHI2,PHI3,PHI4) RESULT(VALUE) ! Function that checks whether a given bielectronic integral can a priori be predicted to be zero USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI1,PHI2,PHI3,PHI4 LOGICAL :: SC,VALUE INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree ! If all functions have the same center and any monomial is odd, integral is zero SC=((PHI1%center_id==PHI2%center_id).AND.(PHI2%center_id==PHI3%center_id).AND.(PHI3%center_id==PHI4%center_id)) IF(SC) THEN IF(ANY(MOD(GLOBALMONOMIALDEGREE,2)==1)) THEN VALUE = .TRUE. RETURN END IF END IF ! Plane symmetries IF((SYM_SX .AND. MOD(GLOBALMONOMIALDEGREE(1),2) == 1).OR.& &(SYM_SY .AND. MOD(GLOBALMONOMIALDEGREE(2),2) == 1).OR.& &(SYM_SZ .AND. MOD(GLOBALMONOMIALDEGREE(3),2) == 1)) THEN VALUE = .TRUE. RETURN END IF VALUE = .FALSE. END FUNCTION APRIORI_ZERO SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE INTEGER :: I,J,K,L LOGICAL :: SS = .TRUE. - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(PHI(I),PHI(J),PHI(K),PHI(L))) THEN IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) IF(SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 - OPEN(LUNIT,form='UNFORMATTED') + OPEN(LUNIT,access='STREAM') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! LLSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SL' SUBSIZE(2)=SUBSIZE(2)+1 GO TO 2 END IF END DO END DO END DO END DO END DO END DO 2 CONTINUE END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O NBF=NGBF ! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=1,NGBF(1) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-1)*(I)*(I+1)*(I+2)/24 N=(I-2)*(I-1)*(I)*(I+1)/24 O=(I-3)*(I-2)*(I-1)*(I)/24 DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO IF (SLINTEGRALS) THEN ! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(N,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN ! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE diff --git a/src/matrices.F90 b/src/matrices.F90 index fe76d24..85f8898 100644 --- a/src/matrices.F90 +++ b/src/matrices.F90 @@ -1,1110 +1,1110 @@ SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PDM=(0.D0,0.D0) DO I=LOON,HOON CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_relativistic SUBROUTINE FORMDM_nonrelativistic_nonorthogonal(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). Same as FORMDM_nonrelativistic, but does not expect orthogonal eigenvectors USE metric_nonrelativistic ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EIGVEC_GS,S INTEGER :: I,J EIGVEC_GS = EIGVEC S = UNPACK(PS,NBAST) PDM=0.D0 DO I=LOON,HOON DO J=LOON,I-1 EIGVEC_GS(:,I) = EIGVEC_GS(:,I) - dot_product(EIGVEC_GS(:,J),MATMUL(S,EIGVEC_GS(:,I))) * EIGVEC_GS(:,J) END DO EIGVEC_GS(:,I) = EIGVEC_GS(:,I) / SQRT(dot_product(EIGVEC_GS(:,I),MATMUL(S,EIGVEC_GS(:,I)))) CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_nonrelativistic_nonorthogonal SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON) ! Assembly of the density matrix from selected eigenvectors associated to (occupied) electronic orbitals (only the upper triangular part of the matrix is stored in packed format). INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PDM=0.D0 DO I=LOON,HOON CALL DSPR('U',NBAST,1.D0,EIGVEC(:,I),1,PDM) END DO END SUBROUTINE FORMDM_nonrelativistic SUBROUTINE FORMPROJ(PPROJM,EIGVEC,NBAST,LOON) ! Assembly of the matrix of the projector on the "positive" space (i.e., the electronic states) associated to a Dirac-Fock Hamiltonian (only the upper triangular part of the matrix is stored in packed format). INTEGER,INTENT(IN) :: NBAST,LOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PPROJM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC INTEGER :: I PPROJM=(0.D0,0.D0) DO I=0,NBAST-LOON CALL ZHPR('U',NBAST,1.D0,EIGVEC(:,LOON+I),1,PPROJM) END DO END SUBROUTINE FORMPROJ SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS) ! Computation and assembly of the overlap matrix between basis functions, i.e., the Gram matrix of the basis with respect to the $L^2(\mathbb{R}^3,\mathbb{C}^4)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE POM=(0.D0,0.D0) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO POM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO POM(I+(J-1)*J/2)=VALUE END DO END DO END SUBROUTINE BUILDOM_relativistic SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST) ! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J DO J=1,NBAST DO I=1,J POM(I+(J-1)*J/2)=OVERLAPVALUE(PHI(I),PHI(J)) END DO END DO END SUBROUTINE BUILDOM_nonrelativistic SUBROUTINE BUILDOM_GHF(POM,PHI,NBAST) ! Computation and assembly of the overlap matrix between basis functions, i.e. the Gram matrix of the basis with respacet to the $L^2(\mathbb{R}^3)$ inner product (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POM_nonrelativistic TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI ! matrix is block-diagonal CALL BUILDOM_nonrelativistic(POM_nonrelativistic,PHI(1:NBAST/2),NBAST/2) CALL BUILD_BLOCK_DIAGONAL(POM,POM_nonrelativistic,NBAST/2) END SUBROUTINE BUILDOM_GHF SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST) ! Computation and assembly of the kinetic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J,N DOUBLE PRECISION :: VALUE DO J=1,NBAST DO I=1,J PKPFM(I+(J-1)*J/2)=KINETICVALUE(PHI(I),PHI(J))/2.D0 END DO END DO END SUBROUTINE BUILDKPFM_nonrelativistic SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed form) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: I,J,K,L,M,N DOUBLE COMPLEX :: TMP,VALUE POEFM=(0.D0,0.D0) ! potential energy for L spinors DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) DO N=1,NBN VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N)) END DO END DO END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO IF(MODEL == 3) THEN ! schrodinger kinetic energy DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE+PHI(I)%coefficients(K,M)*PHI(J)%coefficients(K,L)*& &KINETICVALUE(PHI(I)%contractions(K,M),PHI(J)%contractions(K,L))/2 END DO END DO END DO POEFM(I+(J-1)*J/2)=POEFM(I+(J-1)*J/2) + VALUE END DO END DO ELSE ! kinetic energy alpha.p DO J=NBAS(1)+1,SUM(NBAS) DO I=1,NBAS(1) VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(1,L),3)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),2), & & DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L),1)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE-C*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(-DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),2), & & DERIVVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L),1)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+C*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,DERIVVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(2,L),3)) END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO !potential energy for S spinors DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) TMP=2.D0*C*C*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) DO N=1,NBN TMP=TMP+Z(N)*POTENTIALVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),CENTER(:,N)) END DO VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L))*TMP END DO END DO END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO END IF END SUBROUTINE BUILDOEFM_relativistic SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE data_parameters ; USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,J,N DOUBLE PRECISION :: VALUE POEFM=0.D0 DO J=1,NBAST DO I=1,J VALUE=KINETICVALUE(PHI(I),PHI(J))/2.D0 DO N=1,NBN VALUE=VALUE-Z(N)*POTENTIALVALUE(PHI(I),PHI(J),CENTER(:,N)) END DO POEFM(I+(J-1)*J/2)=VALUE END DO END DO END SUBROUTINE BUILDOEFM_nonrelativistic SUBROUTINE BUILDOEFM_GHF(POEFM,PHI,NBAST) ! Computation and assembly of the monoelectronic part of the Fock matrix (only the upper triangular part of the matrix is stored in packed format). USE data_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM DOUBLE PRECISION,DIMENSION(NBAST/2*(NBAST/2+1)/2) :: POEFM_nonrelativistic TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI ! the one-electron Fock operator does not couple spins, matrix is block-diagonal CALL BUILDOEFM_nonrelativistic(POEFM_nonrelativistic,PHI(1:NBAST/2),NBAST/2) CALL BUILD_BLOCK_DIAGONAL(POEFM,POEFM_nonrelativistic,NBAST/2) END SUBROUTINE BUILDOEFM_GHF SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the bielectronic part of the Fock matrix associated to a given density matrix using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER :: I,J,K,L,N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: TEFM,DM TEFM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) - IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED') - IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') + IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') + IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF ! IF ((I==J).AND.(I==K).AND.(I==L)) THEN ! NO CONTRIBUTION ! ELSE IF ((I==J).AND.(I/=K).AND.(I==L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(K,I)-DM(I,K)) ! ELSE IF ((I==J).AND.(I==K).AND.(I/=L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,L)-DM(L,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(I==L)) THEN ! TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(J==K).AND.(J==L)) THEN ! TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I==K).AND.(I/=L).AND.(J/=L)) THEN ! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(I,L)-DM(L,I)) ! TEFM(I,L)=TEFM(I,L)+INTGRL*(DM(I,J)-DM(J,I)) ! ELSE IF ((I/=J).AND.(I/=K).AND.(J/=K).AND.(J==L)) THEN ! TEFM(I,J)=TEFM(I,J)+INTGRL*(DM(K,J)-DM(J,K)) ! TEFM(K,J)=TEFM(K,J)+INTGRL*(DM(I,J)-DM(J,I)) ELSE TEFM(I,J)=TEFM(I,J)+INTGRL*DM(K,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(K,L)=TEFM(K,L)+INTGRL*DM(I,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_relativistic SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=2J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: TEFM,DM INTEGER :: I,J,K,L,N DOUBLE PRECISION :: INTGRL TEFM=0.D0 DM=UNPACK(PDM,NBAST) - IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') + IF (.NOT.DIRECT.AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the values of the bielectronic integrals are computed "on the fly" I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (USEDISK) THEN ! the list and values of the bielectronic integrals are read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE ! the list and values of the bielectronic integrals are read in memory I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=RBIVALUES(N) END IF END IF ! 1 value for the 4 indices IF ((I==J).AND.(J==K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+INTGRL*DM(I,I) ! 2 distinct values for the 4 indices ELSE IF ((I>J).AND.(J==K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,J) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)+INTGRL*(DM(I,J)+DM(J,I)) ELSE IF ((I==J).AND.(J==K).AND.(K>L)) THEN TEFM(L,I)=TEFM(L,I)+INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)+INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+INTGRL*(DM(L,I)+DM(I,L)) ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I) ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I) TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J) TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I) ! 3 distinct values for the 4 indices ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J)) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I) ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I)) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J) ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I)) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J) ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K) ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I) ! 4 distinct values for the 4 indices ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) & .OR.((I>K).AND.(K>J).AND.(J>L)) & .OR.((I>K).AND.(K>L).AND.(L>J))) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K) END IF END DO IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_RHF SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) PTEFM=PCM-PEM END SUBROUTINE BUILDTEFM_GHF SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER :: I,J,K,L,N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM CM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) - IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED') - IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') + IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') + IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN CM(I,J)=CM(I,J)+INTGRL*DM(I,J) ELSE CM(I,J)=CM(I,J)+INTGRL*DM(K,L) CM(K,L)=CM(K,L)+INTGRL*DM(I,J) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_relativistic SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is CM(I,J) = sum over k,l of (IJ|KL) D(I,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM INTEGER :: I,J,K,L,N DOUBLE PRECISION :: INTGRL CM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) CM(I,J) = CM(I,J) + INTGRL*DM(K,L) #include "forall.f90" #undef ACTION PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_nonrelativistic SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER :: I,J,K,L,N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM EM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) - IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED') - IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') + IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,access='STREAM') + IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,access='STREAM') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN EM(I,J)=EM(I,J)+INTGRL*DM(J,I) ELSE EM(I,L)=EM(I,L)+INTGRL*DM(J,K) EM(K,J)=EM(K,J)+INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_relativistic SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM INTEGER :: I,J,K,L,N DOUBLE PRECISION :: INTGRL EM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) EM(I,K) = EM(I,K) + INTGRL*DM(L,J) #include "forall.f90" #undef ACTION PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_nonrelativistic SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE PSAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (2) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (3) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO END SELECT END SUBROUTINE BUILDSAMCM SUBROUTINE BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the orbital angular momentum operator L=x^p (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE POAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (2) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (3) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO END SELECT END SUBROUTINE BUILDOAMCM SUBROUTINE BUILDTAMCM(PTAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the total angular momentum operator J=L+S (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PSAMCM,POAMCM CALL BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) CALL BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT) PTAMCM=PSAMCM+POAMCM END SUBROUTINE BUILDTAMCM SUBROUTINE BUILDA(PA,NBAST,NBO,PHI,EIGVEC,EIG) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools USE case_parameters ; USE data_parameters ; USE basis_parameters INTEGER,INTENT(IN) :: NBAST,NBO DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO),NBO*(NBAST-NBO)) :: A DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO)*(NBO*(NBAST-NBO)+1)/2) :: PA TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM INTEGER :: I,J,K,L,N,OI,OJ,VA,VB DOUBLE PRECISION :: INTGRL A = 0 DO OI=1,NBO DO VA=1,NBAST-NBO A((OI-1)*(NBAST-NBO)+VA,(OI-1)*(NBAST-NBO)+VA)=(EIG(NBO+VA)-EIG(OI)) END DO END DO #define ACTION(I,J,K,L) \ DO OI=1,NBO ;\ DO VA=1,NBAST-NBO ;\ DO OJ=1,NBO ;\ DO VB=1,NBAST-NBO ;\ A((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)=A((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)+INTGRL*(EIGVEC(J,OI)*EIGVEC(I,NBO+VA)*EIGVEC(K,OJ)*EIGVEC(L,NBO+VB) -EIGVEC(L,OI)*EIGVEC(I,NBO+VA)*EIGVEC(K,OJ)*EIGVEC(J,NBO+VB));\ END DO ;\ END DO ;\ END DO ;\ END DO #include "forall.f90" #undef ACTION PA = PACK(A,(NBAST-NBO)*NBO) END SUBROUTINE BUILDA SUBROUTINE BUILDB(PB,NBAST,NBO,PHI,EIGVEC,EIG) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools USE case_parameters ; USE data_parameters ; USE basis_parameters INTEGER,INTENT(IN) :: NBAST,NBO DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO),NBO*(NBAST-NBO)) :: B DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO)*(NBO*(NBAST-NBO)+1)/2) :: PB TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM INTEGER :: I,J,K,L,N,OI,OJ,VA,VB DOUBLE PRECISION :: INTGRL #define ACTION(I,J,K,L) \ DO OI=1,NBO ;\ DO VA=1,NBAST-NBO ;\ DO OJ=1,NBO ;\ DO VB=1,NBAST-NBO ;\ B((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)=B((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)+INTGRL*(EIGVEC(J,OI)*EIGVEC(I,NBO+VA)*EIGVEC(L,OJ)*EIGVEC(K,NBO+VB) -EIGVEC(L,OI)*EIGVEC(I,NBO+VA)*EIGVEC(J,OJ)*EIGVEC(K,NBO+VB));\ END DO ;\ END DO ;\ END DO ;\ END DO #include "forall.f90" #undef ACTION PB = PACK(B,NBO*(NBAST-NBO)) END SUBROUTINE BUILDB MODULE matrices INTERFACE FORMDM SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON) INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC END SUBROUTINE SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON) INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC END SUBROUTINE END INTERFACE INTERFACE BUILDOM SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS END SUBROUTINE SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDKPFM SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDOEFM SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS END SUBROUTINE SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDTEFM SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE INTERFACE BUILDCOULOMB SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE INTERFACE BUILDEXCHANGE SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE END MODULE
antoine-levitt/ACCQUAREL
8a20131648e57d782df4b41c69001ab098fb9768
Fix "no theta" code
diff --git a/src/esa.f90 b/src/esa.f90 index 590bdfa..5ab50ad 100644 --- a/src/esa.f90 +++ b/src/esa.f90 @@ -1,289 +1,288 @@ MODULE esa_mod USE basis_parameters INTEGER,POINTER :: NBAST_P DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_P,PTDM_P,PDMDIF_P TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_P CHARACTER,POINTER :: METHOD_P CONTAINS FUNCTION THETA(PDM,POEFM,N,PHI,METHOD) RESULT (PDMNEW) ! Function that computes the value of $\Theta(D)$ (with $D$ a hermitian matrix of size N, which upper triangular part is stored in packed form in PDM) with precision TOL (if the (geometrical) convergence of the fixed-point iterative sequence is attained), \Theta being the function defined in: A new definition of the Dirac-Fock ground state, Eric Séré, preprint (2009). USE case_parameters ; USE basis_parameters ; USE matrices USE matrix_tools ; USE metric_relativistic USE debug CHARACTER,INTENT(IN) :: METHOD INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDM,POEFM TYPE(twospinor),DIMENSION(N),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDMNEW INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-8 INTEGER :: ITER,INFO,LOON DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PTEFM,PFM,PDMOLD,PPROJM DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF + IF (METHOD=='N') THEN + PDMNEW = PDM + RETURN + END IF + ITER=0 PDMOLD=PDM IF (THETA_CHECK) THEN WRITE(13,*)'tr(SD)=',REAL(TRACEOFPRODUCT(PS,PDM,N)) ! PTMP=PDM ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF ! Fixed-point iterative sequence DO ITER=ITER+1 ! Projection of the current density matrix CALL BUILDTEFM(PTEFM,N,PHI,PDMOLD) PFM=POEFM+PTEFM IF (METHOD=='D') THEN ! computation of the "positive" spectral projector associated to the Fock matrix based on the current density matrix via diagonalization CALL EIGENSOLVER(PFM,PCFS,N,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 1 CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-C*C)) PDMNEW=ABCBA(PPROJM,PS,PDMOLD,N) ELSEIF(METHOD=='S') THEN ! OR ! computation of the "positive" spectral projector via the sign function obtained by polynomial recursion DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+C*C*PS,N) TSF=TRANSPOSE(CONJG(SF)) PDMNEW=PACK((DM+MATMUL(DM,TSF)+MATMUL(SF,DM+MATMUL(DM,TSF)))/4.D0,N) - ELSE !METHOD=='N' - PDMNEW = PDMOLD END IF IF (THETA_CHECK) THEN WRITE(13,*)'Iter #',ITER WRITE(13,*)'tr(SPSDSP)=',REAL(TRACEOFPRODUCT(PS,PDMNEW,N)) ! PTMP=PDMNEW ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF IF (THETA_CHECK) WRITE(13,*)'Residual =',NORM(ABA(PSRS,PDMNEW-PDMOLD,N),N,'I') IF (NORM(PDMNEW-PDMOLD,N,'I')<TOL) THEN IF (THETA_CHECK) THEN WRITE(13,'(a,i3,a)')' Function THETA: convergence after ',ITER,' iteration(s).' WRITE(13,*)ITER,NORM(PDMNEW-PDMOLD,N,'I') END IF RETURN ELSE IF (ITER>=ITERMAX) THEN WRITE(*,*)'Function THETA: no convergence after ',ITER,' iteration(s).' IF (THETA_CHECK) THEN WRITE(13,*)'Function THETA: no convergence after ',ITER,' iteration(s).' WRITE(13,*)'Residual =',NORM(PDMNEW-PDMOLD,N,'I') END IF STOP END IF PDMOLD=PDMNEW END DO 1 WRITE(*,*)'(called from subroutine THETA)' END FUNCTION THETA FUNCTION SIGN(PA,N) RESULT (SA) ! Function that computes the sign function of the hermitian matrix of a selfadjoint operator, which upper triangular part is stored in packed form, using a polynomial recursion (PINVS contains the inverse of the overlap matrix, which upper triangular part is stored in packed form). ! Note: the result is an unpacked matrix due to subsequent use. USE matrix_tools ; USE metric_relativistic INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: SA DOUBLE COMPLEX,DIMENSION(N,N) :: A,ISRS INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-15 INTEGER :: I,ITER A=UNPACK(PA,N) ; ISRS=UNPACK(PISRS,N) SA=MATMUL(UNPACK(PIS,N),A)/NORM(MATMUL(ISRS,MATMUL(A,ISRS)),N,'F') ITER=0 DO ITER=ITER+1 A=SA SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0 IF (NORM(SA-A,N,'F')<TOL) THEN RETURN ELSE IF (ITER==ITERMAX) THEN WRITE(*,*)'Function SIGN: no convergence after ',ITER,' iteration(s).' STOP END IF END DO END FUNCTION SIGN END MODULE FUNCTION DFE(LAMBDA) RESULT (ETOT) USE common_functions ; USE matrices ; USE matrix_tools ; USE esa_mod DOUBLE PRECISION,INTENT(IN) :: LAMBDA DOUBLE PRECISION :: ETOT DOUBLE COMPLEX,DIMENSION(NBAST_P*(NBAST_P+1)/2) :: PDM,PTEFM,PTMP PDM=THETA(PTDM_P+LAMBDA*PDMDIF_P,POEFM_P,NBAST_P,PHI_P,METHOD_P) CALL BUILDTEFM(PTEFM,NBAST_P,PHI_P,PDM) ETOT=ENERGY(POEFM_P,PTEFM,PDM,NBAST_P) END FUNCTION DFE SUBROUTINE ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Eric Séré's Algorithm USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools USE optimization_tools ; USE esa_mod USE debug INTEGER,INTENT(IN),TARGET :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME CHARACTER,TARGET :: METHOD INTEGER :: ITER,LOON,INFO,I,NUM DOUBLE PRECISION :: ALPHA,BETA,LAMBDA DOUBLE PRECISION :: DPDUMMY,TOL DOUBLE PRECISION :: ETOT,ETOT1,ETTOT,PDMDIFNORM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: PTDM,PDMDIF LOGICAL :: NUMCONV INTERFACE DOUBLE PRECISION FUNCTION DFE(LAMBDA) DOUBLE PRECISION,INTENT(IN) :: LAMBDA END FUNCTION END INTERFACE ! INITIALIZATIONS AND PRELIMINARIES OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) READ(100,'(/,a)')METHOD CLOSE(100) IF (METHOD=='D') THEN WRITE(*,*)'Function $Theta$ computed using diagonalization' ELSEIF(METHOD=='S') THEN WRITE(*,*)'Function $Theta$ computed using polynomial recursion' ELSE WRITE(*,*)'Function $Theta$ ignored' END IF ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ! Pointer assignments NBAST_P=>NBAST ; POEFM_P=>POEFM ; PTDM_P=>PTDM ; PDMDIF_P=>PDMDIF ; PHI_P=>PHI ; METHOD_P=>METHOD ITER=0 TOL=1.D-4 PDM=(0.D0,0.D0) ; PTDM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/esaenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/esacrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/esacrit2.txt',STATUS='unknown',ACTION='write') OPEN(19,FILE='plots/esaenrgyt.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) PDM1=PDM CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! test ERIC ! PFM=POEFM+PTEFM ! CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) ! CALL CHECKORB(EIG,NBAST,LOON) ! computation of the positive spectral projector associated to PFM ! CALL FORMDM(PTMP,EIGVEC,NBAST,LOON,NBAST) ! infinity norm of the commutator between PFM and its positive spectral projector ! WRITE(44,*)ITER,NORM(COMMUTATOR(POEFM+PTEFM,PTMP,PS,NBAST),NBAST,'I') ! fin test ERIC ! Computation of the pseudo density matrix IF (THETA_CHECK) WRITE(13,*)'theta(D-~D)' - IF(METHOD == 'N') THEN - PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,'D') - ELSE - PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD) - END IF + PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD) PDMDIFNORM=NORM(ABA(PSRS,PDMDIF,NBAST),NBAST,'I') WRITE(*,*)'Infinity norm of the difference D_{n-1}-~D_{n-2}=',PDMDIFNORM IF (PDMDIFNORM<=TRSHLD) GO TO 2 BETA=REAL(TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)) write(*,*)'beta=',beta IF (BETA>0.D0) THEN WRITE(*,*)'Warning: internal computation error (beta>0).' GO TO 4 ELSE CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF) ALPHA=REAL(TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)) write(*,*)'alpha=',alpha IF (ALPHA>0.D0) THEN LAMBDA=-BETA/ALPHA IF (LAMBDA<1.D0) THEN WRITE(*,*)'lambda=',LAMBDA ! on peut raffiner avec la methode de la section doree (la fonction n'etant a priori pas quadratique), voir comment optimiser un peu cela... ! WRITE(*,*)'refinement using golden section search (',0.D0,',',LAMBDA,',',1.D0,')' ! DPDUMMY=GOLDEN(0.D0,LAMBDA,1.D0,DFE,TOL,LAMBDA) IF (THETA_CHECK) WRITE(13,*)'theta(~D+s(D-~D))' PTDM=THETA(PTDM+LAMBDA*PDMDIF,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) END IF ELSE IF (ALPHA<0.D0) THEN WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'Warning: internal computation error (alpha=0).' GO TO 4 END IF END IF ! Trace of the pseudo density matrix WRITE(*,*)'tr(tilde{D}_n)=',REAL(TRACE(ABA(PSRS,PTDM,NBAST),NBAST)) ! Energy associated to the pseudo density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST) WRITE(19,*)ETTOT WRITE(*,*)'E(tilde{D}_n)=',ETTOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: convergence after',ITER,'iteration(s).' GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: no convergence after',ITER,'iteration(s).' GO TO 6 4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: computation stopped after',ITER,'iteration(s).' GO TO 6 5 WRITE(*,*)'(called from subroutine ESA)' GO TO 7 6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) 7 NULLIFY(NBAST_P,POEFM_P,PTDM_P,PDMDIF_P,PHI_P) DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) ; CLOSE(19) END SUBROUTINE ESA
antoine-levitt/ACCQUAREL
1ab015bc64553887a10f0e2cb15978b703a1728b
Fix information for Theta function
diff --git a/src/esa.f90 b/src/esa.f90 index 958887a..590bdfa 100644 --- a/src/esa.f90 +++ b/src/esa.f90 @@ -1,287 +1,289 @@ MODULE esa_mod USE basis_parameters INTEGER,POINTER :: NBAST_P DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_P,PTDM_P,PDMDIF_P TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_P CHARACTER,POINTER :: METHOD_P CONTAINS FUNCTION THETA(PDM,POEFM,N,PHI,METHOD) RESULT (PDMNEW) ! Function that computes the value of $\Theta(D)$ (with $D$ a hermitian matrix of size N, which upper triangular part is stored in packed form in PDM) with precision TOL (if the (geometrical) convergence of the fixed-point iterative sequence is attained), \Theta being the function defined in: A new definition of the Dirac-Fock ground state, Eric Séré, preprint (2009). USE case_parameters ; USE basis_parameters ; USE matrices USE matrix_tools ; USE metric_relativistic USE debug CHARACTER,INTENT(IN) :: METHOD INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDM,POEFM TYPE(twospinor),DIMENSION(N),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDMNEW INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-8 INTEGER :: ITER,INFO,LOON DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PTEFM,PFM,PDMOLD,PPROJM DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF ITER=0 PDMOLD=PDM IF (THETA_CHECK) THEN WRITE(13,*)'tr(SD)=',REAL(TRACEOFPRODUCT(PS,PDM,N)) ! PTMP=PDM ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF ! Fixed-point iterative sequence DO ITER=ITER+1 ! Projection of the current density matrix CALL BUILDTEFM(PTEFM,N,PHI,PDMOLD) PFM=POEFM+PTEFM IF (METHOD=='D') THEN ! computation of the "positive" spectral projector associated to the Fock matrix based on the current density matrix via diagonalization CALL EIGENSOLVER(PFM,PCFS,N,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 1 CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-C*C)) PDMNEW=ABCBA(PPROJM,PS,PDMOLD,N) ELSEIF(METHOD=='S') THEN ! OR ! computation of the "positive" spectral projector via the sign function obtained by polynomial recursion DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+C*C*PS,N) TSF=TRANSPOSE(CONJG(SF)) PDMNEW=PACK((DM+MATMUL(DM,TSF)+MATMUL(SF,DM+MATMUL(DM,TSF)))/4.D0,N) ELSE !METHOD=='N' PDMNEW = PDMOLD END IF IF (THETA_CHECK) THEN WRITE(13,*)'Iter #',ITER WRITE(13,*)'tr(SPSDSP)=',REAL(TRACEOFPRODUCT(PS,PDMNEW,N)) ! PTMP=PDMNEW ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF IF (THETA_CHECK) WRITE(13,*)'Residual =',NORM(ABA(PSRS,PDMNEW-PDMOLD,N),N,'I') IF (NORM(PDMNEW-PDMOLD,N,'I')<TOL) THEN IF (THETA_CHECK) THEN WRITE(13,'(a,i3,a)')' Function THETA: convergence after ',ITER,' iteration(s).' WRITE(13,*)ITER,NORM(PDMNEW-PDMOLD,N,'I') END IF RETURN ELSE IF (ITER>=ITERMAX) THEN WRITE(*,*)'Function THETA: no convergence after ',ITER,' iteration(s).' IF (THETA_CHECK) THEN WRITE(13,*)'Function THETA: no convergence after ',ITER,' iteration(s).' WRITE(13,*)'Residual =',NORM(PDMNEW-PDMOLD,N,'I') END IF STOP END IF PDMOLD=PDMNEW END DO 1 WRITE(*,*)'(called from subroutine THETA)' END FUNCTION THETA FUNCTION SIGN(PA,N) RESULT (SA) ! Function that computes the sign function of the hermitian matrix of a selfadjoint operator, which upper triangular part is stored in packed form, using a polynomial recursion (PINVS contains the inverse of the overlap matrix, which upper triangular part is stored in packed form). ! Note: the result is an unpacked matrix due to subsequent use. USE matrix_tools ; USE metric_relativistic INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: SA DOUBLE COMPLEX,DIMENSION(N,N) :: A,ISRS INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-15 INTEGER :: I,ITER A=UNPACK(PA,N) ; ISRS=UNPACK(PISRS,N) SA=MATMUL(UNPACK(PIS,N),A)/NORM(MATMUL(ISRS,MATMUL(A,ISRS)),N,'F') ITER=0 DO ITER=ITER+1 A=SA SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0 IF (NORM(SA-A,N,'F')<TOL) THEN RETURN ELSE IF (ITER==ITERMAX) THEN WRITE(*,*)'Function SIGN: no convergence after ',ITER,' iteration(s).' STOP END IF END DO END FUNCTION SIGN END MODULE FUNCTION DFE(LAMBDA) RESULT (ETOT) USE common_functions ; USE matrices ; USE matrix_tools ; USE esa_mod DOUBLE PRECISION,INTENT(IN) :: LAMBDA DOUBLE PRECISION :: ETOT DOUBLE COMPLEX,DIMENSION(NBAST_P*(NBAST_P+1)/2) :: PDM,PTEFM,PTMP PDM=THETA(PTDM_P+LAMBDA*PDMDIF_P,POEFM_P,NBAST_P,PHI_P,METHOD_P) CALL BUILDTEFM(PTEFM,NBAST_P,PHI_P,PDM) ETOT=ENERGY(POEFM_P,PTEFM,PDM,NBAST_P) END FUNCTION DFE SUBROUTINE ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Eric Séré's Algorithm USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools USE optimization_tools ; USE esa_mod USE debug INTEGER,INTENT(IN),TARGET :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME CHARACTER,TARGET :: METHOD INTEGER :: ITER,LOON,INFO,I,NUM DOUBLE PRECISION :: ALPHA,BETA,LAMBDA DOUBLE PRECISION :: DPDUMMY,TOL DOUBLE PRECISION :: ETOT,ETOT1,ETTOT,PDMDIFNORM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: PTDM,PDMDIF LOGICAL :: NUMCONV INTERFACE DOUBLE PRECISION FUNCTION DFE(LAMBDA) DOUBLE PRECISION,INTENT(IN) :: LAMBDA END FUNCTION END INTERFACE ! INITIALIZATIONS AND PRELIMINARIES OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) READ(100,'(/,a)')METHOD CLOSE(100) IF (METHOD=='D') THEN WRITE(*,*)'Function $Theta$ computed using diagonalization' - ELSE + ELSEIF(METHOD=='S') THEN WRITE(*,*)'Function $Theta$ computed using polynomial recursion' + ELSE + WRITE(*,*)'Function $Theta$ ignored' END IF ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ! Pointer assignments NBAST_P=>NBAST ; POEFM_P=>POEFM ; PTDM_P=>PTDM ; PDMDIF_P=>PDMDIF ; PHI_P=>PHI ; METHOD_P=>METHOD ITER=0 TOL=1.D-4 PDM=(0.D0,0.D0) ; PTDM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/esaenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/esacrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/esacrit2.txt',STATUS='unknown',ACTION='write') OPEN(19,FILE='plots/esaenrgyt.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) PDM1=PDM CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! test ERIC ! PFM=POEFM+PTEFM ! CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) ! CALL CHECKORB(EIG,NBAST,LOON) ! computation of the positive spectral projector associated to PFM ! CALL FORMDM(PTMP,EIGVEC,NBAST,LOON,NBAST) ! infinity norm of the commutator between PFM and its positive spectral projector ! WRITE(44,*)ITER,NORM(COMMUTATOR(POEFM+PTEFM,PTMP,PS,NBAST),NBAST,'I') ! fin test ERIC ! Computation of the pseudo density matrix IF (THETA_CHECK) WRITE(13,*)'theta(D-~D)' IF(METHOD == 'N') THEN PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,'D') ELSE PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD) END IF PDMDIFNORM=NORM(ABA(PSRS,PDMDIF,NBAST),NBAST,'I') WRITE(*,*)'Infinity norm of the difference D_{n-1}-~D_{n-2}=',PDMDIFNORM IF (PDMDIFNORM<=TRSHLD) GO TO 2 BETA=REAL(TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)) write(*,*)'beta=',beta IF (BETA>0.D0) THEN WRITE(*,*)'Warning: internal computation error (beta>0).' GO TO 4 ELSE CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF) ALPHA=REAL(TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)) write(*,*)'alpha=',alpha IF (ALPHA>0.D0) THEN LAMBDA=-BETA/ALPHA IF (LAMBDA<1.D0) THEN WRITE(*,*)'lambda=',LAMBDA ! on peut raffiner avec la methode de la section doree (la fonction n'etant a priori pas quadratique), voir comment optimiser un peu cela... ! WRITE(*,*)'refinement using golden section search (',0.D0,',',LAMBDA,',',1.D0,')' ! DPDUMMY=GOLDEN(0.D0,LAMBDA,1.D0,DFE,TOL,LAMBDA) IF (THETA_CHECK) WRITE(13,*)'theta(~D+s(D-~D))' PTDM=THETA(PTDM+LAMBDA*PDMDIF,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) END IF ELSE IF (ALPHA<0.D0) THEN WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'Warning: internal computation error (alpha=0).' GO TO 4 END IF END IF ! Trace of the pseudo density matrix WRITE(*,*)'tr(tilde{D}_n)=',REAL(TRACE(ABA(PSRS,PTDM,NBAST),NBAST)) ! Energy associated to the pseudo density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST) WRITE(19,*)ETTOT WRITE(*,*)'E(tilde{D}_n)=',ETTOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: convergence after',ITER,'iteration(s).' GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: no convergence after',ITER,'iteration(s).' GO TO 6 4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: computation stopped after',ITER,'iteration(s).' GO TO 6 5 WRITE(*,*)'(called from subroutine ESA)' GO TO 7 6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) 7 NULLIFY(NBAST_P,POEFM_P,PTDM_P,PDMDIF_P,PHI_P) DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) ; CLOSE(19) END SUBROUTINE ESA
antoine-levitt/ACCQUAREL
06f1a82290f8c79e2e05e850f98ec20fd476542d
Add option NONE (N) to avoid using theta in ESA
diff --git a/src/esa.f90 b/src/esa.f90 index 87dc100..958887a 100644 --- a/src/esa.f90 +++ b/src/esa.f90 @@ -1,281 +1,287 @@ MODULE esa_mod USE basis_parameters INTEGER,POINTER :: NBAST_P DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_P,PTDM_P,PDMDIF_P TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_P CHARACTER,POINTER :: METHOD_P CONTAINS FUNCTION THETA(PDM,POEFM,N,PHI,METHOD) RESULT (PDMNEW) ! Function that computes the value of $\Theta(D)$ (with $D$ a hermitian matrix of size N, which upper triangular part is stored in packed form in PDM) with precision TOL (if the (geometrical) convergence of the fixed-point iterative sequence is attained), \Theta being the function defined in: A new definition of the Dirac-Fock ground state, Eric Séré, preprint (2009). USE case_parameters ; USE basis_parameters ; USE matrices USE matrix_tools ; USE metric_relativistic USE debug CHARACTER,INTENT(IN) :: METHOD INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PDM,POEFM TYPE(twospinor),DIMENSION(N),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PDMNEW INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-8 INTEGER :: ITER,INFO,LOON DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PTEFM,PFM,PDMOLD,PPROJM DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,DM,SF,TSF ITER=0 PDMOLD=PDM IF (THETA_CHECK) THEN WRITE(13,*)'tr(SD)=',REAL(TRACEOFPRODUCT(PS,PDM,N)) ! PTMP=PDM ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF ! Fixed-point iterative sequence DO ITER=ITER+1 ! Projection of the current density matrix CALL BUILDTEFM(PTEFM,N,PHI,PDMOLD) PFM=POEFM+PTEFM IF (METHOD=='D') THEN ! computation of the "positive" spectral projector associated to the Fock matrix based on the current density matrix via diagonalization CALL EIGENSOLVER(PFM,PCFS,N,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 1 CALL FORMPROJ(PPROJM,EIGVEC,N,MINLOC(EIG,DIM=1,MASK=EIG>-C*C)) PDMNEW=ABCBA(PPROJM,PS,PDMOLD,N) - ELSE + ELSEIF(METHOD=='S') THEN ! OR ! computation of the "positive" spectral projector via the sign function obtained by polynomial recursion DM=UNPACK(PDMOLD,N) ; SF=SIGN(PFM+C*C*PS,N) TSF=TRANSPOSE(CONJG(SF)) PDMNEW=PACK((DM+MATMUL(DM,TSF)+MATMUL(SF,DM+MATMUL(DM,TSF)))/4.D0,N) + ELSE !METHOD=='N' + PDMNEW = PDMOLD END IF IF (THETA_CHECK) THEN WRITE(13,*)'Iter #',ITER WRITE(13,*)'tr(SPSDSP)=',REAL(TRACEOFPRODUCT(PS,PDMNEW,N)) ! PTMP=PDMNEW ; CALL ZHPEV('N','U',N,PTMP,EIG,EIGVEC,N,WORK,RWORK,INFO) ! IF (INFO==0) WRITE(13,*)' Eigenvalues:',EIG END IF IF (THETA_CHECK) WRITE(13,*)'Residual =',NORM(ABA(PSRS,PDMNEW-PDMOLD,N),N,'I') IF (NORM(PDMNEW-PDMOLD,N,'I')<TOL) THEN IF (THETA_CHECK) THEN WRITE(13,'(a,i3,a)')' Function THETA: convergence after ',ITER,' iteration(s).' WRITE(13,*)ITER,NORM(PDMNEW-PDMOLD,N,'I') END IF RETURN ELSE IF (ITER>=ITERMAX) THEN WRITE(*,*)'Function THETA: no convergence after ',ITER,' iteration(s).' IF (THETA_CHECK) THEN WRITE(13,*)'Function THETA: no convergence after ',ITER,' iteration(s).' WRITE(13,*)'Residual =',NORM(PDMNEW-PDMOLD,N,'I') END IF STOP END IF PDMOLD=PDMNEW END DO 1 WRITE(*,*)'(called from subroutine THETA)' END FUNCTION THETA FUNCTION SIGN(PA,N) RESULT (SA) ! Function that computes the sign function of the hermitian matrix of a selfadjoint operator, which upper triangular part is stored in packed form, using a polynomial recursion (PINVS contains the inverse of the overlap matrix, which upper triangular part is stored in packed form). ! Note: the result is an unpacked matrix due to subsequent use. USE matrix_tools ; USE metric_relativistic INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: SA DOUBLE COMPLEX,DIMENSION(N,N) :: A,ISRS INTEGER,PARAMETER :: ITERMAX=50 DOUBLE PRECISION,PARAMETER :: TOL=1.D-15 INTEGER :: I,ITER A=UNPACK(PA,N) ; ISRS=UNPACK(PISRS,N) SA=MATMUL(UNPACK(PIS,N),A)/NORM(MATMUL(ISRS,MATMUL(A,ISRS)),N,'F') ITER=0 DO ITER=ITER+1 A=SA SA=(3.D0*SA-MATMUL(SA,MATMUL(SA,SA)))/2.D0 IF (NORM(SA-A,N,'F')<TOL) THEN RETURN ELSE IF (ITER==ITERMAX) THEN WRITE(*,*)'Function SIGN: no convergence after ',ITER,' iteration(s).' STOP END IF END DO END FUNCTION SIGN END MODULE FUNCTION DFE(LAMBDA) RESULT (ETOT) USE common_functions ; USE matrices ; USE matrix_tools ; USE esa_mod DOUBLE PRECISION,INTENT(IN) :: LAMBDA DOUBLE PRECISION :: ETOT DOUBLE COMPLEX,DIMENSION(NBAST_P*(NBAST_P+1)/2) :: PDM,PTEFM,PTMP PDM=THETA(PTDM_P+LAMBDA*PDMDIF_P,POEFM_P,NBAST_P,PHI_P,METHOD_P) CALL BUILDTEFM(PTEFM,NBAST_P,PHI_P,PDM) ETOT=ENERGY(POEFM_P,PTEFM,PDM,NBAST_P) END FUNCTION DFE SUBROUTINE ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Eric Séré's Algorithm USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE setup_tools USE optimization_tools ; USE esa_mod USE debug INTEGER,INTENT(IN),TARGET :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(INOUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(INOUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME CHARACTER,TARGET :: METHOD INTEGER :: ITER,LOON,INFO,I,NUM DOUBLE PRECISION :: ALPHA,BETA,LAMBDA DOUBLE PRECISION :: DPDUMMY,TOL DOUBLE PRECISION :: ETOT,ETOT1,ETTOT,PDMDIFNORM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PTTEFM,PFM,PDM,PDM1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: PTDM,PDMDIF LOGICAL :: NUMCONV INTERFACE DOUBLE PRECISION FUNCTION DFE(LAMBDA) DOUBLE PRECISION,INTENT(IN) :: LAMBDA END FUNCTION END INTERFACE ! INITIALIZATIONS AND PRELIMINARIES OPEN(100,FILE=SETUP_FILE,STATUS='OLD',ACTION='READ') CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) READ(100,'(/,a)')METHOD CLOSE(100) IF (METHOD=='D') THEN WRITE(*,*)'Function $Theta$ computed using diagonalization' ELSE WRITE(*,*)'Function $Theta$ computed using polynomial recursion' END IF ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PTTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ! Pointer assignments NBAST_P=>NBAST ; POEFM_P=>POEFM ; PTDM_P=>PTDM ; PDMDIF_P=>PDMDIF ; PHI_P=>PHI ; METHOD_P=>METHOD ITER=0 TOL=1.D-4 PDM=(0.D0,0.D0) ; PTDM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/esaenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/esacrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/esacrit2.txt',STATUS='unknown',ACTION='write') OPEN(19,FILE='plots/esaenrgyt.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the pseudo-density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) PFM=POEFM+PTTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 5 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) PDM1=PDM CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! test ERIC ! PFM=POEFM+PTEFM ! CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) ! CALL CHECKORB(EIG,NBAST,LOON) ! computation of the positive spectral projector associated to PFM ! CALL FORMDM(PTMP,EIGVEC,NBAST,LOON,NBAST) ! infinity norm of the commutator between PFM and its positive spectral projector ! WRITE(44,*)ITER,NORM(COMMUTATOR(POEFM+PTEFM,PTMP,PS,NBAST),NBAST,'I') ! fin test ERIC ! Computation of the pseudo density matrix IF (THETA_CHECK) WRITE(13,*)'theta(D-~D)' - PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD) + IF(METHOD == 'N') THEN + PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,'D') + ELSE + PDMDIF=THETA(PDM-PTDM,POEFM,NBAST,PHI,METHOD) + END IF PDMDIFNORM=NORM(ABA(PSRS,PDMDIF,NBAST),NBAST,'I') WRITE(*,*)'Infinity norm of the difference D_{n-1}-~D_{n-2}=',PDMDIFNORM IF (PDMDIFNORM<=TRSHLD) GO TO 2 BETA=REAL(TRACEOFPRODUCT(POEFM+PTTEFM,PDMDIF,NBAST)) write(*,*)'beta=',beta IF (BETA>0.D0) THEN WRITE(*,*)'Warning: internal computation error (beta>0).' GO TO 4 ELSE CALL BUILDTEFM(PTTEFM,NBAST,PHI,PDMDIF) ALPHA=REAL(TRACEOFPRODUCT(PTTEFM,PDMDIF,NBAST)) write(*,*)'alpha=',alpha IF (ALPHA>0.D0) THEN LAMBDA=-BETA/ALPHA IF (LAMBDA<1.D0) THEN WRITE(*,*)'lambda=',LAMBDA ! on peut raffiner avec la methode de la section doree (la fonction n'etant a priori pas quadratique), voir comment optimiser un peu cela... ! WRITE(*,*)'refinement using golden section search (',0.D0,',',LAMBDA,',',1.D0,')' ! DPDUMMY=GOLDEN(0.D0,LAMBDA,1.D0,DFE,TOL,LAMBDA) IF (THETA_CHECK) WRITE(13,*)'theta(~D+s(D-~D))' PTDM=THETA(PTDM+LAMBDA*PDMDIF,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) END IF ELSE IF (ALPHA<0.D0) THEN WRITE(*,*)'lambda=1.' IF (THETA_CHECK) WRITE(13,*)'theta(D)' PTDM=THETA(PDM,POEFM,NBAST,PHI,METHOD) ELSE WRITE(*,*)'Warning: internal computation error (alpha=0).' GO TO 4 END IF END IF ! Trace of the pseudo density matrix WRITE(*,*)'tr(tilde{D}_n)=',REAL(TRACE(ABA(PSRS,PTDM,NBAST),NBAST)) ! Energy associated to the pseudo density matrix CALL BUILDTEFM(PTTEFM,NBAST,PHI,PTDM) ETTOT=ENERGY(POEFM,PTTEFM,PTDM,NBAST) WRITE(19,*)ETTOT WRITE(*,*)'E(tilde{D}_n)=',ETTOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: convergence after',ITER,'iteration(s).' GO TO 6 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: no convergence after',ITER,'iteration(s).' GO TO 6 4 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ESA: computation stopped after',ITER,'iteration(s).' GO TO 6 5 WRITE(*,*)'(called from subroutine ESA)' GO TO 7 6 OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) 7 NULLIFY(NBAST_P,POEFM_P,PTDM_P,PDMDIF_P,PHI_P) DEALLOCATE(PDM,PDM1,PTDM,PDMDIF,PTEFM,PTTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) ; CLOSE(19) END SUBROUTINE ESA diff --git a/src/setup.f90 b/src/setup.f90 index 2f557ab..ae8e1dd 100644 --- a/src/setup.f90 +++ b/src/setup.f90 @@ -271,540 +271,540 @@ FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL) CASE (35) ; SYMBOL='Br' CASE (36) ; SYMBOL='Kr' CASE (37) ; SYMBOL='Rb' CASE (38) ; SYMBOL='Sr' CASE (39) ; SYMBOL='Y' CASE (40) ; SYMBOL='Zr' CASE (41) ; SYMBOL='Nb' CASE (42) ; SYMBOL='Mo' CASE (43) ; SYMBOL='Tc' CASE (44) ; SYMBOL='Ru' CASE (45) ; SYMBOL='Rh' CASE (46) ; SYMBOL='Pd' CASE (47) ; SYMBOL='Ag' CASE (48) ; SYMBOL='Cd' CASE (49) ; SYMBOL='In' CASE (50) ; SYMBOL='Sn' CASE (51) ; SYMBOL='Sb' CASE (52) ; SYMBOL='Te' CASE (53) ; SYMBOL='I' CASE (54) ; SYMBOL='Xe' CASE (55) ; SYMBOL='Cs' CASE (56) ; SYMBOL='Ba' CASE (57) ; SYMBOL='La' ! Lanthanide elements (lanthanoids) CASE (58) ; SYMBOL='Ce' CASE (59) ; SYMBOL='Pr' CASE (60) ; SYMBOL='Nd' CASE (61) ; SYMBOL='Pm' CASE (62) ; SYMBOL='Sm' CASE (63) ; SYMBOL='Eu' CASE (64) ; SYMBOL='Gd' CASE (65) ; SYMBOL='Tb' CASE (66) ; SYMBOL='Dy' CASE (67) ; SYMBOL='Ho' CASE (68) ; SYMBOL='Er' CASE (69) ; SYMBOL='Tm' CASE (70) ; SYMBOL='Yb' CASE (71) ; SYMBOL='Lu' CASE (72) ; SYMBOL='Hf' CASE (73) ; SYMBOL='Ta' CASE (74) ; SYMBOL='W' CASE (75) ; SYMBOL='Re' CASE (76) ; SYMBOL='Os' CASE (77) ; SYMBOL='Ir' CASE (78) ; SYMBOL='Pt' CASE (79) ; SYMBOL='Au' CASE (80) ; SYMBOL='Hg' CASE (81) ; SYMBOL='Tl' CASE (82) ; SYMBOL='Pb' CASE (83) ; SYMBOL='Bi' CASE (84) ; SYMBOL='Po' CASE (85) ; SYMBOL='As' CASE (86) ; SYMBOL='Rn' CASE (87) ; SYMBOL='Fr' CASE (88) ; SYMBOL='Ra' CASE (89) ; SYMBOL='Ac' ! Actinide elements (actinoids) CASE (90) ; SYMBOL='Th' CASE (91) ; SYMBOL='Pa' CASE (92) ; SYMBOL='U' CASE (93) ; SYMBOL='Np' CASE (94) ; SYMBOL='Pu' CASE (95) ; SYMBOL='Am' CASE (96) ; SYMBOL='Cm' CASE (97) ; SYMBOL='Bk' CASE (98) ; SYMBOL='Cf' CASE (99) ; SYMBOL='Es' CASE (100); SYMBOL='Fm' CASE (101); SYMBOL='Md' CASE (102); SYMBOL='No' CASE (103); SYMBOL='Lr' CASE (104); SYMBOL='Rf' END SELECT END FUNCTION IDENTIFYZ SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system. INTEGER :: I,J DOUBLE PRECISION,DIMENSION(3) :: DIFF INTERNUCLEAR_ENERGY=0.D0 DO I=1,NBN DO J=I+1,NBN DIFF=CENTER(:,I)-CENTER(:,J) INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF)) END DO END DO END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Various functions for the Hartree model with temperature FUNCTION POSITIVE_PART(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN FUNC=0.D0 ELSE FUNC=X END IF END FUNCTION POSITIVE_PART FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC) ! beta test function for the entropy DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC FUNC=POSITIVE_PART(X)**MB/MB END FUNCTION ENTROPY_FUNCTION FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE FUNC=X**(1.D0/(MB-1.D0)) END IF END FUNCTION RECIP_DENTFUNC FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE IF (X==0.D0) THEN STOP'No derivative at origin' ELSE FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0) END IF END FUNCTION FUNCTION FUNCFORMU(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC INTEGER :: I DOUBLE PRECISION :: Y FUNC=-MASS DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE IF (Y>=0.D0) THEN FUNC=FUNC+RECIP_DENTFUNC(Y) END IF END DO END FUNCTION FUNCFORMU SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV INTEGER :: I DOUBLE PRECISION :: Y FVAL=-MASS ; FDERIV=0.D0 DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE FVAL=FVAL+RECIP_DENTFUNC(Y) FDERIV=FDERIV+DRECIP_DENTFUNC(Y) END DO END SUBROUTINE RDENTFUNCD END MODULE MODULE basis_parameters USE iso_c_binding ! flag for the choice of the basis set type (either existing in the library or even-tempered) LOGICAL :: LIBRARY ! PARAMETERS FOR A GIVEN BASIS SET CHARACTER(26) :: BASISFILE INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4 ! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme. ! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET INTEGER :: NUMBER_OF_TERMS DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO ! Various flags for the contraction of the primitives and the Kinetic Balance scheme LOGICAL :: UNCONT LOGICAL :: KINBAL,UKB TYPE gaussianbasisfunction ! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function. ! nbrofexponents: the number of different gaussian primitives present in the contraction ! center: coordinates (x,y,z) of the center of the basis function ! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center) ! exponents: array containing the exponent of each of the gaussian primitives present in the contraction ! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction ! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives ! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance). INTEGER(KIND=C_INT) :: nbrofexponents REAL(KIND=C_DOUBLE),DIMENSION(3) :: center INTEGER :: center_id REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree END TYPE gaussianbasisfunction TYPE twospinor ! Definition of a Pauli 2-spinor type basis function using gaussian basis functions. ! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor ! contractions: array containing the contractions present in each of the components of the 2-spinor ! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes) ! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor ! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0 INTEGER,DIMENSION(2) :: nbrofcontractions TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions INTEGER,DIMENSION(2,MNOGBF) :: contidx DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients END TYPE twospinor CONTAINS SUBROUTINE SETUP_BASIS USE case_parameters ; USE setup_tools CHARACTER(LEN=4) :: CHAR CHARACTER(LEN=26) :: BASISNAME INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## BASIS DEFINITION',INFO) IF (INFO/=0) STOP' The basis definition is not given.' READ(100,'(3/,a)') BASISNAME IF (BASISNAME(1:6)=='BASIS ') THEN ! The basis set is an existing one in the basis library LIBRARY=.TRUE. BASISFILE='basis/'//BASISNAME(7:) READ(100,'(a4)') CHAR IF (CHAR=='UNCO') THEN UNCONT=.TRUE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)' ELSE UNCONT=.FALSE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)' END IF ELSE IF (BASISNAME(1:4)=='EVEN') THEN ! The basis set is an even-tempered one LIBRARY=.FALSE. IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)' WRITE(*,'(a)')' Even-tempered basis set (preliminary support)' READ(100,'(i4)') NUMBER_OF_TERMS WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS READ(100,*) FIRST_TERM WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM READ(100,*) COMMON_RATIO WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO ELSE STOP' Unknown basis set type' END IF IF (RELATIVISTIC) THEN READ(100,'(a2)') CHAR IF (CHAR=='KI') THEN KINBAL=.TRUE. READ(100,'(a4)') CHAR IF (CHAR=='REST') THEN UKB=.FALSE. WRITE(*,'(a)')' Restricted kinetic balance' ELSE UKB=.TRUE. WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance' END IF ELSE KINBAL=.FALSE. WRITE(*,'(a)')' No kinetic balance' END IF END IF CLOSE(100) END SUBROUTINE SETUP_BASIS FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE) ! Function that computes the value of a gaussian basis function at a given point of space. USE iso_c_binding TYPE(gaussianbasisfunction),INTENT(IN) :: GBF DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT REAL(KIND=C_DOUBLE) :: VALUE VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) & & *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), & & EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2))) END FUNCTION GBF_POINTWISE_VALUE SUBROUTINE PRINTGBF(PHI,NUNIT) TYPE(gaussianbasisfunction),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents WRITE(NUNIT,*)' center:',PHI%center WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree DO I=1,PHI%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',I WRITE(NUNIT,*)' exponent:',PHI%exponents(I) WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I) END DO END SUBROUTINE PRINTGBF FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE) ! Function that computes the value of a Pauli 2-spinor basis function at a given point of space. USE iso_c_binding TYPE(twospinor),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT DOUBLE COMPLEX,DIMENSION(2) :: VALUE INTEGER :: I,J DO I=1,2 VALUE(I)=(0.D0,0.D0) DO J=1,PHI%nbrofcontractions(I) VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT) END DO END DO END FUNCTION TWOSPINOR_POINTWISE_VALUE SUBROUTINE PRINT2SPINOR(PHI,NUNIT) TYPE(twospinor),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I,J,K DO K=1,2 WRITE(NUNIT,*)'component #',K IF (PHI%nbrofcontractions(K)==0) THEN WRITE(NUNIT,*)' no contraction' ELSE WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K) DO I=1,PHI%nbrofcontractions(K) WRITE(NUNIT,*)' contraction #',I WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I) WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center DO J=1,PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',J WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J) WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J) END DO END DO END IF END DO END SUBROUTINE PRINT2SPINOR END MODULE MODULE scf_parameters ! number of different SCF algorithms to be used INTEGER :: NBALG ! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only)) INTEGER,DIMENSION(5) :: ALG ! threshold for numerical convergence DOUBLE PRECISION :: TRSHLD ! maximum number of iterations allowed INTEGER :: MAXITR ! flag for the direct computation of the bielectronic integrals LOGICAL :: DIRECT ! flag for the "semi-direct" computation of the bielectronic integrals (relativistic case only) ! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards. LOGICAL :: SEMIDIRECT ! flag for the storage of the computed bielectronic integrals (and/or their list) on disk or in memory LOGICAL :: USEDISK ! flag for the use of the SS-bielectronic integrals LOGICAL :: SSINTEGRALS ! flag for the use of the LS-bielectronic integrals LOGICAL :: SLINTEGRALS ! resume EIG and EIGVEC from last computation LOGICAL :: RESUME ! symmetries of the system LOGICAL :: SYM_SX = .FALSE.,SYM_SY = .FALSE.,SYM_SZ = .FALSE. CONTAINS SUBROUTINE SETUP_SCF !$ USE omp_lib USE case_parameters ; USE setup_tools CHARACTER :: METHOD CHARACTER(4) :: CHAR INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS DOUBLE PRECISION :: SHIFT OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## SCF PARAMETERS',INFO) IF (INFO/=0) STOP' The SCF parameters are not given.' READ(100,'(7/,i1)') NBALG DO I=1,NBALG READ(100,'(i1)') ALG(I) IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN STOP' The Optimal Damping Algorithm is intended for the non-relativistic case only.' ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN STOP' ES''s algorithm is intended for the relativistic case only.' END IF END DO READ(100,*) TRSHLD WRITE(*,*)'Threshold =',TRSHLD READ(100,'(i5)') MAXITR WRITE(*,*)'Maximum number of iterations =',MAXITR READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ; SEMIDIRECT=.FALSE. READ(100,'(a4)') CHAR ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE IF (CHAR=='SEM') THEN DIRECT=.FALSE. ; SEMIDIRECT=.TRUE. WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF IF (MODEL==3) THEN ! Special case: complex GHF SSINTEGRALS=.FALSE. SLINTEGRALS=.FALSE. ELSE REWIND(100) CALL LOOKFOR(100,'NOSS',INFO) IF (INFO==0) THEN SSINTEGRALS=.FALSE. WRITE(*,'(a)')' (SS-integrals are not used in the computation)' ELSE SSINTEGRALS=.TRUE. END IF REWIND(100) CALL LOOKFOR(100,'NOSL',INFO) IF (INFO==0) THEN SLINTEGRALS=.FALSE. WRITE(*,'(a)')' (SL-integrals are not used in the computation)' ELSE SLINTEGRALS=.TRUE. END IF END IF REWIND(100) CALL LOOKFOR(100,'SYMMETRY SX',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses X-plane symmetry)' SYM_SX = .TRUE. END IF REWIND(100) CALL LOOKFOR(100,'SYMMETRY SY',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses Y-plane symmetry)' SYM_SY = .TRUE. END IF REWIND(100) CALL LOOKFOR(100,'SYMMETRY SZ',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses Z-plane symmetry)' SYM_SZ = .TRUE. END IF ELSE IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! the list of the bielectronic integrals is stored in memory ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF END IF ! additional verifications on the parameters of the algorithms DO I=1,NBALG IF (ALG(I)==2) THEN REWIND(100) CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 1 READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT ELSE IF (ALG(I)==3) THEN REWIND(100) CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 2 READ(100,'(/,i2)',ERR=2,END=2)MXSET IF (MXSET<2) GO TO 3 ELSE IF (ALG(I)==5) THEN REWIND(100) CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 4 READ(100,'(/,a)',ERR=4,END=4)METHOD - IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4 + IF ((METHOD/='D').AND.(METHOD/='S').AND.(METHOD/='N')) GO TO 4 END IF END DO RESUME=.FALSE. CALL LOOKFOR(100,'RESUME',INFO) IF(INFO == 0) THEN READ(100,'(a)')CHAR IF(CHAR == 'YES') THEN RESUME = .TRUE. END IF END IF !$ ! determination of the number of threads to be used by OpenMP !$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO) !$ IF (INFO==0) THEN !$ READ(100,'(/,i3)')NUMBER_OF_THREADS !$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS) !$ END IF !$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.' CLOSE(100) RETURN ! MESSAGES 1 STOP'No shift parameter given for the level-shifting algorithm.' 2 STOP'No simplex dimension given for the DIIS algorithm.' 3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.' 4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.' END SUBROUTINE SETUP_SCF END MODULE
antoine-levitt/ACCQUAREL
c89a80df31e364fbc419e41945724f7dfd46582b
removed a "known problem" case from the list following the debugging in A.S.P.I.C
diff --git a/known_problems/RHF_CO_STO3G.log b/known_problems/RHF_CO_STO3G.log deleted file mode 100644 index 639ce8e..0000000 --- a/known_problems/RHF_CO_STO3G.log +++ /dev/null @@ -1,2694 +0,0 @@ - *** ACCQUAREL using A.S.P.I.C. *** - Non-relativistic case - Hartree-Fock approximation (Slater determinant wave function) - Restricted closed-shell formalism - Threshold = 0.000001 - Maximum number of iterations = 100 - Computed bielectronic integrals stored in memory - --- Molecular system --- - ** NAME: CO molecule - * Nucleus # 1 - Charge Z= 6 (element: C ) - Center position = 0.00000000 0.00000000 0.00000000 - * Nucleus # 2 - Charge Z= 8 (element: O ) - Center position = 2.13200000 0.00000000 0.00000000 - * Internuclear repulsion energy of the system = 22.51407129 - * Total number of electrons in the system = 14 - --------- **** --------- - Basis set: BASIS STO-3G (contracted) - Total number of basis functions = 10 - -* Computation and assembly of the overlap matrix -* Computation and assembly of the core hamiltonian matrix -* Creation of the list of nonzero bielectronic integrals - Number of GBF bielectronic integrals to be computed: 1366 -* Computation of the bielectronic integrals of GBF basis functions - 10% done - 20% done - 30% done - 40% done - 50% done - 60% done - 70% done - 80% done - 90% done - 100% done - - Roothaan's algorithm - - # ITER = 1 - E(D_n)= -9.073124781581628E+11 - Infinity norm of the difference D_n-D_{n-1} = 1.2100579819673856 - Frobenius norm of the difference D_n-D_{n-1} = 2.645751311064592 - Infinity norm of the commutator [F(D_n),D_n] = 1.0412161960774183E+12 - Frobenius norm of the commutator [F(D_n),D_n] = 1.338737729383472E+12 - Difference of the energies E_n-E_{n-1} = -9.073124781581628E+11 - - # ITER = 2 - E(D_n)= -6.624089601525484E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3009747150339748 - Frobenius norm of the difference D_n-D_{n-1} = 1.868410256174138 - Infinity norm of the commutator [F(D_n),D_n] = 2.767526807413616E+11 - Frobenius norm of the commutator [F(D_n),D_n] = 3.210571393316269E+11 - Difference of the energies E_n-E_{n-1} = -5.716777123367321E+12 - - # ITER = 3 - E(D_n)= -6.654187827229986E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.04950111641461568 - Frobenius norm of the difference D_n-D_{n-1} = 0.08947695158032672 - Infinity norm of the commutator [F(D_n),D_n] = 5.525877770276561E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 6.415766521772859E+10 - Difference of the energies E_n-E_{n-1} = -3.0098225704501953E+10 - - # ITER = 4 - E(D_n)= -6.655384408772801E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.00965403711996582 - Frobenius norm of the difference D_n-D_{n-1} = 0.017852563679180162 - Infinity norm of the commutator [F(D_n),D_n] = 1.0979032315808683E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 1.274652344568357E+10 - Difference of the energies E_n-E_{n-1} = -1.1965815428144531E+9 - - # ITER = 5 - E(D_n)= -6.655431617733268E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.0019102407484255265 - Frobenius norm of the difference D_n-D_{n-1} = 0.003545775127000044 - Infinity norm of the commutator [F(D_n),D_n] = 2.180026516466998E+9 - Frobenius norm of the commutator [F(D_n),D_n] = 2.5309528983494825E+9 - Difference of the energies E_n-E_{n-1} = -4.7208960466796875E+7 - - # ITER = 6 - E(D_n)= -6.655433478878964E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.0003789972514012589 - Frobenius norm of the difference D_n-D_{n-1} = 0.0007040158252857439 - Infinity norm of the commutator [F(D_n),D_n] = 4.3283035403956103E+8 - Frobenius norm of the commutator [F(D_n),D_n] = 5.0250324153350693E+8 - Difference of the energies E_n-E_{n-1} = -1861145.6962890625 - - # ITER = 7 - E(D_n)= -6.655433552243254E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.00007523548509311476 - Frobenius norm of the difference D_n-D_{n-1} = 0.00013977620780798253 - Infinity norm of the commutator [F(D_n),D_n] = 8.593414929641753E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 9.97669541118814E+7 - Difference of the energies E_n-E_{n-1} = -73364.2900390625 - - # ITER = 8 - E(D_n)= -6.655433555135134E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000014936782321012737 - Frobenius norm of the difference D_n-D_{n-1} = 0.00002775110746219737 - Infinity norm of the commutator [F(D_n),D_n] = 1.7061307498857487E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 1.9807661096722428E+7 - Difference of the energies E_n-E_{n-1} = -2891.8798828125 - - # ITER = 9 - E(D_n)= -6.655433555249118E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000002965519959713296 - Frobenius norm of the difference D_n-D_{n-1} = 0.0000055096834507478994 - Infinity norm of the commutator [F(D_n),D_n] = 3387337.9916560412 - Frobenius norm of the commutator [F(D_n),D_n] = 3932596.7006554697 - Difference of the energies E_n-E_{n-1} = -113.984375 - - # ITER = 10 - E(D_n)= -6.65543355525362E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.887711653437171E-7 - Frobenius norm of the difference D_n-D_{n-1} = 0.000001093887931496685 - Infinity norm of the commutator [F(D_n),D_n] = 672519.2110593879 - Frobenius norm of the commutator [F(D_n),D_n] = 780774.4094945464 - Difference of the energies E_n-E_{n-1} = -4.501953125 - - # ITER = 11 - E(D_n)= -6.655433555253789E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1689409969135961E-7 - Frobenius norm of the difference D_n-D_{n-1} = 2.1717957812987995E-7 - Infinity norm of the commutator [F(D_n),D_n] = 133521.3860332804 - Frobenius norm of the commutator [F(D_n),D_n] = 155014.28201810445 - Difference of the energies E_n-E_{n-1} = -0.1689453125 - - # ITER = 12 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.3208052611859317E-8 - Frobenius norm of the difference D_n-D_{n-1} = 4.3118647675411076E-8 - Infinity norm of the commutator [F(D_n),D_n] = 26509.223364844573 - Frobenius norm of the commutator [F(D_n),D_n] = 30776.404450294376 - Difference of the energies E_n-E_{n-1} = -0.01171875 - - # ITER = 13 - E(D_n)= -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 4.607707442387816E-9 - Frobenius norm of the difference D_n-D_{n-1} = 8.560739449311445E-9 - Infinity norm of the commutator [F(D_n),D_n] = 5263.117464205615 - Frobenius norm of the commutator [F(D_n),D_n] = 6110.32121917598 - Difference of the energies E_n-E_{n-1} = 0.00390625 - - # ITER = 14 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.148100205317379E-10 - Frobenius norm of the difference D_n-D_{n-1} = 1.6996419901833426E-9 - Infinity norm of the commutator [F(D_n),D_n] = 1044.936542330056 - Frobenius norm of the commutator [F(D_n),D_n] = 1213.1390987967911 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 15 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8162602502733666E-10 - Frobenius norm of the difference D_n-D_{n-1} = 3.37445542826422E-10 - Infinity norm of the commutator [F(D_n),D_n] = 207.46230752511465 - Frobenius norm of the commutator [F(D_n),D_n] = 240.85734112185816 - Difference of the energies E_n-E_{n-1} = -0.0078125 - - # ITER = 16 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 3.60600750635283E-11 - Frobenius norm of the difference D_n-D_{n-1} = 6.699598726726368E-11 - Infinity norm of the commutator [F(D_n),D_n] = 41.189857791829354 - Frobenius norm of the commutator [F(D_n),D_n] = 47.82036259696997 - Difference of the energies E_n-E_{n-1} = 0.0078125 - - # ITER = 17 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 7.15950361286928E-12 - Frobenius norm of the difference D_n-D_{n-1} = 1.3301627036950307E-11 - Infinity norm of the commutator [F(D_n),D_n] = 8.180325184176949 - Frobenius norm of the commutator [F(D_n),D_n] = 9.495587813892667 - Difference of the energies E_n-E_{n-1} = -0.0068359375 - - # ITER = 18 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.421301630769462E-12 - Frobenius norm of the difference D_n-D_{n-1} = 2.6408264422743436E-12 - Infinity norm of the commutator [F(D_n),D_n] = 1.6237587945342689 - Frobenius norm of the commutator [F(D_n),D_n] = 1.8860605386045168 - Difference of the energies E_n-E_{n-1} = 0.00390625 - - # ITER = 19 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.8280614846791427E-13 - Frobenius norm of the difference D_n-D_{n-1} = 5.241859332183749E-13 - Infinity norm of the commutator [F(D_n),D_n] = 0.31994832485684577 - Frobenius norm of the commutator [F(D_n),D_n] = 0.3732624432732286 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 20 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.5770262247640113E-14 - Frobenius norm of the difference D_n-D_{n-1} = 1.0421381881245466E-13 - Infinity norm of the commutator [F(D_n),D_n] = 0.06348466595877274 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0744420903573228 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 21 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1794992107837885E-14 - Frobenius norm of the difference D_n-D_{n-1} = 2.0812864327049814E-14 - Infinity norm of the commutator [F(D_n),D_n] = 0.012731248043732607 - Frobenius norm of the commutator [F(D_n),D_n] = 0.014952016326266023 - Difference of the energies E_n-E_{n-1} = -0.0048828125 - - # ITER = 22 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.5264559601570736E-15 - Frobenius norm of the difference D_n-D_{n-1} = 4.177448683698503E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.006241321000327123 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00577702980703381 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 23 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.0663651827126985E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2571731046273136E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024130865534871516 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0022429412437799064 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 24 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0924393438583185E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5379548164066449E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004393016898259179 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003889174478790022 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 25 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5820106603638713E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4362129619698505E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024382241282984237 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020089274079922483 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 26 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.296946092008408E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.558551199342951E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002887368973104623 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0022896204666690025 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 27 - E(D_n)= -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5403655497560937E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4407239288298634E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002962279413094558 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0025303386598856145 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 28 - E(D_n)= -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1143780651047683E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.096504528946479E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003216803984809231 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00248866780044782 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 29 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.199598593871094E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8102753606885588E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028077427336412612 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026306111495469596 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 30 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.4781367863611494E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8845988722376258E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0033343698805407096 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026287347082889875 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 31 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.215497662517774E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6347230097418927E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037674172625989117 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0038514198986340674 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 32 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6692404107877593E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4028734987710074E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003116721255129899 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023465829476512928 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 33 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.785851182667827E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.0383516402710934E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025596382638359955 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0025048103817702392 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 34 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.6399618868590163E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.2420095368978242E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0009416893855348603 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0010362879123506203 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 35 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.0642508042805921E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.0449618360539438E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0018504803016957218 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017318877162972087 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 36 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.531205688912257E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.114286718827591E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0033330920087327825 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0028290252035016914 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 37 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.174821162976422E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6231802296201945E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027930808403445503 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023283975135527995 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 38 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.652073191288944E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5250297434768896E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002744375522224152 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0027799713561774604 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 39 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.287815273873868E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8571001161536374E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0021310430022561735 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0019184861132037383 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 40 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0868943978344737E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5066476544195228E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024528155760313395 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001957592062143808 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 41 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2245583192079385E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2479599470469577E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00255546856849089 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024637610939157897 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 42 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.836024812515969E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3889375072924388E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0018755689060197375 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016289802623165681 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 43 - E(D_n)= -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5053142486975445E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5701530230283257E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0043472223017318075 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0036035699291977223 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 44 - E(D_n)= -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.0954925030012788E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2172785594654824E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0036532749370245744 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003412506051055545 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 45 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.310385607935654E-16 - Frobenius norm of the difference D_n-D_{n-1} = 1.0238097819877922E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023378015307948118 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001995472363999492 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 46 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8287064954556846E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4454997617475184E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024208845143845 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0021329902159969044 - Difference of the energies E_n-E_{n-1} = -0.005859375 - - # ITER = 47 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.583459936338342E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.526205032896248E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002292184307590269 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017932583817770688 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 48 - E(D_n)= -6.655433555253805E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9973584245512664E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.93940746316494E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0032197204007475854 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002652675049558457 - Difference of the energies E_n-E_{n-1} = -0.005859375 - - # ITER = 49 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.462701503756956E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5942214474498695E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0029488976005574994 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00288622392629348 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 50 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4320977594263452E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.552353176045796E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002416039024402095 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023057453484050167 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 51 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5049668292908863E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4879995049092023E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002272426154393354 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002187091878949049 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 52 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.565465445022753E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.521866319216111E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037294193517665047 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00318951159221864 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 53 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0098737531709958E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5879888240130812E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027318695470487037 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002340432828077849 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 54 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.183683080690805E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6315956951792459E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002810750755186478 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002375873826716119 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 55 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.3048433174179675E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.1381422316439148E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00296978564271568 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002509270754002553 - Difference of the energies E_n-E_{n-1} = 0.00390625 - - # ITER = 56 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.531284803346199E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4996982447048229E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004356481007196702 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0038058491272569507 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 57 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6456417407489271E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5895370593223897E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0034089861444007302 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0028673590404049995 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 58 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2740131384152804E-15 - Frobenius norm of the difference D_n-D_{n-1} = 9.772133157111003E-16 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020064919292034768 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001831127989044424 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 59 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.080066484742418E-16 - Frobenius norm of the difference D_n-D_{n-1} = 9.144059394293123E-16 - Infinity norm of the commutator [F(D_n),D_n] = 0.0035141095445418787 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002764902250964403 - Difference of the energies E_n-E_{n-1} = 0.00390625 - - # ITER = 60 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.831991516382116E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4601529997746403E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00476643712481769 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004236663036087614 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 61 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4264754223725618E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.433544171465437E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003564148633096804 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003091161773172543 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 62 - E(D_n)= -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.833637602859573E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6646194471005038E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004849324655875754 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004198958984630719 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 63 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.955900054169723E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.830946630440475E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002019288914371805 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0019207009360636513 - Difference of the energies E_n-E_{n-1} = -0.0048828125 - - # ITER = 64 - E(D_n)= -6.655433555253791E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.5632716144975154E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.111210643518216E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002645470472951909 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002553361103740994 - Difference of the energies E_n-E_{n-1} = 0.01171875 - - # ITER = 65 - E(D_n)= -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.592710489776708E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6842752631299256E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0026049211906260675 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024730272719932717 - Difference of the energies E_n-E_{n-1} = -0.0068359375 - - # ITER = 66 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3136951883572405E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.48672386825138E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019511113348261867 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0015272045340928495 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 67 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1551958689930185E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1687394231661546E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019015843217016699 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017097598706387934 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 68 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.412631210002455E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4043543278207775E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0031268458012144776 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023556172463693767 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 69 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3476986097419577E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1704502696437055E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0051905527262915705 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004565177855369871 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 70 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4813247119246373E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4584765610637945E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0029208465830667554 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002562204567857459 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 71 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0877384846229874E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.0511999405641613E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002756386993827166 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0022480441880973045 - Difference of the energies E_n-E_{n-1} = -0.0078125 - - # ITER = 72 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4959836327848291E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2538477135955533E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0014861478555778414 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001365973744153223 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 73 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0436976189280442E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.712592277283486E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00319754809892909 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029162072194423923 - Difference of the energies E_n-E_{n-1} = 0.0068359375 - - # ITER = 74 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8470478062017364E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.753276264363653E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025453997309772512 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002409016567527777 - Difference of the energies E_n-E_{n-1} = -0.005859375 - - # ITER = 75 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9040070832491734E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6579275021219072E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001705028019456478 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017708412374545415 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 76 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4997181160845759E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4953187351323488E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0013240659715334205 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0012916475623317763 - Difference of the energies E_n-E_{n-1} = -0.0048828125 - - # ITER = 77 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1142754670666527E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1335156718471834E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0031900974303758103 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002862195264366883 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 78 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3141715638291024E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.398757592580672E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019961498005620646 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017514757659158739 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 79 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1435241815638263E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1324392714531802E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0016628929319463318 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001639784354765737 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 80 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1421066212501112E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1123494235744135E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001916895670794902 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001458214311952928 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 81 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3543739700677892E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.452703225995201E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027214002469273814 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003052125430068439 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 82 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0707651046493513E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.907433918549225E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003836910050700292 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003296863531280521 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 83 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5790510483359209E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3751355388412595E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023568914166857257 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002453931490217884 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 84 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1557053739618588E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.972708047689577E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00357056059087677 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002549386590667836 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 85 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.2780667960426546E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.172501818766816E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037487905196157754 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0031961277839813998 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 86 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6699484510770349E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5498684853762265E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002156252208485264 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018683907768266958 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 87 - E(D_n)= -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6814972515387206E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5594534533197526E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0036991533840117895 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029876341536602164 - Difference of the energies E_n-E_{n-1} = 0.005859375 - - # ITER = 88 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.971849437835913E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8296328504580485E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003260406482465426 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003017730979476884 - Difference of the energies E_n-E_{n-1} = -0.0048828125 - - # ITER = 89 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.525975677830639E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5476645980788574E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002048749498905095 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002009595065958768 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 90 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6864162214795573E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6003951239896633E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027214568588243516 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024899253105826044 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 91 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5504458968656368E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5116772273684845E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002981914912464864 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002562569817077016 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 92 - E(D_n)= -6.655433555253806E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.2814919382855224E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7476155611380961E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003268918989844864 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002681015924734554 - Difference of the energies E_n-E_{n-1} = -0.00390625 - - # ITER = 93 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6470414953947347E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5945568138796426E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028108444209749314 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002391209118894813 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 94 - E(D_n)= -6.655433555253792E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.065797459559391E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.030604129064479E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0038565281546373838 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003529992103090322 - Difference of the energies E_n-E_{n-1} = 0.0107421875 - - # ITER = 95 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.303742259393523E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.106192420540953E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0032123976554728224 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024789197669049033 - Difference of the energies E_n-E_{n-1} = -0.0107421875 - - # ITER = 96 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7276776561520802E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9564879447408627E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0032807758669974145 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0028683598534835616 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 97 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9341818893456386E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9908630939813443E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027787047104193938 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002305954740395489 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 98 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6473792660741585E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2666849220501848E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0030291943666349345 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026056609480209366 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 99 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.929319006529513E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.76685129846894E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019293488867166639 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016125327238965274 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 100 - E(D_n)= -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6811921586833488E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8584516987287646E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0021843886500936644 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0019091157492886414 - Difference of the energies E_n-E_{n-1} = 0.005859375 - - Subroutine ROOTHAAN: no convergence after 100 iteration(s). - - level-shifting algorithm - Shift parameter value = 1.1 - - # ITER = 1 - E(D_n)= -9.073124781581628E+11 - Infinity norm of the difference D_n-D_{n-1} = 1.2100579819673856 - Frobenius norm of the difference D_n-D_{n-1} = 2.645751311064592 - Infinity norm of the commutator [F(D_n),D_n] = 1.0412161960774183E+12 - Frobenius norm of the commutator [F(D_n),D_n] = 1.338737729383472E+12 - Difference of the energies E_n-E_{n-1} = -9.073124781581628E+11 - - # ITER = 2 - E(D_n)= -6.624089601525219E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3009747150339233 - Frobenius norm of the difference D_n-D_{n-1} = 1.8684102561732538 - Infinity norm of the commutator [F(D_n),D_n] = 2.767526807406155E+11 - Frobenius norm of the commutator [F(D_n),D_n] = 3.210571393315542E+11 - Difference of the energies E_n-E_{n-1} = -5.716777123367056E+12 - - # ITER = 3 - E(D_n)= -6.654187827229982E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.049501116414605965 - Frobenius norm of the difference D_n-D_{n-1} = 0.08947695158113371 - Infinity norm of the commutator [F(D_n),D_n] = 5.5258777703036476E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 6.4157665218067215E+10 - Difference of the energies E_n-E_{n-1} = -3.009822570476367E+10 - - # ITER = 4 - E(D_n)= -6.655384408772794E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.009654037120011847 - Frobenius norm of the difference D_n-D_{n-1} = 0.017852563679282285 - Infinity norm of the commutator [F(D_n),D_n] = 1.0979032315878887E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 1.2746523445769403E+10 - Difference of the energies E_n-E_{n-1} = -1.1965815428115234E+9 - - # ITER = 5 - E(D_n)= -6.655431617733269E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.0019102407484366164 - Frobenius norm of the difference D_n-D_{n-1} = 0.0035457751270254324 - Infinity norm of the commutator [F(D_n),D_n] = 2.1800265164862604E+9 - Frobenius norm of the commutator [F(D_n),D_n] = 2.5309528983717155E+9 - Difference of the energies E_n-E_{n-1} = -4.7208960474609375E+7 - - # ITER = 6 - E(D_n)= -6.655433478878961E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.00037899725140389575 - Frobenius norm of the difference D_n-D_{n-1} = 0.0007040158252919248 - Infinity norm of the commutator [F(D_n),D_n] = 4.3283035404692334E+8 - Frobenius norm of the commutator [F(D_n),D_n] = 5.025032415411537E+8 - Difference of the energies E_n-E_{n-1} = -1861145.6923828125 - - # ITER = 7 - E(D_n)= -6.655433552243254E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.00007523548509428596 - Frobenius norm of the difference D_n-D_{n-1} = 0.0001397762078094207 - Infinity norm of the commutator [F(D_n),D_n] = 8.5934149296524E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 9.9766954112936E+7 - Difference of the energies E_n-E_{n-1} = -73364.29296875 - - # ITER = 8 - E(D_n)= -6.65543355513513E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000014936782321530693 - Frobenius norm of the difference D_n-D_{n-1} = 0.000027751107462388918 - Infinity norm of the commutator [F(D_n),D_n] = 1.706130749934471E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 1.9807661097524144E+7 - Difference of the energies E_n-E_{n-1} = -2891.8759765625 - - # ITER = 9 - E(D_n)= -6.655433555249124E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000002965519959471087 - Frobenius norm of the difference D_n-D_{n-1} = 0.000005509683451103695 - Infinity norm of the commutator [F(D_n),D_n] = 3387337.9910368733 - Frobenius norm of the commutator [F(D_n),D_n] = 3932596.7000326714 - Difference of the energies E_n-E_{n-1} = -113.994140625 - - # ITER = 10 - E(D_n)= -6.655433555253616E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.887711657393514E-7 - Frobenius norm of the difference D_n-D_{n-1} = 0.0000010938879314615626 - Infinity norm of the commutator [F(D_n),D_n] = 672519.2125580502 - Frobenius norm of the commutator [F(D_n),D_n] = 780774.411079779 - Difference of the energies E_n-E_{n-1} = -4.4921875 - - # ITER = 11 - E(D_n)= -6.655433555253795E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1689409906397022E-7 - Frobenius norm of the difference D_n-D_{n-1} = 2.1717957839266787E-7 - Infinity norm of the commutator [F(D_n),D_n] = 133521.3884978325 - Frobenius norm of the commutator [F(D_n),D_n] = 155014.2828856127 - Difference of the energies E_n-E_{n-1} = -0.1787109375 - - # ITER = 12 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.320805349626557E-8 - Frobenius norm of the difference D_n-D_{n-1} = 4.311864750184879E-8 - Infinity norm of the commutator [F(D_n),D_n] = 26509.222930308464 - Frobenius norm of the commutator [F(D_n),D_n] = 30776.40473152775 - Difference of the energies E_n-E_{n-1} = -0.0068359375 - - # ITER = 13 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 4.607706731622199E-9 - Frobenius norm of the difference D_n-D_{n-1} = 8.560739718093765E-9 - Infinity norm of the commutator [F(D_n),D_n] = 5263.118375348658 - Frobenius norm of the commutator [F(D_n),D_n] = 6110.320440499358 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 14 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.148104222581935E-10 - Frobenius norm of the difference D_n-D_{n-1} = 1.6996416835168903E-9 - Infinity norm of the commutator [F(D_n),D_n] = 1044.9355186430712 - Frobenius norm of the commutator [F(D_n),D_n] = 1213.1378968784766 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 15 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8162592502330366E-10 - Frobenius norm of the difference D_n-D_{n-1} = 3.3744555067801843E-10 - Infinity norm of the commutator [F(D_n),D_n] = 207.45925129147847 - Frobenius norm of the commutator [F(D_n),D_n] = 240.85532711869234 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 16 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 3.605903299191425E-11 - Frobenius norm of the difference D_n-D_{n-1} = 6.699598807120222E-11 - Infinity norm of the commutator [F(D_n),D_n] = 41.18901955466283 - Frobenius norm of the commutator [F(D_n),D_n] = 47.82028964089175 - Difference of the energies E_n-E_{n-1} = 0.005859375 - - # ITER = 17 - E(D_n)= -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 7.1596051568532415E-12 - Frobenius norm of the difference D_n-D_{n-1} = 1.3301494890153703E-11 - Infinity norm of the commutator [F(D_n),D_n] = 8.180238815883033 - Frobenius norm of the commutator [F(D_n),D_n] = 9.496541922298254 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 18 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4220406252686916E-12 - Frobenius norm of the difference D_n-D_{n-1} = 2.6409327976067845E-12 - Infinity norm of the commutator [F(D_n),D_n] = 1.6228067337419174 - Frobenius norm of the commutator [F(D_n),D_n] = 1.8851738390098745 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 19 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.8262867957941533E-13 - Frobenius norm of the difference D_n-D_{n-1} = 5.244351581896344E-13 - Infinity norm of the commutator [F(D_n),D_n] = 0.3211547985404058 - Frobenius norm of the commutator [F(D_n),D_n] = 0.37300525022727776 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 20 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.617491148090747E-14 - Frobenius norm of the difference D_n-D_{n-1} = 1.0414862129498326E-13 - Infinity norm of the commutator [F(D_n),D_n] = 0.060407333970339046 - Frobenius norm of the commutator [F(D_n),D_n] = 0.07196412984553038 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 21 - E(D_n)= -6.655433555253795E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1232815243460636E-14 - Frobenius norm of the difference D_n-D_{n-1} = 2.060471872377559E-14 - Infinity norm of the commutator [F(D_n),D_n] = 0.01341008195266276 - Frobenius norm of the commutator [F(D_n),D_n] = 0.014928866275191273 - Difference of the energies E_n-E_{n-1} = 0.0068359375 - - # ITER = 22 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.902360000199907E-15 - Frobenius norm of the difference D_n-D_{n-1} = 4.6102600886451914E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.005703201960379288 - Frobenius norm of the commutator [F(D_n),D_n] = 0.005310991241758122 - Difference of the energies E_n-E_{n-1} = -0.005859375 - - # ITER = 23 - E(D_n)= -6.655433555253805E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7146057080235992E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.892916967947922E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004659904553633058 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004016367705238843 - Difference of the energies E_n-E_{n-1} = -0.00390625 - - # ITER = 24 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.34001951123745E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3886053742460349E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023779233110129833 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023952473966020286 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 25 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.3536748720251777E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.5105830161733297E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0038838205519205393 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0036562195022888755 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 26 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.948644192835776E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7568201884993077E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003695096097309196 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00362888794861616 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 27 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.723638185861969E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.349307313617425E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003627727284743582 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029968960044416525 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 28 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.4961033352086425E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.041215865489333E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004510023951869889 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004122942783649866 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 29 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.182135895379544E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6436307884375601E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024315854659314544 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026615730942987303 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 30 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2899229325596924E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2794397795470573E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0022543398506768984 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002056224123734628 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 31 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6407270933351559E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8770793291067013E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028187006315760306 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026995613669978684 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 32 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5277824335566373E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.664064335262989E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002129328028176386 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001991312282009049 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 33 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.766189233360975E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.217667847223501E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0012349254297945923 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001268940356554623 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 34 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3895950341975232E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5639625527847236E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0031188141469456576 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029510141791983567 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 35 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.425294605389433E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.319114663772353E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020649945470012465 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002134254121325441 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 36 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.177859337350941E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7593039876178453E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004028409292767199 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0031406401323786914 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 37 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9863810052677914E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9031196733067287E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020431251742312473 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018021938399267854 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 38 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.9639029475378016E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.7116587420904516E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027224464322281147 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002778486512494355 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 39 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8612542305108104E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.680619111544433E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0013815431031834746 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014816728825524674 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 40 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2320986052812848E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.159308243018417E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024459984740322644 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020534846235652775 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 41 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.521890703874513E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4433260003276919E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0018560580813618852 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018052168781848576 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 42 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7512624007515045E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4610511442398246E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00309805512934904 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0028022352944337943 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 43 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 7.785367261699696E-16 - Frobenius norm of the difference D_n-D_{n-1} = 8.821709465017456E-16 - Infinity norm of the commutator [F(D_n),D_n] = 0.003753893319979949 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0033000645455176416 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 44 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3969486607107209E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2883606894210518E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0016855662416790187 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018176431477524722 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 45 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1507008549124978E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3221625385409835E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0008950759113456783 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0008069779924626556 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 46 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8633962910404734E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9123854060490792E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025194941156323532 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00220191956179292 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 47 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8467548131229104E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.571719303248434E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002845747123576674 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002330411956420513 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 48 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1416289099340594E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5700405541315892E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0015724586448458546 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016725751415039938 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 49 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6560112065429575E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4076787421928584E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019642794177996367 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017608060940645554 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 50 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8180516439737497E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5868076662087032E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0031102331813933114 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026506822993574036 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 51 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.778634585835367E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.610181023171139E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028341014837112437 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002584036544653592 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 52 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.946130449640405E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6465403251273567E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025088987236029803 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00223284586340221 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 53 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.4981130788212554E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8945515343673254E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023412098382394374 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002221317939643421 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 54 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3221069060994256E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.0677077359565993E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0033458138659906247 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0033776794231631124 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 55 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.005726909367486E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6162037730316824E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003046040511942998 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024694235433841308 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 56 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.480230531364914E-16 - Frobenius norm of the difference D_n-D_{n-1} = 9.034671662960456E-16 - Infinity norm of the commutator [F(D_n),D_n] = 0.0017519042095874321 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017164417603154779 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 57 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0055538702164296E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7254685102317826E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0015822869637988728 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001637981653374403 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 58 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3486145875944363E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2423678821416308E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0026276421620212206 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023440697349027878 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 59 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1451867046834924E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4641187597756003E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004559385779806142 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0040160360489173005 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 60 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9074731996028484E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9779992996048705E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0029534120965349236 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002805780399568268 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 61 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.920213261997042E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6783043672100237E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002236309461661207 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020344149395005095 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 62 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6989982169328257E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5966792289759508E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0017913116749688285 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001584757236708651 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 63 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.2809363551266637E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.0803063058264327E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0045862990045995805 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004375822422634495 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 64 - E(D_n)= -6.655433555253805E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.855940351646107E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6793241930528448E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0022617440521731846 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0019847455321155335 - Difference of the energies E_n-E_{n-1} = -0.005859375 - - # ITER = 65 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2675066252720992E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4725224166023896E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00241401867212272 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00195446814877175 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 66 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4308255124014565E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7175825163805075E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0031299457812694526 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026472264422338506 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 67 - E(D_n)= -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1795703152864722E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.216791805586696E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0033789115790586422 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003095582884221552 - Difference of the energies E_n-E_{n-1} = 0.0048828125 - - # ITER = 68 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5340212925395138E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6897202911254319E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028555586586626195 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002329940498555879 - Difference of the energies E_n-E_{n-1} = -0.0068359375 - - # ITER = 69 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.249764030862798E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8519120153306954E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00339142187192904 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003118401415535157 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - # ITER = 70 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1394149034930833E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7006081903314902E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0018841882799569996 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001743670181623593 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 71 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2377152892194371E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2983065308260958E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003859678609773924 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0035670039833352396 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 72 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3881535354726147E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.390751411494478E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0017925905128258154 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002031283374497696 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 73 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.653478260887279E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3357825663531981E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0030120898843344723 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002635203633412092 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 74 - E(D_n)= -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1108148602235483E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.0549367330720002E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001821254322818507 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017191487526669693 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 75 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1630779757724153E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1136804283157341E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0015410476371945328 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016005472358077604 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 76 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7580127225649172E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4639562940187268E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020875660660637763 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018789454366076185 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 77 - E(D_n)= -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4022955261556682E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.266023893279133E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002188278766880555 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001965341848648317 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 78 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.6626515964804743E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.415527712541485E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003473540973134743 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0027565718360459865 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 79 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4901603316329465E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8152320836225484E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020975453576018697 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0021171106108036374 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 80 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8960034297896252E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.591326018512362E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001445053398176912 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017951097315876392 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 81 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7718470176068557E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3723520406085777E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002364765042655777 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00225204983488161 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 82 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0868130614855607E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.779977634607116E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004064847605969519 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0034693439086801907 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 83 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.818827449659671E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9306682231125365E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002259929851134784 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020739087490510935 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 84 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 3.626354716455502E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.670362785074607E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003303978997060238 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029696222859228122 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 85 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.475146745593262E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2791865774224873E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004075783666277635 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003627293879549404 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 86 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4981551972955885E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4915333141589496E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00198798520998066 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020164243296378545 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 87 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.0084096138252484E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3507753522589954E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00244711536003363 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024395738050744086 - Difference of the energies E_n-E_{n-1} = 0.001953125 - - # ITER = 88 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.0888898383177666E-15 - Frobenius norm of the difference D_n-D_{n-1} = 9.846949868880474E-16 - Infinity norm of the commutator [F(D_n),D_n] = 0.0014001453977338751 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001579816799718993 - Difference of the energies E_n-E_{n-1} = -0.001953125 - - # ITER = 89 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7317366532314776E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7112851516078085E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002879610789653731 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003117003435236781 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 90 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8516548299815686E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5192006908248988E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002047151513477929 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001913832987970602 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 91 - E(D_n)= -6.655433555253807E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4829231374684825E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3878991060476685E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003341408632337509 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002728362131219283 - Difference of the energies E_n-E_{n-1} = -0.00390625 - - # ITER = 92 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3887474197483944E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3667272985617038E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0017156660689294381 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017406843522517438 - Difference of the energies E_n-E_{n-1} = 0.005859375 - - # ITER = 93 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3633317551305643E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1166089378040925E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025232389233060286 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001981367897432053 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 94 - E(D_n)= -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1959713367546596E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6854397832146798E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0029516684449275893 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002613597946191936 - Difference of the energies E_n-E_{n-1} = 0.005859375 - - # ITER = 95 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.570802235896228E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5023677689724584E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0018839531336237918 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0019762153023678503 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - - # ITER = 96 - E(D_n)= -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.526427276320859E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4561463782848622E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004037360582274023 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0030516357682752494 - Difference of the energies E_n-E_{n-1} = 0. - - # ITER = 97 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8492030954718437E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5174632783273863E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003388820873085592 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0028517935666603255 - Difference of the energies E_n-E_{n-1} = -0.00390625 - - # ITER = 98 - E(D_n)= -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6196634018587168E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.454848094045395E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024014596319193943 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024110769595258865 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - - # ITER = 99 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.506046175984396E-16 - Frobenius norm of the difference D_n-D_{n-1} = 8.741541436869206E-16 - Infinity norm of the commutator [F(D_n),D_n] = 0.0016865510892264473 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0015982881214882188 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - - # ITER = 100 - E(D_n)= -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4500508221583538E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2238105464764717E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002731237112807404 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023190683198061014 - Difference of the energies E_n-E_{n-1} = 0. - - Subroutine LEVELSHIFTING: no convergence after 100 iteration(s). - - DIIS algorithm - - # ITER = 1 - Total energy = -9.073124781581628E+11 - Infinity norm of the difference D_n-D_{n-1} = 1.2100579819673856 - Frobenius norm of the difference D_n-D_{n-1} = 2.645751311064592 - Infinity norm of the commutator [F(D_n),D_n] = 1.0412161960774183E+12 - Frobenius norm of the commutator [F(D_n),D_n] = 1.338737729383472E+12 - Difference of the energies E_n-E_{n-1} = -9.073124781581628E+11 - - # ITER = 2 - Total energy = -6.624089601525484E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3009747150339748 - Frobenius norm of the difference D_n-D_{n-1} = 1.868410256174138 - Infinity norm of the commutator [F(D_n),D_n] = 2.767526807413616E+11 - Frobenius norm of the commutator [F(D_n),D_n] = 3.210571393316269E+11 - Difference of the energies E_n-E_{n-1} = -5.716777123367321E+12 - Dimension of the density matrix simplex = 2 - - # ITER = 3 - Total energy = -6.654019855345912E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.04877947580688821 - Frobenius norm of the difference D_n-D_{n-1} = 0.08795782490081558 - Infinity norm of the commutator [F(D_n),D_n] = 5.853601009597538E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 6.81416960075015E+10 - Difference of the energies E_n-E_{n-1} = -2.9930253820427734E+10 - Dimension of the density matrix simplex = 3 - - # ITER = 4 - Total energy = -6.655433552522406E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.012785207468761746 - Frobenius norm of the difference D_n-D_{n-1} = 0.023831544652953146 - Infinity norm of the commutator [F(D_n),D_n] = 7.456205762817943E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 9.066507843265098E+7 - Difference of the energies E_n-E_{n-1} = -1.4136971764941406E+9 - Dimension of the density matrix simplex = 4 - - # ITER = 5 - Total energy = -6.655433555253611E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000016326941907152767 - Frobenius norm of the difference D_n-D_{n-1} = 0.00003406232785365991 - Infinity norm of the commutator [F(D_n),D_n] = 656004.7185293536 - Frobenius norm of the commutator [F(D_n),D_n] = 778416.4090698628 - Difference of the energies E_n-E_{n-1} = -2731.205078125 - Dimension of the density matrix simplex = 5 - - # ITER = 6 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4355870233571942E-7 - Frobenius norm of the difference D_n-D_{n-1} = 2.825203255449354E-7 - Infinity norm of the commutator [F(D_n),D_n] = 34.46678266457197 - Frobenius norm of the commutator [F(D_n),D_n] = 42.17512741861965 - Difference of the energies E_n-E_{n-1} = -0.189453125 - Dimension of the density matrix simplex = 6 - - # ITER = 7 - Total energy = -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.289012533945272E-10 - Frobenius norm of the difference D_n-D_{n-1} = 2.4799800601678553E-10 - Infinity norm of the commutator [F(D_n),D_n] = 556.7004917508897 - Frobenius norm of the commutator [F(D_n),D_n] = 653.2140331204763 - Difference of the energies E_n-E_{n-1} = 0.0048828125 - Dimension of the density matrix simplex = 7 - - # ITER = 8 - Total energy = -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7285743904052028E-10 - Frobenius norm of the difference D_n-D_{n-1} = 3.305451743890205E-10 - Infinity norm of the commutator [F(D_n),D_n] = 236.81035795137703 - Frobenius norm of the commutator [F(D_n),D_n] = 277.8795289022291 - Difference of the energies E_n-E_{n-1} = -0.0078125 - Dimension of the density matrix simplex = 8 - - # ITER = 9 - Total energy = -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.0411745907208905E-11 - Frobenius norm of the difference D_n-D_{n-1} = 9.640722783743083E-11 - Infinity norm of the commutator [F(D_n),D_n] = 5.396761381627831 - Frobenius norm of the commutator [F(D_n),D_n] = 6.33373252916833 - Difference of the energies E_n-E_{n-1} = 0.0068359375 - Dimension of the density matrix simplex = 9 - - # ITER = 10 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 4.838761508181621E-13 - Frobenius norm of the difference D_n-D_{n-1} = 9.252038660724876E-13 - Infinity norm of the commutator [F(D_n),D_n] = 3.176404252134073 - Frobenius norm of the commutator [F(D_n),D_n] = 3.727592691113972 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 11 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2995928516896714E-13 - Frobenius norm of the difference D_n-D_{n-1} = 2.468237686083284E-13 - Infinity norm of the commutator [F(D_n),D_n] = 2.5809165018128732 - Frobenius norm of the commutator [F(D_n),D_n] = 3.0308146405663154 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 12 - Total energy = -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.585186061660721E-13 - Frobenius norm of the difference D_n-D_{n-1} = 1.0681774543430009E-12 - Infinity norm of the commutator [F(D_n),D_n] = 0.016034006252787357 - Frobenius norm of the commutator [F(D_n),D_n] = 0.02086706822393591 - Difference of the energies E_n-E_{n-1} = -0.005859375 - Dimension of the density matrix simplex = 10 - - # ITER = 13 - Total energy = -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 3.4929950674956464E-14 - Frobenius norm of the difference D_n-D_{n-1} = 7.231870496619662E-14 - Infinity norm of the commutator [F(D_n),D_n] = 0.17295398905924725 - Frobenius norm of the commutator [F(D_n),D_n] = 0.2128589959182456 - Difference of the energies E_n-E_{n-1} = 0.0068359375 - Dimension of the density matrix simplex = 10 - - # ITER = 14 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 3.835602591347908E-14 - Frobenius norm of the difference D_n-D_{n-1} = 8.099865410055638E-14 - Infinity norm of the commutator [F(D_n),D_n] = 0.002568285525000057 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001927719501975746 - Difference of the energies E_n-E_{n-1} = -0.005859375 - Dimension of the density matrix simplex = 10 - - # ITER = 15 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1489535865976682E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7491084207283184E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028997414724857905 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026743973773011268 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 16 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.3678972843736943E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.0327667785016193E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024170259354576256 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0022181336085059637 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 17 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.2445728950519745E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8826092285836355E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020706995684678328 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020665440881283584 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 18 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8408109274163285E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.858383922328121E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0018272708077915732 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018260747539557197 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 19 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8348745317219723E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.92313532390882E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00266324380860071 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002501242344265213 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 20 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.551188024323511E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.815662664344447E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0021012064619609617 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020889088966869764 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 21 - Total energy = -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5526430788974613E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5067504497708255E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.00229024750361706 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002219506319498286 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 22 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1456955565678E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.855835804369537E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0016646677517472676 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014203564621056307 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 23 - Total energy = -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8905238562594195E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.082700623014091E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003972874847635916 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003437559962109324 - Difference of the energies E_n-E_{n-1} = 0.0048828125 - Dimension of the density matrix simplex = 10 - - # ITER = 24 - Total energy = -6.655433555253795E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8624620593227853E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.791320108226764E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037949167643235235 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003436624753156349 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 25 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8130976575913653E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6779412933664262E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0027667874920006192 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0021391216299603737 - Difference of the energies E_n-E_{n-1} = -0.0078125 - Dimension of the density matrix simplex = 10 - - # ITER = 26 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.168656227467439E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2185610283073846E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002327699327876215 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020028029264791618 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 27 - Total energy = -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4251043657612506E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5776594809171817E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0030402123552816587 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026278478547788336 - Difference of the energies E_n-E_{n-1} = 0.0048828125 - Dimension of the density matrix simplex = 10 - - # ITER = 28 - Total energy = -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1325827349888056E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.074458507637755E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002018768567930174 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001745364573120627 - Difference of the energies E_n-E_{n-1} = -0.0068359375 - Dimension of the density matrix simplex = 10 - - # ITER = 29 - Total energy = -6.655433555253806E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7050697979913856E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8880384031938648E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0039579489723507895 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003635015154257328 - Difference of the energies E_n-E_{n-1} = -0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 30 - Total energy = -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.36293400267495E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.19145879210979E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023165996114311396 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002249563643403169 - Difference of the energies E_n-E_{n-1} = 0.0068359375 - Dimension of the density matrix simplex = 10 - - # ITER = 31 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5522569931882794E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7660201180543547E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002374229623803484 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002148579328496175 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 32 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.525010349769297E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7623699497861515E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037193034393542867 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0030284943566077434 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 33 - Total energy = -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1330321670938284E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.069967805281533E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004289712826923652 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003499198027528867 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 34 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.5825954672950273E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.425423602470132E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002136635736149523 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002144174566757923 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 35 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4455664287392514E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3490352012746833E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028776206712028433 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0025341140988557934 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 36 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.559009482525242E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.436643888812364E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002627105847923689 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018224679610920572 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 37 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8596924481558428E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4643195693351447E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003900768943097188 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003078485213679615 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 38 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7524407242746085E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5782519872389196E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028658876812854023 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002542553555415288 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 39 - Total energy = -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.126903550845933E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7024740225931817E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002299087667191637 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001969212467023594 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 40 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4961761592083807E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4106593683654903E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004232990380879351 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0032099082157603072 - Difference of the energies E_n-E_{n-1} = 0.005859375 - Dimension of the density matrix simplex = 10 - - # ITER = 41 - Total energy = -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.750336067176583E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5132082263852549E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004967913838959713 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004328226936784717 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 42 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.2888622505306437E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.2417191483296444E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028061865907022944 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0028703830268731753 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 43 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.049005628682055E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5979886332047977E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023461260871773856 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024243591242652054 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 44 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1372958342594826E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2935554681339216E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0026919552185149295 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001972732947030798 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 45 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2427772874451654E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3803092734535917E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0033926069299956563 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0027279985236350847 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 46 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5678323186713672E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5570932128964993E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002418294604815077 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017607641990774175 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 47 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2828943962110019E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3258156027906255E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0013723061937833444 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0013642370276989047 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 48 - Total energy = -6.655433555253799E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.581649891120042E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7223129128488529E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004748112892082949 - Frobenius norm of the commutator [F(D_n),D_n] = 0.004498842832260404 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 49 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.911407090967673E-16 - Frobenius norm of the difference D_n-D_{n-1} = 1.1043102437662828E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004509377769875977 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0038120515605093446 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 50 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3019256860834267E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4515178844840936E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024931054314282566 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0022320570847033754 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 51 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.780155479335872E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6577210990354214E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0029101456695090552 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002286888347721663 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 52 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.4792106175459044E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.0064354449639703E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0024660506861096006 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0019478106628359978 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 53 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.140689254658796E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.1175001331765741E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023663114171881324 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0021457814083266657 - Difference of the energies E_n-E_{n-1} = -0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 54 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3272358648771014E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2133367961765065E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0031899571949450052 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002800133015794835 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 55 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6341452427095554E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5742778449235937E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.004208033528675369 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003887081567438868 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 56 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.466545707103043E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3458863316123054E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0038748871289885924 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003378875320375529 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 57 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3365414429654764E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2840843753088457E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0032899490286413145 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002798248170594703 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 58 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7369302058005743E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.185032609334943E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0013252485551817723 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001375030137971234 - Difference of the energies E_n-E_{n-1} = 0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 59 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.7344269590344696E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.806336982440483E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0032252717475589115 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029571610556980927 - Difference of the energies E_n-E_{n-1} = -0.0048828125 - Dimension of the density matrix simplex = 10 - - # ITER = 60 - Total energy = -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3720280668933856E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5326302469729257E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0034640697633503666 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0029189854479542833 - Difference of the energies E_n-E_{n-1} = 0.005859375 - Dimension of the density matrix simplex = 10 - - # ITER = 61 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.0936715082975114E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3244672326416996E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0030566946025930367 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002747624396120293 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 62 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.806532518908382E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9157510097818518E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019163438965060092 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002106023414404717 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 63 - Total energy = -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.292777753155462E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.896661004770316E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001518975992448728 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0017531783703775377 - Difference of the energies E_n-E_{n-1} = -0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 64 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.158438704702889E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.1687865949783013E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0032028844542917488 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0031476024197973486 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 65 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9890808578251458E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.0024642394042308E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0022962627778531867 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002072355669706186 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 66 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 3.0107660144515253E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.7565278889345623E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0035929479862400857 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0031194447489706007 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 67 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.415788366996742E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.277482235582364E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002868105043805674 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002804951907786756 - Difference of the energies E_n-E_{n-1} = -0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 68 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4745662288355022E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4458101888894664E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0028618308434414405 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024266381413493997 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 69 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.4573823574793524E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.685075056319309E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002467740377155356 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0021641253823296044 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 70 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4505032248176799E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2442988041944105E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003305245229830404 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0032949838535013716 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 71 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8129455289572947E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6386565523129223E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002561950079140506 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0022789253444239414 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 72 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.7753901388929543E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.9715498395115108E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023054035852809497 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0020275007969110448 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 73 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.777153676693806E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.516496900240165E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025646992209179143 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0026081415833957614 - Difference of the energies E_n-E_{n-1} = -0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 74 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5279282033010096E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7423201914641847E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0015411863450538093 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014384489383060175 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 75 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.8584530129483332E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6867474013250843E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0025222022269274385 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002423396192085406 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 76 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.931245295372821E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.766586548456577E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0030620692957245093 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003248799638154326 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 77 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4928134232356845E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6187783384478315E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0017441967678956936 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0015042545806426152 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 78 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.9569970989888544E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.718752982099009E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019494747389400774 - Frobenius norm of the commutator [F(D_n),D_n] = 0.00159267566114545 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 79 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.96744850675812E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6096001209133589E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0015906853223574978 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014963848757296202 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 80 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6035779246735416E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.204582448221353E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003582597614925748 - Frobenius norm of the commutator [F(D_n),D_n] = 0.003460992805372109 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 81 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.3522306969419936E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8596203680651683E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020451264271007423 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016397016911374436 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 82 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.044700501230033E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.868721958901782E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0026115996615840276 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024962536480528453 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 83 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4929025204866779E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.606027998282481E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002626681371791257 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023343589248404108 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 84 - Total energy = -6.655433555253798E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5686102692558306E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5164126784786907E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037037324011883204 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0031169975490401604 - Difference of the energies E_n-E_{n-1} = 0.0048828125 - Dimension of the density matrix simplex = 10 - - # ITER = 85 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.6475014730233957E-15 - Frobenius norm of the difference D_n-D_{n-1} = 2.193718698525185E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0021721422906340357 - Frobenius norm of the commutator [F(D_n),D_n] = 0.002182491035751315 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 86 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.952965269197455E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.4195218942454363E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0019185661510358915 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0018323233429454052 - Difference of the energies E_n-E_{n-1} = -0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 87 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3146450707999106E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.31436679386038E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0012890128886380585 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014289984822466867 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 88 - Total energy = -6.655433555253805E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4682963165904752E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3156512841054287E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0039933710128823505 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0032831764821497815 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 89 - Total energy = -6.655433555253804E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.01901368784709E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.8383589905144765E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0012848734213804502 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014436892201257357 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 90 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5212866735725656E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6976795721661342E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0020941363830924153 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016901139946892952 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 91 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.4985018371330482E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.6150414008376356E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001259324182024846 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001569396277862994 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 92 - Total energy = -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.410568195122474E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.2423644472193031E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003047348663397586 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023905156834826257 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 93 - Total energy = -6.655433555253796E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.558287707469312E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5178660230941565E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0013372265537098457 - Frobenius norm of the commutator [F(D_n),D_n] = 0.001376626488901646 - Difference of the energies E_n-E_{n-1} = 0.0048828125 - Dimension of the density matrix simplex = 10 - - # ITER = 94 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5518910950453107E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.597334310216641E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0037791918241326084 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0033890708798628186 - Difference of the energies E_n-E_{n-1} = -0.00390625 - Dimension of the density matrix simplex = 10 - - # ITER = 95 - Total energy = -6.655433555253803E+12 - Infinity norm of the difference D_n-D_{n-1} = 9.324763544293792E-16 - Frobenius norm of the difference D_n-D_{n-1} = 1.1814808370976944E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.003895802524045866 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0031918241852614574 - Difference of the energies E_n-E_{n-1} = -0.0029296875 - Dimension of the density matrix simplex = 10 - - # ITER = 96 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.5420135408351338E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.3712476520272001E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0014807209414924548 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0014762417946500175 - Difference of the energies E_n-E_{n-1} = 0.0009765625 - Dimension of the density matrix simplex = 10 - - # ITER = 97 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.2727435204306678E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.164909281946801E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0015524607084016306 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0011776007304338683 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 98 - Total energy = -6.655433555253802E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.748468845689062E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.7085277243861877E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.002618846587371706 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0023651000046968143 - Difference of the energies E_n-E_{n-1} = 0. - Dimension of the density matrix simplex = 10 - - # ITER = 99 - Total energy = -6.6554335552538E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.1142670416369788E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.79196234736172E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.0023882422285759833 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0024153892721062212 - Difference of the energies E_n-E_{n-1} = 0.001953125 - Dimension of the density matrix simplex = 10 - - # ITER = 100 - Total energy = -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.6082778045809468E-15 - Frobenius norm of the difference D_n-D_{n-1} = 1.5595536781376775E-15 - Infinity norm of the commutator [F(D_n),D_n] = 0.001677355738263048 - Frobenius norm of the commutator [F(D_n),D_n] = 0.0016418030508362806 - Difference of the energies E_n-E_{n-1} = 0.0029296875 - - Subroutine DIIS: no convergence after 100 iteration(s). - - Optimal damping algorithm (ODA) - - # ITER = 1 - E(D_n)= -9.073124781581628E+11 - Infinity norm of the difference D_n-D_{n-1} = 1.2100579819673856 - Frobenius norm of the difference D_n-D_{n-1} = 2.645751311064592 - Infinity norm of the commutator [F(D_n),D_n] = 1.0412161960774183E+12 - Frobenius norm of the commutator [F(D_n),D_n] = 1.338737729383472E+12 - Difference of the energies E_n-E_{n-1} = -9.073124781581628E+11 - alpha = -9.073124779781814E+11 beta = -101.24781936180648 - lambda=1. - E(tilde{D}_n)= -9.073124781581628E+11 - - # ITER = 2 - E(D_n)= -6.624089601525484E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.3009747150339748 - Frobenius norm of the difference D_n-D_{n-1} = 1.868410256174138 - Infinity norm of the commutator [F(D_n),D_n] = 2.767526807413616E+11 - Frobenius norm of the commutator [F(D_n),D_n] = 3.210571393316269E+11 - Difference of the energies E_n-E_{n-1} = -5.716777123367321E+12 - alpha = -2.1800274052363254E+12 beta = -1.7683748590654978E+12 - lambda=1. - E(tilde{D}_n)= -6.624089601525484E+12 - - # ITER = 3 - E(D_n)= -6.654187827229986E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.04950111641461568 - Frobenius norm of the difference D_n-D_{n-1} = 0.08947695158032672 - Infinity norm of the commutator [F(D_n),D_n] = 5.525877770276561E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 6.415766521772859E+10 - Difference of the energies E_n-E_{n-1} = -3.0098225704501953E+10 - alpha = -5.041577546329225E+9 beta = -1.252832407908651E+10 - lambda=1. - E(tilde{D}_n)= -6.654187827229986E+12 - - # ITER = 4 - E(D_n)= -6.655384408772801E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.00965403711996582 - Frobenius norm of the difference D_n-D_{n-1} = 0.017852563679180162 - Infinity norm of the commutator [F(D_n),D_n] = 1.0979032315808683E+10 - Frobenius norm of the commutator [F(D_n),D_n] = 1.274652344568357E+10 - Difference of the energies E_n-E_{n-1} = -1.1965815428144531E+9 - alpha = -1.9838115888265717E+8 beta = -4.991001919655052E+8 - lambda=1. - E(tilde{D}_n)= -6.655384408772801E+12 - - # ITER = 5 - E(D_n)= -6.655431617733268E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.0019102407484255265 - Frobenius norm of the difference D_n-D_{n-1} = 0.003545775127000044 - Infinity norm of the commutator [F(D_n),D_n] = 2.180026516466998E+9 - Frobenius norm of the commutator [F(D_n),D_n] = 2.5309528983494825E+9 - Difference of the energies E_n-E_{n-1} = -4.7208960466796875E+7 - alpha = -7821082.474936166 beta = -1.9693938996090245E+7 - lambda=1. - E(tilde{D}_n)= -6.655431617733268E+12 - - # ITER = 6 - E(D_n)= -6.655433478878964E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.0003789972514012589 - Frobenius norm of the difference D_n-D_{n-1} = 0.0007040158252857439 - Infinity norm of the commutator [F(D_n),D_n] = 4.3283035403956103E+8 - Frobenius norm of the commutator [F(D_n),D_n] = 5.0250324153350693E+8 - Difference of the energies E_n-E_{n-1} = -1861145.6962890625 - alpha = -308306.716204242 beta = -776419.4899402597 - lambda=1. - E(tilde{D}_n)= -6.655433478878964E+12 - - # ITER = 7 - E(D_n)= -6.655433552243254E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.00007523548509311476 - Frobenius norm of the difference D_n-D_{n-1} = 0.00013977620780798253 - Infinity norm of the commutator [F(D_n),D_n] = 8.593414929641753E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 9.97669541118814E+7 - Difference of the energies E_n-E_{n-1} = -73364.2900390625 - alpha = -12152.912461354432 beta = -30605.68926586127 - lambda=1. - E(tilde{D}_n)= -6.655433552243254E+12 - - # ITER = 8 - E(D_n)= -6.655433555135134E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000014936782321012737 - Frobenius norm of the difference D_n-D_{n-1} = 0.00002775110746219737 - Infinity norm of the commutator [F(D_n),D_n] = 1.7061307498857487E+7 - Frobenius norm of the commutator [F(D_n),D_n] = 1.9807661096722428E+7 - Difference of the energies E_n-E_{n-1} = -2891.8798828125 - alpha = -479.0421063537402 beta = -1206.4185106099867 - lambda=1. - E(tilde{D}_n)= -6.655433555135134E+12 - - # ITER = 9 - E(D_n)= -6.655433555249118E+12 - Infinity norm of the difference D_n-D_{n-1} = 0.000002965519959713296 - Frobenius norm of the difference D_n-D_{n-1} = 0.0000055096834507478994 - Infinity norm of the commutator [F(D_n),D_n] = 3387337.9916560412 - Frobenius norm of the commutator [F(D_n),D_n] = 3932596.7006554697 - Difference of the energies E_n-E_{n-1} = -113.984375 - alpha = -18.882790985723855 beta = -47.550786578673495 - lambda=1. - E(tilde{D}_n)= -6.655433555249118E+12 - - # ITER = 10 - E(D_n)= -6.65543355525362E+12 - Infinity norm of the difference D_n-D_{n-1} = 5.887711653437171E-7 - Frobenius norm of the difference D_n-D_{n-1} = 0.000001093887931496685 - Infinity norm of the commutator [F(D_n),D_n] = 672519.2110593879 - Frobenius norm of the commutator [F(D_n),D_n] = 780774.4094945464 - Difference of the energies E_n-E_{n-1} = -4.501953125 - alpha = -0.7443179979486894 beta = -1.878891222791765 - lambda=1. - E(tilde{D}_n)= -6.65543355525362E+12 - - # ITER = 11 - E(D_n)= -6.655433555253789E+12 - Infinity norm of the difference D_n-D_{n-1} = 1.1689409969135961E-7 - Frobenius norm of the difference D_n-D_{n-1} = 2.1717957812987995E-7 - Infinity norm of the commutator [F(D_n),D_n] = 133521.3860332804 - Frobenius norm of the commutator [F(D_n),D_n] = 155014.28201810445 - Difference of the energies E_n-E_{n-1} = -0.1689453125 - alpha = -0.029339372678813123 beta = -0.06972295463048361 - lambda=1. - E(tilde{D}_n)= -6.655433555253789E+12 - - # ITER = 12 - E(D_n)= -6.655433555253801E+12 - Infinity norm of the difference D_n-D_{n-1} = 2.3208052611859317E-8 - Frobenius norm of the difference D_n-D_{n-1} = 4.3118647675411076E-8 - Infinity norm of the commutator [F(D_n),D_n] = 26509.223364844573 - Frobenius norm of the commutator [F(D_n),D_n] = 30776.404450294376 - Difference of the energies E_n-E_{n-1} = -0.01171875 - alpha = -0.0011564932554084648 beta = -0.005535354647492774 - lambda=1. - E(tilde{D}_n)= -6.655433555253801E+12 - - # ITER = 13 - E(D_n)= -6.655433555253797E+12 - Infinity norm of the difference D_n-D_{n-1} = 4.607707442387816E-9 - Frobenius norm of the difference D_n-D_{n-1} = 8.560739449311445E-9 - Infinity norm of the commutator [F(D_n),D_n] = 5263.117464205615 - Frobenius norm of the commutator [F(D_n),D_n] = 6110.32121917598 - Difference of the energies E_n-E_{n-1} = 0.00390625 - Warning: internal computation error (beta>0). - - Subroutine ODA: computation stopped after 13 iteration(s). - - Elapsed CPU time is 2.484155 seconds. diff --git a/known_problems/RHF_CO_STO3G_setup b/known_problems/RHF_CO_STO3G_setup deleted file mode 100644 index 097849d..0000000 --- a/known_problems/RHF_CO_STO3G_setup +++ /dev/null @@ -1,45 +0,0 @@ -# This file is for a reference calculation documented (table 3.12, page 192) in Szabo & Ostlund, Modern quantum chemistry: introduction to advanced electronic structure theory, 1989. -## CASE -NONRELATIVISTIC -## APPROXIMATION -HARTREE-FOCK -## MODEL -RHF -## DESCRIPTION OF THE MOLECULAR SYSTEM -* The first entry is the number of atoms in the system. -* For each atom, the nucleus charge and position are given. -* The last entry is the total number of electrons in the system -CO molecule -2 -6 0. 0. 0. -8 2.132 0. 0. -14 -## BASIS DEFINITION -* The first entry is the keyword 'BASIS' followed by the name of the basis set contained in the basis/ directory or the keywords 'EVEN-TEMPERED BASIS'. -* The second entry is the choice of CONTRACTED or UNCONTRACTED basis functions for the calculation or the number of exponents for the even-tempered basis set. In the last case, the first term and the common ratio of the geometric series must be given, in this order, as two separate entries. -* The next two entries are are for the relativistic case: application or not of the Kinetic Balance scheme (KINBAL/NOTKINBAL) and, if so, choice between the RESTRICTED or UNRESTRICTED scheme. -BASIS STO-3G -CONTRACTED -## SCF PARAMETERS OF THE COMPUTATION -* They are: -* - the number of different scf algorithms to be used on the considered case, -* - the "numbers" of the algorithms (1 is for Roothaan, 2 is for level-shifting, 3 is for DIIS, 4 is for ODA, 5 is for ES's), -* - the threshold for numerical convergence, -* - the maximum number of iterations allowed, -* - two indicators to know if the bielectronic integrals are directly computed and, if not, if their list and values are stored on disk or not, -* - an indicator to make the computation without using the SS-bielectronic integrals in the relativistic case. -4 -1 -2 -3 -4 -1.E-6 -100 -NOTDIRECT -MEMORY -## LEVEL-SHIFTING ALGORITHM PARAMETERS -* Value of the shift -1.1 -## DIIS ALGORITHM PARAMETERS -* Maximum dimension of the density matrix simplex -10 diff --git a/known_problems/known_problems_list b/known_problems/known_problems_list index ca809c3..7e3e567 100644 --- a/known_problems/known_problems_list +++ b/known_problems/known_problems_list @@ -1,2 +1 @@ * N2 RHF computation with STO-3G basis (the converged value of the energy is not the one given in Szabo & Ostlund, table 3.12, page 192) -* CO RHF computation with STO-3G basis (nonsense result to be compared with the one given in Szabo & Ostlund, table 3.12, page 192)
antoine-levitt/ACCQUAREL
d3bcead3709ce652bf9b2bba3bc6716a25a309f1
clean up useless code
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index 729e699..8129e18 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,563 +1,562 @@ MODULE integrals ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic FUNCTION APRIORI_ZERO(PHI1,PHI2,PHI3,PHI4) RESULT(VALUE) ! Function that checks whether a given bielectronic integral can a priori be predicted to be zero USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI1,PHI2,PHI3,PHI4 LOGICAL :: SC,VALUE INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree ! If all functions have the same center and any monomial is odd, integral is zero SC=((PHI1%center_id==PHI2%center_id).AND.(PHI2%center_id==PHI3%center_id).AND.(PHI3%center_id==PHI4%center_id)) IF(SC) THEN - GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree IF(ANY(MOD(GLOBALMONOMIALDEGREE,2)==1)) THEN VALUE = .TRUE. RETURN END IF END IF ! Plane symmetries IF((SYM_SX .AND. MOD(GLOBALMONOMIALDEGREE(1),2) == 1).OR.& &(SYM_SY .AND. MOD(GLOBALMONOMIALDEGREE(2),2) == 1).OR.& &(SYM_SZ .AND. MOD(GLOBALMONOMIALDEGREE(3),2) == 1)) THEN VALUE = .TRUE. RETURN END IF VALUE = .FALSE. END FUNCTION APRIORI_ZERO SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE INTEGER :: I,J,K,L LOGICAL :: SS = .TRUE. OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(PHI(I),PHI(J),PHI(K),PHI(L))) THEN IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) IF(SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! LLSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SL' SUBSIZE(2)=SUBSIZE(2)+1 GO TO 2 END IF END DO END DO END DO END DO END DO END DO 2 CONTINUE END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O NBF=NGBF ! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=1,NGBF(1) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-1)*(I)*(I+1)*(I+2)/24 N=(I-2)*(I-1)*(I)*(I+1)/24 O=(I-3)*(I-2)*(I-1)*(I)/24 DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO IF (SLINTEGRALS) THEN ! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(N,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN ! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE
antoine-levitt/ACCQUAREL
33034e20db4911aa80fdcc7f85805f962e113a10
Fix compile under gfortran 4.5
diff --git a/src/gradient.f90 b/src/gradient.f90 index 6f74e50..9ef0f81 100644 --- a/src/gradient.f90 +++ b/src/gradient.f90 @@ -1,380 +1,381 @@ MODULE gradient_mod USE basis_parameters DOUBLE COMPLEX,POINTER,DIMENSION(:) :: POEFM_PG,PDM_PG,PFM_PG DOUBLE COMPLEX,POINTER,DIMENSION(:,:) :: CMT_PG TYPE(twospinor),POINTER,DIMENSION(:) :: PHI_PG INTEGER,POINTER :: NBAST_PG CONTAINS FUNCTION OBJECTIVE(EPS) USE esa_mod ; USE metric_relativistic ; USE matrix_tools ; USE common_functions USE matrices DOUBLE COMPLEX,DIMENSION(NBAST_PG*(NBAST_PG+1)/2) :: PDMNEW,PTEFM - DOUBLE PRECISION :: OBJECTIVE,EPS + DOUBLE PRECISION :: OBJECTIVE + DOUBLE PRECISION, INTENT(IN) :: EPS PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT_PG,NBAST_PG),UNPACK(PDM_PG,NBAST_PG)),& &UNPACK(PS,NBAST_PG)),EXPONENTIAL(-EPS,CMT_PG,NBAST_PG)),UNPACK(PIS,NBAST_PG)),NBAST_PG) PDMNEW = THETA(PDMNEW,POEFM_PG,NBAST_PG,PHI_PG,'D') CALL BUILDTEFM(PTEFM,NBAST_PG,PHI_PG,PDMNEW) OBJECTIVE=ENERGY(POEFM_PG,PTEFM,PDMNEW,NBAST_PG) END FUNCTION OBJECTIVE FUNCTION LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output USE esa_mod ; USE optimization_tools IMPLICIT NONE INTEGER :: INFO,LOON INTEGER,INTENT(IN),TARGET :: NBAST DOUBLE PRECISION,DIMENSION(NBAST) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC DOUBLE PRECISION :: E,EPS,ax,bx,cx,fa,fb,fc DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN),TARGET :: POEFM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),TARGET :: CMT,CMTCMT TYPE(twospinor),DIMENSION(NBAST),INTENT(IN),TARGET :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),TARGET :: PTEFM,PFM,PDM,PDMNEW POEFM_PG => POEFM ; PDM_PG => PDM; PFM_PG => PFM; CMT_PG => CMT; PHI_PG => PHI; NBAST_PG => NBAST E = golden(0.D0,0.001D0,10.D0,OBJECTIVE,0.001D0,EPS) write(*,*) EPS PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') END FUNCTION LINESEARCH_golden ! performs a linesearch about PDM FUNCTION LINESEARCH(CMT,PDM,NBAST,POEFM,PFM,PHI) RESULT(PDMNEW) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output USE esa_mod IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,CMTCMT TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER :: I,INFO,LOON DOUBLE PRECISION :: E,EAFTER,EBEFORE,FIRST_DER,SECOND_DER,EPS,DER_AFTER DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PTEFM,PFM,PDM,PDMNEW INTEGER,PARAMETER :: N_POINTS = 20 DOUBLE PRECISION, DIMENSION(N_POINTS) :: ENERGIES DOUBLE PRECISION, PARAMETER :: EPS_MIN = 0D0 DOUBLE PRECISION, PARAMETER :: EPS_MAX = 10D0 CHARACTER(1),PARAMETER :: ALGORITHM = 'E' CHARACTER(1),PARAMETER :: SEARCH_SPACE = 'L' ! compute EPS IF(ALGORITHM == 'F') THEN ! fixed EPS = 0.1 ELSEIF(ALGORITHM == 'E') THEN ! exhaustive search ! energy at PDM PDMNEW=PDM CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) E=ENERGY(POEFM,PTEFM,PDMNEW,NBAST) do I=1,N_POINTS if(SEARCH_SPACE == 'L') THEN eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) ELSE eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) eps = 10**eps END if ! energy at PDM + eps PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) ENERGIES(I)=ENERGY(POEFM,PTEFM,PDMNEW,NBAST) end do I = MINLOC(ENERGIES,1) if(SEARCH_SPACE == 'L') THEN eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) ELSE eps = EPS_MIN + (I-1)*(EPS_MAX-EPS_MIN)/(N_POINTS-1) eps = 10**eps END if write(*,*) eps END IF PDMNEW=PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& &UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) PDMNEW = THETA(PDMNEW,POEFM,NBAST,PHI,'D') ! uncomment for a roothaan step ! ! Assembly and diagonalization of the Fock matrix ! CALL BUILDTEFM(PTEFM,NBAST,PHI,PDMNEW) ! CALL EIGENSOLVER(POEFM+PTEFM,PCFS,NBAST,EIG,EIGVEC,INFO) ! ! Assembly of the density matrix according to the aufbau principle ! CALL CHECKORB(EIG,NBAST,LOON) ! CALL FORMDM(PDMNEW,EIGVEC,NBAST,LOON,LOON+NBE-1) END FUNCTION LINESEARCH END MODULE gradient_mod SUBROUTINE GRADIENT_relativistic(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism). ! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_relativistic ; USE scf_tools ; USE output USE esa_mod ; USE gradient_mod IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CMT,ISRS TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,LOON,INFO,I DOUBLE PRECISION :: ETOT,ETOT1 DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1,PPM LOGICAL :: NUMCONV ! INITIALIZATION AND PRELIMINARIES ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ALLOCATE(PPM(1:NBAST*(NBAST+1)/2)) ITER=0 PDM=(0.D0,0.D0) PTEFM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! Assembly of the density matrix according to the aufbau principle CALL CHECKORB(EIG,NBAST,LOON) PDM1=PDM CALL FORMDM(PDM,EIGVEC,NBAST,LOON,LOON+NBE-1) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 5 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 6 4 WRITE(*,*)'(called from subroutine ROOTHAAN)' 5 DEALLOCATE(PDM,PDM1,PTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) STOP ! Gradient algorithm 6 WRITE(*,*) ' ' WRITE(*,*) 'Switching to gradient algorithm' WRITE(*,*) ' ' PDM = THETA(PDM,POEFM,NBAST,PHI,'D') ITER = 0 7 ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! computation of the commutator ! CMT in ON basis = DF - Sm1 F D S CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - & MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) PDM1 = PDM ! PDM by line search PDM = LINESEARCH_golden(CMT,PDM,NBAST,POEFM,PFM,PHI) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) GO TO 2 ELSE IF (ITER==200*MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 5 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 7 END IF END SUBROUTINE GRADIENT_relativistic SUBROUTINE GRADIENT_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! Roothaan's algorithm (closed-shell Dirac-Hartree-Fock formalism). ! Reference: C. C. J. Roothaan, New developments in molecular orbital theory, Rev. Modern Phys., 23(2), 69-89, 1951. USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE common_functions USE matrices ; USE matrix_tools ; USE metric_nonrelativistic ; USE scf_tools ; USE output IMPLICIT NONE INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST),INTENT(OUT) :: EIG DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(OUT) :: EIGVEC DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: POEFM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CMT,ISRS TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,INTENT(IN) :: TRSHLD INTEGER,INTENT(IN) :: MAXITR LOGICAL,INTENT(IN) :: RESUME INTEGER :: ITER,INFO,I DOUBLE PRECISION :: ETOT,ETOT1,EPS DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTEFM,PFM,PDM,PDM1 LOGICAL :: NUMCONV ! INITIALIZATION AND PRELIMINARIES ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2)) ITER=0 PDM=(0.D0,0.D0) PTEFM=(0.D0,0.D0) ETOT1=0.D0 OPEN(16,FILE='plots/rootenrgy.txt',STATUS='unknown',ACTION='write') OPEN(17,FILE='plots/rootcrit1.txt',STATUS='unknown',ACTION='write') OPEN(18,FILE='plots/rootcrit2.txt',STATUS='unknown',ACTION='write') ! LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! Assembly of the density matrix according to the aufbau principle PDM1 = PDM CALL FORMDM(PDM,EIGVEC,NBAST,1,NBE/2) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached GO TO 2 ELSE IF (ITER==MAXITR) THEN ! Maximum number of iterations reached without convergence GO TO 3 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 1 END IF ! MESSAGES 2 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 5 3 WRITE(*,*)' ' ; WRITE(*,*)'Subroutine ROOTHAAN: no convergence after',ITER,'iteration(s).' OPEN(9,FILE='eigenvalues.txt',STATUS='UNKNOWN',ACTION='WRITE') DO I=1,NBAST WRITE(9,'(i4,e22.14)')I,EIG(I) END DO CLOSE(9) GO TO 6 4 WRITE(*,*)'(called from subroutine ROOTHAAN)' 5 DEALLOCATE(PDM,PDM1,PTEFM,PFM) CLOSE(16) ; CLOSE(17) ; CLOSE(18) STOP ! Gradient algorithm 6 WRITE(*,*) ' ' WRITE(*,*) 'Switching to gradient algorithm' WRITE(*,*) ' ' ITER = 0 7 ITER=ITER+1 WRITE(*,'(a)')' ' WRITE(*,'(a,i3)')'# ITER = ',ITER ! Assembly and diagonalization of the Fock matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFS,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 4 ! computation of the commutator EPS = .05 PDM1 = PDM ! CMT in ON basis = DF - Sm1 F D S CMT = MATMUL(UNPACK(PDM,NBAST),UNPACK(PFM,NBAST)) - & MATMUL(MATMUL(MATMUL(UNPACK(PIS,NBAST),UNPACK(PFM,NBAST)),UNPACK(PDM,NBAST)),UNPACK(PS,NBAST)) PDM = PACK(MATMUL(MATMUL(MATMUL(MATMUL(EXPONENTIAL(EPS,CMT,NBAST),UNPACK(PDM,NBAST)),& UNPACK(PS,NBAST)),EXPONENTIAL(-EPS,CMT,NBAST)),UNPACK(PIS,NBAST)),NBAST) ! Computation of the energy associated to the density matrix CALL BUILDTEFM(PTEFM,NBAST,PHI,PDM) ETOT=ENERGY(POEFM,PTEFM,PDM,NBAST) WRITE(*,*)'E(D_n)=',ETOT ! CALL OUTPUT_ITER(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) ! Numerical convergence check CALL CHECKNUMCONV(PDM,PDM1,POEFM+PTEFM,NBAST,ETOT,ETOT1,TRSHLD,NUMCONV) IF (NUMCONV) THEN ! Convergence reached ! CALL OUTPUT_FINALIZE(ITER,PDM,PHI,NBAST,EIG,EIGVEC,ETOT) GO TO 2 ELSE IF (ITER==1000*MAXITR+200) THEN ! Maximum number of iterations reached without convergence GO TO 5 ELSE ! Convergence not reached, increment ETOT1=ETOT GO TO 7 END IF END SUBROUTINE
antoine-levitt/ACCQUAREL
e50f2bfc1eb149f3990b620eb2da8689f1f38575
also parallelise SS computations
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index 6906ee3..729e699 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,554 +1,563 @@ MODULE integrals ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic FUNCTION APRIORI_ZERO(PHI1,PHI2,PHI3,PHI4) RESULT(VALUE) ! Function that checks whether a given bielectronic integral can a priori be predicted to be zero USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI1,PHI2,PHI3,PHI4 LOGICAL :: SC,VALUE INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree ! If all functions have the same center and any monomial is odd, integral is zero SC=((PHI1%center_id==PHI2%center_id).AND.(PHI2%center_id==PHI3%center_id).AND.(PHI3%center_id==PHI4%center_id)) IF(SC) THEN GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree IF(ANY(MOD(GLOBALMONOMIALDEGREE,2)==1)) THEN VALUE = .TRUE. RETURN END IF END IF ! Plane symmetries IF((SYM_SX .AND. MOD(GLOBALMONOMIALDEGREE(1),2) == 1).OR.& &(SYM_SY .AND. MOD(GLOBALMONOMIALDEGREE(2),2) == 1).OR.& &(SYM_SZ .AND. MOD(GLOBALMONOMIALDEGREE(3),2) == 1)) THEN VALUE = .TRUE. RETURN END IF VALUE = .FALSE. END FUNCTION APRIORI_ZERO SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE INTEGER :: I,J,K,L LOGICAL :: SS = .TRUE. OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(PHI(I),PHI(J),PHI(K),PHI(L))) THEN IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) IF(SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! LLSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SL' SUBSIZE(2)=SUBSIZE(2)+1 GO TO 2 END IF END DO END DO END DO END DO END DO END DO 2 CONTINUE END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O NBF=NGBF ! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 - DO I=1,NGBF(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K + ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. + !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) + DO I=1,NGBF(1) + ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). + M=(I-1)*(I)*(I+1)*(I+2)/24 + N=(I-2)*(I-1)*(I)*(I+1)/24 + O=(I-3)*(I-2)*(I-1)*(I)/24 + + DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO + !$OMP END PARALLEL DO IF (SLINTEGRALS) THEN ! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(N,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN ! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE
antoine-levitt/ACCQUAREL
c0b5839179e28354aa243c80bfd53d6356ddfeb6
purify diagonal of ABA for hermitian matrices
diff --git a/src/tools.f90 b/src/tools.f90 index e46d3eb..9f00f74 100644 --- a/src/tools.f90 +++ b/src/tools.f90 @@ -1,788 +1,792 @@ MODULE constants DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0 ! speed of light in the vacuum in atomic units (for the relativistic case) ! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006. DOUBLE PRECISION,PARAMETER :: SPEED_OF_LIGHT=137.035999967994D0 END MODULE MODULE random CONTAINS ! call this once SUBROUTINE INIT_RANDOM() ! initialises random generator ! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED INTEGER :: i, n, clock INTEGER, DIMENSION(:), ALLOCATABLE :: seed CALL RANDOM_SEED(size = n) ALLOCATE(seed(n)) CALL SYSTEM_CLOCK(COUNT=clock) seed = clock + 37 * (/ (i - 1, i = 1, n) /) CALL RANDOM_SEED(PUT = seed) DEALLOCATE(seed) END SUBROUTINE INIT_RANDOM ! returns an array of random numbers of size N in (0, 1) FUNCTION GET_RANDOM(N) RESULT(r) REAL, DIMENSION(N) :: r INTEGER :: N CALL RANDOM_NUMBER(r) END FUNCTION get_random END MODULE random MODULE matrix_tools INTERFACE PACK MODULE PROCEDURE PACK_symmetric,PACK_hermitian END INTERFACE INTERFACE UNPACK MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian END INTERFACE INTERFACE ABA MODULE PROCEDURE ABA_symmetric,ABA_hermitian END INTERFACE INTERFACE ABCBA MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian END INTERFACE INTERFACE ABC_CBA MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian END INTERFACE INTERFACE FINNERPRODUCT MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex END INTERFACE INTERFACE NORM MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian END INTERFACE INTERFACE INVERSE MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian END INTERFACE INTERFACE SQUARE_ROOT MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian END INTERFACE INTERFACE EXPONENTIAL MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex END INTERFACE EXPONENTIAL INTERFACE TRACE MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian END INTERFACE INTERFACE TRACEOFPRODUCT MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian END INTERFACE INTERFACE EIGENSOLVER MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized END INTERFACE INTERFACE COMMUTATOR MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian END INTERFACE INTERFACE PRINTMATRIX MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian,PRINTMATRIX_complex,PRINTMATRIX_real END INTERFACE INTERFACE READMATRIX MODULE PROCEDURE READMATRIX_complex,READMATRIX_real END INTERFACE READMATRIX INTERFACE BUILD_BLOCK_DIAGONAL MODULE PROCEDURE BUILD_BLOCK_DIAGONAL_symmetric END INTERFACE BUILD_BLOCK_DIAGONAL CONTAINS ! handling of symmetric and hermitian matrices stored in packed form. FUNCTION PACK_symmetric(A,N) RESULT (PA) ! Function that stores the upper triangular part of a symmetric matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=(A(I,J)+A(J,I))/2.D0 END DO END DO END FUNCTION PACK_symmetric FUNCTION PACK_hermitian(A,N) RESULT (PA) ! Function that stores the upper triangular part of a hermitian matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=A(I,J) PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0 END DO END DO END FUNCTION PACK_hermitian FUNCTION UNPACK_symmetric(PA,N) RESULT (A) ! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=PA(1+J:I-1+J) END DO END FUNCTION UNPACK_symmetric FUNCTION UNPACK_hermitian(PA,N) RESULT (A) ! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=CONJG(PA(1+J:I-1+J)) END DO END FUNCTION UNPACK_hermitian FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO END DO END DO END FUNCTION ABA_symmetric FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2)) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO END DO END DO + + DO I=1,N + PC(I*(I+1)/2) = REAL(PC(I*(I+1)/2)) + END DO END FUNCTION ABA_hermitian FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N) END FUNCTION ABCBA_symmetric FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD PD=ABA(PA,ABA(PB,PC,N),N) END FUNCTION ABCBA_hermitian FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_symmetric FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_hermitian ! diverse linear algebra routines FUNCTION INVERSE_real(A,N) RESULT(INVA) ! Function that computes the inverse of a square real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N) :: A DOUBLE PRECISION,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK INVA=A CALL DGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_real FUNCTION INVERSE_complex(A,N) RESULT(INVA) ! Function that computes the inverse of a square complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK INVA=A CALL ZGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_complex FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA) ! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK PINVA=PA CALL DSPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_symmetric FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA) ! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK PINVA=PA CALL ZHPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_hermitian FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA) ! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_symmetric FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA) ! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_hermitian FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N real matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine DGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_real FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine ZGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_complex FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE) ! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION :: TRACE INTEGER :: I TRACE=0.D0 DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_symmetric FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE) ! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX :: TRACE INTEGER :: I TRACE=(0.D0,0.D0) DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_hermitian FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: TRACE INTEGER :: I,J TRACE=0.D0 DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_real FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square complex matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: TRACE INTEGER :: I,J TRACE=(0.D0,0.D0) DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_complex FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION :: TRACE INTEGER :: I,J,IJ,JI TRACE=0.D0 DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*PB(IJ) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+PA(JI)*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_symmetric FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX :: TRACE INTEGER :: I,J,IJ,JI TRACE=(0.D0,0.D0) DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*CONJG(PB(IJ)) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+CONJG(PA(JI))*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_hermitian FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: FIP INTEGER :: I,J FIP=0.D0 DO I=1,N DO J=1,N FIP=FIP+A(I,J)*B(I,J) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_real FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: FIP INTEGER :: I,J FIP=(0.D0,0.D0) DO I=1,N DO J=1,N FIP=FIP+A(I,J)*CONJG(B(I,J)) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_complex SUBROUTINE NORM_check_norm(CHAR) CHARACTER(1),INTENT(IN) :: CHAR IF((CHAR /= 'F') .AND. & &(CHAR /= 'I') .AND. & &(CHAR /= '1') .AND. & &(CHAR /= 'M')) THEN WRITE(*,*) 'Invalid norm' STOP END IF END SUBROUTINE NORM_check_norm FUNCTION NORM_real(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANGE CALL NORM_check_norm(CHAR) NORM = DLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_real FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANGE CALL NORM_check_norm(CHAR) NORM = ZLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_complex FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANSP CALL NORM_check_norm(CHAR) NORM = DLANSP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_symmetric FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANHP CALL NORM_check_norm(CHAR) NORM = ZLANHP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_hermitian SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's DSPGV subroutine.
antoine-levitt/ACCQUAREL
e54f84ec8085c20ff1c4c913b53d6ad5b990da03
Be kind, rewind
diff --git a/src/setup.f90 b/src/setup.f90 index 5620178..2f557ab 100644 --- a/src/setup.f90 +++ b/src/setup.f90 @@ -214,594 +214,597 @@ SUBROUTINE SETUP_DATA READ(100,'(2(i3))')NBEA,NBEB WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!' ! ELSE IF (MODEL==3) THEN END IF END IF WRITE(*,'(a)')' --------- **** ---------' END IF CLOSE(100) END SUBROUTINE SETUP_DATA FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL) ! Function returning the symbol of a chemical element given its atomic number Z. INTEGER,INTENT(IN) :: Z CHARACTER(2) :: SYMBOL IF (Z>104) THEN WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!' STOP END IF ! List of symbols from Hydrogen up to Rutherfordium. SELECT CASE (Z) CASE (1) ; SYMBOL='H' CASE (2) ; SYMBOL='He' CASE (3) ; SYMBOL='Li' CASE (4) ; SYMBOL='Be' CASE (5) ; SYMBOL='B' CASE (6) ; SYMBOL='C' CASE (7) ; SYMBOL='N' CASE (8) ; SYMBOL='O' CASE (9) ; SYMBOL='F' CASE (10) ; SYMBOL='Ne' CASE (11) ; SYMBOL='Na' CASE (12) ; SYMBOL='Mg' CASE (13) ; SYMBOL='Al' CASE (14) ; SYMBOL='Si' CASE (15) ; SYMBOL='P' CASE (16) ; SYMBOL='S' CASE (17) ; SYMBOL='Cl' CASE (18) ; SYMBOL='Ar' CASE (19) ; SYMBOL='K' CASE (20) ; SYMBOL='Ca' CASE (21) ; SYMBOL='Sc' CASE (22) ; SYMBOL='Ti' CASE (23) ; SYMBOL='V' CASE (24) ; SYMBOL='Cr' CASE (25) ; SYMBOL='Mn' CASE (26) ; SYMBOL='Fe' CASE (27) ; SYMBOL='Co' CASE (28) ; SYMBOL='Ni' CASE (29) ; SYMBOL='Cu' CASE (30) ; SYMBOL='Zn' CASE (31) ; SYMBOL='Ga' CASE (32) ; SYMBOL='Ge' CASE (33) ; SYMBOL='As' CASE (34) ; SYMBOL='Se' CASE (35) ; SYMBOL='Br' CASE (36) ; SYMBOL='Kr' CASE (37) ; SYMBOL='Rb' CASE (38) ; SYMBOL='Sr' CASE (39) ; SYMBOL='Y' CASE (40) ; SYMBOL='Zr' CASE (41) ; SYMBOL='Nb' CASE (42) ; SYMBOL='Mo' CASE (43) ; SYMBOL='Tc' CASE (44) ; SYMBOL='Ru' CASE (45) ; SYMBOL='Rh' CASE (46) ; SYMBOL='Pd' CASE (47) ; SYMBOL='Ag' CASE (48) ; SYMBOL='Cd' CASE (49) ; SYMBOL='In' CASE (50) ; SYMBOL='Sn' CASE (51) ; SYMBOL='Sb' CASE (52) ; SYMBOL='Te' CASE (53) ; SYMBOL='I' CASE (54) ; SYMBOL='Xe' CASE (55) ; SYMBOL='Cs' CASE (56) ; SYMBOL='Ba' CASE (57) ; SYMBOL='La' ! Lanthanide elements (lanthanoids) CASE (58) ; SYMBOL='Ce' CASE (59) ; SYMBOL='Pr' CASE (60) ; SYMBOL='Nd' CASE (61) ; SYMBOL='Pm' CASE (62) ; SYMBOL='Sm' CASE (63) ; SYMBOL='Eu' CASE (64) ; SYMBOL='Gd' CASE (65) ; SYMBOL='Tb' CASE (66) ; SYMBOL='Dy' CASE (67) ; SYMBOL='Ho' CASE (68) ; SYMBOL='Er' CASE (69) ; SYMBOL='Tm' CASE (70) ; SYMBOL='Yb' CASE (71) ; SYMBOL='Lu' CASE (72) ; SYMBOL='Hf' CASE (73) ; SYMBOL='Ta' CASE (74) ; SYMBOL='W' CASE (75) ; SYMBOL='Re' CASE (76) ; SYMBOL='Os' CASE (77) ; SYMBOL='Ir' CASE (78) ; SYMBOL='Pt' CASE (79) ; SYMBOL='Au' CASE (80) ; SYMBOL='Hg' CASE (81) ; SYMBOL='Tl' CASE (82) ; SYMBOL='Pb' CASE (83) ; SYMBOL='Bi' CASE (84) ; SYMBOL='Po' CASE (85) ; SYMBOL='As' CASE (86) ; SYMBOL='Rn' CASE (87) ; SYMBOL='Fr' CASE (88) ; SYMBOL='Ra' CASE (89) ; SYMBOL='Ac' ! Actinide elements (actinoids) CASE (90) ; SYMBOL='Th' CASE (91) ; SYMBOL='Pa' CASE (92) ; SYMBOL='U' CASE (93) ; SYMBOL='Np' CASE (94) ; SYMBOL='Pu' CASE (95) ; SYMBOL='Am' CASE (96) ; SYMBOL='Cm' CASE (97) ; SYMBOL='Bk' CASE (98) ; SYMBOL='Cf' CASE (99) ; SYMBOL='Es' CASE (100); SYMBOL='Fm' CASE (101); SYMBOL='Md' CASE (102); SYMBOL='No' CASE (103); SYMBOL='Lr' CASE (104); SYMBOL='Rf' END SELECT END FUNCTION IDENTIFYZ SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system. INTEGER :: I,J DOUBLE PRECISION,DIMENSION(3) :: DIFF INTERNUCLEAR_ENERGY=0.D0 DO I=1,NBN DO J=I+1,NBN DIFF=CENTER(:,I)-CENTER(:,J) INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF)) END DO END DO END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Various functions for the Hartree model with temperature FUNCTION POSITIVE_PART(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN FUNC=0.D0 ELSE FUNC=X END IF END FUNCTION POSITIVE_PART FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC) ! beta test function for the entropy DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC FUNC=POSITIVE_PART(X)**MB/MB END FUNCTION ENTROPY_FUNCTION FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE FUNC=X**(1.D0/(MB-1.D0)) END IF END FUNCTION RECIP_DENTFUNC FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE IF (X==0.D0) THEN STOP'No derivative at origin' ELSE FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0) END IF END FUNCTION FUNCTION FUNCFORMU(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC INTEGER :: I DOUBLE PRECISION :: Y FUNC=-MASS DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE IF (Y>=0.D0) THEN FUNC=FUNC+RECIP_DENTFUNC(Y) END IF END DO END FUNCTION FUNCFORMU SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV INTEGER :: I DOUBLE PRECISION :: Y FVAL=-MASS ; FDERIV=0.D0 DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE FVAL=FVAL+RECIP_DENTFUNC(Y) FDERIV=FDERIV+DRECIP_DENTFUNC(Y) END DO END SUBROUTINE RDENTFUNCD END MODULE MODULE basis_parameters USE iso_c_binding ! flag for the choice of the basis set type (either existing in the library or even-tempered) LOGICAL :: LIBRARY ! PARAMETERS FOR A GIVEN BASIS SET CHARACTER(26) :: BASISFILE INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4 ! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme. ! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET INTEGER :: NUMBER_OF_TERMS DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO ! Various flags for the contraction of the primitives and the Kinetic Balance scheme LOGICAL :: UNCONT LOGICAL :: KINBAL,UKB TYPE gaussianbasisfunction ! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function. ! nbrofexponents: the number of different gaussian primitives present in the contraction ! center: coordinates (x,y,z) of the center of the basis function ! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center) ! exponents: array containing the exponent of each of the gaussian primitives present in the contraction ! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction ! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives ! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance). INTEGER(KIND=C_INT) :: nbrofexponents REAL(KIND=C_DOUBLE),DIMENSION(3) :: center INTEGER :: center_id REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree END TYPE gaussianbasisfunction TYPE twospinor ! Definition of a Pauli 2-spinor type basis function using gaussian basis functions. ! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor ! contractions: array containing the contractions present in each of the components of the 2-spinor ! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes) ! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor ! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0 INTEGER,DIMENSION(2) :: nbrofcontractions TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions INTEGER,DIMENSION(2,MNOGBF) :: contidx DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients END TYPE twospinor CONTAINS SUBROUTINE SETUP_BASIS USE case_parameters ; USE setup_tools CHARACTER(LEN=4) :: CHAR CHARACTER(LEN=26) :: BASISNAME INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## BASIS DEFINITION',INFO) IF (INFO/=0) STOP' The basis definition is not given.' READ(100,'(3/,a)') BASISNAME IF (BASISNAME(1:6)=='BASIS ') THEN ! The basis set is an existing one in the basis library LIBRARY=.TRUE. BASISFILE='basis/'//BASISNAME(7:) READ(100,'(a4)') CHAR IF (CHAR=='UNCO') THEN UNCONT=.TRUE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)' ELSE UNCONT=.FALSE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)' END IF ELSE IF (BASISNAME(1:4)=='EVEN') THEN ! The basis set is an even-tempered one LIBRARY=.FALSE. IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)' WRITE(*,'(a)')' Even-tempered basis set (preliminary support)' READ(100,'(i4)') NUMBER_OF_TERMS WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS READ(100,*) FIRST_TERM WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM READ(100,*) COMMON_RATIO WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO ELSE STOP' Unknown basis set type' END IF IF (RELATIVISTIC) THEN READ(100,'(a2)') CHAR IF (CHAR=='KI') THEN KINBAL=.TRUE. READ(100,'(a4)') CHAR IF (CHAR=='REST') THEN UKB=.FALSE. WRITE(*,'(a)')' Restricted kinetic balance' ELSE UKB=.TRUE. WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance' END IF ELSE KINBAL=.FALSE. WRITE(*,'(a)')' No kinetic balance' END IF END IF CLOSE(100) END SUBROUTINE SETUP_BASIS FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE) ! Function that computes the value of a gaussian basis function at a given point of space. USE iso_c_binding TYPE(gaussianbasisfunction),INTENT(IN) :: GBF DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT REAL(KIND=C_DOUBLE) :: VALUE VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) & & *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), & & EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2))) END FUNCTION GBF_POINTWISE_VALUE SUBROUTINE PRINTGBF(PHI,NUNIT) TYPE(gaussianbasisfunction),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents WRITE(NUNIT,*)' center:',PHI%center WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree DO I=1,PHI%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',I WRITE(NUNIT,*)' exponent:',PHI%exponents(I) WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I) END DO END SUBROUTINE PRINTGBF FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE) ! Function that computes the value of a Pauli 2-spinor basis function at a given point of space. USE iso_c_binding TYPE(twospinor),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT DOUBLE COMPLEX,DIMENSION(2) :: VALUE INTEGER :: I,J DO I=1,2 VALUE(I)=(0.D0,0.D0) DO J=1,PHI%nbrofcontractions(I) VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT) END DO END DO END FUNCTION TWOSPINOR_POINTWISE_VALUE SUBROUTINE PRINT2SPINOR(PHI,NUNIT) TYPE(twospinor),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I,J,K DO K=1,2 WRITE(NUNIT,*)'component #',K IF (PHI%nbrofcontractions(K)==0) THEN WRITE(NUNIT,*)' no contraction' ELSE WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K) DO I=1,PHI%nbrofcontractions(K) WRITE(NUNIT,*)' contraction #',I WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I) WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center DO J=1,PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',J WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J) WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J) END DO END DO END IF END DO END SUBROUTINE PRINT2SPINOR END MODULE MODULE scf_parameters ! number of different SCF algorithms to be used INTEGER :: NBALG ! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only)) INTEGER,DIMENSION(5) :: ALG ! threshold for numerical convergence DOUBLE PRECISION :: TRSHLD ! maximum number of iterations allowed INTEGER :: MAXITR ! flag for the direct computation of the bielectronic integrals LOGICAL :: DIRECT ! flag for the "semi-direct" computation of the bielectronic integrals (relativistic case only) ! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards. LOGICAL :: SEMIDIRECT ! flag for the storage of the computed bielectronic integrals (and/or their list) on disk or in memory LOGICAL :: USEDISK ! flag for the use of the SS-bielectronic integrals LOGICAL :: SSINTEGRALS ! flag for the use of the LS-bielectronic integrals LOGICAL :: SLINTEGRALS ! resume EIG and EIGVEC from last computation LOGICAL :: RESUME ! symmetries of the system LOGICAL :: SYM_SX = .FALSE.,SYM_SY = .FALSE.,SYM_SZ = .FALSE. CONTAINS SUBROUTINE SETUP_SCF !$ USE omp_lib USE case_parameters ; USE setup_tools CHARACTER :: METHOD CHARACTER(4) :: CHAR INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS DOUBLE PRECISION :: SHIFT OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## SCF PARAMETERS',INFO) IF (INFO/=0) STOP' The SCF parameters are not given.' READ(100,'(7/,i1)') NBALG DO I=1,NBALG READ(100,'(i1)') ALG(I) IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN STOP' The Optimal Damping Algorithm is intended for the non-relativistic case only.' ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN STOP' ES''s algorithm is intended for the relativistic case only.' END IF END DO READ(100,*) TRSHLD WRITE(*,*)'Threshold =',TRSHLD READ(100,'(i5)') MAXITR WRITE(*,*)'Maximum number of iterations =',MAXITR READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ; SEMIDIRECT=.FALSE. READ(100,'(a4)') CHAR ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE IF (CHAR=='SEM') THEN DIRECT=.FALSE. ; SEMIDIRECT=.TRUE. WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF IF (MODEL==3) THEN ! Special case: complex GHF SSINTEGRALS=.FALSE. SLINTEGRALS=.FALSE. ELSE REWIND(100) CALL LOOKFOR(100,'NOSS',INFO) IF (INFO==0) THEN SSINTEGRALS=.FALSE. WRITE(*,'(a)')' (SS-integrals are not used in the computation)' ELSE SSINTEGRALS=.TRUE. END IF REWIND(100) CALL LOOKFOR(100,'NOSL',INFO) IF (INFO==0) THEN SLINTEGRALS=.FALSE. WRITE(*,'(a)')' (SL-integrals are not used in the computation)' ELSE SLINTEGRALS=.TRUE. END IF END IF + REWIND(100) CALL LOOKFOR(100,'SYMMETRY SX',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses X-plane symmetry)' SYM_SX = .TRUE. END IF + REWIND(100) CALL LOOKFOR(100,'SYMMETRY SY',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses Y-plane symmetry)' SYM_SY = .TRUE. END IF + REWIND(100) CALL LOOKFOR(100,'SYMMETRY SZ',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses Z-plane symmetry)' SYM_SZ = .TRUE. END IF ELSE IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! the list of the bielectronic integrals is stored in memory ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF END IF ! additional verifications on the parameters of the algorithms DO I=1,NBALG IF (ALG(I)==2) THEN REWIND(100) CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 1 READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT ELSE IF (ALG(I)==3) THEN REWIND(100) CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 2 READ(100,'(/,i2)',ERR=2,END=2)MXSET IF (MXSET<2) GO TO 3 ELSE IF (ALG(I)==5) THEN REWIND(100) CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 4 READ(100,'(/,a)',ERR=4,END=4)METHOD IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4 END IF END DO RESUME=.FALSE. CALL LOOKFOR(100,'RESUME',INFO) IF(INFO == 0) THEN READ(100,'(a)')CHAR IF(CHAR == 'YES') THEN RESUME = .TRUE. END IF END IF !$ ! determination of the number of threads to be used by OpenMP !$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO) !$ IF (INFO==0) THEN !$ READ(100,'(/,i3)')NUMBER_OF_THREADS !$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS) !$ END IF !$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.' CLOSE(100) RETURN ! MESSAGES 1 STOP'No shift parameter given for the level-shifting algorithm.' 2 STOP'No simplex dimension given for the DIIS algorithm.' 3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.' 4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.' END SUBROUTINE SETUP_SCF END MODULE
antoine-levitt/ACCQUAREL
f4cfe1d9a14389cc3762fc7f13f00491465b8dff
Remove bogus NOSL check
diff --git a/src/setup.f90 b/src/setup.f90 index 6501d57..5620178 100644 --- a/src/setup.f90 +++ b/src/setup.f90 @@ -213,602 +213,595 @@ SUBROUTINE SETUP_DATA ELSE IF (MODEL==2) THEN READ(100,'(2(i3))')NBEA,NBEB WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!' ! ELSE IF (MODEL==3) THEN END IF END IF WRITE(*,'(a)')' --------- **** ---------' END IF CLOSE(100) END SUBROUTINE SETUP_DATA FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL) ! Function returning the symbol of a chemical element given its atomic number Z. INTEGER,INTENT(IN) :: Z CHARACTER(2) :: SYMBOL IF (Z>104) THEN WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!' STOP END IF ! List of symbols from Hydrogen up to Rutherfordium. SELECT CASE (Z) CASE (1) ; SYMBOL='H' CASE (2) ; SYMBOL='He' CASE (3) ; SYMBOL='Li' CASE (4) ; SYMBOL='Be' CASE (5) ; SYMBOL='B' CASE (6) ; SYMBOL='C' CASE (7) ; SYMBOL='N' CASE (8) ; SYMBOL='O' CASE (9) ; SYMBOL='F' CASE (10) ; SYMBOL='Ne' CASE (11) ; SYMBOL='Na' CASE (12) ; SYMBOL='Mg' CASE (13) ; SYMBOL='Al' CASE (14) ; SYMBOL='Si' CASE (15) ; SYMBOL='P' CASE (16) ; SYMBOL='S' CASE (17) ; SYMBOL='Cl' CASE (18) ; SYMBOL='Ar' CASE (19) ; SYMBOL='K' CASE (20) ; SYMBOL='Ca' CASE (21) ; SYMBOL='Sc' CASE (22) ; SYMBOL='Ti' CASE (23) ; SYMBOL='V' CASE (24) ; SYMBOL='Cr' CASE (25) ; SYMBOL='Mn' CASE (26) ; SYMBOL='Fe' CASE (27) ; SYMBOL='Co' CASE (28) ; SYMBOL='Ni' CASE (29) ; SYMBOL='Cu' CASE (30) ; SYMBOL='Zn' CASE (31) ; SYMBOL='Ga' CASE (32) ; SYMBOL='Ge' CASE (33) ; SYMBOL='As' CASE (34) ; SYMBOL='Se' CASE (35) ; SYMBOL='Br' CASE (36) ; SYMBOL='Kr' CASE (37) ; SYMBOL='Rb' CASE (38) ; SYMBOL='Sr' CASE (39) ; SYMBOL='Y' CASE (40) ; SYMBOL='Zr' CASE (41) ; SYMBOL='Nb' CASE (42) ; SYMBOL='Mo' CASE (43) ; SYMBOL='Tc' CASE (44) ; SYMBOL='Ru' CASE (45) ; SYMBOL='Rh' CASE (46) ; SYMBOL='Pd' CASE (47) ; SYMBOL='Ag' CASE (48) ; SYMBOL='Cd' CASE (49) ; SYMBOL='In' CASE (50) ; SYMBOL='Sn' CASE (51) ; SYMBOL='Sb' CASE (52) ; SYMBOL='Te' CASE (53) ; SYMBOL='I' CASE (54) ; SYMBOL='Xe' CASE (55) ; SYMBOL='Cs' CASE (56) ; SYMBOL='Ba' CASE (57) ; SYMBOL='La' ! Lanthanide elements (lanthanoids) CASE (58) ; SYMBOL='Ce' CASE (59) ; SYMBOL='Pr' CASE (60) ; SYMBOL='Nd' CASE (61) ; SYMBOL='Pm' CASE (62) ; SYMBOL='Sm' CASE (63) ; SYMBOL='Eu' CASE (64) ; SYMBOL='Gd' CASE (65) ; SYMBOL='Tb' CASE (66) ; SYMBOL='Dy' CASE (67) ; SYMBOL='Ho' CASE (68) ; SYMBOL='Er' CASE (69) ; SYMBOL='Tm' CASE (70) ; SYMBOL='Yb' CASE (71) ; SYMBOL='Lu' CASE (72) ; SYMBOL='Hf' CASE (73) ; SYMBOL='Ta' CASE (74) ; SYMBOL='W' CASE (75) ; SYMBOL='Re' CASE (76) ; SYMBOL='Os' CASE (77) ; SYMBOL='Ir' CASE (78) ; SYMBOL='Pt' CASE (79) ; SYMBOL='Au' CASE (80) ; SYMBOL='Hg' CASE (81) ; SYMBOL='Tl' CASE (82) ; SYMBOL='Pb' CASE (83) ; SYMBOL='Bi' CASE (84) ; SYMBOL='Po' CASE (85) ; SYMBOL='As' CASE (86) ; SYMBOL='Rn' CASE (87) ; SYMBOL='Fr' CASE (88) ; SYMBOL='Ra' CASE (89) ; SYMBOL='Ac' ! Actinide elements (actinoids) CASE (90) ; SYMBOL='Th' CASE (91) ; SYMBOL='Pa' CASE (92) ; SYMBOL='U' CASE (93) ; SYMBOL='Np' CASE (94) ; SYMBOL='Pu' CASE (95) ; SYMBOL='Am' CASE (96) ; SYMBOL='Cm' CASE (97) ; SYMBOL='Bk' CASE (98) ; SYMBOL='Cf' CASE (99) ; SYMBOL='Es' CASE (100); SYMBOL='Fm' CASE (101); SYMBOL='Md' CASE (102); SYMBOL='No' CASE (103); SYMBOL='Lr' CASE (104); SYMBOL='Rf' END SELECT END FUNCTION IDENTIFYZ SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system. INTEGER :: I,J DOUBLE PRECISION,DIMENSION(3) :: DIFF INTERNUCLEAR_ENERGY=0.D0 DO I=1,NBN DO J=I+1,NBN DIFF=CENTER(:,I)-CENTER(:,J) INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF)) END DO END DO END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Various functions for the Hartree model with temperature FUNCTION POSITIVE_PART(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN FUNC=0.D0 ELSE FUNC=X END IF END FUNCTION POSITIVE_PART FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC) ! beta test function for the entropy DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC FUNC=POSITIVE_PART(X)**MB/MB END FUNCTION ENTROPY_FUNCTION FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE FUNC=X**(1.D0/(MB-1.D0)) END IF END FUNCTION RECIP_DENTFUNC FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE IF (X==0.D0) THEN STOP'No derivative at origin' ELSE FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0) END IF END FUNCTION FUNCTION FUNCFORMU(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC INTEGER :: I DOUBLE PRECISION :: Y FUNC=-MASS DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE IF (Y>=0.D0) THEN FUNC=FUNC+RECIP_DENTFUNC(Y) END IF END DO END FUNCTION FUNCFORMU SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV INTEGER :: I DOUBLE PRECISION :: Y FVAL=-MASS ; FDERIV=0.D0 DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE FVAL=FVAL+RECIP_DENTFUNC(Y) FDERIV=FDERIV+DRECIP_DENTFUNC(Y) END DO END SUBROUTINE RDENTFUNCD END MODULE MODULE basis_parameters USE iso_c_binding ! flag for the choice of the basis set type (either existing in the library or even-tempered) LOGICAL :: LIBRARY ! PARAMETERS FOR A GIVEN BASIS SET CHARACTER(26) :: BASISFILE INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4 ! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme. ! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET INTEGER :: NUMBER_OF_TERMS DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO ! Various flags for the contraction of the primitives and the Kinetic Balance scheme LOGICAL :: UNCONT LOGICAL :: KINBAL,UKB TYPE gaussianbasisfunction ! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function. ! nbrofexponents: the number of different gaussian primitives present in the contraction ! center: coordinates (x,y,z) of the center of the basis function ! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center) ! exponents: array containing the exponent of each of the gaussian primitives present in the contraction ! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction ! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives ! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance). INTEGER(KIND=C_INT) :: nbrofexponents REAL(KIND=C_DOUBLE),DIMENSION(3) :: center INTEGER :: center_id REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree END TYPE gaussianbasisfunction TYPE twospinor ! Definition of a Pauli 2-spinor type basis function using gaussian basis functions. ! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor ! contractions: array containing the contractions present in each of the components of the 2-spinor ! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes) ! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor ! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0 INTEGER,DIMENSION(2) :: nbrofcontractions TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions INTEGER,DIMENSION(2,MNOGBF) :: contidx DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients END TYPE twospinor CONTAINS SUBROUTINE SETUP_BASIS USE case_parameters ; USE setup_tools CHARACTER(LEN=4) :: CHAR CHARACTER(LEN=26) :: BASISNAME INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## BASIS DEFINITION',INFO) IF (INFO/=0) STOP' The basis definition is not given.' READ(100,'(3/,a)') BASISNAME IF (BASISNAME(1:6)=='BASIS ') THEN ! The basis set is an existing one in the basis library LIBRARY=.TRUE. BASISFILE='basis/'//BASISNAME(7:) READ(100,'(a4)') CHAR IF (CHAR=='UNCO') THEN UNCONT=.TRUE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)' ELSE UNCONT=.FALSE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)' END IF ELSE IF (BASISNAME(1:4)=='EVEN') THEN ! The basis set is an even-tempered one LIBRARY=.FALSE. IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)' WRITE(*,'(a)')' Even-tempered basis set (preliminary support)' READ(100,'(i4)') NUMBER_OF_TERMS WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS READ(100,*) FIRST_TERM WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM READ(100,*) COMMON_RATIO WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO ELSE STOP' Unknown basis set type' END IF IF (RELATIVISTIC) THEN READ(100,'(a2)') CHAR IF (CHAR=='KI') THEN KINBAL=.TRUE. READ(100,'(a4)') CHAR IF (CHAR=='REST') THEN UKB=.FALSE. WRITE(*,'(a)')' Restricted kinetic balance' ELSE UKB=.TRUE. WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance' END IF ELSE KINBAL=.FALSE. WRITE(*,'(a)')' No kinetic balance' END IF END IF CLOSE(100) END SUBROUTINE SETUP_BASIS FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE) ! Function that computes the value of a gaussian basis function at a given point of space. USE iso_c_binding TYPE(gaussianbasisfunction),INTENT(IN) :: GBF DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT REAL(KIND=C_DOUBLE) :: VALUE VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) & & *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), & & EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2))) END FUNCTION GBF_POINTWISE_VALUE SUBROUTINE PRINTGBF(PHI,NUNIT) TYPE(gaussianbasisfunction),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents WRITE(NUNIT,*)' center:',PHI%center WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree DO I=1,PHI%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',I WRITE(NUNIT,*)' exponent:',PHI%exponents(I) WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I) END DO END SUBROUTINE PRINTGBF FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE) ! Function that computes the value of a Pauli 2-spinor basis function at a given point of space. USE iso_c_binding TYPE(twospinor),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT DOUBLE COMPLEX,DIMENSION(2) :: VALUE INTEGER :: I,J DO I=1,2 VALUE(I)=(0.D0,0.D0) DO J=1,PHI%nbrofcontractions(I) VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT) END DO END DO END FUNCTION TWOSPINOR_POINTWISE_VALUE SUBROUTINE PRINT2SPINOR(PHI,NUNIT) TYPE(twospinor),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I,J,K DO K=1,2 WRITE(NUNIT,*)'component #',K IF (PHI%nbrofcontractions(K)==0) THEN WRITE(NUNIT,*)' no contraction' ELSE WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K) DO I=1,PHI%nbrofcontractions(K) WRITE(NUNIT,*)' contraction #',I WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I) WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center DO J=1,PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',J WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J) WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J) END DO END DO END IF END DO END SUBROUTINE PRINT2SPINOR END MODULE MODULE scf_parameters ! number of different SCF algorithms to be used INTEGER :: NBALG ! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only)) INTEGER,DIMENSION(5) :: ALG ! threshold for numerical convergence DOUBLE PRECISION :: TRSHLD ! maximum number of iterations allowed INTEGER :: MAXITR ! flag for the direct computation of the bielectronic integrals LOGICAL :: DIRECT ! flag for the "semi-direct" computation of the bielectronic integrals (relativistic case only) ! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards. LOGICAL :: SEMIDIRECT ! flag for the storage of the computed bielectronic integrals (and/or their list) on disk or in memory LOGICAL :: USEDISK ! flag for the use of the SS-bielectronic integrals LOGICAL :: SSINTEGRALS ! flag for the use of the LS-bielectronic integrals LOGICAL :: SLINTEGRALS ! resume EIG and EIGVEC from last computation LOGICAL :: RESUME ! symmetries of the system LOGICAL :: SYM_SX = .FALSE.,SYM_SY = .FALSE.,SYM_SZ = .FALSE. CONTAINS SUBROUTINE SETUP_SCF !$ USE omp_lib USE case_parameters ; USE setup_tools CHARACTER :: METHOD CHARACTER(4) :: CHAR INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS DOUBLE PRECISION :: SHIFT OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## SCF PARAMETERS',INFO) IF (INFO/=0) STOP' The SCF parameters are not given.' READ(100,'(7/,i1)') NBALG DO I=1,NBALG READ(100,'(i1)') ALG(I) IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN STOP' The Optimal Damping Algorithm is intended for the non-relativistic case only.' ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN STOP' ES''s algorithm is intended for the relativistic case only.' END IF END DO READ(100,*) TRSHLD WRITE(*,*)'Threshold =',TRSHLD READ(100,'(i5)') MAXITR WRITE(*,*)'Maximum number of iterations =',MAXITR READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ; SEMIDIRECT=.FALSE. READ(100,'(a4)') CHAR ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE IF (CHAR=='SEM') THEN DIRECT=.FALSE. ; SEMIDIRECT=.TRUE. WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF IF (MODEL==3) THEN ! Special case: complex GHF SSINTEGRALS=.FALSE. SLINTEGRALS=.FALSE. ELSE REWIND(100) CALL LOOKFOR(100,'NOSS',INFO) IF (INFO==0) THEN SSINTEGRALS=.FALSE. WRITE(*,'(a)')' (SS-integrals are not used in the computation)' ELSE SSINTEGRALS=.TRUE. END IF REWIND(100) CALL LOOKFOR(100,'NOSL',INFO) IF (INFO==0) THEN SLINTEGRALS=.FALSE. WRITE(*,'(a)')' (SL-integrals are not used in the computation)' ELSE SLINTEGRALS=.TRUE. END IF END IF - READ(100,'(a4)') CHAR - IF (CHAR=='NOSL') THEN - SLINTEGRALS=.FALSE. - WRITE(*,'(a)')' (SL-integrals are not used in the computation)' - ELSE - SLINTEGRALS=.TRUE. - END IF CALL LOOKFOR(100,'SYMMETRY SX',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses X-plane symmetry)' SYM_SX = .TRUE. END IF CALL LOOKFOR(100,'SYMMETRY SY',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses Y-plane symmetry)' SYM_SY = .TRUE. END IF CALL LOOKFOR(100,'SYMMETRY SZ',INFO) IF (INFO==0) THEN WRITE(*,'(a)')' (System possesses Z-plane symmetry)' SYM_SZ = .TRUE. END IF ELSE IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! the list of the bielectronic integrals is stored in memory ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF END IF ! additional verifications on the parameters of the algorithms DO I=1,NBALG IF (ALG(I)==2) THEN REWIND(100) CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 1 READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT ELSE IF (ALG(I)==3) THEN REWIND(100) CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 2 READ(100,'(/,i2)',ERR=2,END=2)MXSET IF (MXSET<2) GO TO 3 ELSE IF (ALG(I)==5) THEN REWIND(100) CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 4 READ(100,'(/,a)',ERR=4,END=4)METHOD IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4 END IF END DO RESUME=.FALSE. CALL LOOKFOR(100,'RESUME',INFO) IF(INFO == 0) THEN READ(100,'(a)')CHAR IF(CHAR == 'YES') THEN RESUME = .TRUE. END IF END IF !$ ! determination of the number of threads to be used by OpenMP !$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO) !$ IF (INFO==0) THEN !$ READ(100,'(/,i3)')NUMBER_OF_THREADS !$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS) !$ END IF !$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.' CLOSE(100) RETURN ! MESSAGES 1 STOP'No shift parameter given for the level-shifting algorithm.' 2 STOP'No simplex dimension given for the DIIS algorithm.' 3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.' 4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.' END SUBROUTINE SETUP_SCF END MODULE
antoine-levitt/ACCQUAREL
1513405a562b8efd3dd6b6ef4e78988b9063ab10
SX, SY, SZ symmetries
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index 79fa8ed..6906ee3 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,546 +1,554 @@ MODULE integrals ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic FUNCTION APRIORI_ZERO(PHI1,PHI2,PHI3,PHI4) RESULT(VALUE) ! Function that checks whether a given bielectronic integral can a priori be predicted to be zero - USE case_parameters ; USE basis_parameters + USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI1,PHI2,PHI3,PHI4 - LOGICAL :: SC,SYM,VALUE + LOGICAL :: SC,VALUE INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE - ! same center and odd global monomial degree + GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree + ! If all functions have the same center and any monomial is odd, integral is zero SC=((PHI1%center_id==PHI2%center_id).AND.(PHI2%center_id==PHI3%center_id).AND.(PHI3%center_id==PHI4%center_id)) IF(SC) THEN GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree IF(ANY(MOD(GLOBALMONOMIALDEGREE,2)==1)) THEN VALUE = .TRUE. RETURN END IF END IF - VALUE = .FALSE. + ! Plane symmetries + IF((SYM_SX .AND. MOD(GLOBALMONOMIALDEGREE(1),2) == 1).OR.& + &(SYM_SY .AND. MOD(GLOBALMONOMIALDEGREE(2),2) == 1).OR.& + &(SYM_SZ .AND. MOD(GLOBALMONOMIALDEGREE(3),2) == 1)) THEN + VALUE = .TRUE. + RETURN + END IF + VALUE = .FALSE. END FUNCTION APRIORI_ZERO SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE INTEGER :: I,J,K,L LOGICAL :: SS = .TRUE. OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(PHI(I),PHI(J),PHI(K),PHI(L))) THEN IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) IF(SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! LLSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SL' SUBSIZE(2)=SUBSIZE(2)+1 GO TO 2 END IF END DO END DO END DO END DO END DO END DO 2 CONTINUE END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O NBF=NGBF ! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 DO I=1,NGBF(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(N,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN ! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE diff --git a/src/setup.f90 b/src/setup.f90 index cda8926..6501d57 100644 --- a/src/setup.f90 +++ b/src/setup.f90 @@ -126,664 +126,689 @@ SUBROUTINE SETUP_FORMALISM RETURN 1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!' STOP END SUBROUTINE SETUP_FORMALISM END MODULE MODULE data_parameters USE iso_c_binding ! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS ** ! number of nuclei in the molecular system (at most 10) INTEGER :: NBN ! atomic numbers of the nuclei INTEGER,DIMENSION(10) :: Z ! positions of the nucleii DOUBLE PRECISION,DIMENSION(3,10) :: CENTER ! total number of electrons in the molecular system INTEGER :: NBE ! total number of electrons in the closed shells (open-shell DHF formalism) INTEGER :: NBECS ! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism) INTEGER :: NBEOS,NBOOS ! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms) INTEGER :: NBEA,NBEB ! internuclear repulsion energy DOUBLE PRECISION :: INTERNUCLEAR_ENERGY ! ** DATA FOR BOSON STAR MODEL ** DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0 ! mass DOUBLE PRECISION :: MASS ! temperature DOUBLE PRECISION :: TEMPERATURE ! exponent for the function defining the Tsallis-related entropy term DOUBLE PRECISION :: MB ! INTEGER,POINTER :: RANK_P DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I CONTAINS SUBROUTINE SETUP_DATA USE case_parameters ; USE setup_tools IMPLICIT NONE CHARACTER(30) :: NAME INTEGER :: INFO,N OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO) IF (INFO/=0) STOP' The description of the boson star is not given.' WRITE(*,'(a)')' --- **** ---' READ(100,*) NAME READ(100,*) MASS WRITE(*,'(a,f5.3)')' * Mass = ',MASS READ(100,*) TEMPERATURE WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE READ(100,*) MB WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB WRITE(*,'(a)')' --- **** ---' ELSE CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO) IF (INFO/=0) STOP' The description of the molecular system is not given.' WRITE(*,'(a)')' --- Molecular system ---' READ(100,'(3/,a)')NAME WRITE(*,'(a,a)')' ** NAME: ',NAME READ(100,'(i2)') NBN DO N=1,NBN WRITE(*,'(a,i2)')' * Nucleus #',N READ(100,*) Z(N),CENTER(:,N) WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')' WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N) END DO CALL INTERNUCLEAR_REPULSION_ENERGY WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY READ(100,'(i3)') NBE WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE IF (RELATIVISTIC) THEN IF (MODEL==2) THEN READ(100,'(3(i3))')NBECS,NBEOS,NBOOS WRITE(*,'(a,i3)')' - number of closed-shell electrons = ',NBECS WRITE(*,'(a,i3)')' - number of open-shell electrons = ',NBEOS WRITE(*,'(a,i3)')' - number of open-shell orbitals = ',NBOOS IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons' IF (NBOOS<=NBEOS) STOP' Problem with the number of open-shell orbitals!' END IF ELSE IF (MODEL==1) THEN IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!' ELSE IF (MODEL==2) THEN READ(100,'(2(i3))')NBEA,NBEB WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!' ! ELSE IF (MODEL==3) THEN END IF END IF WRITE(*,'(a)')' --------- **** ---------' END IF CLOSE(100) END SUBROUTINE SETUP_DATA FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL) ! Function returning the symbol of a chemical element given its atomic number Z. INTEGER,INTENT(IN) :: Z CHARACTER(2) :: SYMBOL IF (Z>104) THEN WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!' STOP END IF ! List of symbols from Hydrogen up to Rutherfordium. SELECT CASE (Z) CASE (1) ; SYMBOL='H' CASE (2) ; SYMBOL='He' CASE (3) ; SYMBOL='Li' CASE (4) ; SYMBOL='Be' CASE (5) ; SYMBOL='B' CASE (6) ; SYMBOL='C' CASE (7) ; SYMBOL='N' CASE (8) ; SYMBOL='O' CASE (9) ; SYMBOL='F' CASE (10) ; SYMBOL='Ne' CASE (11) ; SYMBOL='Na' CASE (12) ; SYMBOL='Mg' CASE (13) ; SYMBOL='Al' CASE (14) ; SYMBOL='Si' CASE (15) ; SYMBOL='P' CASE (16) ; SYMBOL='S' CASE (17) ; SYMBOL='Cl' CASE (18) ; SYMBOL='Ar' CASE (19) ; SYMBOL='K' CASE (20) ; SYMBOL='Ca' CASE (21) ; SYMBOL='Sc' CASE (22) ; SYMBOL='Ti' CASE (23) ; SYMBOL='V' CASE (24) ; SYMBOL='Cr' CASE (25) ; SYMBOL='Mn' CASE (26) ; SYMBOL='Fe' CASE (27) ; SYMBOL='Co' CASE (28) ; SYMBOL='Ni' CASE (29) ; SYMBOL='Cu' CASE (30) ; SYMBOL='Zn' CASE (31) ; SYMBOL='Ga' CASE (32) ; SYMBOL='Ge' CASE (33) ; SYMBOL='As' CASE (34) ; SYMBOL='Se' CASE (35) ; SYMBOL='Br' CASE (36) ; SYMBOL='Kr' CASE (37) ; SYMBOL='Rb' CASE (38) ; SYMBOL='Sr' CASE (39) ; SYMBOL='Y' CASE (40) ; SYMBOL='Zr' CASE (41) ; SYMBOL='Nb' CASE (42) ; SYMBOL='Mo' CASE (43) ; SYMBOL='Tc' CASE (44) ; SYMBOL='Ru' CASE (45) ; SYMBOL='Rh' CASE (46) ; SYMBOL='Pd' CASE (47) ; SYMBOL='Ag' CASE (48) ; SYMBOL='Cd' CASE (49) ; SYMBOL='In' CASE (50) ; SYMBOL='Sn' CASE (51) ; SYMBOL='Sb' CASE (52) ; SYMBOL='Te' CASE (53) ; SYMBOL='I' CASE (54) ; SYMBOL='Xe' CASE (55) ; SYMBOL='Cs' CASE (56) ; SYMBOL='Ba' CASE (57) ; SYMBOL='La' ! Lanthanide elements (lanthanoids) CASE (58) ; SYMBOL='Ce' CASE (59) ; SYMBOL='Pr' CASE (60) ; SYMBOL='Nd' CASE (61) ; SYMBOL='Pm' CASE (62) ; SYMBOL='Sm' CASE (63) ; SYMBOL='Eu' CASE (64) ; SYMBOL='Gd' CASE (65) ; SYMBOL='Tb' CASE (66) ; SYMBOL='Dy' CASE (67) ; SYMBOL='Ho' CASE (68) ; SYMBOL='Er' CASE (69) ; SYMBOL='Tm' CASE (70) ; SYMBOL='Yb' CASE (71) ; SYMBOL='Lu' CASE (72) ; SYMBOL='Hf' CASE (73) ; SYMBOL='Ta' CASE (74) ; SYMBOL='W' CASE (75) ; SYMBOL='Re' CASE (76) ; SYMBOL='Os' CASE (77) ; SYMBOL='Ir' CASE (78) ; SYMBOL='Pt' CASE (79) ; SYMBOL='Au' CASE (80) ; SYMBOL='Hg' CASE (81) ; SYMBOL='Tl' CASE (82) ; SYMBOL='Pb' CASE (83) ; SYMBOL='Bi' CASE (84) ; SYMBOL='Po' CASE (85) ; SYMBOL='As' CASE (86) ; SYMBOL='Rn' CASE (87) ; SYMBOL='Fr' CASE (88) ; SYMBOL='Ra' CASE (89) ; SYMBOL='Ac' ! Actinide elements (actinoids) CASE (90) ; SYMBOL='Th' CASE (91) ; SYMBOL='Pa' CASE (92) ; SYMBOL='U' CASE (93) ; SYMBOL='Np' CASE (94) ; SYMBOL='Pu' CASE (95) ; SYMBOL='Am' CASE (96) ; SYMBOL='Cm' CASE (97) ; SYMBOL='Bk' CASE (98) ; SYMBOL='Cf' CASE (99) ; SYMBOL='Es' CASE (100); SYMBOL='Fm' CASE (101); SYMBOL='Md' CASE (102); SYMBOL='No' CASE (103); SYMBOL='Lr' CASE (104); SYMBOL='Rf' END SELECT END FUNCTION IDENTIFYZ SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system. INTEGER :: I,J DOUBLE PRECISION,DIMENSION(3) :: DIFF INTERNUCLEAR_ENERGY=0.D0 DO I=1,NBN DO J=I+1,NBN DIFF=CENTER(:,I)-CENTER(:,J) INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF)) END DO END DO END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Various functions for the Hartree model with temperature FUNCTION POSITIVE_PART(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN FUNC=0.D0 ELSE FUNC=X END IF END FUNCTION POSITIVE_PART FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC) ! beta test function for the entropy DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC FUNC=POSITIVE_PART(X)**MB/MB END FUNCTION ENTROPY_FUNCTION FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE FUNC=X**(1.D0/(MB-1.D0)) END IF END FUNCTION RECIP_DENTFUNC FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE IF (X==0.D0) THEN STOP'No derivative at origin' ELSE FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0) END IF END FUNCTION FUNCTION FUNCFORMU(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC INTEGER :: I DOUBLE PRECISION :: Y FUNC=-MASS DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE IF (Y>=0.D0) THEN FUNC=FUNC+RECIP_DENTFUNC(Y) END IF END DO END FUNCTION FUNCFORMU SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV INTEGER :: I DOUBLE PRECISION :: Y FVAL=-MASS ; FDERIV=0.D0 DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE FVAL=FVAL+RECIP_DENTFUNC(Y) FDERIV=FDERIV+DRECIP_DENTFUNC(Y) END DO END SUBROUTINE RDENTFUNCD END MODULE MODULE basis_parameters USE iso_c_binding ! flag for the choice of the basis set type (either existing in the library or even-tempered) LOGICAL :: LIBRARY ! PARAMETERS FOR A GIVEN BASIS SET CHARACTER(26) :: BASISFILE INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4 ! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme. ! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET INTEGER :: NUMBER_OF_TERMS DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO ! Various flags for the contraction of the primitives and the Kinetic Balance scheme LOGICAL :: UNCONT LOGICAL :: KINBAL,UKB TYPE gaussianbasisfunction ! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function. ! nbrofexponents: the number of different gaussian primitives present in the contraction ! center: coordinates (x,y,z) of the center of the basis function ! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center) ! exponents: array containing the exponent of each of the gaussian primitives present in the contraction ! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction ! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives ! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance). INTEGER(KIND=C_INT) :: nbrofexponents REAL(KIND=C_DOUBLE),DIMENSION(3) :: center INTEGER :: center_id REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree END TYPE gaussianbasisfunction TYPE twospinor ! Definition of a Pauli 2-spinor type basis function using gaussian basis functions. ! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor ! contractions: array containing the contractions present in each of the components of the 2-spinor ! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes) ! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor ! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0 INTEGER,DIMENSION(2) :: nbrofcontractions TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions INTEGER,DIMENSION(2,MNOGBF) :: contidx DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients END TYPE twospinor CONTAINS SUBROUTINE SETUP_BASIS USE case_parameters ; USE setup_tools CHARACTER(LEN=4) :: CHAR CHARACTER(LEN=26) :: BASISNAME INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## BASIS DEFINITION',INFO) IF (INFO/=0) STOP' The basis definition is not given.' READ(100,'(3/,a)') BASISNAME IF (BASISNAME(1:6)=='BASIS ') THEN ! The basis set is an existing one in the basis library LIBRARY=.TRUE. BASISFILE='basis/'//BASISNAME(7:) READ(100,'(a4)') CHAR IF (CHAR=='UNCO') THEN UNCONT=.TRUE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)' ELSE UNCONT=.FALSE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)' END IF ELSE IF (BASISNAME(1:4)=='EVEN') THEN ! The basis set is an even-tempered one LIBRARY=.FALSE. IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)' WRITE(*,'(a)')' Even-tempered basis set (preliminary support)' READ(100,'(i4)') NUMBER_OF_TERMS WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS READ(100,*) FIRST_TERM WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM READ(100,*) COMMON_RATIO WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO ELSE STOP' Unknown basis set type' END IF IF (RELATIVISTIC) THEN READ(100,'(a2)') CHAR IF (CHAR=='KI') THEN KINBAL=.TRUE. READ(100,'(a4)') CHAR IF (CHAR=='REST') THEN UKB=.FALSE. WRITE(*,'(a)')' Restricted kinetic balance' ELSE UKB=.TRUE. WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance' END IF ELSE KINBAL=.FALSE. WRITE(*,'(a)')' No kinetic balance' END IF END IF CLOSE(100) END SUBROUTINE SETUP_BASIS FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE) ! Function that computes the value of a gaussian basis function at a given point of space. USE iso_c_binding TYPE(gaussianbasisfunction),INTENT(IN) :: GBF DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT REAL(KIND=C_DOUBLE) :: VALUE VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) & & *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), & & EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2))) END FUNCTION GBF_POINTWISE_VALUE SUBROUTINE PRINTGBF(PHI,NUNIT) TYPE(gaussianbasisfunction),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents WRITE(NUNIT,*)' center:',PHI%center WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree DO I=1,PHI%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',I WRITE(NUNIT,*)' exponent:',PHI%exponents(I) WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I) END DO END SUBROUTINE PRINTGBF FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE) ! Function that computes the value of a Pauli 2-spinor basis function at a given point of space. USE iso_c_binding TYPE(twospinor),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT DOUBLE COMPLEX,DIMENSION(2) :: VALUE INTEGER :: I,J DO I=1,2 VALUE(I)=(0.D0,0.D0) DO J=1,PHI%nbrofcontractions(I) VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT) END DO END DO END FUNCTION TWOSPINOR_POINTWISE_VALUE SUBROUTINE PRINT2SPINOR(PHI,NUNIT) TYPE(twospinor),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I,J,K DO K=1,2 WRITE(NUNIT,*)'component #',K IF (PHI%nbrofcontractions(K)==0) THEN WRITE(NUNIT,*)' no contraction' ELSE WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K) DO I=1,PHI%nbrofcontractions(K) WRITE(NUNIT,*)' contraction #',I WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I) WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center DO J=1,PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',J WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J) WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J) END DO END DO END IF END DO END SUBROUTINE PRINT2SPINOR END MODULE MODULE scf_parameters ! number of different SCF algorithms to be used INTEGER :: NBALG ! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only)) INTEGER,DIMENSION(5) :: ALG ! threshold for numerical convergence DOUBLE PRECISION :: TRSHLD ! maximum number of iterations allowed INTEGER :: MAXITR ! flag for the direct computation of the bielectronic integrals LOGICAL :: DIRECT ! flag for the "semi-direct" computation of the bielectronic integrals (relativistic case only) ! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards. LOGICAL :: SEMIDIRECT ! flag for the storage of the computed bielectronic integrals (and/or their list) on disk or in memory LOGICAL :: USEDISK ! flag for the use of the SS-bielectronic integrals LOGICAL :: SSINTEGRALS ! flag for the use of the LS-bielectronic integrals LOGICAL :: SLINTEGRALS ! resume EIG and EIGVEC from last computation LOGICAL :: RESUME +! symmetries of the system + LOGICAL :: SYM_SX = .FALSE.,SYM_SY = .FALSE.,SYM_SZ = .FALSE. CONTAINS SUBROUTINE SETUP_SCF !$ USE omp_lib USE case_parameters ; USE setup_tools CHARACTER :: METHOD CHARACTER(4) :: CHAR INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS DOUBLE PRECISION :: SHIFT OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## SCF PARAMETERS',INFO) IF (INFO/=0) STOP' The SCF parameters are not given.' READ(100,'(7/,i1)') NBALG DO I=1,NBALG READ(100,'(i1)') ALG(I) IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN STOP' The Optimal Damping Algorithm is intended for the non-relativistic case only.' ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN STOP' ES''s algorithm is intended for the relativistic case only.' END IF END DO READ(100,*) TRSHLD WRITE(*,*)'Threshold =',TRSHLD READ(100,'(i5)') MAXITR WRITE(*,*)'Maximum number of iterations =',MAXITR READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ; SEMIDIRECT=.FALSE. READ(100,'(a4)') CHAR ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE IF (CHAR=='SEM') THEN DIRECT=.FALSE. ; SEMIDIRECT=.TRUE. WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF IF (MODEL==3) THEN ! Special case: complex GHF SSINTEGRALS=.FALSE. SLINTEGRALS=.FALSE. ELSE REWIND(100) CALL LOOKFOR(100,'NOSS',INFO) IF (INFO==0) THEN SSINTEGRALS=.FALSE. WRITE(*,'(a)')' (SS-integrals are not used in the computation)' ELSE SSINTEGRALS=.TRUE. END IF REWIND(100) CALL LOOKFOR(100,'NOSL',INFO) IF (INFO==0) THEN SLINTEGRALS=.FALSE. WRITE(*,'(a)')' (SL-integrals are not used in the computation)' ELSE SLINTEGRALS=.TRUE. END IF END IF + READ(100,'(a4)') CHAR + IF (CHAR=='NOSL') THEN + SLINTEGRALS=.FALSE. + WRITE(*,'(a)')' (SL-integrals are not used in the computation)' + ELSE + SLINTEGRALS=.TRUE. + END IF + + CALL LOOKFOR(100,'SYMMETRY SX',INFO) + IF (INFO==0) THEN + WRITE(*,'(a)')' (System possesses X-plane symmetry)' + SYM_SX = .TRUE. + END IF + CALL LOOKFOR(100,'SYMMETRY SY',INFO) + IF (INFO==0) THEN + WRITE(*,'(a)')' (System possesses Y-plane symmetry)' + SYM_SY = .TRUE. + END IF + CALL LOOKFOR(100,'SYMMETRY SZ',INFO) + IF (INFO==0) THEN + WRITE(*,'(a)')' (System possesses Z-plane symmetry)' + SYM_SZ = .TRUE. + END IF ELSE IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! the list of the bielectronic integrals is stored in memory ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF END IF ! additional verifications on the parameters of the algorithms DO I=1,NBALG IF (ALG(I)==2) THEN REWIND(100) CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 1 READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT ELSE IF (ALG(I)==3) THEN REWIND(100) CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 2 READ(100,'(/,i2)',ERR=2,END=2)MXSET IF (MXSET<2) GO TO 3 ELSE IF (ALG(I)==5) THEN REWIND(100) CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 4 READ(100,'(/,a)',ERR=4,END=4)METHOD IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4 END IF END DO RESUME=.FALSE. CALL LOOKFOR(100,'RESUME',INFO) IF(INFO == 0) THEN READ(100,'(a)')CHAR IF(CHAR == 'YES') THEN RESUME = .TRUE. END IF END IF !$ ! determination of the number of threads to be used by OpenMP !$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO) !$ IF (INFO==0) THEN !$ READ(100,'(/,i3)')NUMBER_OF_THREADS !$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS) !$ END IF !$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.' CLOSE(100) RETURN ! MESSAGES 1 STOP'No shift parameter given for the level-shifting algorithm.' 2 STOP'No simplex dimension given for the DIIS algorithm.' 3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.' 4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.' END SUBROUTINE SETUP_SCF END MODULE
antoine-levitt/ACCQUAREL
5ccc6142d1727720a970b254083863f330eaf7e4
Integrals : factor out checks for zero integrals
diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index c5486c7..79fa8ed 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,560 +1,546 @@ MODULE integrals ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic +FUNCTION APRIORI_ZERO(PHI1,PHI2,PHI3,PHI4) RESULT(VALUE) + ! Function that checks whether a given bielectronic integral can a priori be predicted to be zero + USE case_parameters ; USE basis_parameters + TYPE(gaussianbasisfunction),INTENT(IN) :: PHI1,PHI2,PHI3,PHI4 + LOGICAL :: SC,SYM,VALUE + INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE + + ! same center and odd global monomial degree + SC=((PHI1%center_id==PHI2%center_id).AND.(PHI2%center_id==PHI3%center_id).AND.(PHI3%center_id==PHI4%center_id)) + IF(SC) THEN + GLOBALMONOMIALDEGREE=PHI1%monomialdegree+PHI2%monomialdegree+PHI3%monomialdegree+PHI4%monomialdegree + IF(ANY(MOD(GLOBALMONOMIALDEGREE,2)==1)) THEN + VALUE = .TRUE. + RETURN + END IF + END IF + + VALUE = .FALSE. + +END FUNCTION APRIORI_ZERO + SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE INTEGER :: I,J,K,L - INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE - LOGICAL :: SC,SS - - ! same spin check. Not used outside GHF - SS=.TRUE. - + LOGICAL :: SS = .TRUE. + OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K - ! same center? - SC=((PHI(I)%center_id==PHI(J)%center_id).AND.(PHI(J)%center_id==PHI(K)%center_id).AND.(PHI(K)%center_id==PHI(L)%center_id)) - GLOBALMONOMIALDEGREE=PHI(I)%monomialdegree+PHI(J)%monomialdegree+PHI(K)%monomialdegree+PHI(L)%monomialdegree - ! same spin? i must have same spin as j, same for k and l - IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& - &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) -! parity check on the product of the monomials if the four functions share the same center - IF (((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)).AND.SS) THEN - LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L + IF (.NOT.APRIORI_ZERO(PHI(I),PHI(J),PHI(K),PHI(L))) THEN + IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& + &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) + IF(SS) THEN + LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L + END IF + IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 - INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE - LOGICAL :: SC OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) - SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & - & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & - & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) - GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & - & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! LLSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) - SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & - & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & - & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) - GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & - & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SL' SUBSIZE(2)=SUBSIZE(2)+1 GO TO 2 END IF END DO END DO END DO END DO END DO END DO 2 CONTINUE END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) - SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & - & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & - & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) - GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & - & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + IF(.NOT.APRIORI_ZERO(PHI(I)%contractions(I1,I2),PHI(J)%contractions(I1,I3),PHI(K)%contractions(I4,I5),PHI(L)%contractions(I4,I6))) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O - INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE - LOGICAL :: SC NBF=NGBF ! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 DO I=1,NGBF(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K - SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id)) - GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree -! parity check (one center case) - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO IF (SLINTEGRALS) THEN ! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. - !$OMP PARALLEL DO PRIVATE(N,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1) + !$OMP PARALLEL DO PRIVATE(N,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K - SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.& - &(GBF(K)%center_id==GBF(L)%center_id)) - GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree - ! parity check (one center case) - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN ! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 - !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1) + !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K - SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id)) - GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree -! parity check (one center case) - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + IF (.NOT.APRIORI_ZERO(GBF(I),GBF(J),GBF(K),GBF(L))) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE
antoine-levitt/ACCQUAREL
c1845bdd5fe2571b8b8935ed96514574e7255bd8
small correction
diff --git a/src/setup.f90 b/src/setup.f90 index 5019596..cda8926 100644 --- a/src/setup.f90 +++ b/src/setup.f90 @@ -203,587 +203,587 @@ SUBROUTINE SETUP_DATA READ(100,'(3(i3))')NBECS,NBEOS,NBOOS WRITE(*,'(a,i3)')' - number of closed-shell electrons = ',NBECS WRITE(*,'(a,i3)')' - number of open-shell electrons = ',NBEOS WRITE(*,'(a,i3)')' - number of open-shell orbitals = ',NBOOS IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons' IF (NBOOS<=NBEOS) STOP' Problem with the number of open-shell orbitals!' END IF ELSE IF (MODEL==1) THEN IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!' ELSE IF (MODEL==2) THEN READ(100,'(2(i3))')NBEA,NBEB WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!' ! ELSE IF (MODEL==3) THEN END IF END IF WRITE(*,'(a)')' --------- **** ---------' END IF CLOSE(100) END SUBROUTINE SETUP_DATA FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL) ! Function returning the symbol of a chemical element given its atomic number Z. INTEGER,INTENT(IN) :: Z CHARACTER(2) :: SYMBOL IF (Z>104) THEN WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!' STOP END IF ! List of symbols from Hydrogen up to Rutherfordium. SELECT CASE (Z) CASE (1) ; SYMBOL='H' CASE (2) ; SYMBOL='He' CASE (3) ; SYMBOL='Li' CASE (4) ; SYMBOL='Be' CASE (5) ; SYMBOL='B' CASE (6) ; SYMBOL='C' CASE (7) ; SYMBOL='N' CASE (8) ; SYMBOL='O' CASE (9) ; SYMBOL='F' CASE (10) ; SYMBOL='Ne' CASE (11) ; SYMBOL='Na' CASE (12) ; SYMBOL='Mg' CASE (13) ; SYMBOL='Al' CASE (14) ; SYMBOL='Si' CASE (15) ; SYMBOL='P' CASE (16) ; SYMBOL='S' CASE (17) ; SYMBOL='Cl' CASE (18) ; SYMBOL='Ar' CASE (19) ; SYMBOL='K' CASE (20) ; SYMBOL='Ca' CASE (21) ; SYMBOL='Sc' CASE (22) ; SYMBOL='Ti' CASE (23) ; SYMBOL='V' CASE (24) ; SYMBOL='Cr' CASE (25) ; SYMBOL='Mn' CASE (26) ; SYMBOL='Fe' CASE (27) ; SYMBOL='Co' CASE (28) ; SYMBOL='Ni' CASE (29) ; SYMBOL='Cu' CASE (30) ; SYMBOL='Zn' CASE (31) ; SYMBOL='Ga' CASE (32) ; SYMBOL='Ge' CASE (33) ; SYMBOL='As' CASE (34) ; SYMBOL='Se' CASE (35) ; SYMBOL='Br' CASE (36) ; SYMBOL='Kr' CASE (37) ; SYMBOL='Rb' CASE (38) ; SYMBOL='Sr' CASE (39) ; SYMBOL='Y' CASE (40) ; SYMBOL='Zr' CASE (41) ; SYMBOL='Nb' CASE (42) ; SYMBOL='Mo' CASE (43) ; SYMBOL='Tc' CASE (44) ; SYMBOL='Ru' CASE (45) ; SYMBOL='Rh' CASE (46) ; SYMBOL='Pd' CASE (47) ; SYMBOL='Ag' CASE (48) ; SYMBOL='Cd' CASE (49) ; SYMBOL='In' CASE (50) ; SYMBOL='Sn' CASE (51) ; SYMBOL='Sb' CASE (52) ; SYMBOL='Te' CASE (53) ; SYMBOL='I' CASE (54) ; SYMBOL='Xe' CASE (55) ; SYMBOL='Cs' CASE (56) ; SYMBOL='Ba' CASE (57) ; SYMBOL='La' ! Lanthanide elements (lanthanoids) CASE (58) ; SYMBOL='Ce' CASE (59) ; SYMBOL='Pr' CASE (60) ; SYMBOL='Nd' CASE (61) ; SYMBOL='Pm' CASE (62) ; SYMBOL='Sm' CASE (63) ; SYMBOL='Eu' CASE (64) ; SYMBOL='Gd' CASE (65) ; SYMBOL='Tb' CASE (66) ; SYMBOL='Dy' CASE (67) ; SYMBOL='Ho' CASE (68) ; SYMBOL='Er' CASE (69) ; SYMBOL='Tm' CASE (70) ; SYMBOL='Yb' CASE (71) ; SYMBOL='Lu' CASE (72) ; SYMBOL='Hf' CASE (73) ; SYMBOL='Ta' CASE (74) ; SYMBOL='W' CASE (75) ; SYMBOL='Re' CASE (76) ; SYMBOL='Os' CASE (77) ; SYMBOL='Ir' CASE (78) ; SYMBOL='Pt' CASE (79) ; SYMBOL='Au' CASE (80) ; SYMBOL='Hg' CASE (81) ; SYMBOL='Tl' CASE (82) ; SYMBOL='Pb' CASE (83) ; SYMBOL='Bi' CASE (84) ; SYMBOL='Po' CASE (85) ; SYMBOL='As' CASE (86) ; SYMBOL='Rn' CASE (87) ; SYMBOL='Fr' CASE (88) ; SYMBOL='Ra' CASE (89) ; SYMBOL='Ac' ! Actinide elements (actinoids) CASE (90) ; SYMBOL='Th' CASE (91) ; SYMBOL='Pa' CASE (92) ; SYMBOL='U' CASE (93) ; SYMBOL='Np' CASE (94) ; SYMBOL='Pu' CASE (95) ; SYMBOL='Am' CASE (96) ; SYMBOL='Cm' CASE (97) ; SYMBOL='Bk' CASE (98) ; SYMBOL='Cf' CASE (99) ; SYMBOL='Es' CASE (100); SYMBOL='Fm' CASE (101); SYMBOL='Md' CASE (102); SYMBOL='No' CASE (103); SYMBOL='Lr' CASE (104); SYMBOL='Rf' END SELECT END FUNCTION IDENTIFYZ SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system. INTEGER :: I,J DOUBLE PRECISION,DIMENSION(3) :: DIFF INTERNUCLEAR_ENERGY=0.D0 DO I=1,NBN DO J=I+1,NBN DIFF=CENTER(:,I)-CENTER(:,J) INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF)) END DO END DO END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Various functions for the Hartree model with temperature FUNCTION POSITIVE_PART(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN FUNC=0.D0 ELSE FUNC=X END IF END FUNCTION POSITIVE_PART FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC) ! beta test function for the entropy DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC FUNC=POSITIVE_PART(X)**MB/MB END FUNCTION ENTROPY_FUNCTION FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE FUNC=X**(1.D0/(MB-1.D0)) END IF END FUNCTION RECIP_DENTFUNC FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE IF (X==0.D0) THEN STOP'No derivative at origin' ELSE FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0) END IF END FUNCTION FUNCTION FUNCFORMU(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC INTEGER :: I DOUBLE PRECISION :: Y FUNC=-MASS DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE IF (Y>=0.D0) THEN FUNC=FUNC+RECIP_DENTFUNC(Y) END IF END DO END FUNCTION FUNCFORMU SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV INTEGER :: I DOUBLE PRECISION :: Y FVAL=-MASS ; FDERIV=0.D0 DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE FVAL=FVAL+RECIP_DENTFUNC(Y) FDERIV=FDERIV+DRECIP_DENTFUNC(Y) END DO END SUBROUTINE RDENTFUNCD END MODULE MODULE basis_parameters USE iso_c_binding ! flag for the choice of the basis set type (either existing in the library or even-tempered) LOGICAL :: LIBRARY ! PARAMETERS FOR A GIVEN BASIS SET CHARACTER(26) :: BASISFILE INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4 ! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme. ! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET INTEGER :: NUMBER_OF_TERMS DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO ! Various flags for the contraction of the primitives and the Kinetic Balance scheme LOGICAL :: UNCONT LOGICAL :: KINBAL,UKB TYPE gaussianbasisfunction ! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function. ! nbrofexponents: the number of different gaussian primitives present in the contraction ! center: coordinates (x,y,z) of the center of the basis function ! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center) ! exponents: array containing the exponent of each of the gaussian primitives present in the contraction ! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction ! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives ! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance). INTEGER(KIND=C_INT) :: nbrofexponents REAL(KIND=C_DOUBLE),DIMENSION(3) :: center INTEGER :: center_id REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree END TYPE gaussianbasisfunction TYPE twospinor ! Definition of a Pauli 2-spinor type basis function using gaussian basis functions. ! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor ! contractions: array containing the contractions present in each of the components of the 2-spinor ! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes) ! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor ! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0 INTEGER,DIMENSION(2) :: nbrofcontractions TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions INTEGER,DIMENSION(2,MNOGBF) :: contidx DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients END TYPE twospinor CONTAINS SUBROUTINE SETUP_BASIS USE case_parameters ; USE setup_tools CHARACTER(LEN=4) :: CHAR CHARACTER(LEN=26) :: BASISNAME INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## BASIS DEFINITION',INFO) IF (INFO/=0) STOP' The basis definition is not given.' READ(100,'(3/,a)') BASISNAME IF (BASISNAME(1:6)=='BASIS ') THEN ! The basis set is an existing one in the basis library LIBRARY=.TRUE. BASISFILE='basis/'//BASISNAME(7:) READ(100,'(a4)') CHAR IF (CHAR=='UNCO') THEN UNCONT=.TRUE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)' ELSE UNCONT=.FALSE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)' END IF ELSE IF (BASISNAME(1:4)=='EVEN') THEN ! The basis set is an even-tempered one LIBRARY=.FALSE. IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)' WRITE(*,'(a)')' Even-tempered basis set (preliminary support)' READ(100,'(i4)') NUMBER_OF_TERMS WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS READ(100,*) FIRST_TERM WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM READ(100,*) COMMON_RATIO WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO ELSE STOP' Unknown basis set type' END IF IF (RELATIVISTIC) THEN READ(100,'(a2)') CHAR IF (CHAR=='KI') THEN KINBAL=.TRUE. READ(100,'(a4)') CHAR IF (CHAR=='REST') THEN UKB=.FALSE. WRITE(*,'(a)')' Restricted kinetic balance' ELSE UKB=.TRUE. WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance' END IF ELSE KINBAL=.FALSE. WRITE(*,'(a)')' No kinetic balance' END IF END IF CLOSE(100) END SUBROUTINE SETUP_BASIS FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE) ! Function that computes the value of a gaussian basis function at a given point of space. USE iso_c_binding TYPE(gaussianbasisfunction),INTENT(IN) :: GBF DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT REAL(KIND=C_DOUBLE) :: VALUE VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) & & *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), & & EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2))) END FUNCTION GBF_POINTWISE_VALUE SUBROUTINE PRINTGBF(PHI,NUNIT) TYPE(gaussianbasisfunction),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents WRITE(NUNIT,*)' center:',PHI%center WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree DO I=1,PHI%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',I WRITE(NUNIT,*)' exponent:',PHI%exponents(I) WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I) END DO END SUBROUTINE PRINTGBF FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE) ! Function that computes the value of a Pauli 2-spinor basis function at a given point of space. USE iso_c_binding TYPE(twospinor),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT DOUBLE COMPLEX,DIMENSION(2) :: VALUE INTEGER :: I,J DO I=1,2 VALUE(I)=(0.D0,0.D0) DO J=1,PHI%nbrofcontractions(I) VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT) END DO END DO END FUNCTION TWOSPINOR_POINTWISE_VALUE SUBROUTINE PRINT2SPINOR(PHI,NUNIT) TYPE(twospinor),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I,J,K DO K=1,2 WRITE(NUNIT,*)'component #',K IF (PHI%nbrofcontractions(K)==0) THEN WRITE(NUNIT,*)' no contraction' ELSE WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K) DO I=1,PHI%nbrofcontractions(K) WRITE(NUNIT,*)' contraction #',I WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I) WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center DO J=1,PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',J WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J) WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J) END DO END DO END IF END DO END SUBROUTINE PRINT2SPINOR END MODULE MODULE scf_parameters ! number of different SCF algorithms to be used INTEGER :: NBALG ! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only)) INTEGER,DIMENSION(5) :: ALG ! threshold for numerical convergence DOUBLE PRECISION :: TRSHLD ! maximum number of iterations allowed INTEGER :: MAXITR ! flag for the direct computation of the bielectronic integrals LOGICAL :: DIRECT ! flag for the "semi-direct" computation of the bielectronic integrals (relativistic case only) ! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards. LOGICAL :: SEMIDIRECT ! flag for the storage of the computed bielectronic integrals (and/or their list) on disk or in memory LOGICAL :: USEDISK ! flag for the use of the SS-bielectronic integrals LOGICAL :: SSINTEGRALS ! flag for the use of the LS-bielectronic integrals LOGICAL :: SLINTEGRALS ! resume EIG and EIGVEC from last computation LOGICAL :: RESUME CONTAINS SUBROUTINE SETUP_SCF !$ USE omp_lib USE case_parameters ; USE setup_tools CHARACTER :: METHOD CHARACTER(4) :: CHAR INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS DOUBLE PRECISION :: SHIFT OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## SCF PARAMETERS',INFO) IF (INFO/=0) STOP' The SCF parameters are not given.' READ(100,'(7/,i1)') NBALG DO I=1,NBALG READ(100,'(i1)') ALG(I) IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN STOP' The Optimal Damping Algorithm is intended for the non-relativistic case only.' ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN STOP' ES''s algorithm is intended for the relativistic case only.' END IF END DO READ(100,*) TRSHLD WRITE(*,*)'Threshold =',TRSHLD READ(100,'(i5)') MAXITR WRITE(*,*)'Maximum number of iterations =',MAXITR READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ; SEMIDIRECT=.FALSE. READ(100,'(a4)') CHAR ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE IF (CHAR=='SEM') THEN DIRECT=.FALSE. ; SEMIDIRECT=.TRUE. WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF IF (MODEL==3) THEN ! Special case: complex GHF SSINTEGRALS=.FALSE. SLINTEGRALS=.FALSE. ELSE REWIND(100) CALL LOOKFOR(100,'NOSS',INFO) IF (INFO==0) THEN SSINTEGRALS=.FALSE. WRITE(*,'(a)')' (SS-integrals are not used in the computation)' ELSE SSINTEGRALS=.TRUE. END IF REWIND(100) - CALL LOOKFOR(100,'NOLS',INFO) + CALL LOOKFOR(100,'NOSL',INFO) IF (INFO==0) THEN SLINTEGRALS=.FALSE. WRITE(*,'(a)')' (SL-integrals are not used in the computation)' ELSE SLINTEGRALS=.TRUE. END IF END IF ELSE IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! the list of the bielectronic integrals is stored in memory ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF END IF ! additional verifications on the parameters of the algorithms DO I=1,NBALG IF (ALG(I)==2) THEN REWIND(100) CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 1 READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT ELSE IF (ALG(I)==3) THEN REWIND(100) CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 2 READ(100,'(/,i2)',ERR=2,END=2)MXSET IF (MXSET<2) GO TO 3 ELSE IF (ALG(I)==5) THEN REWIND(100) CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 4 READ(100,'(/,a)',ERR=4,END=4)METHOD IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4 END IF END DO RESUME=.FALSE. CALL LOOKFOR(100,'RESUME',INFO) IF(INFO == 0) THEN READ(100,'(a)')CHAR IF(CHAR == 'YES') THEN RESUME = .TRUE. END IF END IF !$ ! determination of the number of threads to be used by OpenMP !$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO) !$ IF (INFO==0) THEN !$ READ(100,'(/,i3)')NUMBER_OF_THREADS !$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS) !$ END IF !$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.' CLOSE(100) RETURN ! MESSAGES 1 STOP'No shift parameter given for the level-shifting algorithm.' 2 STOP'No simplex dimension given for the DIIS algorithm.' 3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.' 4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.' END SUBROUTINE SETUP_SCF END MODULE
antoine-levitt/ACCQUAREL
f1f7dfadb998e7c290242da0595a5713ced565d9
Various changes to the setup routines
diff --git a/src/Makefile b/src/Makefile index 31d9103..11b815a 100644 --- a/src/Makefile +++ b/src/Makefile @@ -1,102 +1,102 @@ ### MAKEFILE PREAMBLE ### F95 = g95 #F95 = gfortran #F95 = ifort # common to compilers and linker DEBUGFFLAGS = -fbounds-check -fimplicit-none -ffpe-trap=invalid,zero,denormal PRODFFLAGS = -fimplicit-none COMMONFLAGS = -O3 -g FFLAGS = $(PRODFFLAGS) $(COMMONFLAGS) ifndef ASPICROOT ASPICROOT=../A.S.P.I.C endif ifeq ($(F95),g95) - F95FLAGS = -c $(FLAGS) -fmod=$(MODDIR) $(FFLAGS) + F95FLAGS = -c -ffree-line-length-huge $(FLAGS) -fmod=$(MODDIR) $(FFLAGS) LD = g95 FLIBS = -llapack -lblas -lm endif ifeq ($(F95),gfortran) - F95FLAGS = -c $(FLAGS) -fopenmp -J $(MODDIR) $(FFLAGS) + F95FLAGS = -c -ffree-line-length-none $(FLAGS) -fopenmp -J $(MODDIR) $(FFLAGS) LD = gfortran FLIBS = -lgomp -llapack -lblas -lm endif ifeq ($(F95),ifort) F95FLAGS = -c $(FLAGS) -module $(MODDIR) $(FFLAGS) LD = ifort FLIBS = -llapack -lblas -lm endif LDFLAGS = $(COMMONFLAGS) CPP = g++ CXXFLAGS = -c $(COMMONFLAGS) ## DIRECTORIES ## TARGET = accquarel.exe EXEDIR = ../ MODDIR = ../mod/ OBJDIR = ../obj/ SRCDIR = ./ ## ASPIC code ## ASPICINCPATH = -I$(ASPICROOT)/include ASPICLIBPATH = -L$(ASPICROOT)/lib XERCESCLIBPATH = -L$(XERCESCROOT)/lib ifeq ($(shell uname),Darwin) ## cluster osx darwin ASPICLIBS = $(ASPICLIBPATH) -lgIntegrals -lchemics -lxmlParser -lgaussian -lpolynome -lcontainor -laspicUtils $(XERCESCLIBPATH) -lxerces-c -L/usr/lib/gcc/i686-apple-darwin9/4.0.1 -lstdc++ endif ifeq ($(shell uname),Linux) ## linux ubuntu ASPICLIBS = $(ASPICLIBPATH) -lgIntegrals -lchemics -lxmlParser -lgaussian -lpolynome -lcontainor -laspicUtils $(XERCESCLIBPATH) -lxerces-c -L/usr/lib/gcc/i686-linux-gnu/4.4/ -lstdc++ endif ## ACCQUAREL code ## OBJ = \ $(OBJDIR)expokit.o \ $(OBJDIR)optimization.o \ $(OBJDIR)rootfinding.o \ $(OBJDIR)tools.o \ $(OBJDIR)setup.o \ $(OBJDIR)common.o \ $(OBJDIR)integrals_c.o \ $(OBJDIR)integrals_f.o \ $(OBJDIR)basis.o \ $(OBJDIR)matrices.o \ $(OBJDIR)scf.o \ $(OBJDIR)roothaan.o \ $(OBJDIR)levelshifting.o \ $(OBJDIR)diis.o \ $(OBJDIR)oda.o \ $(OBJDIR)esa.o \ $(OBJDIR)gradient.o \ $(OBJDIR)algorithms.o \ $(OBJDIR)drivers.o \ $(OBJDIR)main.o # Compilation rules $(TARGET) : $(OBJ) $(LD) $(LDFLAGS) $(OBJ) -o $(EXEDIR)$(TARGET) $(FLIBS) $(ASPICLIBS) @echo " ----------- $(TARGET) created ----------- " $(OBJDIR)%.o : $(SRCDIR)%.F90 $(F95) $(F95FLAGS) -o $@ $< $(OBJDIR)%.o : $(SRCDIR)%.f90 $(F95) $(F95FLAGS) -o $@ $< $(OBJDIR)%.o : $(SRCDIR)%.f $(F95) $(F95FLAGS) -o $@ $< $(OBJDIR)%.o : $(SRCDIR)%.cpp $(CPP) $(CXXFLAGS) -o $@ $(ASPICINCPATH) $< # clean : rm $(EXEDIR)$(TARGET) $(OBJ) $(MODDIR)*.mod diff --git a/src/drivers.f90 b/src/drivers.f90 index d136d83..cdf8688 100644 --- a/src/drivers.f90 +++ b/src/drivers.f90 @@ -1,533 +1,527 @@ SUBROUTINE DRIVER_relativistic USE case_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools USE metric_relativistic ; USE scf_algorithms IMPLICIT NONE INTEGER :: NBAST TYPE(twospinor),DIMENSION(:),ALLOCATABLE :: PHI INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: GBF INTEGER,DIMENSION(2) :: NGBF INTEGER :: TYPENMBR(3),INFO,I DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: EIG DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: POEFM DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM DOUBLE COMPLEX,DIMENSION(:,:),ALLOCATABLE :: EIGVEC - - ! complex GHF - IF(MODEL == 3) THEN - SSINTEGRALS = .FALSE. - SLINTEGRALS = .FALSE. - END IF ! Computation of the discretization basis CALL FORMBASIS(PHI,NBAS,GBF,NGBF) NBAST=SUM(NBAS) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) CALL BUILDOM(POM,PHI,NBAST,NBAS) ; PS=>POM ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL ZPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM IF (INFO/=0) GOTO 1 ! Condition number WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1') ! Computation and assembly of the core hamiltonian matrix WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) CALL BUILDOEFM(POEFM,PHI,NBAST,NBAS) ! Creation of the list of nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAS,BINMBR,TYPENMBR) IF (DIRECT) THEN IF (.NOT.USEDISK) THEN ! storage of the list of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4)) OPEN(LUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(I,:) END DO CLOSE(LUNIT,STATUS='DELETE') END IF ELSE IF (.NOT.DIRECT) THEN ! Precomputation of the bielectronic integrals is preferred to "on the fly" computation ! Precomputation of the bielectronic integrals involving gaussian basis functions WRITE(*,'(a)')'* Computation and storage in memory of the bielectronic integrals of GBF' CALL PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) IF (SEMIDIRECT) THEN IF (.NOT.USEDISK) THEN ! storage the list and the type of nonzero bielectronic integrals (in order to use the precomputed GBF bielectronic integrals) in memory ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:BINMBR)) OPEN(LUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(I,:),BITYPE(I) END DO CLOSE(LUNIT,STATUS='DELETE') END IF ELSE WRITE(*,'(a)')'* Computation of the bielectronic integrals of 2-spinors basis functions' IF (USEDISK) THEN ! storage of the list and values of nonzero bielectronic integrals on disk ALLOCATE(BILIST(1:1,1:4),BITYPE(1:1)) OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(1,:),BITYPE(1) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4)),BITYPE(1)) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) DEALLOCATE(BILIST,BITYPE) ELSE ! storage of the list and values of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4),BITYPE(1:1),CBIVALUES(1:BINMBR)) OPEN(LUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(I,:),BITYPE(1) CBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4)),BITYPE(1)) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO CLOSE(LUNIT,STATUS='DELETE') DEALLOCATE(BITYPE) END IF CALL DEALLOCATE_INTEGRALS END IF END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) IF(RESUME) THEN OPEN(100,FILE='eig.txt') READ(100,*) EIG OPEN(101,FILE='eigvec_r.txt') OPEN(102,FILE='eigvec_i.txt') CALL READMATRIX(EIGVEC,NBAST,101,102) CLOSE(100) CLOSE(101) CLOSE(102) END IF DO I=1,NBALG SELECT CASE (ALG(I)) CASE (1) WRITE(*,'(/,a)')' Roothaan''s algorithm' SELECT CASE (MODEL) CASE (1) CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) ! CALL ROOTHAAN_test(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR) CASE (2) CALL ROOTHAAN_AOCOSDHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR) CASE (3) CALL ROOTHAAN(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (2) WRITE(*,'(/,a)')' level-shifting algorithm' CALL LEVELSHIFTING(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (3) WRITE(*,'(/,a)')' DIIS algorithm' CALL DIIS(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (5) WRITE(*,'(/,a)')' Eric Sere''s algorithm' CALL ESA(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (6) WRITE(*,'(/,a)')' Roothaan/Gradient algorithm' CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT END DO IF (DIRECT) THEN IF (USEDISK) THEN OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST) END IF ELSE IF (SEMIDIRECT) THEN IF (USEDISK) THEN OPEN(LUNIT,form='UNFORMATTED') ; CLOSE(LUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,BITYPE) END IF CALL DEALLOCATE_INTEGRALS ELSE IF (USEDISK) THEN OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,CBIVALUES) END IF END IF END IF OPEN(100,FILE='eig.txt') WRITE(100,*) EIG OPEN(101,FILE='eigvec_r.txt') OPEN(102,FILE='eigvec_i.txt') CALL PRINTMATRIX(EIGVEC,NBAST,101,102) CLOSE(100) CLOSE(101) CLOSE(102) DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF WRITE(*,*)'(called from subroutine DRIVER)' STOP END SUBROUTINE DRIVER_relativistic SUBROUTINE DRIVER_nonrelativistic USE case_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE metric_nonrelativistic USE scf_algorithms IMPLICIT NONE INTEGER :: NBAST TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS INTEGER :: INFO,I DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,EIG DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC ! Computation of the discretization basis IF(MODEL == 4) THEN CALL FORMBASIS_GHF(PHI,NBAS) ELSE CALL FORMBASIS(PHI,NBAS) END IF NBAST=SUM(NBAS) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) IF(MODEL == 4) THEN CALL BUILDOM_GHF(POM,PHI,NBAST) ELSE CALL BUILDOM(POM,PHI,NBAST) END IF PS=>POM ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) ; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL DPPTRF('U',NBAST,PCFOM,INFO) ; PCFS=>PCFOM IF (INFO/=0) GOTO 1 ! Condition number WRITE(*,'(a,f16.2)')'* Condition number of the overlap matrix:', NORM(PS,NBAST,'1')*NORM(PIS,NBAST,'1') ! Computation and assembly of the matrix of the free hamiltonian WRITE(*,'(a)')'* Computation and assembly of the core hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) IF(MODEL == 4) THEN CALL BUILDOEFM_GHF(POEFM,PHI,NBAST) ELSE CALL BUILDOEFM(POEFM,PHI,NBAST) END IF ! Creation of the list of the nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAST,BINMBR) IF (DIRECT) THEN ! Computation of the bielectronic integrals will be done "on the fly" ! storage of the list of nonzero bielectronic integrals in memory ALLOCATE(BILIST(1:BINMBR,1:4)) OPEN(LUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(I,:) END DO CLOSE(LUNIT,STATUS='DELETE') ELSE ! Precomputation of the bielectronic integrals WRITE(*,'(a)')'* Computation of the bielectronic integrals of GBF basis functions' IF (USEDISK) THEN ALLOCATE(BILIST(1:1,1:4)) OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(1,:) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO DEALLOCATE(BILIST) CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) ELSE ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR)) OPEN(LUNIT,form='UNFORMATTED') !$OMP PARALLEL DO SCHEDULE(STATIC,1) DO I=1,BINMBR READ(LUNIT)BILIST(I,:) RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO !$OMP END PARALLEL DO CLOSE(LUNIT,STATUS='DELETE') END IF END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) IF(RESUME) THEN OPEN(100,FILE='eig.txt') READ(100,*) EIG OPEN(101,FILE='eigvec.txt') CALL READMATRIX(EIGVEC,NBAST,101) CLOSE(100) CLOSE(101) END IF DO I=1,NBALG SELECT CASE (ALG(I)) CASE (1) WRITE(*,'(/,a)')' Roothaan''s algorithm' SELECT CASE (MODEL) CASE (1) CALL ROOTHAAN_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) CALL ROOTHAAN_UHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL ROOTHAAN_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (2) WRITE(*,'(/,a)')' level-shifting algorithm' SELECT CASE (MODEL) CASE (1) CALL LEVELSHIFTING_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL LEVELSHIFTING_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (3) WRITE(*,'(/,a)')' DIIS algorithm' SELECT CASE (MODEL) CASE (1) CALL DIIS_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL DIIS_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE (4) WRITE(*,'(/,a)')' Optimal damping algorithm (ODA)' SELECT CASE (MODEL) CASE (1) CALL ODA_RHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) CALL ODA_GHF(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) END SELECT CASE(6) WRITE(*,*)' Roothaan/Gradient algorithm' SELECT CASE (MODEL) CASE (1) CALL GRADIENT(EIG,EIGVEC,NBAST,POEFM,PHI,TRSHLD,MAXITR,RESUME) CASE (2) WRITE(*,*)' Not implemented yet!' CASE (3) WRITE(*,*)' Not implemented yet!' CASE (4) WRITE(*,*)' Not implemented yet!' END SELECT END SELECT END DO OPEN(100,FILE='eig.txt') WRITE(100,*) EIG OPEN(101,FILE='eigvec.txt') CALL PRINTMATRIX(EIGVEC,NBAST,101) CLOSE(100) CLOSE(101) IF (DIRECT) THEN DEALLOCATE(BILIST) ELSE IF (USEDISK) THEN OPEN(BIUNIT,form='UNFORMATTED') ; CLOSE(BIUNIT,STATUS='DELETE') ELSE DEALLOCATE(BILIST,RBIVALUES) END IF END IF DEALLOCATE(NBAS,PHI,EIG,EIGVEC,POEFM,POM,PIOM,PSROM,PISROM) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZPPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZPPTRF: the leading minor of order',INFO,'is not positive definite, & &and the factorization could not be completed' END IF WRITE(*,*)'(called from subroutine DRIVER)' STOP END SUBROUTINE DRIVER_nonrelativistic SUBROUTINE DRIVER_boson_star ! Preliminary driver for the boson star model (G. Aki, J. Dolbeault: a Hartree model with temperature for boson stars) USE case_parameters ; USE data_parameters ; USE basis_parameters ; USE scf_parameters USE basis ; USE integrals ; USE matrices ; USE matrix_tools ; USE common_functions USE metric_nonrelativistic ; USE scf_tools ; USE rootfinding_tools ; USE constants INTEGER :: NBAST,ITER,I,J,INFO INTEGER,TARGET :: RANK INTEGER,DIMENSION(:),ALLOCATABLE :: NBAS DOUBLE PRECISION :: MU,ETOT,ETOT1,SHIFT DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: POEFM,PTEFM,PFM,PDM,PDM1,PTMP,LAMBDA DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PTTEFM,PTDM,PDMDIF DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE,TARGET :: POM,PIOM,PSROM,PISROM,PCFOM,EIG DOUBLE PRECISION,DIMENSION(:,:),ALLOCATABLE :: EIGVEC TYPE(gaussianbasisfunction),DIMENSION(:),ALLOCATABLE :: PHI LOGICAL :: NUMCONV ! boucle sur la temperature INTEGER :: K ! test ! DOUBLE PRECISION :: RCOND ! INTEGER,DIMENSION(:),ALLOCATABLE :: IPIV,IWORK ! DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: PA,WORK DOUBLE PRECISION,PARAMETER :: SCALING=32.15530615624011D0 ! Computation of the discretization basis CALL FORMBASIS(PHI,NBAS) NBAST=NBAS(1) ! Computations of the tensors relative to the metric ! - computation and assembly of the overlap matrix WRITE(*,'(/,a)')'* Computation and assembly of the overlap matrix' ALLOCATE(POM(1:NBAST*(NBAST+1)/2)) CALL BUILDOM(POM,PHI,NBAST) ; PS=>POM ! tests ! ALLOCATE(PA(1:NBAST*(NBAST+1)/2),WORK(1:2*NBAST),IPIV(NBAST),IWORK(NBAST)) ! PA=POM ! CALL DSPTRF('U',NBAST,PA,IPIV,INFO) ! CALL DSPCON('U',NBAST,PA,IPIV,NORM(POM,NBAST,'1'),RCOND,WORK,IWORK,INFO) ! DEALLOCATE(PA,WORK,IPIV,IWORK) ! write(*,*)' estimate of the reciprocal cond. numb. of this matrix =',RCOND ! tests ! - computation of the inverse of the overlap matrix ALLOCATE(PIOM(1:NBAST*(NBAST+1)/2)) PIOM=INVERSE(POM,NBAST) !; PIS=>PIOM ! - computation of the square root of the overlap matrix ALLOCATE(PSROM(1:NBAST*(NBAST+1)/2)) PSROM=SQUARE_ROOT(POM,NBAST) ; PSRS=>PSROM ! - computation of the inverse of the square root of the overlap matrix ALLOCATE(PISROM(1:NBAST*(NBAST+1)/2)) PISROM=INVERSE(PSROM,NBAST) ; PISRS=>PISROM ! - computation of the Cholesky factorization of the overlap matrix ALLOCATE(PCFOM(1:NBAST*(NBAST+1)/2)) PCFOM=POM CALL DPPTRF('U',NBAST,PCFOM,INFO) !; PCFS=>PCFOM IF (INFO/=0) GO TO 5 ! Computation and assembly of the matrix of the free hamiltonian WRITE(*,'(a)')'* Computation and assembly of the hamiltonian matrix' ALLOCATE(POEFM(1:NBAST*(NBAST+1)/2)) CALL BUILDKPFM(POEFM,PHI,NBAST) ! Creation of the list of nonzero bielectronic integrals WRITE(*,'(a)')'* Creation of the list of nonzero bielectronic integrals' CALL BUILDBILIST(PHI,NBAST,BINMBR) ! Computation of the Coulomb integrals WRITE(*,'(a)')'* Computation of the bielectronic integrals' IF (USEDISK) THEN ALLOCATE(BILIST(1:1,1:4)) OPEN(LUNIT,form='UNFORMATTED') ; OPEN(BIUNIT,form='UNFORMATTED') DO I=1,BINMBR READ(LUNIT)BILIST(1,:) WRITE(BIUNIT)BILIST(1,:),COULOMBVALUE(PHI(BILIST(1,1)),PHI(BILIST(1,2)),PHI(BILIST(1,3)),PHI(BILIST(1,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO DEALLOCATE(BILIST) CLOSE(LUNIT,STATUS='DELETE') ; CLOSE(BIUNIT) ELSE ALLOCATE(BILIST(1:BINMBR,1:4),RBIVALUES(1:BINMBR)) OPEN(LUNIT,form='UNFORMATTED') !$OMP PARALLEL DO SCHEDULE(STATIC, 1) DO I=1,BINMBR READ(LUNIT)BILIST(I,:) RBIVALUES(I)=COULOMBVALUE(PHI(BILIST(I,1)),PHI(BILIST(I,2)),PHI(BILIST(I,3)),PHI(BILIST(I,4))) IF (BINMBR>=10.AND.MODULO(I,BINMBR/10)==0) WRITE(*,'(a1,i3,a6)')' ',CEILING(100.*I/BINMBR),'% done' END DO !$OMP END PARALLEL DO CLOSE(LUNIT,STATUS='DELETE') END IF ! ! SCF CYCLES ! ALLOCATE(EIG(1:NBAST),EIGVEC(1:NBAST,1:NBAST)) ALLOCATE(PDM(1:NBAST*(NBAST+1)/2),PDM1(1:NBAST*(NBAST+1)/2)) ALLOCATE(PTEFM(1:NBAST*(NBAST+1)/2),PFM(1:NBAST*(NBAST+1)/2),PTMP(1:NBAST*(NBAST+1)/2)) ALLOCATE(LAMBDA(1:NBAST)) ALLOCATE(PTTEFM(1:NBAST*(NBAST+1)/2),PTDM(1:NBAST*(NBAST+1)/2),PDMDIF(1:NBAST*(NBAST+1)/2)) ! Initialisation CALL EIGENSOLVER(POEFM,PCFOM,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 6 OPEN(33) DO I=1,NBAST write(33,*)EIG(I) END DO CLOSE(33) RANK=1 ; CALL FORMDM(PDM,EIGVEC,NBAST,1,1) ; PDM=MASS*PDM PDM1=0.D0 LAMBDA=0.D0 ; ! IF (TEMPERATURE==0) LAMBDA(1)=MASS LAMBDA(1)=MASS ETOT1=0.D0 CALL BUILDCOULOMB(PTEFM,NBAST,PHI,PDM) PTEFM=KAPPA*MASS*PTEFM/(4.D0*PI) DO K=0,1000 ! TEMPERATURE LOOP TEMPERATURE=DBLE(K)*0.0001 ITER=0 ! ROOTHAAN'S ALGORITHM LOOP 1 CONTINUE ITER=ITER+1 WRITE(*,*)' ' WRITE(*,*)'# ITER =',ITER ! Assembly and diagonalization of the Fock matrix associated to the density matrix PFM=POEFM+PTEFM CALL EIGENSOLVER(PFM,PCFOM,NBAST,EIG,EIGVEC,INFO) IF (INFO/=0) GO TO 6 IF (TEMPERATURE>0.D0) THEN ! Computation (using the bisection method) of the lagrangian multiplier $\mu$ associated to the constraint on the trace of the density matrix MU_I=>EIG ; RANK_P=>RANK MU=RTBIS(FUNCFORMU,EIG(1),EIG(NBAST),1.D-16) WRITE(*,*)'mu=',MU WRITE(*,*)'Residual f(mu)=',FUNCFORMU(MU) ! Computation of the updated occupation numbers DO I=1,NBAST IF (MU-EIG(I)>0.D0) THEN LAMBDA(I)=RECIP_DENTFUNC((MU-EIG(I))/TEMPERATURE) RANK=I ELSE LAMBDA(I)=0.D0 END IF ! WRITE(*,*)'lambda_',I,'=',LAMBDA(I) END DO write(*,*)'Rank(gamma)=',RANK,', sumlambda_i=',SUM(LAMBDA) END IF ! Assembly of the density matrix diff --git a/src/integrals_f.f90 b/src/integrals_f.f90 index 9c57dfa..c5486c7 100644 --- a/src/integrals_f.f90 +++ b/src/integrals_f.f90 @@ -1,564 +1,560 @@ MODULE integrals ! Note: all the integrals involving gaussian basis functions are computed by the A.S.P.I.C. code (written in C++ by F. Lodier, see http://www.ann.jussieu.fr/A.S.P.I.C/). ! number of a priori nonzero bielectronic integrals INTEGER :: BINMBR ! arrays for the list, values (real/complex for GBF/2-spinor basis functions in the non-relativistic/relativistic case) and "class" (relativistic case only) of bielectronic integrals (when stored in memory) INTEGER,DIMENSION(:,:),ALLOCATABLE :: BILIST DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: RBIVALUES DOUBLE COMPLEX,DIMENSION(:),ALLOCATABLE :: CBIVALUES CHARACTER(2),DIMENSION(:),ALLOCATABLE :: BITYPE ! arrays for the values of precomputed GBF bielectronic integrals used to compute more efficiently (thanks to the use of symmetries) the 2-spinor bielectronic integrals in the relativistic case DOUBLE PRECISION,DIMENSION(:),ALLOCATABLE :: LLIJKL,LLIKJL,LLILJK,SLIJKL,SSIJKL,SSIKJL,SSILJK INTEGER,DIMENSION(2) :: NBF ! unit number for the list of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: LUNIT=10 ! unit number for both the list and values of nonzero bielectronic integrals (when stored on disk) INTEGER,PARAMETER :: BIUNIT=11 INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrolloverlap(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrolloverlap") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollkinetic(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b) & & BIND(C,NAME="unrollkinetic") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension) & & BIND(C,NAME="unrollderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollpotential(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & center) & & BIND(C,NAME="unrollpotential") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollxderiv(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & dimension1,dimension2) & & BIND(C,NAME="unrollxderiv") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b INTEGER(KIND=C_INT),VALUE :: dimension1,dimension2 END FUNCTION END INTERFACE INTERFACE REAL(KIND=C_DOUBLE) FUNCTION unrollcoulomb(nbrofprimitives_a,center_a,exponents_a,coefficients_a,monomialdegree_a, & & nbrofprimitives_b,center_b,exponents_b,coefficients_b,monomialdegree_b, & & nbrofprimitives_c,center_c,exponents_c,coefficients_c,monomialdegree_c, & & nbrofprimitives_d,center_d,exponents_d,coefficients_d,monomialdegree_d) & & BIND(C,NAME="unrollcoulomb") USE iso_c_binding INTEGER(KIND=C_INT),VALUE :: nbrofprimitives_a,nbrofprimitives_b,nbrofprimitives_c,nbrofprimitives_d REAL(KIND=C_DOUBLE),DIMENSION(3) :: center_a,center_b,center_c,center_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents_a,exponents_b,exponents_c,exponents_d REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients_a,coefficients_b,coefficients_c,coefficients_d INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree_a,monomialdegree_b,monomialdegree_c,monomialdegree_d END FUNCTION END INTERFACE INTERFACE COULOMBVALUE MODULE PROCEDURE COULOMBVALUE_relativistic,COULOMBVALUE_nonrelativistic,COULOMBVALUE_precomputed END INTERFACE INTERFACE BUILDBILIST MODULE PROCEDURE BUILDBILIST_relativistic,BUILDBILIST_nonrelativistic END INTERFACE CONTAINS FUNCTION OVERLAPVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrolloverlap(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION OVERLAPVALUE FUNCTION KINETICVALUE(PHI_A,PHI_B) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the scalar product between the gradients of two gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollkinetic(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree) END FUNCTION KINETICVALUE FUNCTION DERIVVALUE(PHI_A,PHI_B,DIMENSION) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to a space variable) of a gaussain basis function with another gaussian basis function (this kind of integrals appear in the variational formulation involving the Dirac operator). ! Note: if DIMENSION = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION-1) END FUNCTION DERIVVALUE FUNCTION POTENTIALVALUE(PHI_A,PHI_B,CENTER) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of two gaussian basis functions times a coulombic potential centered on a given point. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B REAL(KIND=C_DOUBLE),DIMENSION(3),INTENT(IN) :: CENTER REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollpotential(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & CENTER) END FUNCTION POTENTIALVALUE FUNCTION XDERIVVALUE(PHI_A,PHI_B,DIMENSION1,DIMENSION2) RESULT (VALUE) ! Function that computes the value of the integral over R^3 of the product of the partial derivative (with respect to the space variable x, y or z) of a gaussian basis function with another gaussian basis function, times x, y or z (this kind of integral appears in variational formulations involving the J operator). ! Notes: - if DIMENSION1 = 1 (respectively 2, 3) then partial derivative with respect to x (respectively y, z). ! - if DIMENSION2 = 1 (respectively 2, 3) then the product is multiplied by x (respectively y, z). USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B INTEGER(KIND=C_INT),INTENT(IN) :: DIMENSION1,DIMENSION2 REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollxderiv(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & DIMENSION1-1,DIMENSION2-1) END FUNCTION XDERIVVALUE FUNCTION COULOMBVALUE_nonrelativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four gaussian basis functions. USE iso_c_binding ; USE basis_parameters TYPE(gaussianbasisfunction),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D REAL(KIND=C_DOUBLE) :: VALUE VALUE=unrollcoulomb(PHI_A%nbrofexponents,PHI_A%center,PHI_A%exponents,PHI_A%coefficients,PHI_A%monomialdegree, & & PHI_B%nbrofexponents,PHI_B%center,PHI_B%exponents,PHI_B%coefficients,PHI_B%monomialdegree, & & PHI_C%nbrofexponents,PHI_C%center,PHI_C%exponents,PHI_C%coefficients,PHI_C%monomialdegree, & & PHI_D%nbrofexponents,PHI_D%center,PHI_D%exponents,PHI_D%coefficients,PHI_D%monomialdegree) END FUNCTION COULOMBVALUE_nonrelativistic SUBROUTINE BUILDBILIST_nonrelativistic(PHI,NBAST,LISTSIZE) ! Subroutine that generates the list (without redundancy as symmetries are taken into account) of the bielectronic integrals with nonzero value. ! Reference: R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974. USE case_parameters ; USE basis_parameters TYPE(gaussianbasisfunction),DIMENSION(:),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NBAST INTEGER,INTENT(OUT) :: LISTSIZE INTEGER :: I,J,K,L INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE LOGICAL :: SC,SS ! same spin check. Not used outside GHF - SS = .TRUE. + SS=.TRUE. OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list LISTSIZE=0 DO I=1,NBAST ; DO J=1,I ; DO K=1,J ; DO L=1,K ! same center? SC=((PHI(I)%center_id==PHI(J)%center_id).AND.(PHI(J)%center_id==PHI(K)%center_id).AND.(PHI(K)%center_id==PHI(L)%center_id)) GLOBALMONOMIALDEGREE=PHI(I)%monomialdegree+PHI(J)%monomialdegree+PHI(K)%monomialdegree+PHI(L)%monomialdegree ! same spin? i must have same spin as j, same for k and l IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (J <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (J > NBAST/2))).AND.& &(((K <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((K > NBAST/2) .AND. (L > NBAST/2))) ! parity check on the product of the monomials if the four functions share the same center IF (((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,J,K,L IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (K > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (L > NBAST/2))) IF ((K<J).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,K,J,L END IF IF(MODEL == 4) SS = (((I <= NBAST/2) .AND. (L <= NBAST/2)) .OR. ((I > NBAST/2) .AND. (L > NBAST/2))).AND.& &(((J <= NBAST/2) .AND. (K <= NBAST/2)) .OR. ((J > NBAST/2) .AND. (K > NBAST/2))) IF ((J<I).AND.(L<K).AND.SS) THEN LISTSIZE=LISTSIZE+1 ; WRITE(LUNIT)I,L,J,K END IF END IF END DO ; END DO ; END DO ; END DO CLOSE(LUNIT) WRITE(*,*)' Number of GBF bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_nonrelativistic FUNCTION COULOMBVALUE_relativistic(PHI_A,PHI_B,PHI_C,PHI_D) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *COULOMBVALUE(PHI_A%contractions(I,IA),PHI_B%contractions(I,IB),PHI_C%contractions(J,JC), & & PHI_D%contractions(J,JD)) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_relativistic FUNCTION COULOMBVALUE_precomputed(PHI_A,PHI_B,PHI_C,PHI_D,CLASS) RESULT (VALUE) ! Function that computes the value of the bielectronic integral between four 2-spinor basis functions from lists containing the precomputed values of the bielectronic integrals between scalar gaussian basis functions. USE basis_parameters TYPE(twospinor),INTENT(IN) :: PHI_A,PHI_B,PHI_C,PHI_D CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: I,IA,IB,J,JC,JD VALUE=(0.D0,0.D0) DO I=1,2 DO IA=1,PHI_A%nbrofcontractions(I) ; DO IB=1,PHI_B%nbrofcontractions(I) DO J=1,2 DO JC=1,PHI_C%nbrofcontractions(J) ; DO JD=1,PHI_D%nbrofcontractions(J) VALUE=VALUE+PHI_A%coefficients(I,IA)*CONJG(PHI_B%coefficients(I,IB)) & & *PHI_C%coefficients(J,JC)*CONJG(PHI_D%coefficients(J,JD)) & & *PRECOMPUTEDCOULOMBVALUE(PHI_A%contidx(I,IA),PHI_B%contidx(I,IB),PHI_C%contidx(J,JC), & & PHI_D%contidx(J,JD),CLASS) END DO ; END DO END DO END DO ; END DO END DO END FUNCTION COULOMBVALUE_precomputed SUBROUTINE BUILDBILIST_relativistic(PHI,NBAS,LISTSIZE,SUBSIZE) ! Subroutine that generates the list (more or less without redundancy since the a priori symmetries for complex 2-spinor functions are taken into account) of the bielectronic integrals with nonzero value. USE case_parameters ; USE basis_parameters ; USE scf_parameters TYPE(twospinor),DIMENSION(:),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER,INTENT(OUT) :: LISTSIZE,SUBSIZE(3) INTEGER :: I,J,K,L,I1,I2,I3,I4,I5,I6 INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE LOGICAL :: SC OPEN(LUNIT,form='UNFORMATTED') ! determination of the number of elements (i.e., integer quadruples) that compose the list SUBSIZE=0 ! LLLL-type integrals DO I=1,NBAS(1) ; DO J=1,NBAS(1) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) IF (L+K*NBAS(1)<=J+I*NBAS(1)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) - GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree & - & +PHI(J)%contractions(I1,I3)%monomialdegree & - & +PHI(K)%contractions(I4,I5)%monomialdegree & - & +PHI(L)%contractions(I4,I6)%monomialdegree + GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & + & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN SUBSIZE(1)=SUBSIZE(1)+1 WRITE(LUNIT)I,J,K,L,'LL' GO TO 1 END IF END DO END DO END DO END DO END DO END DO 1 CONTINUE END IF END DO ; END DO ; END DO ; END DO -! SSLL-type integrals - IF(SLINTEGRALS) THEN - DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) - DO I1=1,2 - DO I2=1,PHI(I)%nbrofcontractions(I1) - DO I3=1,PHI(J)%nbrofcontractions(I1) - DO I4=1,2 - DO I5=1,PHI(K)%nbrofcontractions(I4) - DO I6=1,PHI(L)%nbrofcontractions(I4) - SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & - & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & - & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) - GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & - & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree - IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN - WRITE(LUNIT)I,J,K,L,'SL' - SUBSIZE(2)=SUBSIZE(2)+1 - GO TO 2 - END IF + IF (SLINTEGRALS) THEN +! LLSS-type integrals + DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=1,NBAS(1) ; DO L=1,NBAS(1) + DO I1=1,2 + DO I2=1,PHI(I)%nbrofcontractions(I1) + DO I3=1,PHI(J)%nbrofcontractions(I1) + DO I4=1,2 + DO I5=1,PHI(K)%nbrofcontractions(I4) + DO I6=1,PHI(L)%nbrofcontractions(I4) + SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & + & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & + & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) + GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & + & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree + IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN + WRITE(LUNIT)I,J,K,L,'SL' + SUBSIZE(2)=SUBSIZE(2)+1 + GO TO 2 + END IF + END DO END DO END DO END DO END DO END DO - END DO -2 CONTINUE - END DO; END DO ; END DO ; END DO +2 CONTINUE + END DO; END DO ; END DO ; END DO END IF IF (SSINTEGRALS) THEN ! SSSS-type integrals DO I=NBAS(1)+1,SUM(NBAS) ; DO J=NBAS(1)+1,SUM(NBAS) ; DO K=NBAS(1)+1,SUM(NBAS) ; DO L=NBAS(1)+1,SUM(NBAS) IF (L+K*NBAS(2)<=J+I*NBAS(2)) THEN DO I1=1,2 DO I2=1,PHI(I)%nbrofcontractions(I1) DO I3=1,PHI(J)%nbrofcontractions(I1) DO I4=1,2 DO I5=1,PHI(K)%nbrofcontractions(I4) DO I6=1,PHI(L)%nbrofcontractions(I4) SC=((PHI(I)%contractions(I1,I2)%center_id==PHI(J)%contractions(I1,I3)%center_id) & & .AND.(PHI(J)%contractions(I1,I3)%center_id==PHI(K)%contractions(I4,I5)%center_id) & & .AND.(PHI(K)%contractions(I4,I5)%center_id==PHI(L)%contractions(I4,I6)%center_id)) - GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree & - & +PHI(J)%contractions(I1,I3)%monomialdegree & - & +PHI(K)%contractions(I4,I5)%monomialdegree & - & +PHI(L)%contractions(I4,I6)%monomialdegree + GLOBALMONOMIALDEGREE= PHI(I)%contractions(I1,I2)%monomialdegree+PHI(J)%contractions(I1,I3)%monomialdegree & + & +PHI(K)%contractions(I4,I5)%monomialdegree+PHI(L)%contractions(I4,I6)%monomialdegree IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN WRITE(LUNIT)I,J,K,L,'SS' SUBSIZE(3)=SUBSIZE(3)+1 GO TO 3 END IF END DO END DO END DO END DO END DO END DO 3 CONTINUE END IF END DO ; END DO ; END DO ; END DO END IF LISTSIZE=SUM(SUBSIZE) CLOSE(LUNIT) WRITE(*,*)' Number of 2-spinor-type orbital bielectronic integrals to be computed =',LISTSIZE END SUBROUTINE BUILDBILIST_relativistic SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES(GBF,NGBF) ! Routine that computes the values of the bielectronic integrals over a cartesian gaussian basis, taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). These values are next used to compute more efficiently the bielectronic integrals over a cartesian 2-spinor-type orbital basis in the relativistic case (see the GETPRECOMPUTEDCOULOMBVALUE function). USE basis_parameters ; USE scf_parameters INTEGER,DIMENSION(2),INTENT(IN) :: NGBF TYPE(gaussianbasisfunction),DIMENSION(SUM(NGBF)),INTENT(IN) :: GBF INTEGER :: I,J,K,L,M,N,O INTEGER,DIMENSION(3) :: GLOBALMONOMIALDEGREE LOGICAL :: SC NBF=NGBF -! (LL|LL) integrals +! computations for LLLL-type integrals WRITE(*,*)'- Computing LL integrals' ALLOCATE(LLIJKL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+5*NGBF(1)+6)/24), & & LLIKJL(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2+NGBF(1)-2)/24), & & LLILJK(1:NGBF(1)*(NGBF(1)+1)*(NGBF(1)**2-3*NGBF(1)+2)/24)) M=0 ; N=0 ; O=0 DO I=1,NGBF(1) ; DO J=1,I ; DO K=1,J ; DO L=1,K SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id)) GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree ! parity check (one center case) IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN M=M+1 ; LLIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; LLIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; LLIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; LLIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; LLILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO - IF(SLINTEGRALS) THEN - ! (SS|LL) integrals + IF (SLINTEGRALS) THEN +! computations for SSLL-type integrals WRITE(*,*)'- Computing SL integrals' ALLOCATE(SLIJKL(1:NGBF(1)*(NGBF(1)+1)*NGBF(2)*(NGBF(2)+1)/4)) N=0 ! Here the first integrals are faster to compute than the last ones: therefore, schedule with CHUNK=1 to distribute work evenly. !$OMP PARALLEL DO PRIVATE(N,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the value of N needs to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). N=NGBF(1)*(NGBF(1)+1)/2*(I-NGBF(1)-1)*(I-NGBF(1))/2 ! this takes N(N+1)/2*(I-N) iters DO J=NGBF(1)+1,I ; DO K=1,NGBF(1) ; DO L=1,K SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.& &(GBF(K)%center_id==GBF(L)%center_id)) GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree ! parity check (one center case) IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN N=N+1 ; SLIJKL(N)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) ELSE N=N+1 ; SLIJKL(N)=(0.D0,0.D0) END IF END DO; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF IF (SSINTEGRALS) THEN -! (SS|SS) integrals +! computations for SSSS-type integrals WRITE(*,*)'- Computing SS integrals' ALLOCATE(SSIJKL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+5*NGBF(2)+6)/24), & & SSIKJL(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2+NGBF(2)-2)/24), & & SSILJK(1:NGBF(2)*(NGBF(2)+1)*(NGBF(2)**2-3*NGBF(2)+2)/24)) M=0 ; N=0 ; O=0 !$OMP PARALLEL DO PRIVATE(I,M,N,O,J,K,L,SC,GLOBALMONOMIALDEGREE) SCHEDULE(STATIC,1) DO I=NGBF(1)+1,SUM(NGBF) ! Note: the values of M, N and O need to be reinitialized when the loop is parallel (this does nothing if the loop is sequential). M=(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)*(I-NGBF(1)+2)/24 N=(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))*(I-NGBF(1)+1)/24 O=(I-NGBF(1)-3)*(I-NGBF(1)-2)*(I-NGBF(1)-1)*(I-NGBF(1))/24 DO J=NGBF(1)+1,I ; DO K=NGBF(1)+1,J ; DO L=NGBF(1)+1,K SC=((GBF(I)%center_id==GBF(J)%center_id).AND.(GBF(J)%center_id==GBF(K)%center_id).AND.(GBF(K)%center_id==GBF(L)%center_id)) GLOBALMONOMIALDEGREE=GBF(I)%monomialdegree+GBF(J)%monomialdegree+GBF(K)%monomialdegree+GBF(L)%monomialdegree ! parity check (one center case) IF ((SC.AND.ALL(MOD(GLOBALMONOMIALDEGREE,2)==0)).OR.(.NOT.SC)) THEN M=M+1 ; SSIJKL(M)=COULOMBVALUE(GBF(I),GBF(J),GBF(K),GBF(L)) IF (K<J) THEN N=N+1 ; SSIKJL(N)=COULOMBVALUE(GBF(I),GBF(K),GBF(J),GBF(L)) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=COULOMBVALUE(GBF(I),GBF(L),GBF(J),GBF(K)) END IF ELSE M=M+1 ; SSIJKL(M)=(0.D0,0.D0) IF (K<J) THEN N=N+1 ; SSIKJL(N)=(0.D0,0.D0) END IF IF ((J<I).AND.(L<K)) THEN O=O+1 ; SSILJK(O)=(0.D0,0.D0) END IF END IF END DO ; END DO ; END DO ; END DO !$OMP END PARALLEL DO END IF END SUBROUTINE PRECOMPUTEGBFCOULOMBVALUES FUNCTION PRECOMPUTEDCOULOMBVALUE(I,J,K,L,CLASS) RESULT(VALUE) ! Functions that returns the value of a precomputed bielectronic integral of class LL, SL or SS between four (real) cartesian gaussian basis functions stored in a list taking into account the eightfold permutational symmetry of the integrals (see R. Ahlrichs, Methods for efficient evaluation of integrals for gaussian type basis sets, Theoret. Chim. Acta, 33, 157-167, 1974). ! note: this function is called for the computation of bielectronic integrals over a (complex) 2-spinor, cartesian gaussian-type orbital basis, which does not naturally possess as many symmetries as a real scalar gaussian basis. USE basis_parameters INTEGER,INTENT(IN) :: I,J,K,L CHARACTER(2),INTENT(IN) :: CLASS DOUBLE COMPLEX :: VALUE INTEGER :: IDX INTEGER,DIMENSION(4) :: N,TMP ! Preliminaries N=(/I,J,K,L/) TMP=N ; IF (N(1)<N(2)) N(1:2)=(/TMP(2),TMP(1)/) TMP=N ; IF (N(3)<N(4)) N(3:4)=(/TMP(4),TMP(3)/) TMP=N ; IF (N(1)<N(3)) N=(/TMP(3),TMP(4),TMP(1),TMP(2)/) IF (CLASS.EQ.'LL') THEN ! integral (LL|LL) between four "upper 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=LLIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=LLIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=LLILJK(IDX) END IF ELSE IF (CLASS=='SL') THEN ! integral (SS|LL) between two "lower 2-spinor" and two "upper 2-spinor" scalar gaussian basis functions N(1:2)=N(1:2)-(/NBF(1),NBF(1)/) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+N(1)*(N(1)-1)/2-1)*NBF(1)*(NBF(1)+1)/2 VALUE=SLIJKL(IDX) ELSE IF (CLASS=='SS') THEN N=N-(/NBF(1),NBF(1),NBF(1),NBF(1)/) ! integral (SS|SS) between four "lower 2-spinor" scalar gaussian basis functions IF (N(3)<=N(2)) THEN ! integral of type (IJ|KL) IDX=N(4)+N(3)*(N(3)-1)/2+(N(2)+1)*N(2)*(N(2)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF ((N(1)==N(3)).AND.(N(1)==N(4))) THEN ! integral of type (IJ|KL) IDX=N(2)+N(1)*(N(1)-1)/2+(N(1)+1)*N(1)*(N(1)-1)/6+(N(1)-1)*N(1)*(N(1)+1)*(N(1)+2)/24 VALUE=SSIJKL(IDX) ELSE IF (N(4)<=N(2)) THEN ! integral of type (IK|JL) IDX=N(4)+N(2)*(N(2)-1)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE IF (N(1)==N(3)) THEN ! integral of type (IK|JL) IDX=N(2)+N(4)*(N(4)-1)/2+N(1)*(N(1)-1)*(N(1)-2)/6+N(1)*(N(1)-1)*(N(1)*(N(1)-1)-2)/24 VALUE=SSIKJL(IDX) ELSE ! integral of type (IL|JK) IDX=N(2)+(N(4)-1)*(N(4)-2)/2+N(3)*(N(3)-1)*(N(3)-2)/6+N(1)*(N(1)-1)*((N(1)-1)*(N(1)-4)+2)/24 VALUE=SSILJK(IDX) END IF END IF END FUNCTION PRECOMPUTEDCOULOMBVALUE SUBROUTINE DEALLOCATE_INTEGRALS USE scf_parameters ! Routine that deallocate the arrays containing the values of the bielectronic integrals over a cartesian gaussian basis. DEALLOCATE(LLIJKL,LLIKJL,LLILJK) IF (SSINTEGRALS) DEALLOCATE(SSIJKL,SSIKJL,SSILJK) IF (SLINTEGRALS) DEALLOCATE(SLIJKL) END SUBROUTINE DEALLOCATE_INTEGRALS END MODULE diff --git a/src/setup.f90 b/src/setup.f90 index eb564d6..5019596 100644 --- a/src/setup.f90 +++ b/src/setup.f90 @@ -1,774 +1,789 @@ MODULE case_parameters ! relativistic or non-relativistic case flag LOGICAL :: RELATIVISTIC -! speed of light. Might be defined by the user via a scale factor +! apparent speed of light (can be defined by the user via a scaling factor) DOUBLE PRECISION :: C ! approximation index (1 is Hartree, 2 is Hartree-Fock) INTEGER :: APPROXIMATION ! model/formalism index (see below) INTEGER :: MODEL CONTAINS SUBROUTINE SETUP_CASE - USE setup_tools -! speed of light in the vacuum in atomic units (for the relativistic case) -! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006. - DOUBLE PRECISION,PARAMETER :: SPEED_OF_LIGHT=137.035999967994D0 - DOUBLE PRECISION :: SCALING_FACTOR=1.D0 + USE constants ; USE setup_tools + DOUBLE PRECISION :: SCALING_FACTOR CHARACTER(2) :: CHAR INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## CASE',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The computational case is not given.' READ(100,'(a2)') CHAR IF (CHAR=='RE') THEN RELATIVISTIC=.TRUE. WRITE(*,'(a)')' Relativistic case' - CALL LOOKFOR(100,'## SPEED OF LIGHT SCALE FACTOR',INFO) + REWIND(100) + CALL LOOKFOR(100,'## SPEED OF LIGHT SCALING FACTOR',INFO) IF (INFO==0) THEN READ(100,*) SCALING_FACTOR + ELSE + SCALING_FACTOR=1.D0 END IF - C = SCALING_FACTOR*SPEED_OF_LIGHT - WRITE(*,'(a,f16.8)')' Speed of light c = ',C + C=SCALING_FACTOR*SPEED_OF_LIGHT + WRITE(*,'(a,f20.12)')' Speed of light c = ',C ELSE IF (CHAR=='NO') THEN RELATIVISTIC=.FALSE. WRITE(*,'(a)')' Non-relativistic case' ELSE WRITE(*,*)'Subroutine SETUP_CASE: error!' STOP END IF CLOSE(100) END SUBROUTINE SETUP_CASE SUBROUTINE SETUP_APPROXIMATION USE setup_tools CHARACTER(12) :: CHAR INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## APPROXIMATION',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The approximation type is not given.' READ(100,'(a12)') CHAR IF (LEN_TRIM(CHAR)==7) THEN APPROXIMATION=1 WRITE(*,'(a)')' Hartree approximation (Hartree product wave function)' IF (RELATIVISTIC) STOP' This option is incompatible with the previous one (for the time being)' ELSE IF (LEN_TRIM(CHAR)>7) THEN APPROXIMATION=2 WRITE(*,'(a)')' Hartree-Fock approximation (Slater determinant wave function)' ELSE WRITE(*,*)'Subroutine SETUP_APPROXIMATION: error!' STOP END IF CLOSE(100) END SUBROUTINE SETUP_APPROXIMATION SUBROUTINE SETUP_FORMALISM USE setup_tools CHARACTER(3) :: CHAR INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## MODEL',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The formalism is not given.' READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (APPROXIMATION==2) THEN IF (CHAR=='CSD') THEN MODEL=1 WRITE(*,'(a)')' Closed-shell formalism' ELSE IF (CHAR=='OSD') THEN MODEL=2 WRITE(*,'(a)')' Average-of-configuration open-shell formalism' ELSE IF (CHAR=='CGH') THEN MODEL=3 - WRITE(*,'(a)')' Complex general hartree-fock' + WRITE(*,'(a)')' Complex General Hartree-Fock' ELSE GO TO 1 END IF END IF ELSE IF (APPROXIMATION==1) THEN IF (CHAR=='BOS') THEN ! MODEL=1 WRITE(*,'(a)')' Boson star model (preliminary)' ELSE GO TO 1 END IF ELSE IF (APPROXIMATION==2) THEN IF (CHAR=='RHF') THEN -! Restricted (closed-shell) Hartree-Fock (RHF) formalism (doubly occupied orbitals) +! Restricted Hartree-Fock (RHF) formalism (doubly occupied orbitals) MODEL=1 - WRITE(*,'(a)')' Restricted (closed-shell) Hartree-Fock (RHF) formalism' + WRITE(*,'(a)')' (Real) Restricted Hartree-Fock (RHF) formalism' ELSE IF (CHAR=='UHF') THEN -! Unrestricted (open-shell) Hartree-Fock (UHF) formalism (different orbitals for different spins (DODS method)) +! Unrestricted Hartree-Fock (UHF) formalism (different orbitals for different spins (DODS method)) ! Reference: J. A. Pople and R. K. Nesbet, Self-consistent orbitals for radicals, J. Chem. Phys., 22(3), 571-572, 1954. MODEL=2 - WRITE(*,'(a)')' Unrestricted (open-shell) Hartree-Fock (UHF) formalism' + WRITE(*,'(a)')' (Real) Unrestricted (open-shell) Hartree-Fock (UHF) formalism' ELSE IF (CHAR=='ROH') THEN ! Restricted Open-shell Hartree-Fock (ROHF) formalism ! Reference: C. C. J. Roothaan, Self-consistent field theory for open shells of electronic systems, Rev. Modern Phys., 32(2), 179-185, 1960. MODEL=3 WRITE(*,'(a)')' Restricted Open-shell Hartree-Fock (ROHF) formalism' WRITE(*,*)'Option not implemented yet!' STOP ELSE IF (CHAR=='GHF') THEN - ! General Hartree-Fock (ROHF) formalism + ! General Hartree-Fock (GHF) formalism MODEL=4 - WRITE(*,'(a)')' General Hartree-Fock formalism' + WRITE(*,'(a)')' (Real) General Hartree-Fock formalism' ELSE GO TO 1 END IF END IF END IF CLOSE(100) RETURN 1 WRITE(*,*)'Subroutine SETUP_FORMALISM: no known formalism given!' STOP END SUBROUTINE SETUP_FORMALISM END MODULE MODULE data_parameters USE iso_c_binding ! ** DATA FOR ATOMIC OR MOLECULAR SYSTEMS ** ! number of nuclei in the molecular system (at most 10) INTEGER :: NBN ! atomic numbers of the nuclei INTEGER,DIMENSION(10) :: Z ! positions of the nucleii DOUBLE PRECISION,DIMENSION(3,10) :: CENTER ! total number of electrons in the molecular system INTEGER :: NBE ! total number of electrons in the closed shells (open-shell DHF formalism) INTEGER :: NBECS ! number of open shell electrons and number of open shell orbitals (open-shell DHF formalism) INTEGER :: NBEOS,NBOOS ! respective numbers of electrons of $\alpha$ and $\beta$ spin (UHF and ROHF formalisms) INTEGER :: NBEA,NBEB ! internuclear repulsion energy DOUBLE PRECISION :: INTERNUCLEAR_ENERGY ! ** DATA FOR BOSON STAR MODEL ** DOUBLE PRECISION,PARAMETER :: KAPPA=-1.D0 ! mass DOUBLE PRECISION :: MASS ! temperature DOUBLE PRECISION :: TEMPERATURE ! exponent for the function defining the Tsallis-related entropy term DOUBLE PRECISION :: MB ! INTEGER,POINTER :: RANK_P DOUBLE PRECISION,POINTER,DIMENSION(:) :: MU_I CONTAINS SUBROUTINE SETUP_DATA USE case_parameters ; USE setup_tools IMPLICIT NONE CHARACTER(30) :: NAME INTEGER :: INFO,N OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') IF (.NOT.RELATIVISTIC.AND.APPROXIMATION==1) THEN CALL LOOKFOR(100,'## DESCRIPTION OF THE BOSON STAR',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The description of the boson star is not given.' WRITE(*,'(a)')' --- **** ---' READ(100,*) NAME READ(100,*) MASS WRITE(*,'(a,f5.3)')' * Mass = ',MASS READ(100,*) TEMPERATURE WRITE(*,'(a,f5.3)')' * Temperature = ',TEMPERATURE READ(100,*) MB WRITE(*,'(a,f5.3)')' * Exponent for the function defining the Tsallis-related entropy term = ',MB WRITE(*,'(a)')' --- **** ---' ELSE CALL LOOKFOR(100,'## DESCRIPTION OF THE MOLECULAR SYSTEM',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The description of the molecular system is not given.' WRITE(*,'(a)')' --- Molecular system ---' READ(100,'(3/,a)')NAME WRITE(*,'(a,a)')' ** NAME: ',NAME READ(100,'(i2)') NBN DO N=1,NBN WRITE(*,'(a,i2)')' * Nucleus #',N READ(100,*) Z(N),CENTER(:,N) WRITE(*,'(a,i3,a,a,a)')' Charge Z=',Z(N),' (element: ',IDENTIFYZ(Z(N)),')' WRITE(*,'(a,3(f16.8))')' Center position = ',CENTER(:,N) END DO CALL INTERNUCLEAR_REPULSION_ENERGY WRITE(*,'(a,f16.8)')' * Internuclear repulsion energy of the system = ',INTERNUCLEAR_ENERGY READ(100,'(i3)') NBE WRITE(*,'(a,i3)')' * Total number of electrons in the system = ',NBE IF (RELATIVISTIC) THEN IF (MODEL==2) THEN READ(100,'(3(i3))')NBECS,NBEOS,NBOOS - WRITE(*,'(a,i3)')' - number of closed shell electrons = ',NBECS - WRITE(*,'(a,i3)')' - number of open shell electrons = ',NBEOS - WRITE(*,'(a,i3)')' - number of open shell orbitals = ',NBOOS + WRITE(*,'(a,i3)')' - number of closed-shell electrons = ',NBECS + WRITE(*,'(a,i3)')' - number of open-shell electrons = ',NBEOS + WRITE(*,'(a,i3)')' - number of open-shell orbitals = ',NBOOS IF (NBE/=NBECS+NBEOS) STOP' Problem with the total number of electrons' - IF (NBOOS<=NBEOS) STOP' Problem with the number of open shell orbitals!' + IF (NBOOS<=NBEOS) STOP' Problem with the number of open-shell orbitals!' END IF ELSE IF (MODEL==1) THEN IF (MODULO(NBE,2)/=0) STOP' Problem: the number of electrons must be even!' ELSE IF (MODEL==2) THEN READ(100,'(2(i3))')NBEA,NBEB WRITE(*,'(a,i3)')' - number of electrons of $\alpha$ spin = ',NBEA WRITE(*,'(a,i3)')' - number of electrons of $\beta$ spin = ',NBEB IF (NBE/=NBEA+NBEB) STOP' Problem with the total number of electrons!' ! ELSE IF (MODEL==3) THEN END IF END IF WRITE(*,'(a)')' --------- **** ---------' END IF CLOSE(100) END SUBROUTINE SETUP_DATA FUNCTION IDENTIFYZ(Z) RESULT (SYMBOL) ! Function returning the symbol of a chemical element given its atomic number Z. INTEGER,INTENT(IN) :: Z CHARACTER(2) :: SYMBOL IF (Z>104) THEN WRITE(*,*)'Function IDENTIFYZ: unknown chemical element!' STOP END IF ! List of symbols from Hydrogen up to Rutherfordium. SELECT CASE (Z) CASE (1) ; SYMBOL='H' CASE (2) ; SYMBOL='He' CASE (3) ; SYMBOL='Li' CASE (4) ; SYMBOL='Be' CASE (5) ; SYMBOL='B' CASE (6) ; SYMBOL='C' CASE (7) ; SYMBOL='N' CASE (8) ; SYMBOL='O' CASE (9) ; SYMBOL='F' CASE (10) ; SYMBOL='Ne' CASE (11) ; SYMBOL='Na' CASE (12) ; SYMBOL='Mg' CASE (13) ; SYMBOL='Al' CASE (14) ; SYMBOL='Si' CASE (15) ; SYMBOL='P' CASE (16) ; SYMBOL='S' CASE (17) ; SYMBOL='Cl' CASE (18) ; SYMBOL='Ar' CASE (19) ; SYMBOL='K' CASE (20) ; SYMBOL='Ca' CASE (21) ; SYMBOL='Sc' CASE (22) ; SYMBOL='Ti' CASE (23) ; SYMBOL='V' CASE (24) ; SYMBOL='Cr' CASE (25) ; SYMBOL='Mn' CASE (26) ; SYMBOL='Fe' CASE (27) ; SYMBOL='Co' CASE (28) ; SYMBOL='Ni' CASE (29) ; SYMBOL='Cu' CASE (30) ; SYMBOL='Zn' CASE (31) ; SYMBOL='Ga' CASE (32) ; SYMBOL='Ge' CASE (33) ; SYMBOL='As' CASE (34) ; SYMBOL='Se' CASE (35) ; SYMBOL='Br' CASE (36) ; SYMBOL='Kr' CASE (37) ; SYMBOL='Rb' CASE (38) ; SYMBOL='Sr' CASE (39) ; SYMBOL='Y' CASE (40) ; SYMBOL='Zr' CASE (41) ; SYMBOL='Nb' CASE (42) ; SYMBOL='Mo' CASE (43) ; SYMBOL='Tc' CASE (44) ; SYMBOL='Ru' CASE (45) ; SYMBOL='Rh' CASE (46) ; SYMBOL='Pd' CASE (47) ; SYMBOL='Ag' CASE (48) ; SYMBOL='Cd' CASE (49) ; SYMBOL='In' CASE (50) ; SYMBOL='Sn' CASE (51) ; SYMBOL='Sb' CASE (52) ; SYMBOL='Te' CASE (53) ; SYMBOL='I' CASE (54) ; SYMBOL='Xe' CASE (55) ; SYMBOL='Cs' CASE (56) ; SYMBOL='Ba' CASE (57) ; SYMBOL='La' ! Lanthanide elements (lanthanoids) CASE (58) ; SYMBOL='Ce' CASE (59) ; SYMBOL='Pr' CASE (60) ; SYMBOL='Nd' CASE (61) ; SYMBOL='Pm' CASE (62) ; SYMBOL='Sm' CASE (63) ; SYMBOL='Eu' CASE (64) ; SYMBOL='Gd' CASE (65) ; SYMBOL='Tb' CASE (66) ; SYMBOL='Dy' CASE (67) ; SYMBOL='Ho' CASE (68) ; SYMBOL='Er' CASE (69) ; SYMBOL='Tm' CASE (70) ; SYMBOL='Yb' CASE (71) ; SYMBOL='Lu' CASE (72) ; SYMBOL='Hf' CASE (73) ; SYMBOL='Ta' CASE (74) ; SYMBOL='W' CASE (75) ; SYMBOL='Re' CASE (76) ; SYMBOL='Os' CASE (77) ; SYMBOL='Ir' CASE (78) ; SYMBOL='Pt' CASE (79) ; SYMBOL='Au' CASE (80) ; SYMBOL='Hg' CASE (81) ; SYMBOL='Tl' CASE (82) ; SYMBOL='Pb' CASE (83) ; SYMBOL='Bi' CASE (84) ; SYMBOL='Po' CASE (85) ; SYMBOL='As' CASE (86) ; SYMBOL='Rn' CASE (87) ; SYMBOL='Fr' CASE (88) ; SYMBOL='Ra' CASE (89) ; SYMBOL='Ac' ! Actinide elements (actinoids) CASE (90) ; SYMBOL='Th' CASE (91) ; SYMBOL='Pa' CASE (92) ; SYMBOL='U' CASE (93) ; SYMBOL='Np' CASE (94) ; SYMBOL='Pu' CASE (95) ; SYMBOL='Am' CASE (96) ; SYMBOL='Cm' CASE (97) ; SYMBOL='Bk' CASE (98) ; SYMBOL='Cf' CASE (99) ; SYMBOL='Es' CASE (100); SYMBOL='Fm' CASE (101); SYMBOL='Md' CASE (102); SYMBOL='No' CASE (103); SYMBOL='Lr' CASE (104); SYMBOL='Rf' END SELECT END FUNCTION IDENTIFYZ SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Function that computes the internuclear repulsion energy for the given specific geometry of the molecular system. INTEGER :: I,J DOUBLE PRECISION,DIMENSION(3) :: DIFF INTERNUCLEAR_ENERGY=0.D0 DO I=1,NBN DO J=I+1,NBN DIFF=CENTER(:,I)-CENTER(:,J) INTERNUCLEAR_ENERGY=INTERNUCLEAR_ENERGY+Z(I)*Z(J)/SQRT(DOT_PRODUCT(DIFF,DIFF)) END DO END DO END SUBROUTINE INTERNUCLEAR_REPULSION_ENERGY ! Various functions for the Hartree model with temperature FUNCTION POSITIVE_PART(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN FUNC=0.D0 ELSE FUNC=X END IF END FUNCTION POSITIVE_PART FUNCTION ENTROPY_FUNCTION(X) RESULT(FUNC) ! beta test function for the entropy DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC FUNC=POSITIVE_PART(X)**MB/MB END FUNCTION ENTROPY_FUNCTION FUNCTION RECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE FUNC=X**(1.D0/(MB-1.D0)) END IF END FUNCTION RECIP_DENTFUNC FUNCTION DRECIP_DENTFUNC(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC IF (X<0.D0) THEN STOP'beta is not a bijection on R_-' ELSE IF (X==0.D0) THEN STOP'No derivative at origin' ELSE FUNC=X**((2.D0-MB)/(MB-1.D0))/(MB-1.D0) END IF END FUNCTION FUNCTION FUNCFORMU(X) RESULT(FUNC) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION :: FUNC INTEGER :: I DOUBLE PRECISION :: Y FUNC=-MASS DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE IF (Y>=0.D0) THEN FUNC=FUNC+RECIP_DENTFUNC(Y) END IF END DO END FUNCTION FUNCFORMU SUBROUTINE RDENTFUNCD(X,FVAL,FDERIV) DOUBLE PRECISION,INTENT(IN) :: X DOUBLE PRECISION,INTENT(OUT) :: FVAL,FDERIV INTEGER :: I DOUBLE PRECISION :: Y FVAL=-MASS ; FDERIV=0.D0 DO I=1,RANK_P Y=(X-MU_I(I))/TEMPERATURE FVAL=FVAL+RECIP_DENTFUNC(Y) FDERIV=FDERIV+DRECIP_DENTFUNC(Y) END DO END SUBROUTINE RDENTFUNCD END MODULE MODULE basis_parameters USE iso_c_binding ! flag for the choice of the basis set type (either existing in the library or even-tempered) LOGICAL :: LIBRARY ! PARAMETERS FOR A GIVEN BASIS SET CHARACTER(26) :: BASISFILE INTEGER,PARAMETER :: MAQN=4,MNOP=38,MNOC=38,MNOGBF=4 ! Note: MAQN is the maximum number of different cartesian GBF function types (= maximum angular quantum number + 1) allowed, MNOP is the maximum number of primitives (of different exponents) allowed in any of these types, MNOC is the maximum number of contractions allowed in any of these types, MNOGBF is the maximum number of different GBF allowed in each component of a 2-spinor basis function (necessary for the lower 2-spinor basis due to the use of the Restricted Kinetic Balance scheme). MAQN, MNOP and MNOC depend on the basis that is used, MNOGBF depends on MAQN through the RKB scheme. ! PARAMETERS FOR AN EVEN-TEMPERED BASIS SET INTEGER :: NUMBER_OF_TERMS DOUBLE PRECISION :: FIRST_TERM,COMMON_RATIO ! Various flags for the contraction of the primitives and the Kinetic Balance scheme LOGICAL :: UNCONT LOGICAL :: KINBAL,UKB TYPE gaussianbasisfunction ! Definition of a contracted cartesian gaussian type "orbital" (CGTO) basis function. ! nbrofexponents: the number of different gaussian primitives present in the contraction ! center: coordinates (x,y,z) of the center of the basis function ! center_id: number of the nucleus relative to the center of the basis function in the list of the nuclei forming the molecular system (used for checking the parity of the bielectronic integrands when the four basis functions share the same center) ! exponents: array containing the exponent of each of the gaussian primitives present in the contraction ! coefficients: array containing the coefficient of each of the gaussian primitives present in the contraction ! monomialdegrees: array containing the degrees (n_x,n_y,n_z) of the monomial common to each of the gaussian primitives ! Note: the maximum number of terms in a contraction is set to 6 (see the basis for Cr in 6-31G for instance). INTEGER(KIND=C_INT) :: nbrofexponents REAL(KIND=C_DOUBLE),DIMENSION(3) :: center INTEGER :: center_id REAL(KIND=C_DOUBLE),DIMENSION(6) :: exponents REAL(KIND=C_DOUBLE),DIMENSION(6) :: coefficients INTEGER(KIND=C_INT),DIMENSION(3) :: monomialdegree END TYPE gaussianbasisfunction TYPE twospinor ! Definition of a Pauli 2-spinor type basis function using gaussian basis functions. ! nbrofcontractions: array containing the number of different contractions (<=MNOGT0) present in each of the components of the 2-spinor ! contractions: array containing the contractions present in each of the components of the 2-spinor ! contidx : array containing the indices of the gaussian primitives appearing in the contractions with respect to a secondary array of gaussian primitives (used for precomputation purposes) ! coefficients: array containing the complex coefficient of each of the contractions present in each of the components of the 2-spinor ! Note: if one of the components of the 2-spinor is zero then the corresponding nbrofcontractions is set to 0 INTEGER,DIMENSION(2) :: nbrofcontractions TYPE(gaussianbasisfunction),DIMENSION(2,MNOGBF) :: contractions INTEGER,DIMENSION(2,MNOGBF) :: contidx DOUBLE COMPLEX,DIMENSION(2,MNOGBF) :: coefficients END TYPE twospinor CONTAINS SUBROUTINE SETUP_BASIS USE case_parameters ; USE setup_tools CHARACTER(LEN=4) :: CHAR CHARACTER(LEN=26) :: BASISNAME INTEGER :: INFO OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## BASIS DEFINITION',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The basis definition is not given.' READ(100,'(3/,a)') BASISNAME IF (BASISNAME(1:6)=='BASIS ') THEN ! The basis set is an existing one in the basis library LIBRARY=.TRUE. BASISFILE='basis/'//BASISNAME(7:) READ(100,'(a4)') CHAR IF (CHAR=='UNCO') THEN UNCONT=.TRUE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (uncontracted)' ELSE UNCONT=.FALSE. WRITE(*,'(a,a,a)')' Basis set: ',BASISNAME,' (contracted)' END IF ELSE IF (BASISNAME(1:4)=='EVEN') THEN ! The basis set is an even-tempered one LIBRARY=.FALSE. IF (RELATIVISTIC.OR.MODEL>1) STOP' Option not implemented (even-tempered basis set)' WRITE(*,'(a)')' Even-tempered basis set (preliminary support)' READ(100,'(i4)') NUMBER_OF_TERMS WRITE(*,'(a,i4)')' * number of exponents = ',NUMBER_OF_TERMS READ(100,*) FIRST_TERM WRITE(*,'(a,f16.8)')' * first term of the geometric series = ',FIRST_TERM READ(100,*) COMMON_RATIO WRITE(*,'(a,f16.8)')' * common ratio of the geometric series = ',COMMON_RATIO ELSE STOP' Unknown basis set type' END IF IF (RELATIVISTIC) THEN READ(100,'(a2)') CHAR IF (CHAR=='KI') THEN KINBAL=.TRUE. READ(100,'(a4)') CHAR IF (CHAR=='REST') THEN UKB=.FALSE. WRITE(*,'(a)')' Restricted kinetic balance' ELSE UKB=.TRUE. WRITE(*,'(a)')' (impaired) Unrestricted kinetic balance' END IF ELSE KINBAL=.FALSE. WRITE(*,'(a)')' No kinetic balance' END IF END IF CLOSE(100) END SUBROUTINE SETUP_BASIS FUNCTION GBF_POINTWISE_VALUE(GBF,POINT) RESULT(VALUE) ! Function that computes the value of a gaussian basis function at a given point of space. USE iso_c_binding TYPE(gaussianbasisfunction),INTENT(IN) :: GBF DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT REAL(KIND=C_DOUBLE) :: VALUE VALUE=PRODUCT((POINT-GBF%center)**GBF%monomialdegree) & & *DOT_PRODUCT(GBF%coefficients(1:GBF%nbrofexponents), & & EXP(-GBF%exponents(1:GBF%nbrofexponents)*SUM((POINT-GBF%center)**2))) END FUNCTION GBF_POINTWISE_VALUE SUBROUTINE PRINTGBF(PHI,NUNIT) TYPE(gaussianbasisfunction),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I WRITE(NUNIT,*)' number of exponents:',PHI%nbrofexponents WRITE(NUNIT,*)' center:',PHI%center WRITE(NUNIT,*)' common monomial:',PHI%monomialdegree DO I=1,PHI%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',I WRITE(NUNIT,*)' exponent:',PHI%exponents(I) WRITE(NUNIT,*)' coefficient:',PHI%coefficients(I) END DO END SUBROUTINE PRINTGBF FUNCTION TWOSPINOR_POINTWISE_VALUE(PHI,POINT) RESULT(VALUE) ! Function that computes the value of a Pauli 2-spinor basis function at a given point of space. USE iso_c_binding TYPE(twospinor),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(3),INTENT(IN) :: POINT DOUBLE COMPLEX,DIMENSION(2) :: VALUE INTEGER :: I,J DO I=1,2 VALUE(I)=(0.D0,0.D0) DO J=1,PHI%nbrofcontractions(I) VALUE(I)=VALUE(I)+PHI%coefficients(I,J)*GBF_POINTWISE_VALUE(PHI%contractions(I,J),POINT) END DO END DO END FUNCTION TWOSPINOR_POINTWISE_VALUE SUBROUTINE PRINT2SPINOR(PHI,NUNIT) TYPE(twospinor),INTENT(IN) :: PHI INTEGER,INTENT(IN) :: NUNIT INTEGER :: I,J,K DO K=1,2 WRITE(NUNIT,*)'component #',K IF (PHI%nbrofcontractions(K)==0) THEN WRITE(NUNIT,*)' no contraction' ELSE WRITE(NUNIT,*)' number of contractions:',PHI%nbrofcontractions(K) DO I=1,PHI%nbrofcontractions(K) WRITE(NUNIT,*)' contraction #',I WRITE(NUNIT,*)' coefficient:',PHI%coefficients(K,I) WRITE(NUNIT,*)' number of gaussian primitives:',PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' common monomial:',PHI%contractions(K,I)%monomialdegree WRITE(NUNIT,*)' center:',PHI%contractions(K,I)%center DO J=1,PHI%contractions(K,I)%nbrofexponents WRITE(NUNIT,*)' gaussian primitive #',J WRITE(NUNIT,*)' exponent:',PHI%contractions(K,I)%exponents(J) WRITE(NUNIT,*)' coefficient:',PHI%contractions(K,I)%coefficients(J) END DO END DO END IF END DO END SUBROUTINE PRINT2SPINOR END MODULE MODULE scf_parameters ! number of different SCF algorithms to be used INTEGER :: NBALG ! SCF algorithm index (1: Roothaan, 2: level-shifting, 3: DIIS, 4: ODA (non-relativistic case only), 5: Eric Séré's (relativistic case only)) INTEGER,DIMENSION(5) :: ALG ! threshold for numerical convergence DOUBLE PRECISION :: TRSHLD ! maximum number of iterations allowed INTEGER :: MAXITR -! direct computation of the bielectronic integrals or not +! flag for the direct computation of the bielectronic integrals LOGICAL :: DIRECT -! "semi-direct" computation of the bielectronic integrals (relativistic case only) +! flag for the "semi-direct" computation of the bielectronic integrals (relativistic case only) ! Note: the case is considered as a (DIRECT==.FALSE.) subcase: GBF bielectronic integrals are precomputed and kept in memory, 2-spinor bielectronic integrals being computed "directly" using these values afterwards. LOGICAL :: SEMIDIRECT -! storage of the computed bielectronic integrals (and/or their list) on disk or in memory +! flag for the storage of the computed bielectronic integrals (and/or their list) on disk or in memory LOGICAL :: USEDISK -! use of the SS-bielectronic integrals +! flag for the use of the SS-bielectronic integrals LOGICAL :: SSINTEGRALS +! flag for the use of the LS-bielectronic integrals + LOGICAL :: SLINTEGRALS ! resume EIG and EIGVEC from last computation LOGICAL :: RESUME - ! use of the SL-bielectronic integrals. Should not be set by the user directly - LOGICAL :: SLINTEGRALS = .TRUE. CONTAINS SUBROUTINE SETUP_SCF !$ USE omp_lib USE case_parameters ; USE setup_tools CHARACTER :: METHOD CHARACTER(4) :: CHAR INTEGER :: I,INFO,MXSET,STAT,NUMBER_OF_THREADS DOUBLE PRECISION :: SHIFT OPEN(100,FILE=SETUP_FILE,STATUS='old',ACTION='read') CALL LOOKFOR(100,'## SCF PARAMETERS',INFO) - IF (INFO/=0) STOP + IF (INFO/=0) STOP' The SCF parameters are not given.' READ(100,'(7/,i1)') NBALG DO I=1,NBALG READ(100,'(i1)') ALG(I) IF (RELATIVISTIC.AND.(ALG(I)==4)) THEN - STOP'The Optimal Damping Algorithm is intended for the non-relativistic case only.' + STOP' The Optimal Damping Algorithm is intended for the non-relativistic case only.' ELSE IF ((.NOT.RELATIVISTIC).AND.(ALG(I)==5)) THEN - STOP'ES''s algorithm is intended for the relativistic case only.' + STOP' ES''s algorithm is intended for the relativistic case only.' END IF END DO READ(100,*) TRSHLD WRITE(*,*)'Threshold =',TRSHLD READ(100,'(i5)') MAXITR WRITE(*,*)'Maximum number of iterations =',MAXITR READ(100,'(a3)') CHAR IF (RELATIVISTIC) THEN IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ; SEMIDIRECT=.FALSE. READ(100,'(a4)') CHAR ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE IF (CHAR=='SEM') THEN DIRECT=.FALSE. ; SEMIDIRECT=.TRUE. WRITE(*,'(a)')' "Semi-direct" computation of the bielectronic integrals' ! check if the list of the bielectronic integrals is stored on disk or in memory READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. ELSE USEDISK=.FALSE. END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF - READ(100,'(a4)') CHAR - IF (CHAR=='NOSS') THEN + IF (MODEL==3) THEN +! Special case: complex GHF SSINTEGRALS=.FALSE. - WRITE(*,'(a)')' (SS-integrals are not used in the computation)' + SLINTEGRALS=.FALSE. ELSE - SSINTEGRALS=.TRUE. + REWIND(100) + CALL LOOKFOR(100,'NOSS',INFO) + IF (INFO==0) THEN + SSINTEGRALS=.FALSE. + WRITE(*,'(a)')' (SS-integrals are not used in the computation)' + ELSE + SSINTEGRALS=.TRUE. + END IF + REWIND(100) + CALL LOOKFOR(100,'NOLS',INFO) + IF (INFO==0) THEN + SLINTEGRALS=.FALSE. + WRITE(*,'(a)')' (SL-integrals are not used in the computation)' + ELSE + SLINTEGRALS=.TRUE. + END IF END IF ELSE IF (CHAR=='DIR') THEN DIRECT=.TRUE. WRITE(*,'(a)')' Direct computation of the bielectronic integrals' ! the list of the bielectronic integrals is stored in memory ELSE IF (CHAR=='NOT') THEN DIRECT=.FALSE. ! the list of the bielectronic integrals is stored in the same way as the integrals are (on disk or in memory) READ(100,'(a4)') CHAR IF (CHAR=='DISK') THEN USEDISK=.TRUE. WRITE(*,'(a)')' Computed bielectronic integrals stored on disk' ELSE USEDISK=.FALSE. WRITE(*,'(a)')' Computed bielectronic integrals stored in memory' END IF ELSE WRITE(*,*)'Subroutine SETUP_SCF: unknown type of computation for bielectronic integrals.' STOP END IF END IF ! additional verifications on the parameters of the algorithms DO I=1,NBALG IF (ALG(I)==2) THEN REWIND(100) CALL LOOKFOR(100,'LEVEL-SHIFTING ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 1 READ(100,'(/,f16.8)',ERR=1,END=1)SHIFT ELSE IF (ALG(I)==3) THEN REWIND(100) CALL LOOKFOR(100,'DIIS ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 2 READ(100,'(/,i2)',ERR=2,END=2)MXSET IF (MXSET<2) GO TO 3 ELSE IF (ALG(I)==5) THEN REWIND(100) CALL LOOKFOR(100,'SERE''S ALGORITHM PARAMETERS',INFO) IF (INFO/=0) GO TO 4 READ(100,'(/,a)',ERR=4,END=4)METHOD IF ((METHOD/='D').AND.(METHOD/='S')) GO TO 4 END IF END DO - RESUME = .FALSE. + RESUME=.FALSE. CALL LOOKFOR(100,'RESUME',INFO) IF(INFO == 0) THEN READ(100,'(a)')CHAR IF(CHAR == 'YES') THEN RESUME = .TRUE. END IF END IF !$ ! determination of the number of threads to be used by OpenMP !$ CALL LOOKFOR(100,'PARALLELIZATION PARAMETERS',INFO) !$ IF (INFO==0) THEN !$ READ(100,'(/,i3)')NUMBER_OF_THREADS !$ CALL OMP_SET_NUM_THREADS(NUMBER_OF_THREADS) !$ END IF !$ WRITE(*,'(a,i2,a)') ' The number of thread(s) to be used is ',OMP_GET_MAX_THREADS(),'.' CLOSE(100) RETURN ! MESSAGES 1 STOP'No shift parameter given for the level-shifting algorithm.' 2 STOP'No simplex dimension given for the DIIS algorithm.' 3 STOP'The simplex dimension for the DIIS algorithm must be at least equal to two.' 4 STOP'No method given for the computation of $Theta$ in ES''s algorithm.' END SUBROUTINE SETUP_SCF END MODULE diff --git a/src/tools.f90 b/src/tools.f90 index 930e8ea..e46d3eb 100644 --- a/src/tools.f90 +++ b/src/tools.f90 @@ -1,514 +1,517 @@ MODULE constants DOUBLE PRECISION,PARAMETER :: PI=3.14159265358979323846D0 +! speed of light in the vacuum in atomic units (for the relativistic case) +! Note : One has $c=\frac{e^2h_e}{\hbar\alpha}$, where $\alpha$ is the fine structure constant, $c$ is the speed of light in the vacuum, $e$ is the elementary charge, $\hbar$ is the reduced Planck constant and $k_e$ is the Coulomb constant. In Hartree atomic units, the numerical values of the electron mass, the elementary charge, the reduced Planck constant and the Coulomb constant are all unity by definition, so that $c=\alpha^{-1}$. The value chosen here is the one recommended in: P. J. Mohr, B. N. Taylor, and D. B. Newell, CODATA recommended values of the fundamental physical constants: 2006. + DOUBLE PRECISION,PARAMETER :: SPEED_OF_LIGHT=137.035999967994D0 END MODULE MODULE random CONTAINS ! call this once SUBROUTINE INIT_RANDOM() ! initialises random generator ! based on http://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fSEED.html#RANDOM_005fSEED INTEGER :: i, n, clock INTEGER, DIMENSION(:), ALLOCATABLE :: seed CALL RANDOM_SEED(size = n) ALLOCATE(seed(n)) CALL SYSTEM_CLOCK(COUNT=clock) seed = clock + 37 * (/ (i - 1, i = 1, n) /) CALL RANDOM_SEED(PUT = seed) DEALLOCATE(seed) END SUBROUTINE INIT_RANDOM ! returns an array of random numbers of size N in (0, 1) FUNCTION GET_RANDOM(N) RESULT(r) REAL, DIMENSION(N) :: r INTEGER :: N CALL RANDOM_NUMBER(r) END FUNCTION get_random END MODULE random MODULE matrix_tools INTERFACE PACK MODULE PROCEDURE PACK_symmetric,PACK_hermitian END INTERFACE INTERFACE UNPACK MODULE PROCEDURE UNPACK_symmetric,UNPACK_hermitian END INTERFACE INTERFACE ABA MODULE PROCEDURE ABA_symmetric,ABA_hermitian END INTERFACE INTERFACE ABCBA MODULE PROCEDURE ABCBA_symmetric,ABCBA_hermitian END INTERFACE INTERFACE ABC_CBA MODULE PROCEDURE ABC_CBA_symmetric,ABC_CBA_hermitian END INTERFACE INTERFACE FINNERPRODUCT MODULE PROCEDURE FROBENIUSINNERPRODUCT_real,FROBENIUSINNERPRODUCT_complex END INTERFACE INTERFACE NORM MODULE PROCEDURE NORM_real,NORM_complex,NORM_symmetric,NORM_hermitian END INTERFACE INTERFACE INVERSE MODULE PROCEDURE INVERSE_real,INVERSE_complex,INVERSE_symmetric,INVERSE_hermitian END INTERFACE INTERFACE SQUARE_ROOT MODULE PROCEDURE SQUARE_ROOT_symmetric,SQUARE_ROOT_hermitian END INTERFACE INTERFACE EXPONENTIAL MODULE PROCEDURE EXPONENTIAL_real,EXPONENTIAL_complex END INTERFACE EXPONENTIAL INTERFACE TRACE MODULE PROCEDURE TRACE_symmetric,TRACE_hermitian END INTERFACE INTERFACE TRACEOFPRODUCT MODULE PROCEDURE TRACEOFPRODUCT_real,TRACEOFPRODUCT_complex,TRACEOFPRODUCT_symmetric,TRACEOFPRODUCT_hermitian END INTERFACE INTERFACE EIGENSOLVER MODULE PROCEDURE EIGENSOLVER_symmetric_prefactorized,EIGENSOLVER_hermitian_prefactorized END INTERFACE INTERFACE COMMUTATOR MODULE PROCEDURE COMMUTATOR_symmetric,COMMUTATOR_hermitian END INTERFACE INTERFACE PRINTMATRIX MODULE PROCEDURE PRINTMATRIX_symmetric,PRINTMATRIX_hermitian,PRINTMATRIX_complex,PRINTMATRIX_real END INTERFACE INTERFACE READMATRIX MODULE PROCEDURE READMATRIX_complex,READMATRIX_real END INTERFACE READMATRIX INTERFACE BUILD_BLOCK_DIAGONAL MODULE PROCEDURE BUILD_BLOCK_DIAGONAL_symmetric END INTERFACE BUILD_BLOCK_DIAGONAL CONTAINS ! handling of symmetric and hermitian matrices stored in packed form. FUNCTION PACK_symmetric(A,N) RESULT (PA) ! Function that stores the upper triangular part of a symmetric matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=(A(I,J)+A(J,I))/2.D0 END DO END DO END FUNCTION PACK_symmetric FUNCTION PACK_hermitian(A,N) RESULT (PA) ! Function that stores the upper triangular part of a hermitian matrix in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PA INTEGER :: IJ,I,J IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 PA(IJ)=A(I,J) PA(IJ)=(A(I,J)+conjg(A(J,I)))/2.D0 END DO END DO END FUNCTION PACK_hermitian FUNCTION UNPACK_symmetric(PA,N) RESULT (A) ! Function that unpacks a symmetric matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=PA(1+J:I-1+J) END DO END FUNCTION UNPACK_symmetric FUNCTION UNPACK_hermitian(PA,N) RESULT (A) ! Function that unpacks a hermitian matrix which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N,N) :: A INTEGER :: I,J DO I=1,N J=I*(I-1)/2 A(1:I,I)=PA(1+J:I+J) A(I,1:I-1)=CONJG(PA(1+J:I-1+J)) END DO END FUNCTION UNPACK_hermitian FUNCTION ABA_symmetric(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(K+(I-1)*I/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(L+(K-1)*K/2)*PA(J+(L-1)*L/2) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(J+(L-1)*L/2) END DO END DO END DO END DO END FUNCTION ABA_symmetric FUNCTION ABA_hermitian(PA,PB,N) RESULT (PC) ! Function that computes the product ABA, where A and B are two hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PC INTEGER :: I,J,K,L,IJ PC=(0.D0,0.D0) IJ=0 DO J=1,N DO I=1,J IJ=IJ+1 DO K=1,I DO L=1,K PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+CONJG(PA(K+(I-1)*I/2))*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=I+1,J DO L=1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=K+1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*PA(L+(J-1)*J/2) END DO DO L=J+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO DO K=J+1,N DO L=1,J PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*PA(L+(J-1)*J/2) END DO DO L=J+1,K PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*CONJG(PB(L+(K-1)*K/2))*CONJG(PA(J+(L-1)*L/2)) END DO DO L=K+1,N PC(IJ)=PC(IJ)+PA(I+(K-1)*K/2)*PB(K+(L-1)*L/2)*CONJG(PA(J+(L-1)*L/2)) END DO END DO END DO END DO END FUNCTION ABA_hermitian FUNCTION ABCBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,MATMUL(C,MATMUL(B,A)))),N) END FUNCTION ABCBA_symmetric FUNCTION ABCBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the product ABCBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD PD=ABA(PA,ABA(PB,PC,N),N) END FUNCTION ABCBA_hermitian FUNCTION ABC_CBA_symmetric(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three symmetric matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PD DOUBLE PRECISION,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_symmetric FUNCTION ABC_CBA_hermitian(PA,PB,PC,N) RESULT (PD) ! Function that computes the sum ABC+CBA, where A, B, and C are three hermitian matrices, which upper triangular parts are stored in packed format (the resulting matrix being also stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PC DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PD DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,C A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; C=UNPACK(PC,N) PD=PACK(MATMUL(A,MATMUL(B,C))+MATMUL(C,MATMUL(B,A)),N) END FUNCTION ABC_CBA_hermitian ! diverse linear algebra routines FUNCTION INVERSE_real(A,N) RESULT(INVA) ! Function that computes the inverse of a square real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N) :: A DOUBLE PRECISION,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK INVA=A CALL DGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_real FUNCTION INVERSE_complex(A,N) RESULT(INVA) ! Function that computes the inverse of a square complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: INVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK INVA=A CALL ZGETRF(N,N,INVA,N,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZGETRI(N,INVA,N,IPIV,WORK,N,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRF: U(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the factor U is exactly singular, and division by zero will & &occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZGETRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZGETRI: U(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_complex FUNCTION INVERSE_symmetric(PA,N) RESULT(PINVA) ! Function that computes the inverse of a symmetric matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: WORK PINVA=PA CALL DSPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL DSPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_symmetric FUNCTION INVERSE_hermitian(PA,N) RESULT(PINVA) ! Function that computes the inverse of an hermitian matrix which upper triangular part is stored in packed format (its inverse being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PINVA INTEGER :: INFO INTEGER,DIMENSION(N) :: IPIV DOUBLE COMPLEX,DIMENSION(N) :: WORK PINVA=PA CALL ZHPTRF('U',N,PINVA,IPIV,INFO) IF (INFO/=0) GOTO 1 CALL ZHPTRI('U',N,PINVA,IPIV,WORK,INFO) IF (INFO/=0) GOTO 2 RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRF: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRF: D(',INFO,',',INFO,') is exactly zero. The factorization & &has been completed, but the block diagonal matrix D is exactly singular, and division & &by zero will occur if it is used to solve a system of equations' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPTRI: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPTRI: D(',INFO,',',INFO,') is exactly zero; & &the matrix is singular and its inverse could not be computed' END IF 3 WRITE(*,*)'(called from function INVERSE)' STOP END FUNCTION INVERSE_hermitian FUNCTION SQUARE_ROOT_symmetric(PA,N) RESULT(PSQRA) ! Function that computes the square root of a symmetric, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL DSPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(EIGVEC)),N) RETURN 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO, & &'off-diagonal elements of an intermediate tridiagonal form did not converge to zero' END IF WRITE(*,*)'(called from function SQUARE_ROOT)' STOP END FUNCTION SQUARE_ROOT_symmetric FUNCTION SQUARE_ROOT_hermitian(PA,N) RESULT(PSQRA) ! Function that computes the square root of an hermitian, positive-definite matrix which upper triangular part is stored in packed format (its square root being stored as such). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: PSQRA INTEGER :: INFO,I INTEGER,DIMENSION(N) :: IPIV DOUBLE PRECISION,DIMENSION(N) :: EIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N,N) :: EIGVEC,M PSQRA=PA CALL ZHPEV('V','U',N,PSQRA,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GOTO 1 FORALL(I=1:N) M(:,I)=SQRT(EIG(I))*EIGVEC(:,I) PSQRA=PACK(MATMUL(M,TRANSPOSE(CONJG(EIGVEC))),N) @@ -530,516 +533,515 @@ FUNCTION EXPONENTIAL_real(T,A,N) result(EXPTA) DOUBLE PRECISION,INTENT(IN) :: T DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A DOUBLE PRECISION,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE PRECISION,DIMENSION(4*N*N+IDEG+1) :: WSP CALL DGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine DGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_real FUNCTION EXPONENTIAL_complex(T,A,N) result(EXPTA) ! Function that computes the matrix exponential exp(tA), where A is an N-by-N complex matrix and t is a real scalar, using the Expokit software package (http://www.maths.uq.edu.au/expokit/). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,INTENT(IN) :: T DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A DOUBLE COMPLEX,DIMENSION(N,N) :: EXPTA INTEGER :: IEXP,NS,IFLAG INTEGER,DIMENSION(N) :: IWSP INTEGER,PARAMETER :: IDEG=6 DOUBLE COMPLEX,DIMENSION(4*N*N+IDEG+1) :: WSP CALL ZGPADM(IDEG,N,T,A,N,WSP,SIZE(WSP,1),IWSP,IEXP,NS,IFLAG) IF (IFLAG/=0) GO TO 1 EXPTA=RESHAPE(WSP(IEXP:IEXP+N*N-1),SHAPE(EXPTA)) RETURN 1 WRITE(*,*)'Subroutine ZGPADM: there is a problem' WRITE(*,*)'(called from function EXPONENTIAL)' STOP END FUNCTION EXPONENTIAL_complex FUNCTION TRACE_symmetric(PA,N) RESULT (TRACE) ! Function that computes the trace of a symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION :: TRACE INTEGER :: I TRACE=0.D0 DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_symmetric FUNCTION TRACE_hermitian(PA,N) RESULT (TRACE) ! Function that computes the trace of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE COMPLEX :: TRACE INTEGER :: I TRACE=(0.D0,0.D0) DO I=1,N TRACE=TRACE+PA((I+1)*I/2) END DO END FUNCTION TRACE_hermitian FUNCTION TRACEOFPRODUCT_real(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: TRACE INTEGER :: I,J TRACE=0.D0 DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_real FUNCTION TRACEOFPRODUCT_complex(A,B,N) RESULT (TRACE) ! Function that computes the trace of the product of two square complex matrices A and B. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: TRACE INTEGER :: I,J TRACE=(0.D0,0.D0) DO I=1,N DO J=1,N TRACE=TRACE+A(I,J)*B(J,I) END DO END DO END FUNCTION TRACEOFPRODUCT_complex FUNCTION TRACEOFPRODUCT_symmetric(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two symmetric matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE PRECISION :: TRACE INTEGER :: I,J,IJ,JI TRACE=0.D0 DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*PB(IJ) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+PA(JI)*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_symmetric FUNCTION TRACEOFPRODUCT_hermitian(PA,PB,N) RESULT (TRACE) ! Function that computes the trace of the product of two hermitian matrices A and B, which upper triangular parts are stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB DOUBLE COMPLEX :: TRACE INTEGER :: I,J,IJ,JI TRACE=(0.D0,0.D0) DO J=1,N DO I=1,J IJ=I+(J-1)*J/2 TRACE=TRACE+PA(IJ)*CONJG(PB(IJ)) END DO DO I=J+1,N JI=J+(I-1)*I/2 TRACE=TRACE+CONJG(PA(JI))*PB(JI) END DO END DO END FUNCTION TRACEOFPRODUCT_hermitian FUNCTION FROBENIUSINNERPRODUCT_real(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square real matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}b_{ij}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE PRECISION :: FIP INTEGER :: I,J FIP=0.D0 DO I=1,N DO J=1,N FIP=FIP+A(I,J)*B(I,J) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_real FUNCTION FROBENIUSINNERPRODUCT_complex(A,B,N) RESULT (FIP) ! Function that computes the Frobenius inner product between two square complex matrices (i.e. $<A,B>_F=\sum_{i,j=1}^n a_{ij}\overline{b_{ij}}$). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: A,B DOUBLE COMPLEX :: FIP INTEGER :: I,J FIP=(0.D0,0.D0) DO I=1,N DO J=1,N FIP=FIP+A(I,J)*CONJG(B(I,J)) END DO END DO END FUNCTION FROBENIUSINNERPRODUCT_complex SUBROUTINE NORM_check_norm(CHAR) CHARACTER(1),INTENT(IN) :: CHAR IF((CHAR /= 'F') .AND. & &(CHAR /= 'I') .AND. & &(CHAR /= '1') .AND. & &(CHAR /= 'M')) THEN WRITE(*,*) 'Invalid norm' STOP END IF END SUBROUTINE NORM_check_norm FUNCTION NORM_real(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a real matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANGE CALL NORM_check_norm(CHAR) NORM = DLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_real FUNCTION NORM_complex(M,N,CHAR) RESULT (NORM) ! Function that computes the one norm, or the Frobenius norm, or the infinity norm of a complex matrix. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: M CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANGE CALL NORM_check_norm(CHAR) NORM = ZLANGE(CHAR,N,N,M,N,WORK) END FUNCTION NORM_complex FUNCTION NORM_symmetric(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a real symmetric matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: DLANSP CALL NORM_check_norm(CHAR) NORM = DLANSP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_symmetric FUNCTION NORM_hermitian(PM,N,CHAR) RESULT (NORM) ! Function that returns the one norm, or the Frobenius norm, or the infinity norm of a hermitian matrix, which upper triangular part is stored in packed format. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PM CHARACTER(1),INTENT(IN) :: CHAR DOUBLE PRECISION :: NORM DOUBLE PRECISION,DIMENSION(N) :: WORK DOUBLE PRECISION,EXTERNAL :: ZLANHP CALL NORM_check_norm(CHAR) NORM = ZLANHP(CHAR,'U',N,PM,WORK) END FUNCTION NORM_hermitian SUBROUTINE EIGENSOLVER_symmetric_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a real generalized symmetric-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be symmetric, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's DSPGV subroutine. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: EIGVEC INTEGER,INTENT(OUT) :: INFO INTEGER :: I,NEIG DOUBLE PRECISION,DIMENSION(3*N) :: WORK DOUBLE PRECISION,DIMENSION(N*(N+1)/2) :: AP,BP AP=PA ; BP=PCFB ! Transform problem to standard eigenvalue problem and solve CALL DSPGST(1,'U',N,AP,BP,INFO) IF (INFO/=0) GO TO 1 CALL DSPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,INFO) IF (INFO/=0) GO TO 2 ! Backtransform eigenvectors to the original problem NEIG=N IF (INFO>0) NEIG=INFO-1 DO I=1,NEIG CALL DTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1) END DO RETURN ! MESSAGES 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPGST: the',-INFO,'-th argument had an illegal value' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine DSPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine DSPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF 3 WRITE(*,*)'(called from subroutine EIGENSOLVER)' RETURN END SUBROUTINE EIGENSOLVER_symmetric_prefactorized SUBROUTINE EIGENSOLVER_hermitian_prefactorized(PA,PCFB,N,EIG,EIGVEC,INFO) ! Subroutine that computes all the eigenvalues and the eigenvectors of a complex generalized hermitian-definite eigenproblem, of the form A*x=(lambda)*B*x. Here A and B are assumed to be hermitian, their upper triangular part being stored in packed format, and B is also positive definite. It is also assumed that the Cholesky factorization of B has previously been computed and stored in packed format. ! Note: it is a simplification of LAPACK's ZHPGV subroutine. IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PCFB DOUBLE PRECISION,DIMENSION(N),INTENT(OUT) :: EIG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: EIGVEC INTEGER,INTENT(OUT) :: INFO INTEGER :: I,NEIG DOUBLE PRECISION,DIMENSION(3*N-2) :: RWORK DOUBLE COMPLEX,DIMENSION(2*N-1) :: WORK DOUBLE COMPLEX,DIMENSION(N*(N+1)/2) :: AP,BP AP=PA ; BP=PCFB ! Transform problem to standard eigenvalue problem and solve CALL ZHPGST(1,'U',N,AP,BP,INFO) IF (INFO/=0) GO TO 1 CALL ZHPEV('V','U',N,AP,EIG,EIGVEC,N,WORK,RWORK,INFO) IF (INFO/=0) GO TO 2 ! Backtransform eigenvectors to the original problem NEIG=N IF (INFO>0) NEIG=INFO-1 DO I=1,NEIG CALL ZTPSV('U','N','Non-unit',N,BP,EIGVEC(1,I),1) END DO RETURN ! MESSAGES 1 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPGST: the',-INFO,'-th argument had an illegal value' END IF GO TO 3 2 IF (INFO<0) THEN WRITE(*,*)'Subroutine ZHPEV: the',-INFO,'-th argument had an illegal value' ELSE WRITE(*,*)'Subroutine ZHPEV: the algorithm failed to converge; ',INFO,'off-diagonal elements & &of an intermediate tridiagonal form did not converge to zero' END IF 3 WRITE(*,*)'(called from subroutine EIGENSOLVER)' RETURN END SUBROUTINE EIGENSOLVER_hermitian_prefactorized FUNCTION COMMUTATOR_symmetric(PA,PB,PS,N) RESULT (C) ! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two symmetric matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS DOUBLE PRECISION,DIMENSION(N,N) :: C DOUBLE PRECISION,DIMENSION(N,N) :: A,B,S A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N) C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A)) END FUNCTION COMMUTATOR_symmetric FUNCTION COMMUTATOR_hermitian(PA,PB,PS,N) RESULT (C) ! Function that computes the "commutator" [A,B]=ABS-SBA in a discrete nonorthonormal basis, A and B being two hermitian matrices of size N (only the upper triangular part of the matrices is stored in packed format) and S being the overlap matrix of the basis (stored similarly). IMPLICIT NONE INTEGER,INTENT(IN) :: N DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PA,PB,PS DOUBLE COMPLEX,DIMENSION(N,N) :: C DOUBLE COMPLEX,DIMENSION(N,N) :: A,B,S A=UNPACK(PA,N) ; B=UNPACK(PB,N) ; S=UNPACK(PS,N) C=MATMUL(MATMUL(A,B),S)-MATMUL(S,MATMUL(B,A)) END FUNCTION COMMUTATOR_hermitian SUBROUTINE READMATRIX_real(MAT,N,LOGUNIT) INTEGER,INTENT(IN) :: N,LOGUNIT INTEGER :: I DOUBLE PRECISION,DIMENSION(N,N),INTENT(OUT) :: MAT DOUBLE PRECISION,DIMENSION(N) :: LINE DO I=1,N READ(LOGUNIT,*) LINE MAT(I,:) = LINE END DO END SUBROUTINE READMATRIX_REAL SUBROUTINE READMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) INTEGER :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N,N),INTENT(OUT) :: MAT DOUBLE PRECISION,DIMENSION(N,N) :: R,I CALL READMATRIX_real(R,N,LOGUNIT_REAL) CALL READMATRIX_real(I,N,LOGUNIT_IMAG) MAT = DCMPLX(R,I) END SUBROUTINE READMATRIX_complex SUBROUTINE PRINTMATRIX_real(MAT,N,LOGUNIT) INTEGER,INTENT(IN) :: N,LOGUNIT INTEGER :: I DOUBLE PRECISION,DIMENSION(N,N),INTENT(IN) :: MAT DO I=1,N WRITE(LOGUNIT,*) MAT(I,:) END DO END SUBROUTINE PRINTMATRIX_real SUBROUTINE PRINTMATRIX_complex(MAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG INTEGER :: I DOUBLE COMPLEX,DIMENSION(N,N),INTENT(IN) :: MAT DO I=1,N IF(LOGUNIT_REAL == LOGUNIT_IMAG) THEN WRITE(LOGUNIT_REAL,*) MAT(I,:) ELSE WRITE(LOGUNIT_REAL,*) REAL(MAT(I,:)) WRITE(LOGUNIT_IMAG,*) AIMAG(MAT(I,:)) END IF END DO END SUBROUTINE PRINTMATRIX_complex SUBROUTINE PRINTMATRIX_symmetric(PMAT,N,LOGUNIT) INTEGER,INTENT(IN) :: N,LOGUNIT DOUBLE PRECISION,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT CALL PRINTMATRIX_real(UNPACK(PMAT,N),N,LOGUNIT) END SUBROUTINE PRINTMATRIX_symmetric SUBROUTINE PRINTMATRIX_hermitian(PMAT,N,LOGUNIT_REAL,LOGUNIT_IMAG) INTEGER,INTENT(IN) :: N,LOGUNIT_REAL,LOGUNIT_IMAG DOUBLE COMPLEX,DIMENSION(N*(N+1)/2),INTENT(IN) :: PMAT CALL PRINTMATRIX_complex(UNPACK(PMAT,N),N,LOGUNIT_REAL,LOGUNIT_IMAG) END SUBROUTINE PRINTMATRIX_hermitian SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric(PB,PA,N) ! Builds B as [A 0;0 A], A is of size N INTEGER,INTENT(IN) :: N DOUBLE PRECISION, DIMENSION(N*(N+1)/2),INTENT(IN) :: PA DOUBLE PRECISION, DIMENSION(N*2*(N*2+1)/2),INTENT(OUT) :: PB DOUBLE PRECISION, DIMENSION(2*N,2*N) :: B B = 0 B(1:N,1:N) = UNPACK(PA,N) B(N+1:2*N,N+1:2*N) = B(1:N,1:N) PB = PACK(B,2*N) END SUBROUTINE BUILD_BLOCK_DIAGONAL_symmetric END MODULE matrix_tools MODULE mathematical_functions INTERFACE DFACT MODULE PROCEDURE DOUBLE_FACTORIAL END INTERFACE CONTAINS FUNCTION FACTORIAL(N) RESULT(FACT) IMPLICIT NONE INTEGER,INTENT(IN) :: N INTEGER :: FACT INTEGER :: I IF (N<0) THEN STOP'Function FACTORIAL: the factorial is undefined for negative integers.' ELSE FACT=1 IF (N>1) THEN DO I=2,N FACT=FACT*I END DO END IF END IF END FUNCTION FACTORIAL FUNCTION DOUBLE_FACTORIAL(N) RESULT(DFACT) IMPLICIT NONE INTEGER,INTENT(IN) :: N INTEGER :: DFACT INTEGER :: I IF (N<-1) THEN STOP'Function DOUBLE_FACTORIAL: the double factorial is undefined for negative integers lower than -1.' ELSE DFACT=1 IF (N>1) THEN I=N DO WHILE (I>1) DFACT=DFACT*I I=I-2 END DO END IF END IF END FUNCTION DOUBLE_FACTORIAL END MODULE MODULE setup_tools ! name of the setup file CHARACTER(100) :: SETUP_FILE CONTAINS SUBROUTINE SETUP_FILENAME ! Subroutine that retrieves the name of the setup file CALL GETARG(1,SETUP_FILE) IF (SETUP_FILE=='') SETUP_FILE='setup' END SUBROUTINE SETUP_FILENAME SUBROUTINE LOOKFOR(NUNIT,SUBSTRING,INFO) ! Subroutine that looks for a given text string in an open unit. IMPLICIT NONE INTEGER,INTENT(IN) :: NUNIT INTEGER,INTENT(OUT) :: INFO CHARACTER(*),INTENT(IN) :: SUBSTRING CHARACTER(80) :: STRING INFO=0 1 READ(100,'(a)',ERR=2,END=2) STRING IF (INDEX(STRING,SUBSTRING)==0) GOTO 1 RETURN -2 WRITE(*,*)'Subroutine LOOKFOR: text string "',SUBSTRING,'" was not found in file.' - INFO=1 +2 INFO=1 END SUBROUTINE LOOKFOR END MODULE
antoine-levitt/ACCQUAREL
3c48c9a55030b0b36a71aeddb23d35823473d0eb
add BUILDA and BUILDB
diff --git a/src/matrices.F90 b/src/matrices.F90 index 70d3e09..fe76d24 100644 --- a/src/matrices.F90 +++ b/src/matrices.F90 @@ -412,624 +412,699 @@ SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) ELSE IF ((I==J).AND.(J>K).AND.(K==L)) THEN TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*DM(I,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,I) ELSE IF ((I==K).AND.(K>J).AND.(J==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(I,J) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(J,I) TEFM(I,J)=TEFM(I,J)+INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)+INTGRL*DM(I,J) TEFM(I,I)=TEFM(I,I)-INTGRL*DM(J,J) TEFM(J,J)=TEFM(J,J)-INTGRL*DM(I,I) ! 3 distinct values for the 4 indices ELSE IF ((I==K).AND.(K>J).AND.(J>L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(I,L)+DM(L,I)) TEFM(I,L)=TEFM(I,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,I)=TEFM(L,I)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(I,I)=TEFM(I,I)-INTGRL*(DM(J,L)+DM(L,J)) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(I,I) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,I) ELSE IF ((I>J).AND.(J==K).AND.(K>L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,L)+DM(L,J)) TEFM(J,L)=TEFM(J,L)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(L,J)=TEFM(L,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,L)+DM(L,I)) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(J,J) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,J) ELSE IF ((I>K).AND.(K>J).AND.(J==L)) THEN TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(J,K)+DM(K,J)) TEFM(J,K)=TEFM(J,K)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(K,J)=TEFM(K,J)+2.D0*INTGRL*(DM(J,I)+DM(I,J)) TEFM(J,J)=TEFM(J,J)-INTGRL*(DM(I,K)+DM(K,I)) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(J,I) TEFM(J,I)=TEFM(J,I)-INTGRL*DM(K,J) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(J,J) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,J) TEFM(I,J)=TEFM(I,J)-INTGRL*DM(J,K) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,J) ELSE IF ((I>J).AND.(I>K).AND.(K==L)) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*DM(K,K) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*DM(K,K) TEFM(K,K)=TEFM(K,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,K) ELSE IF ((I==J).AND.(J>K).AND.(K>L)) THEN TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*DM(I,I) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*DM(I,I) TEFM(I,I)=TEFM(I,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(I,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(I,K) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,I) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,I) ! 4 distinct values for the 4 indices ELSE IF ( ((I>J).AND.(J>K).AND.(K>L)) & .OR.((I>K).AND.(K>J).AND.(J>L)) & .OR.((I>K).AND.(K>L).AND.(L>J))) THEN TEFM(I,J)=TEFM(I,J)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(J,I)=TEFM(J,I)+2.D0*INTGRL*(DM(K,L)+DM(L,K)) TEFM(K,L)=TEFM(K,L)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(L,K)=TEFM(L,K)+2.D0*INTGRL*(DM(I,J)+DM(J,I)) TEFM(K,I)=TEFM(K,I)-INTGRL*DM(L,J) TEFM(L,I)=TEFM(L,I)-INTGRL*DM(K,J) TEFM(K,J)=TEFM(K,J)-INTGRL*DM(L,I) TEFM(L,J)=TEFM(L,J)-INTGRL*DM(K,I) TEFM(I,K)=TEFM(I,K)-INTGRL*DM(J,L) TEFM(I,L)=TEFM(I,L)-INTGRL*DM(J,K) TEFM(J,K)=TEFM(J,K)-INTGRL*DM(I,L) TEFM(J,L)=TEFM(J,L)-INTGRL*DM(I,K) END IF END DO IF (.NOT.DIRECT.AND.USEDISK) CLOSE(BIUNIT) PTEFM=PACK(TEFM,NBAST) END SUBROUTINE BUILDTEFM_RHF SUBROUTINE BUILDTEFM_GHF(PTEFM,NBAST,PHI,PDM) ! Computation and assembly of the two-electron part of the Fock matrix associated to a given density matrix in the restricted closed-shell Hartree-Fock formalism, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! Note: G(D)=J(D)-K(D), with J(D) the Coulomb term and K(D) the exchange term. USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2) :: PCM,PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM CALL BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) CALL BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) PTEFM=PCM-PEM END SUBROUTINE BUILDTEFM_GHF SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER :: I,J,K,L,N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: CM,DM CM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN CM(I,J)=CM(I,J)+INTGRL*DM(I,J) ELSE CM(I,J)=CM(I,J)+INTGRL*DM(K,L) CM(K,L)=CM(K,L)+INTGRL*DM(I,J) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_relativistic SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) ! Computation and assembly of the Coulomb term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is CM(I,J) = sum over k,l of (IJ|KL) D(I,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; use matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: CM,DM INTEGER :: I,J,K,L,N DOUBLE PRECISION :: INTGRL CM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) CM(I,J) = CM(I,J) + INTGRL*DM(K,L) #include "forall.f90" #undef ACTION PCM=PACK(CM,NBAST) END SUBROUTINE BUILDCOULOMB_nonrelativistic SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM INTEGER :: I,J,K,L,N CHARACTER(2) :: CLASS DOUBLE COMPLEX :: INTGRL DOUBLE COMPLEX,DIMENSION(NBAST,NBAST) :: EM,DM EM=(0.D0,0.D0) DM=UNPACK(PDM,NBAST) IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) OPEN(LUNIT,form='UNFORMATTED') IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) OPEN(BIUNIT,form='UNFORMATTED') DO N=1,BINMBR IF (DIRECT) THEN ! the value of the bielectronic integral is computed "on the fly" IF (USEDISK) THEN READ(LUNIT)I,J,K,L ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L)) ELSE IF (SEMIDIRECT) THEN ! the value of the bielectronic integral is computed "on the fly", but using the precomputed values of the involved CGTO bielectronic integrals IF (USEDISK) THEN READ(LUNIT)I,J,K,L,CLASS ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) CLASS=BITYPE(N) END IF INTGRL=COULOMBVALUE(PHI(I),PHI(J),PHI(K),PHI(L),CLASS) ELSE IF (USEDISK) THEN ! the value of the bielectronic integral is read on disk READ(BIUNIT)I,J,K,L,INTGRL ELSE I=BILIST(N,1) ; J=BILIST(N,2) ; K=BILIST(N,3) ; L=BILIST(N,4) INTGRL=CBIVALUES(N) END IF END IF END IF IF ((I/=J).AND.(I==K).AND.(J==L)) THEN EM(I,J)=EM(I,J)+INTGRL*DM(J,I) ELSE EM(I,L)=EM(I,L)+INTGRL*DM(J,K) EM(K,J)=EM(K,J)+INTGRL*DM(L,I) END IF END DO IF ((DIRECT.OR.SEMIDIRECT).AND.USEDISK) CLOSE(LUNIT) IF ((.NOT.DIRECT.AND..NOT.SEMIDIRECT).AND.USEDISK) CLOSE(BIUNIT) PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_relativistic SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM INTEGER :: I,J,K,L,N DOUBLE PRECISION :: INTGRL EM=0.D0 DM=UNPACK(PDM,NBAST) #define ACTION(I,J,K,L) EM(I,K) = EM(I,K) + INTGRL*DM(L,J) #include "forall.f90" #undef ACTION PEM=PACK(EM,NBAST) END SUBROUTINE BUILDEXCHANGE_nonrelativistic SUBROUTINE BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the spin angular momentum operator S=-i/4\alpha^\alpha (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PSAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE PSAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE+.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L)) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L)) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (2) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO L=1,PHI(I)%nbrofcontractions(1) DO M=1,PHI(J)%nbrofcontractions(2) VALUE=VALUE-.5D0*PHI(J)%coefficients(2,M)*CONJG(PHI(I)%coefficients(1,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(2,M),PHI(I)%contractions(1,L))) END DO END DO DO L=1,PHI(I)%nbrofcontractions(2) DO M=1,PHI(J)%nbrofcontractions(1) VALUE=VALUE+.5D0*PHI(J)%coefficients(1,M)*CONJG(PHI(I)%coefficients(2,L)) & & *DCMPLX(0.D0,OVERLAPVALUE(PHI(J)%contractions(1,M),PHI(I)%contractions(2,L))) END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (3) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *.5D0*(-1.D0)**K*OVERLAPVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L)) END DO END DO END DO PSAMCM(I+(J-1)*J/2)=VALUE END DO END DO END SELECT END SUBROUTINE BUILDSAMCM SUBROUTINE BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the orbital angular momentum operator L=x^p (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT INTEGER :: I,J,K,L,M DOUBLE COMPLEX :: VALUE POAMCM=(0.D0,0.D0) SELECT CASE (COMPONENT) CASE (1) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,2) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,3)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (2) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,3) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),3,1)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO CASE (3) DO J=1,NBAS(1) DO I=1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO DO J=NBAS(1)+1,SUM(NBAS) DO I=NBAS(1)+1,J VALUE=(0.D0,0.D0) DO K=1,2 DO L=1,PHI(I)%nbrofcontractions(K) DO M=1,PHI(J)%nbrofcontractions(K) VALUE=VALUE-PHI(J)%coefficients(K,M)*CONJG(PHI(I)%coefficients(K,L)) & & *DCMPLX(0.D0,XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),2,1) & & -XDERIVVALUE(PHI(J)%contractions(K,M),PHI(I)%contractions(K,L),1,2)) END DO END DO END DO POAMCM(I+(J-1)*J/2)=VALUE END DO END DO END SELECT END SUBROUTINE BUILDOAMCM SUBROUTINE BUILDTAMCM(PTAMCM,PHI,NBAST,NBAS,COMPONENT) ! Computation and assembly of the matrix associated to one of the three components of the total angular momentum operator J=L+S (only the upper triangular part of the matrix is stored in packed format). USE basis_parameters ; USE integrals INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTAMCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS INTEGER :: COMPONENT DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2) :: PSAMCM,POAMCM CALL BUILDSAMCM(PSAMCM,PHI,NBAST,NBAS,COMPONENT) CALL BUILDOAMCM(POAMCM,PHI,NBAST,NBAS,COMPONENT) PTAMCM=PSAMCM+POAMCM END SUBROUTINE BUILDTAMCM +SUBROUTINE BUILDA(PA,NBAST,NBO,PHI,EIGVEC,EIG) + ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). + ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) + USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools + USE case_parameters ; USE data_parameters ; USE basis_parameters + INTEGER,INTENT(IN) :: NBAST,NBO + DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO),NBO*(NBAST-NBO)) :: A + DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO)*(NBO*(NBAST-NBO)+1)/2) :: PA + TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI + DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC + DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG + + DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM + INTEGER :: I,J,K,L,N,OI,OJ,VA,VB + DOUBLE PRECISION :: INTGRL + + A = 0 + + DO OI=1,NBO + DO VA=1,NBAST-NBO + A((OI-1)*(NBAST-NBO)+VA,(OI-1)*(NBAST-NBO)+VA)=(EIG(NBO+VA)-EIG(OI)) + END DO + END DO + +#define ACTION(I,J,K,L) \ + DO OI=1,NBO ;\ + DO VA=1,NBAST-NBO ;\ + DO OJ=1,NBO ;\ + DO VB=1,NBAST-NBO ;\ + A((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)=A((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)+INTGRL*(EIGVEC(J,OI)*EIGVEC(I,NBO+VA)*EIGVEC(K,OJ)*EIGVEC(L,NBO+VB) -EIGVEC(L,OI)*EIGVEC(I,NBO+VA)*EIGVEC(K,OJ)*EIGVEC(J,NBO+VB));\ + END DO ;\ + END DO ;\ + END DO ;\ + END DO + +#include "forall.f90" +#undef ACTION + + PA = PACK(A,(NBAST-NBO)*NBO) + +END SUBROUTINE BUILDA + +SUBROUTINE BUILDB(PB,NBAST,NBO,PHI,EIGVEC,EIG) + ! Computation and assembly of the exchange term in the Fock matrix associated to a given density matrix, using a list of the nonzero integrals (only the upper triangular part of the matrix is stored in packed format). + ! The formula is EM(I,K) = sum over J,L of (IJ|KL) D(L,J) + USE scf_parameters ; USE basis_parameters ; USE integrals ; USE matrix_tools + USE case_parameters ; USE data_parameters ; USE basis_parameters + INTEGER,INTENT(IN) :: NBAST,NBO + DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO),NBO*(NBAST-NBO)) :: B + DOUBLE PRECISION,DIMENSION(NBO*(NBAST-NBO)*(NBO*(NBAST-NBO)+1)/2) :: PB + TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI + DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC + DOUBLE PRECISION,DIMENSION(NBAST),INTENT(IN) :: EIG + + DOUBLE PRECISION,DIMENSION(NBAST,NBAST) :: EM,DM + INTEGER :: I,J,K,L,N,OI,OJ,VA,VB + DOUBLE PRECISION :: INTGRL + +#define ACTION(I,J,K,L) \ + DO OI=1,NBO ;\ + DO VA=1,NBAST-NBO ;\ + DO OJ=1,NBO ;\ + DO VB=1,NBAST-NBO ;\ + B((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)=B((OI-1)*(NBAST-NBO)+VA,(OJ-1)*(NBAST-NBO)+VB)+INTGRL*(EIGVEC(J,OI)*EIGVEC(I,NBO+VA)*EIGVEC(L,OJ)*EIGVEC(K,NBO+VB) -EIGVEC(L,OI)*EIGVEC(I,NBO+VA)*EIGVEC(J,OJ)*EIGVEC(K,NBO+VB));\ + END DO ;\ + END DO ;\ + END DO ;\ + END DO + +#include "forall.f90" +#undef ACTION + + PB = PACK(B,NBO*(NBAST-NBO)) +END SUBROUTINE BUILDB + MODULE matrices INTERFACE FORMDM SUBROUTINE FORMDM_relativistic(PDM,EIGVEC,NBAST,LOON,HOON) INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE COMPLEX,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC END SUBROUTINE SUBROUTINE FORMDM_nonrelativistic(PDM,EIGVEC,NBAST,LOON,HOON) INTEGER,INTENT(IN) :: NBAST,LOON,HOON DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PDM DOUBLE PRECISION,DIMENSION(NBAST,NBAST),INTENT(IN) :: EIGVEC END SUBROUTINE END INTERFACE INTERFACE BUILDOM SUBROUTINE BUILDOM_relativistic(POM,PHI,NBAST,NBAS) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS END SUBROUTINE SUBROUTINE BUILDOM_nonrelativistic(POM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDKPFM SUBROUTINE BUILDKPFM_nonrelativistic(PKPFM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PKPFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDOEFM SUBROUTINE BUILDOEFM_relativistic(POEFM,PHI,NBAST,NBAS) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI INTEGER,DIMENSION(2),INTENT(IN) :: NBAS END SUBROUTINE SUBROUTINE BUILDOEFM_nonrelativistic(POEFM,PHI,NBAST) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: POEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI END SUBROUTINE END INTERFACE INTERFACE BUILDTEFM SUBROUTINE BUILDTEFM_relativistic(PTEFM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDTEFM_RHF(PTEFM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PTEFM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE INTERFACE BUILDCOULOMB SUBROUTINE BUILDCOULOMB_relativistic(PCM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDCOULOMB_nonrelativistic(PCM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PCM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE INTERFACE BUILDEXCHANGE SUBROUTINE BUILDEXCHANGE_relativistic(PEM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(twospinor),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE COMPLEX,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE SUBROUTINE BUILDEXCHANGE_nonrelativistic(PEM,NBAST,PHI,PDM) USE basis_parameters INTEGER,INTENT(IN) :: NBAST DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(OUT) :: PEM TYPE(gaussianbasisfunction),DIMENSION(NBAST),INTENT(IN) :: PHI DOUBLE PRECISION,DIMENSION(NBAST*(NBAST+1)/2),INTENT(IN) :: PDM END SUBROUTINE END INTERFACE END MODULE