branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep><?php
function postimg($posturl,$path){
$obj = new CurlFile($path);
$obj->setMimeType("application/octet-stream");//必须指定文件类型,否则会默认为application/octet-stream,二进制流文件</span>
$post['file'] = $obj;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
//启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Chrome 42.0.2311.135');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_URL, $posturl);//上传类
$info= curl_exec($ch);
curl_close($ch);
return $info;
}
echo postimg('http://172.16.17.32:8888/upload/localhost','/home/yuhao/Pictures/Selection_007.png');
| 876700d134a70b75d50c6003de537a4728418150 | [
"PHP"
] | 1 | PHP | chenyuhao829/myblogapi | 4af4011a4aee6c20b35367580a4485fd89a02d3b | 8c9240afaedf891deddf82576dcd94b905733b45 |
refs/heads/master | <file_sep>/*
// Created by <NAME> on 23/01/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
@objc public enum ReachabilityState: Int{
case reachable = 1
case unreacahble
}
public typealias ReachabilityStateChange = (_ state: ReachabilityState) -> ()
@objc public class PVReachabilityService: NSObject{
public static let shared = PVReachabilityService()
private override init() {
super.init()
startNotify()
}
private var reachability = PVReachability()!
private let notifier = PVReachabilityNotifier()
private var cellularType : String? = nil
@objc public static var isNetworkAvailable: Bool{
return PVReachabilityService.shared.reachability.connection != .none
}
@objc public static var isWIFI: Bool{
return PVReachabilityService.shared.reachability.connection == .wifi
}
@objc public static var isCellular: Bool{
return PVReachabilityService.shared.reachability.connection == .cellular
}
@objc public static var networkString: String{
return PVReachabilityService.shared.stringFromNetWork()
}
private func stringFromNetWork() -> String{
if PVReachabilityService.isNetworkAvailable == false{
return ""
}
if PVReachabilityService.isCellular{
if self.cellularType == nil{
self.cellularType = reachability.getCellularType().string
}
if let type = self.cellularType{
return type
}
}
return "wifi"
}
private func startNotify(){
notifier.notify = { state in
self.cellularType = nil
switch state {
case .reachable:
if let reach = PVReachability(){
self.reachability = reach
}
case .unreacahble:
break
}
}
}
}
@objc public class PVReachabilityNotifier: NSObject{
private var reachability = PVReachability()!
public var notify: ReachabilityStateChange?
public override init() {
super.init()
startNotify()
}
@objc private func startNotify(){
reachability.whenReachable = {[weak self] _ in
self?.notify?(.reachable)
}
reachability.whenUnreachable = { [weak self] _ in
self?.notify?(.unreacahble)
}
do {
try reachability.startNotifier()
} catch {}
}
}
<file_sep>//
// ViewController.swift
// PVReachability
//
// Created by <NAME> on 22/01/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let notifier = PVReachabilityNotifier()
override func viewDidLoad() {
super.viewDidLoad()
notifier.notify = { state in
switch state {
case .reachable:
print(PVReachabilityService.isCellular)
print(PVReachabilityService.isWIFI)
print(PVReachabilityService.networkString)
print(PVReachabilityService.isNetworkAvailable)
case .unreacahble:
print("Network unreachable")
}
}
}
}
<file_sep>/*
// Created by <NAME> on 23/01/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import CoreTelephony
enum NetworkType {
case unknown
case noConnection
case wifi
case wwan2g
case wwan3g
case wwan4g
case unknownTechnology(name: String)
var trackingId: String {
switch self {
case .unknown: return "Unknown"
case .noConnection: return "No Connection"
case .wifi: return "Wifi"
case .wwan2g: return "2G"
case .wwan3g: return "3G"
case .wwan4g: return "4G"
case .unknownTechnology(let name): return "Unknown Technology: \"\(name)\""
}
}
}
enum CellularType{
case wwan2g
case wwan3g
case wwan4g
case unknownTechnology(name: String)
case unknown
var string: String{
switch self {
case .wwan2g: return "2g"
case .wwan3g: return "3g"
case .wwan4g: return "4g"
case .unknownTechnology(_): return "unknown"
case .unknown: return "unknown"
}
}
}
extension PVReachability{
func getCellularType() -> CellularType{
//print(CTTelephonyNetworkInfo().serviceCurrentRadioAccessTechnology ?? "nill")
guard let currentRadioAccessTechnology = CTTelephonyNetworkInfo().currentRadioAccessTechnology else { return .unknown }
switch currentRadioAccessTechnology {
case CTRadioAccessTechnologyGPRS,
CTRadioAccessTechnologyEdge,
CTRadioAccessTechnologyCDMA1x:
return .wwan2g
case CTRadioAccessTechnologyWCDMA,
CTRadioAccessTechnologyHSDPA,
CTRadioAccessTechnologyHSUPA,
CTRadioAccessTechnologyCDMAEVDORev0,
CTRadioAccessTechnologyCDMAEVDORevA,
CTRadioAccessTechnologyCDMAEVDORevB,
CTRadioAccessTechnologyeHRPD:
return .wwan3g
case CTRadioAccessTechnologyLTE:
return .wwan4g
default:
return .unknownTechnology(name: currentRadioAccessTechnology)
}
}
}
<file_sep>Pod::Spec.new do |s|
s.name = 'PVReachability'
s.version = '0.1.3'
s.summary = 'Reachability Helper with network names & block notifier'
s.description = <<-DESC
• Now you can get network state change as block
let notifier = PVReachabilityNotifier()
notifier.notify = { state in
switch state {
case .reachable:
print(PVReachabilityService.isCellular)
print(PVReachabilityService.isWIFI)
print(PVReachabilityService.networkString)
print(PVReachabilityService.isNetworkAvailable)
case .unreacahble:
print("Network unreachable")
}
}
DESC
s.homepage = 'https://github.com/chandrasekhar-swift/PVReachability'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Chandra' => '<EMAIL>' }
s.source = { :git => 'https://github.com/chandrasekhar-swift/PVReachability.git', :tag => s.version.to_s }
s.ios.deployment_target = '10.0'
s.source_files = 'PVReachability/cls/*.swift'
end
| b70e0c92a13684ef5615d8120fb5268bd517195e | [
"Swift",
"Ruby"
] | 4 | Swift | chandrasekhar-swift/PVReachability | 9a83bb0a2ea6cefff6cceb5fb89d4e8c35adf859 | dab47f42f4f43fb7381eacc1afdea584deb2cf13 |
refs/heads/master | <file_sep>
module.exports = function(grunt) {
"use strict";
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON("package.json"),
banner: "",
// Task configuration.
concat: {
options: {
banner: "<%= banner %>",
stripBanners: true
},
dist: {
files: [
{
src: ["src/<%= pkg.name %>.js"],
dest: "dist/<%= pkg.name %>.js"
},
{
src: ["src/<%= pkg.name %>.js"],
dest: "dist/<%= pkg.name %>.<%= pkg.version %>.js"
}
]
},
},
uglify: {
options: {
banner: "<%= banner %>"
},
dist: {
files: [
{
src: "<%= concat.dist.files[0].dest %>",
dest: "dist/<%= pkg.name %>.min.js"
},
{
src: "<%= concat.dist.files[0].dest %>",
dest: "dist/<%= pkg.name %>.<%= pkg.version %>.min.js"
}
]
},
},
/*mocha: {
test: {
options: {
run: true,
debug: true,
reporter: "Spec",
},
src: [ "test/index.html" ]
}
},*/
mochaTest: {
unit: {
options: {
reporter: "spec"
},
src: ["test/*.js"]
}
},
// start - code coverage settings
env: {
coverage: {
APP_DIR_FOR_CODE_COVERAGE: "../test/coverage/instrument/app/"
}
},
clean: {
coverage: {
src: ["test/coverage/"]
}
},
copy: {
views: {
expand: true,
flatten: true,
src: ["app/views/*"],
dest: "test/coverage/instrument/app/views"
}
},
instrument: {
files: "app/*.js",
options: {
lazy: true,
basePath: "test/coverage/instrument/"
}
},
storeCoverage: {
options: {
dir: "test/coverage/reports"
}
},
makeReport: {
src: "test/coverage/reports/**/*.json",
options: {
type: "lcov",
dir: "test/coverage/reports",
print: "detail"
}
},
// end - code coverage settings
coveralls: {
options: {
// dont fail if coveralls fails
force: true
},
main_target: {
src: "reports/lcov/lcov.info"
}
},
jshint: {
gruntfile: {
options: {
jshintrc: ".jshintrc"
},
src: "Gruntfile.js"
},
src: {
options: {
jshintrc: "src/.jshintrc"
},
src: ["src/**/*.js"]
},
test: {
options: {
jshintrc: "test/.jshintrc"
},
src: ["test/**/*.js"]
},
},
watch: {
gruntfile: {
files: "<%= jshint.gruntfile.src %>",
tasks: ["jshint:gruntfile"]
},
src: {
files: "<%= jshint.src.src %>",
tasks: ["jshint:src", "qunit"]
},
test: {
files: "<%= jshint.test.src %>",
tasks: ["jshint:test", "qunit"]
},
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-coveralls");
//grunt.loadNpmTasks("grunt-mocha");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.loadNpmTasks("grunt-istanbul");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-copy");
grunt.loadNpmTasks("grunt-nodemon");
grunt.loadNpmTasks("grunt-concurrent");
grunt.loadNpmTasks("grunt-env");
// Default task.
grunt.registerTask("test",["jshint", "mochaTest:unit"]);
grunt.registerTask("default", ["test", "concat", "uglify"]);
grunt.registerTask("coverage", ["jshint", "copy:views", "env:coverage", "instrument", "mochaTest:unit", "storeCoverage", "makeReport"]);
};
<file_sep>Code-Coverage-Mocha
===================
https://github.com/eppz/eppz-js
https://www.npmjs.org/package/grunt-mocha-runner
http://blog.codeship.io/2014/01/22/testing-frontend-javascript-code-using-mocha-chai-and-sinon.html
http://chaijs.com/
https://github.com/mmoulton/grunt-mocha-cov (uses blanket)
https://www.npmjs.org/package/grunt-istanbul
##Assertion
https://github.com/visionmedia/should.js 1520/153
https://github.com/chaijs/chai 1045/123
<file_sep>var expect = chai.expect;
describe("Simple", function() {
describe("Add", function() {
it("should be a number", function() {
expect(typeof $.simpleAdd(1,2)).to.equal("number");
});
it("should add number", function() {
expect($.simpleAdd(1,2)).to.equal(3);
});
});
}); | 86925744537dfbc8394b362e1f8379ccea2af6d6 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | thorst/Code-Coverage-Mocha | a349328b3099a4b979442ff4aeb0cc10d622729b | f758fce8433468b4296e0cf99b2a15d54ab09346 |
refs/heads/master | <repo_name>abberadhi/meeting-scheduler<file_sep>/server/src/controllers/meetings.js
var express = require('express');
var router = express.Router();
var graph = require('../models/graph');
var tokens = require('../models/tokens.js');
var meeting = require('../models/database/meeting.js');
var fs = require('fs');
/* GET /meetings */
router.get('/',
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
req.flash('error_msg', {
message: 'Access forbidden: You have to log in first!'
});
res.redirect('/')
} else {
let params = {
active: { meetings: true }
};
// Get the access token
var accessToken;
try {
accessToken = await tokens.getAccessToken(req);
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
if (accessToken && accessToken.length > 0) {
try {
// Get the events
var events = await graph.getEvents(accessToken);
params.events = events.value;
} catch (err) {
console.log(err);
req.flash('error_msg', {
message: 'Could not fetch events',
debug: JSON.stringify(err)
});
}
} else {
req.flash('error_msg', 'Could not get an access token');
console.log("could ot get access token");
}
let finalMeetings = await meeting.getFinalMeetings(req.user.profile.oid);
params.finalMeetings = finalMeetings;
res.render('meetings', params);
}
}
);
router.post('/create',
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
res.locals.message = 'Access forbidden: You have to log in first!';
res.redirect('/')
}
// Get the access token
var accessToken;
try {
accessToken = await tokens.getAccessToken(req);
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
await meeting.createMeeting(
req.body.title,
req.body.description,
req.body.location,
req.body.meetingDate,
req.body.meetingTimeStart,
req.body.meetingTimeEnd,
req.user.profile.oid,
req.body.attendee,
req
);
console.log([ req.body.meetingDate,
req.body.meetingTimeStart,
req.body.meetingTimeEnd]);
res.redirect('/meetings')
}
);
/* GET /meetings/create */
router.get('/create',
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
res.locals.message = 'Access forbidden: You have to log in first!';
res.redirect('/')
} else {
let params = {
active: { meetings: true }
};
// Get the access token
var accessToken;
try {
accessToken = await tokens.getAccessToken(req);
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
if (accessToken && accessToken.length > 0) {
try {
// Get the events
var events = await graph.getEvents(accessToken);
params.events = events.value;
} catch (err) {
console.log(err);
req.flash('error_msg', {
message: 'Could not fetch events',
debug: JSON.stringify(err)
});
}
} else {
req.flash('error_msg', 'Could not get an access token');
}
res.render('create', params);
}
}
);
/* GET /meetings/view:id */
router.get('/view/:id',
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
res.locals.message = 'Access forbidden: You have to log in first!';
res.redirect('/')
} else {
let params = {
active: { meetings: true }
};
if (!req.params.id) {
res.redirect('/meetings');
}
// Get the access token
var accessToken;
let finalMeetings;
try {
accessToken = await tokens.getAccessToken(req);
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
if (accessToken && accessToken.length > 0) {
try {
// get meetings
finalMeetings = {
meetings: await meeting.getFinalMeetings(req.user.profile.oid),
events: await graph.getEvents(accessToken)
}
} catch (err) {
console.log(err);
req.flash('error_msg', {
message: 'Could not fetch events',
debug: JSON.stringify(err)
});
}
} else {
req.flash('error_msg', 'Could not get an access token');
}
// Check if user belongs to meeting and if meeting exist
if (!await meeting.isAllowedToMeeting(req.user.profile.oid, req.params.id)) {
req.flash('error_msg', {
message: `Meeting doesn't exist or not available for you.`,
});
res.redirect('/meetings');
}
params.finalMeetings = finalMeetings;
// set user to seen
await meeting.setSeenMeeting(req.user.profile.oid, req.params.id);
params.meeting = await meeting.getMeetingById(req.params.id);
// attach profile image to user object if it exists
for (let i = 0; i < params.meeting.attendees.length; i++) {
// check if user has profile picture
await fs.access(`../server/src/public/avatars/${params.meeting.attendees[i].id}.png`, fs.F_OK, (err) => {
if (!err) {
// attach location on user object
try {
params.meeting.attendees[i].picture = `avatars/${params.meeting.attendees[i].id}.png`;
} catch (error) {
console.log("Error has occured: ", error);
}
}
})
}
res.render('viewMeeting', params);
}
}
);
/* GET /meetings/view:id */
router.post('/view/:id',
async function(req, res) {
if (!req.isAuthenticated()) {
// Redirect unauthenticated requests to home page
res.locals.message = 'Access forbidden: You have to log in first!';
res.redirect('/')
} else {
let params = {
active: { meetings: true }
};
if (!req.params.id) {
res.redirect('/meetings');
}
// Get the access token
var accessToken;
try {
accessToken = await tokens.getAccessToken(req);
} catch (err) {
req.flash('error_msg', {
message: 'Could not get access token. Try signing out and signing in again.',
debug: JSON.stringify(err)
});
}
if (accessToken && accessToken.length > 0) {
try {
// Get the events
var events = await graph.getEvents(accessToken);
params.events = events.value;
console.log("params.events", params.events);
} catch (err) {
console.log(err);
req.flash('error_msg', {
message: 'Could not fetch events',
debug: JSON.stringify(err)
});
}
} else {
req.flash('error_msg', 'Could not get an access token');
}
// Check if user belongs to meeting and if meeting exist
if (!await meeting.isAllowedToMeeting(req.user.profile.oid, req.params.id)) {
req.flash('error_msg', {
message: `Meeting doesn't exist or not available for you.`,
});
res.redirect('/meetings');
}
// user voting
if (req.body.vote) {
await meeting.vote(req.body.time, req.user.profile.oid, req.params.id)
}
// user addming new date
if (req.body.addDate) {
console.log("input time")
console.log([req.body.meetingDate,
req.body.meetingTimeStart,
req.body.meetingTimeEnd]);
if (req.body.meetingDate && req.body.meetingTimeStart && req.body.meetingTimeEnd) {
await meeting.addnewDate(
req.user.profile.oid,
req.params.id,
req.body.meetingDate,
req.body.meetingTimeStart,
req.body.meetingTimeEnd
);
} else {
req.flash('error_msg', {
message: "Something went wrong, please try again"
});
}
}
// user leaving meeting
if (req.body.leaveMeeting) {
await meeting.leaveMeeting(
req.params.id,
req.user.profile.oid
);
req.flash('success_msg', {
message: "You left the meeting."
});
res.redirect(`/meetings`);
}
/**
* From here on it's organizer only
*/
// checking if requested by organizer
let currMeeting = await meeting.getMeetingById(req.params.id);
if (req.user.profile.oid !== currMeeting.details[0].organizer_id) {
res.redirect(`/meetings/view/${req.params.id}`);
return;
}
// organizer setting date as final
if (req.body.pollFinal) {
await meeting.pollFinal(req.body.pollFinal, req.params.id);
}
// organizer adding a new member
if (req.body.addUser) {
let errorMessage =
await meeting.addUserToMeeting(
req.body.email,
req.user.profile.oid,
req.params.id,
req);
// attach error message
if (errorMessage) {
req.flash('error_msg', {
message: errorMessage
});
}
}
// organizer removing meeting
if (req.body.removeMeeting) {
await meeting.removeMeetingById(req.params.id);
req.flash('success_msg', {
message: "Meeting removed successfully."
});
res.redirect(`/meetings`);
}
res.redirect(`/meetings/view/${req.params.id}`);
}
}
);
module.exports = router;<file_sep>/server/src/models/database/meeting.js
require('dotenv').config();
const user = require('./user');
const mysql = require("promise-mysql");
let db;
(async function() {
db = await mysql.createConnection({
"host": "localhost",
"user": process.env.DB_USER,
"password": process.env.DB_PASS,
"database": "meetx",
"dateStrings": "date",
"multipleStatements": true
});
process.on("exit", () => {
db.end();
});
})();
module.exports = {
"createMeeting": async (
title,
description,
location,
meetingDate,
meetingTimeStart,
meetingTimeEnd,
organizer,
attendees,
req
) => {
// methods inserts meeting and everything relate into the database
// add meeting to meeting table and get the ID
await db.query(`
INSERT INTO meeting (
title,
description,
organizer_id,
location,
creation_date)
VALUES (
?,
?,
"${organizer}",
?,
UNIX_TIMESTAMP(NOW()));
SELECT LAST_INSERT_ID()`, [
title,
description,
location
]).then(async (res) => {
req.flash('success_msg', {
message: `Meeting created successfully`
});
// get user timezone
let tz = await db.query(`SELECT timezone FROM users WHERE id = "${organizer}";`);
console.log(tz);
tz = tz[0].timezone;
let meetingID = res[0].insertId;
// add attendees to meetingAttendees table
// check if attandees is array, if not make it an array
if (!Array.isArray(attendees)) {
attendees = [attendees];
}
for (let i = 0; i < attendees.length; i++) {
// check if user is registered
// get the user;
await db.query(`SELECT * FROM users WHERE email = ?;`, [attendees[i]])
.then(async (fetchedUser) => {
if (fetchedUser.length > 0) {
// Only if user didn't add themselves.
if (fetchedUser[0].id !== organizer) {
await db.query(`
INSERT INTO meetingAttendees
(meeting_id, user_id, seen)
VALUES
(${meetingID}, "${fetchedUser[0].id}", 0)`)
}
} else {
console.log("User Does not exist: ", attendees[i]);
req.flash('error_msg', {
message: `Warning: Could not find user ${attendees[i]}, therefore ignored.`
});
}
});
}
// add organizer as attendee
await db.query(`
INSERT INTO meetingAttendees
(meeting_id, user_id, seen)
VALUES
(${meetingID}, "${organizer}", 1)`);
// add the suggested times
// if array = multiple dates
if (!Array.isArray(meetingDate)) {
let start = (new Date(`${meetingDate} ${meetingTimeStart}Z`).getTime() + ((-(tz))*60*60*1000)) / 1000;
let end = (new Date(`${meetingDate} ${meetingTimeEnd}Z`).getTime() + ((-(tz))*60*60*1000)) / 1000;
await db.query(`
INSERT INTO pollChoice
(meeting_id, added_by, meeting_date_start, meeting_date_end, final)
VALUES
(?, "${organizer}", ${start}, ${end}, ?);
SELECT LAST_INSERT_ID();`, [meetingID, 1]).then(async (res) => {
await db.query(`INSERT INTO pollVote
(pollChoice_id, user_id)
VALUES
(${res[0].insertId}, "${organizer}");`);
});
} else {
// insert every date choice to the database
for (let i = 0; i < meetingDate.length; i++) {
let start;
let end;
try {
start = (new Date(`${meetingDate[i]} ${meetingTimeStart[i]}Z`).getTime() + ((-(tz))*60*60*1000)) / 1000;
end = (new Date(`${meetingDate[i]} ${meetingTimeEnd[i]}Z`).getTime() + ((-(tz))*60*60*1000)) / 1000;
} catch (err) {
console.log("Error! ", err);
continue;
}
await db.query(`
INSERT INTO pollChoice
(meeting_id, added_by, meeting_date_start, meeting_date_end, final)
VALUES
(?, "${organizer}", ${start}, ${end}, ?);
SELECT LAST_INSERT_ID();`, [meetingID, 0]).then(async (res) => {
await db.query(`INSERT INTO pollVote
(pollChoice_id, user_id)
VALUES
(${res[0].insertId}, "${organizer}");`);
});
}
}
}).catch((err) => {
req.flash('error_msg', {
message: `ERROR: Could not create meeting.: ${err}`
});
});
},
"getFinalMeetings": async (id) => {
// let sqlNew = ``;
// let sqlFinal = ``;
// let sqlNotDetermined = ``;
// let res = {
// new: await db.query(sqlNew),
// final: null,
// notDetermined: null
// }
let res = await db.query(`
SELECT DISTINCT
m.id,
m.title,
m.location,
a.user_id,
(SELECT meeting_date_start FROM pollChoice WHERE final = 1 AND meeting_id = m.id) as meeting_date_start,
(SELECT meeting_date_end FROM pollChoice WHERE final = 1 AND meeting_id = m.id) as meeting_date_end,
a.seen,
(SELECT COUNT(*) FROM meetingAttendees WHERE meeting_id = m.id) as attendeesCounter,
(SELECT MAX((pollChoice.meeting_date_end - UNIX_TIMESTAMP(NOW())) > 0) FROM pollChoice WHERE pollChoice.meeting_id = m.id) as active,
(SELECT COUNT(*) FROM pollVote
LEFT JOIN pollChoice
ON pollVote.pollChoice_id = pollChoice.id
WHERE pollVote.user_id = "${id}" AND pollChoice.meeting_id = m.id
) as voted
FROM meeting AS m
INNER JOIN meetingAttendees AS a
ON m.id = a.meeting_id
INNER JOIN pollChoice AS pc
ON pc.meeting_id = m.id
WHERE a.user_id = "${id}"
GROUP BY m.id, a.seen, pc.meeting_date_end, pc.meeting_date_start;
`);
return res;
},
"isAllowedToMeeting": async (u_id, m_id) => {
let sql = `
SELECT (COUNT(*)>0) as allowed
FROM meetingAttendees
WHERE meeting_id = ? AND
user_id = "${u_id}";
`;
let res = await db.query(sql, [m_id]);
return res[0].allowed;
},
"setSeenMeeting": async (u_id, m_id) => {
await db.query(`
UPDATE meetingAttendees SET seen = 1
WHERE meeting_id = ? AND
user_id = "${u_id}"
`, [m_id]);
},
"getMeetingById": async (m_id) => {
// get meeting details
let meeting = {
details: await db.query(`
SELECT * FROM meeting WHERE id = ?`, [m_id]), // details about meeting
attendees: await db.query(`
SELECT * FROM meetingAttendees AS a
INNER JOIN users AS u
ON a.user_id = u.id
WHERE a.meeting_id = ?;`, [m_id]), // details about attendees
pollChoices: await (async function () {
// get all pollChoices
let pollChoices_db = await db.query(`
SELECT * from pollChoice WHERE meeting_id = ?;`, [m_id]);
// loop through pollChoices array and attach names of who voted
for (let i = 0; i < pollChoices_db.length; i++) {
pollChoices_db[i].votes = await db.query(`
SELECT users.displayName FROM users
INNER JOIN pollVote
ON users.id = pollVote.user_id WHERE pollVote.pollChoice_id = ?;
`, [pollChoices_db[i].id]);
}
return pollChoices_db;
})() // details about prefered time and date & who's voted
};
return meeting;
},
"vote": async (votes, user, meet_id) => {
// remove pollvotes of user on meeting
await db.query(`
DELETE e FROM pollVote e
INNER JOIN pollChoice c
ON e.pollChoice_id = c.id
WHERE c.meeting_id = ? AND
e.user_id = "${user}";
`, meet_id);
if (!votes) return;
// if votes is not an array, make it an array
if (!Array.isArray(votes)) {
votes = [votes];
}
// insert new votes
for (let i = 0; i < votes.length; i++) {
// check if meeting has that pollChoice
await db.query(`SELECT * FROM pollChoice
WHERE id = ? AND meeting_id = ?`, [votes[i], meet_id]).then(async (res) => {
if (res.length > 0) {
// insert new vote
await db.query(`
INSERT INTO pollVote
(pollChoice_id, user_id)
VALUES
(?, "${user}")`, [votes[i]]);
}
})
}
},
"addUserToMeeting": async (userEmail, requestedBy, meetingId, req) => {
// check if user already exist
let err = false;
// get users id
let usr = await db.query(`
SELECT id FROM users WHERE email = ?;
`, [userEmail]);
// if user exists
if (usr.length > 0) {
// check if user already added to the meeting
await db.query(`
SELECT * FROM meetingAttendees WHERE user_id = "${usr[0].id}"
`).then(async (res) => {
if (res.length > 0) {
err = `Warning! User already exists.`;
} else {
// insert new user into table
await db.query(`
INSERT INTO meetingAttendees
(meeting_id, user_id, seen)
VALUES
(?, "${usr[0].id}", 0)
`, [meetingId]);
}
});
} else {
err = `Warning: Could not find user ${userEmail}, therefore ignored.`;
}
return err;
},
"removeMeetingById": async (m_id) => {
// will remove a meeting and everything associated
await db.query(`
START TRANSACTION;
DELETE pollVote
FROM pollVote
INNER JOIN pollChoice
ON pollChoice.id = pollVote.pollChoice_id
WHERE pollChoice.meeting_id = ?;
DELETE FROM pollChoice WHERE meeting_id = ?;
DELETE FROM meetingAttendees WHERE meeting_id = ?;
DELETE FROM meeting WHERE id = ?;
COMMIT;
`, [m_id, m_id, m_id, m_id]);
},
"leaveMeeting": async (m_id, u_id) => {
await db.query(`
DELETE pollVote
FROM pollVote
INNER JOIN pollChoice
ON pollChoice.id = pollVote.pollChoice_id
WHERE
pollChoice.meeting_id = ? AND
pollVote.user_id = "${u_id}";
DELETE FROM meetingAttendees
WHERE
meeting_id = ? AND
user_id = "${u_id}"
;
`, [m_id, m_id]);
},
"pollFinal": async (pollChoice, m_id) => {
// check if pollchoice exists in meeting id
await db.query(`
SELECT * from pollChoice WHERE
id = ? AND
meeting_id = ?;
`,
[pollChoice, m_id]).then(async (res) => {
if (res.length > 0) {
await db.query(`
UPDATE pollChoice SET
final = 1
WHERE id = ? AND
meeting_id = ?;
`, [pollChoice, m_id])
}
});
},
"addnewDate": async (u_id, m_id, m_date, m_start, m_end) => {
// get user timezone
let tz = await db.query(`SELECT timezone FROM users WHERE id = "${u_id}";`);
console.log(tz);
tz = tz[0].timezone;
let start = (new Date(`${m_date} ${m_start}Z`).getTime() + ((-(tz))*60*60*1000)) / 1000;
let end = (new Date(`${m_date} ${m_end}Z`).getTime() + ((-(tz))*60*60*1000)) / 1000;
console.log(start);
console.log(end);
await db.query(`
INSERT INTO pollChoice
(meeting_id, added_by, meeting_date_start, meeting_date_end, final)
VALUES
(?, "${u_id}", ?, ?, 0);
SELECT LAST_INSERT_ID()
`, [m_id, start, end]).then(async (res) => {
await db.query(`INSERT INTO pollVote
(pollChoice_id, user_id)
VALUES
(${res[0].insertId}, "${u_id}")`);
});
}
}
<file_sep>/server/src/models/graph.js
var graph = require('@microsoft/microsoft-graph-client');
const fs = require('fs');
require('isomorphic-fetch');
module.exports = {
getUserDetails: async function(accessToken) {
// await this.getUserPicture(accessToken);
const client = getAuthenticatedClient(accessToken);
// const user = await client.api('/me').get();
const batch = {
"requests": [
{
"url": "/me",
"method": "GET",
"id": "1",
"headers": {
"Content-Type": "application/json"
}
},
{
"url": "/me/photos/48x48/$value",
"method": "GET",
"id": "2",
"headers": {
"Authorization": accessToken
}
}
]
}
let result = await client.api('/$batch')
.version('beta')
.post(batch);
return result;
},
getEvents: async function(accessToken) {
const client = getAuthenticatedClient(accessToken);
const events = await client
.api('/me/events')
.select('subject,organizer,start,end')
.orderby('createdDateTime DESC')
.top(20)
.get();
return events;
}
};
function getAuthenticatedClient(accessToken) {
// Initialize Graph client
const client = graph.Client.init({
// Use the provided access token to authenticate
// requests
authProvider: (done) => {
done(null, accessToken);
}
});
return client;
}<file_sep>/dbsetup/setuptables.sql
DROP TABLE IF EXISTS pollVote;
DROP TABLE IF EXISTS pollChoice;
DROP TABLE IF EXISTS meetingAttendees;
DROP TABLE IF EXISTS meeting;
DROP TABLE IF EXISTS rawUsers;
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id VARCHAR(255),
displayName VARCHAR (255),
email VARCHAR (255),
created_at int(11),
timezone int DEFAULT 2,
PRIMARY KEY (id)
);
CREATE TABLE rawUsers (
id VARCHAR(255),
stringifiedData LONGTEXT
);
CREATE TABLE meeting (
id int NOT NULL AUTO_INCREMENT,
title VARCHAR(255),
description TEXT,
organizer_id VARCHAR(255),
location VARCHAR(255),
creation_date int(11),
negotiable TINYINT(1),
FOREIGN KEY(organizer_id)
REFERENCES users(id),
PRIMARY KEY (id)
);
CREATE TABLE meetingAttendees (
meeting_id int,
user_id VARCHAR(255),
seen TINYINT(1),
FOREIGN KEY(user_id)
REFERENCES users(id),
FOREIGN KEY(meeting_id)
REFERENCES meeting(id)
);
CREATE TABLE pollChoice (
id int NOT NULL AUTO_INCREMENT,
meeting_id int,
added_by VARCHAR(255),
meeting_date_start int(11),
meeting_date_end int(11),
final TINYINT(1),
FOREIGN KEY(added_by)
REFERENCES users(id),
FOREIGN KEY(meeting_id)
REFERENCES meeting(id),
PRIMARY KEY (id)
);
CREATE TABLE pollVote (
pollChoice_id int,
user_id VARCHAR(255),
FOREIGN KEY(user_id)
REFERENCES users(id),
FOREIGN KEY(pollChoice_id)
REFERENCES pollChoice(id)
);<file_sep>/server/src/config/config.js
/**
* Configuration file for the database
*/
// module.exports = {
// port: 8081,
// db: {
// database: process.env.DB_NAME || 'meetingscheduler',
// user: process.env.DB_USER ||
// password:
// options: {
// }
// }
// }<file_sep>/server/src/models/auth.js
var passport = require('passport');
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
var graph = require('./graph');
var fs = require('fs');
const resizeImg = require('resize-img');
const userModel = require('./database/user');
const { json } = require('body-parser');
// Configure passport
var users = {};
// Passport calls serializeUser and deserializeUser to
// manage users
passport.serializeUser(async function(user, done) {
users[user.profile.oid] = user;
// await userModel.updateRawUser(user.profile.oid, JSON.stringify(user));
done(null, user.profile.oid);
// done(null, user.profile.oid);
});
passport.deserializeUser(async function(id, done) {
// let res = await userModel.getRawUser(id);
// done(null, JSON.parse(res.stringifiedData));
done(null, users[id]);
});
// <ConfigureOAuth2Snippet>
// Configure simple-oauth2
const oauth2 = require('simple-oauth2').create({
client: {
id: process.env.OAUTH_APP_ID,
secret: process.env.OAUTH_APP_PASSWORD
},
auth: {
tokenHost: process.env.OAUTH_AUTHORITY,
authorizePath: process.env.OAUTH_AUTHORIZE_ENDPOINT,
tokenPath: process.env.OAUTH_TOKEN_ENDPOINT
}
});
// Callback function called once the sign-in is complete
// and an access token has been obtained
// <SignInCompleteSnippet>
async function signInComplete(iss, sub, profile, accessToken, refreshToken, params, done) {
if (!profile.oid) {
return done(new Error("No OID found in user profile."));
}
try{
const data = await graph.getUserDetails(accessToken);
const raw = {
"profile": profile,
"oauthToken": accessToken
}
const user = data['responses'][0]['body'];
// If image exists, save it.
const image = data['responses'][1];
if (image.status == 200) {
savePicture(profile.oid, image['body'])
}
if (user) {
// Add properties to profile
profile['email'] = user.mail ? user.mail : user.userPrincipalName;
// add user to database if they don't exist
if (!await userModel.userExists(profile.oid)) {
await userModel.registerUser(profile.oid, profile.displayName, profile['email']);
}
}
} catch (err) {
return done(err);
}
// Create a simple-oauth2 token from raw tokens
let oauthToken = oauth2.accessToken.create(params);
// Save the profile and tokens in user storage
users[profile.oid] = { profile, oauthToken };
return done(null, users[profile.oid]);
}
// Configure OIDC strategy
passport.use(new OIDCStrategy(
{
identityMetadata: `${process.env.OAUTH_AUTHORITY}${process.env.OAUTH_ID_METADATA}`,
clientID: process.env.OAUTH_APP_ID,
responseType: 'code id_token',
responseMode: 'form_post',
redirectUrl: process.env.OAUTH_REDIRECT_URI,
allowHttpForRedirectUrl: true,
clientSecret: process.env.OAUTH_APP_PASSWORD,
validateIssuer: false,
passReqToCallback: false,
scope: process.env.OAUTH_SCOPES.split(' ')
},
signInComplete
));
// gets id and image in base64 format
// resizes image and saves id with user id as name
let savePicture = async (id, base64Image) => {
const imageBufferData = Buffer.from(base64Image, `base64`)
const image = await resizeImg(imageBufferData, {
width: 64,
height: 64
});
fs.writeFile(`../server/src/public/avatars/${id}.png`, image, function(err) {
console.log('File created');
console.log(err);
});
};
<file_sep>/server/src/models/database/user.js
require('dotenv').config();
const mysql = require("promise-mysql");
let db;
(async function() {
db = await mysql.createConnection({
"host": "localhost",
"user": process.env.DB_USER,
"password": process.env.DB_PASS,
"database": "meetx",
"multipleStatements": true
});
process.on("exit", () => {
db.end();
});
})();
module.exports = {
"userExists": async (id) => {
let sql = `
SELECT * FROM users WHERE id = ?`;
let res = await db.query(sql, [id]);
return res.length > 0;
},
"registerUser": async (id, displayName, email) => {
let sql = `
INSERT INTO users (id, displayName, email, created_at, timezone)
VALUES (?, ?, ?, UNIX_TIMESTAMP(NOW()), +2)`;
// add user
await db.query(sql, [id, displayName, email]);
let sql2 = `
INSERT INTO rawUsers (id) VALUES (?)`;
// create empty row for user
await db.query(sql2, [id]);
},
"getUserByEmail": async (email) => {
let sql = `
SELECT * FROM users WHERE email = ?`;
let res = await db.query(sql, [email]);
return res[0];
},
"getUserById": async (id) => {
let sql = `
SELECT * FROM users WHERE id = ?`;
let res = await db.query(sql, [id]);
return res;
},
"updateRawUser": async (id, stringifiedData) => {
let sql = `
UPDATE rawUsers
SET
stringifiedData = ?
WHERE
id = ?;`;
// add user
await db.query(sql, [stringifiedData, id]);
},
"getRawUser": async (id) => {
let sql = `
SELECT * from rawUsers WHERE id = ?`;
// get raw user data
let res = await db.query(sql, [id]);
return res[0];
},
"getTimezoneById": async(u_id) => {
let res = await db.query(`
SELECT timezone from users
WHERE id = "${u_id}";
`);
return res[0].timezone;
},
"setTimezone": async (timezone, user) => {
await db.query(`
UPDATE users
SET timezone = ?
WHERE id = "${user}";`, [timezone]);
}
}
<file_sep>/server/src/app.js
require('dotenv').config();
const express = require('express');
var passport = require('passport');
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
const app = require('./middlewares/mw')(express());
require('./models/auth');
var authRouter = require('./controllers/auth');
var indexRouter = require('./controllers/index');
var meetingsRouter = require('./controllers/meetings');
var settings = require('./controllers/settings');
app.use('/auth', authRouter);
app.use('/meetings', meetingsRouter);
app.use('/', indexRouter);
app.use('/settings', settings);
app.listen(process.env.PORT || 8081);<file_sep>/dbsetup/setupdb.sql
DROP DATABASE IF EXISTS meetx;
CREATE DATABASE IF NOT EXISTS meetx;
USE meetx;
DROP USER IF EXISTS 'user'@'%';
CREATE USER IF NOT EXISTS 'user'@'%'
IDENTIFIED WITH mysql_native_password
BY '<PASSWORD>'
;
GRANT ALL PRIVILEGES ON meetx.* TO 'user'@'%';
grant all privileges on meetx.* to 'user'@'%' with grant option;
GRANT SUPER ON *.* TO 'user'@'%';
<file_sep>/README.md
# Meet X
## About
Meeting schedule is a web application that is made to make scheduling meetings easier without having to mail people back and forth.
The web application is completed with Express.js & Handlebars together with MySQL for the database.
This repository is made as a final delivery for the Software Engineering Project course at Blekinge Institute of Technology

## Features
* Microsoft Login with oauth 2.0
* View your Outlook Calendar on the application.
* Add anyone you like to the meeting by entering their email (provided that they're registered).
* The organizer can create a poll that the attendees can vote on for deciding the final date & time of the meeting.
* Attendees can add more poll alternatives if the times provided don't suit them.
* Flash error messages.
* Warning if you already have something scheduled at that date of the meeting.
* Making meeting location clickable if it's a link
* Ability to change timezone based on where you are.
____________
## Getting started
### Before you start make sure you have:
* MySQL installed (tested on MySQL 5.7.31)
* Node (tested on v12.14.1)
* npm (tested on 6.13.4)
* Registered the app with Azure AD and obtained Client ID and Secret (Follow the [official guide](https://docs.microsoft.com/en-us/graph/auth-v2-user))
### Installation
Tested on Linux (Ubuntu 18.04). Other systems might differ.
```bash
# Clone repository.
git clone https://github.com/abberadhi/meeting-scheduler.git
# Change into the directory.
cd meeting-scheduler/
# Install dependencies.
cd server && npm install
# Make a copy of .env file.
cp .env-example .env
# Setup MySQL database, enter your password.
mysql -uroot -p < ../dbsetup/setupdb.sql > /dev/null
# Setup Mysql database tables, enter your password.
mysql -uroot -p meetx < ../dbsetup/setuptables.sql > /dev/null
```
Next up open ``server/.env`` in your text editor and replace the uppercase values with your own credentials.
```
OAUTH_APP_ID=YOUR_CLIENT_ID
OAUTH_APP_PASSWORD=<PASSWORD>
OAUTH_REDIRECT_URI=http://localhost:8081/auth/callback
OAUTH_SCOPES='profile offline_access user.read User.ReadBasic.All calendars.read'
OAUTH_AUTHORITY=https://login.microsoftonline.com/common/
OAUTH_ID_METADATA=v2.0/.well-known/openid-configuration
OAUTH_AUTHORIZE_ENDPOINT=oauth2/v2.0/authorize
OAUTH_TOKEN_ENDPOINT=oauth2/v2.0/token
DB_USER=MYSQL_USERNAME
DB_PASS=<PASSWORD>
```
## Start
Make sure port 8081 isn't occupied by another application.
Go to ``meeting-scheduler/server`` and run ``sudo npm run start``. Then pray to your god of choice that it works.
The server will be live at ``localhost:8081``. | 0e4d29dd580edccc103919f28698f228f40c1d0d | [
"JavaScript",
"SQL",
"Markdown"
] | 10 | JavaScript | abberadhi/meeting-scheduler | a46e4a6c773ac254d7cc1398a0b0aeba14f7e31c | e825ed255d478b9ac0764e76364115eca9df2ff7 |
refs/heads/master | <repo_name>gilang-novrizal/react_practice<file_sep>/src/practice/dashboard_todo.js
import React from "react";
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
data: ["Learn React JS", "Eat", "Sleep"],
};
}
showTodo = () => {
return this.state.data.map((value, index) => (
<tr>
<td>{value}</td>
<td>
<button color="danger" onClick={() => this.delete(index)}>
❌
</button>
</td>
</tr>
));
};
addTodo = () => {
let newArr = this.state.data;
newArr.push(this.refs.list.value);
this.setState({ data: newArr });
console.log(this.state.data);
this.refs.list.value = "";
};
delete = (index) => {
let newArr = this.state.data;
newArr.splice(index, 1);
this.setState({ data: newArr });
console.log(`Delete ${index}`);
};
render() {
return (
<div>
<h1>Your todoList</h1>
<input ref="list" />
<button type="button" onClick={this.addTodo}>
add
</button>
<table>
<thead>
<tr>
<td>Kegiatan</td>
<td>Delete</td>
</tr>
</thead>
<tbody>{this.showTodo()}</tbody>
</table>
</div>
);
}
}
export default Dashboard;
<file_sep>/src/pages/tugas2.jsx
import React from "react";
import FormTugas from "../components/form";
class Tugas2 extends React.Component {
render() {
return (
<div className="container">
<h1>Hello</h1>
<h2>Tugas 2</h2>
<FormTugas className="m-5" />
</div>
);
}
}
export default Tugas2;
| 248aff6e1fe967db22bfba7aee15bcd12a8f79ff | [
"JavaScript"
] | 2 | JavaScript | gilang-novrizal/react_practice | 4167b32675de335d4ab3a9fc31c85ef8d28889d3 | 5ff893aa0c5ee1bc49e9fafc9fd829178537c3f0 |
refs/heads/master | <file_sep>package org.spring.boot.multiple.ds.dao;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author 刘世杰
* @date 2019/8/19
* 商品移仓单百盛dao
*/
@Component
public interface MerchandiseShiftBSDao {
/**
* 查询商品移仓单凭证数据(百盛)
* @param date
* @return
*/
List<Object> getVoucher(DateInfo date);
/**
* 查询商品移仓单凭证分录数据(百盛)
* @param date
* @return
*/
List<Object> getVoucherEntry(DateInfo date);
List<Object> RemoveVoucher(DateInfo date);
List<Object> RemoveVoucherEntry(DateInfo date);
}
<file_sep>package org.spring.boot.multiple.ds.service;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.spring.boot.multiple.ds.bean.TvoucherEntry;
import java.util.List;
/**
* @author 刘世杰
* @date 2019/8/22
* ProductDistributionOrderService:商店配货退货单
*/
public interface ProductDistributionOrderService {
/**
* 商店配货单-查询凭证所需数据(百盛)
* @param date:抽取日期
* @return
*/
List<Tvoucher> productDistributionOrderVoucher(DateInfo date) throws Exception;
/**
* 商品配货单-查询凭证分录所需数据(百盛)
* @param date:抽取日期
* @return
*/
List<TvoucherEntry> productDistributionOrderVoucherEntry(DateInfo date) throws Exception;
/**
* 商品配货单-插入凭证数据(金蝶)
* @param tVoucherList
* @param tVoucherEntryList
* @return
*/
void insertProductDistributionOrderVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) throws Exception;
/**
* 商店退货单-查询凭证所需数据(百盛)
* @param date:抽取日期
* @return
*/
List<Tvoucher> storeReturnOrderVoucher(DateInfo date) throws Exception;
/**
* 商店退货单-查询凭证分录所需数据(百盛)
* @param date:抽取日期
* @return
*/
List<TvoucherEntry> storeReturnOrderVoucherEntry(DateInfo date) throws Exception;
/**
* 商店退货单-插入凭证数据(金蝶)
* @param tVoucherList
* @param tVoucherEntryList
* @return
*/
void insertStoreReturnOrderVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) throws Exception;
}
<file_sep>package org.spring.boot.multiple.ds.service;
/**
* @author 刘世杰
* @date 2019/8/26
* 判断数据是否进行了抽取,避免重复抽取数据
*/
public interface IsExtractService {
/**
* 判断数据是否进行了抽取
* @param type
* @return
*/
Object isExtract(String type);
/**
* 改变数据抽取状态,抽取完成将状态改为1
* @param type
*/
void changeExtractStatus(String type);
}
<file_sep>package org.spring.boot.multiple.ds.bean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author 刘世杰
* @date 2019/8/19
* <code>yml属性值-属性在yml文件进行修改</ode>
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Component
public class YmlProp {
/**
* 应付账款
*/
@Value("${prop.subject.accountsPayable}")
private String subjectAccountsPayable;
/**
* 库存商品
*/
@Value("${prop.subject.stockGoods}")
private String subjectStockGoods;
}
<file_sep>package org.spring.boot.multiple.ds.service;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.spring.boot.multiple.ds.bean.TvoucherEntry;
import java.util.List;
/**
* @author 刘世杰
* @date 2019/8/14
* goodsReceipt:商品进货单
* goodsReturnReceipt:商品退货单
*/
public interface GoodsIntoReturnService {
/**
* 商品进货单-查询凭证所需数据(百盛)
* @param date
* @return
*/
List<Tvoucher> goodsReceiptVoucher(DateInfo date) throws Exception;
/**
* 商品进货单-查询凭证分录所需数据(百盛)
* @param date
* @return
*/
List<TvoucherEntry> goodsReceiptVoucherEntry(DateInfo date) throws Exception;
/**
* 商品进货单-插入凭证数据(金蝶)
* @param tVoucherList
* @param tVoucherEntryList
* @return
*/
int insertGoodsReceiptVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) throws Exception;
/**
* 商品退货单-查询凭证所需数据(百盛)
* @param date
* @return
*/
List<Tvoucher> goodsReturnReceiptVoucher(DateInfo date) throws Exception;
/**
* 商品退货单-查询凭证分录所需数据(百盛)
* @param date
* @return
*/
List<TvoucherEntry> goodsReturnVoucherEntry(DateInfo date) throws Exception;
/**
* 商品退货单-插入凭证数据(金蝶)
* @param tVoucherList
* @param tVoucherEntryList
* @return
*/
void insertGoodsReturnReceiptVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) throws Exception;
}
<file_sep>package org.spring.boot.multiple.ds.dao;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author 刘世杰
* @date 2019/9/20
* 销货收款单百盛dao
*/
@Component
public interface SalesReceiptBSDao {
/**
* 查询销货收款单凭证数据(百盛)
* @param date
* @return
*/
List<Object> getVoucher(DateInfo date);
/**
* 查询销货收款单凭证分录数据(百盛)
* @param djbh:单据编号
* @return
*/
List<Object> getVoucherEntry(String djbh);
/**
* 根据客户代码查询客户名称-table:KEHU
* @param dm1:客户代码
* @return
*/
Object getKHMC(String dm1);
/**
* 根据客户代码查询客户名称-table:KEHU
* @param skzh:收款账号
* @return
*/
Object getZHMC(String skzh);
}
<file_sep>package org.spring.boot.multiple.ds.bean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* 日期相关信息
* @author 刘世杰
* @date 2019/8/13
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class DateInfo {
/**本月25日(yyyy-mm-dd hh:mm:sss)*/
private String currentMonth25;
/**上个月26日(yyyy-mm-dd hh:mm:sss)*/
private String lastMonth26;
/**
* add: 2019/8/19
* 用于获取当前年月
*/
private String currentYear;
private String currentMonth;
/**
* add: 2019/8/28
* 用于获取上月1号与最后一天
*/
private String lastMonthFirstDay;
private String lastMonthLastDay;
/**
* add: 2019/8/29
* 用于获取本月1日以及26日
*/
private String currentMonth1;
private String currentMonth26;
/**
* add: 2019/8/29
* 用于获取此时的年月日时分秒
*/
private String currentTime;
}
<file_sep>package org.spring.boot.multiple.ds;
import java.lang.annotation.*;
/**
* @author donghongchen
* @create 2017-09-04 14:41
**/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String value();
}
<file_sep>package org.spring.boot.multiple.ds;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author donghongchen
* @create 2017-09-04 14:44
* <p>
* 切换数据源Advice
**/
@Aspect
@Order(-10) //保证该aop在@Transaction之前执行
@Component
public class DynamicDataSourceAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* * @Before("@annotation(ds)")
* 的意思是:@Before:在方法执行之前进行执行; @annotation(targetDataSource):会拦截注解targetDataSource的方法,否则不拦截;
* @param point
* @param targetDataSource
*/
@Before("@annotation(targetDataSource)")
public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource){
//获取当前的指定数据源
String dsID = targetDataSource.value();
//如果不在我们注入的所有的数据源范围内,输出警告信息,系统自动使用默认的数据源
if (!DynamicDataSourceContextHolder.containsDataSource(dsID)){
logger.error("数据源["+dsID+"]不存在,使用默认的数据源 > { " + dsID+", 方法签名:"+point.getSignature()+"}");
}else {
logger.info("Use DataSource: {" +dsID+", 方法签名:"+point.getSignature() +"}");
//找到的话,那么设置动态数据源上下文
DynamicDataSourceContextHolder.setDataSourceType(dsID);
}
}
@After("@annotation(targetDataSource)")
public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource){
//方法执行完毕后,销毁当前数据源信息,进行垃圾回收
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
<file_sep>package org.spring.boot.multiple.ds.dao;
import org.apache.ibatis.annotations.Param;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.spring.boot.multiple.ds.bean.TvoucherEntry;
import org.springframework.stereotype.Component;
@Component
public interface GoodsIntoReturnKingDeeDao {
/**
* 插入凭证数据
* @param tvoucher
* @return
*/
int insertPurchase(Tvoucher tvoucher);
/**
* 查询最后新增的数据
* @return
*/
Tvoucher selectLastVoucher();
/**
* 插入凭证分录数据
* @param tvoucherEntry
* @return
*/
int insertVoucherEntry(TvoucherEntry tvoucherEntry);
/**
* 更新凭证数据
* @param FVoucherID
* @return
*/
int updateVoucher(String FVoucherID);
/**
* 根据字段值查询编号
* item: 核算项目类别<exp>5表示仓库;8表示供货商</exp>
* @return
*/
Object selectFNumber(@Param("name") String name, @Param("item") String item);
}
<file_sep>## 悦途数据抽取项目


---
technology stack: <code>lombok</code>,<code>spring-boot</code>,<code>mybatis</code>,<code>druid</code>
#### 说明:
> 结算项目更改请直接在resources/application.yml中直接进行配置,降低代码耦合度
```yml
- 重要表列举(待补充)
t_voucher: 凭证表
t_voucherEntry: 凭证分录表
t_itemPropDesc: 核算项目附表信息描述表
t_itemDetailV: 核算项目使用详情纵表
t_itemDetail: 核算项目使用详情横表
t_item: 核算项目表
t_itemClass: 核算项目类别表
t_account: 科目表
- 重要字段说明
t_itemClass表:
FItemClassID(只列举几个重要的):
## 查询时请使用该类进行区别,否则可能导致查出多条数据
0: *
1: 客户
2: 部门
3: 职员
5: 仓库
8: 供应商
tVoucherEntry表:
FDetail: 核算项目使用ID,0为不下设核算项目
## id来源:t_itemDetailV表下FDetailID字段
## 根据t_item:FName > t_item:FitemID = t_itemDetailV:FItemID > t_itemDetailV:FDeatilID
此处使用的是t_itemDetailV:FDeatilID, fix:凭证抽取bug #1
```
- [x] 商品移仓单(移入):百盛(分销系统/移仓数据分析)-已自测
> 借: 移入仓(核算项目:库存商品);贷: 移出仓(核算项目:库存商品)
- [x] 商品移仓单(移出):百盛(分销系统/移仓数据分析)-已自测
> 借: 移出仓(核算项目:库存商品);贷: 移入仓(核算项目:库存商品)
- [x] 商店配货单:百盛(分销系统/配货数据分析)-已自测
> 借: 商店(核算项目:库存商品);贷: 仓库(核算项目:库存商品)
- [x] 商店退货单:百盛(分销系统/配货数据分析)-已自测
> 借: 仓库(核算项目:库存商品);贷: 商店(核算项目:库存商品)
- [x] 商品进货单:百盛(分销系统/进货数据分析)-已自测
> 借: 仓库(核算项目:库存商品);贷: 供货商(核算项目:应收账款)
- [x] 商品退货单:百盛(分销系统/进货数据分析)-已自测
> 借: 供货商(核算项目:应收账款);贷: 仓库(核算项目:库存商品)
- [x] 进货结算单:百盛(财务系统/进货结算单)
> 借: 仓库(核算项目:库存商品);贷:供货商(核算项目:应收账款)
- [ ] 销售费用单:百盛(财务系统/销货费用数据分析)
> 代垫客户快递费(借:应收账款;贷:应付账款)
> 账扣促销费(借:营业费用;贷:应收账款)
#### 监控sql
- 凭证sql新增(金蝶K3监控)
```
-- 凭证插入
exec sp_executesql N'INSERT INTO t_VoucherEntry (FVoucherID,FEntryID,FExplanation,FAccountID,FCurrencyID,FExchangeRateType,FExchangeRate,FDC,FAmountFor,FAmount,FQuantity,FMeasureUnitID,FUnitPrice,FInternalInd,FAccountID2,FSettleTypeID,FSettleNo,FCashFlowItem,FTaskID,FResourceID,FTransNo,FDetailID) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11,@P12,@P13,@P14,@P15,@P16,@P17,@P18,@P19,@P20,@P21,@P22)',N'@P1 int,@P2 int,@P3 varchar(255),@P4 int,@P5 int,@P6 float,@P7 float,@P8 int,@P9 money,@P10 money,@P11 float,@P12 int,@P13 float,@P14 varchar(10),@P15 int,@P16 int,@P17 varchar(255),@P18 int,@P19 int,@P20 int,@P21 varchar(255),@P22 int',225,0,'测试数据001',1046,1,1,1,1,$1.0000,$1.0000,0,0,0,NULL,1039,0,NULL,0,0,0,NULL,128
-- 凭证分录插入
exec sp_executesql N'INSERT INTO t_Voucher (FDate,FTransDate,FYear,FPeriod,FGroupID,FNumber,FReference,FExplanation,FAttachments,FEntryCount,FDebitTotal,FCreditTotal,FInternalInd,FChecked,FPosted,FPreparerID,FCheckerID,FPosterID,FCashierID,FHandler,FObjectName,FParameter,FSerialNum,FTranType,FOwnerGroupID) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11,@P12,@P13,@P14,@P15,@P16,@P17,@P18,@P19,@P20,@P21,@P22,@P23,@P24,@P25)',N'@P1 datetime,@P2 datetime,@P3 int,@P4 int,@P5 int,@P6 int,@P7 varchar(255),@P8 varchar(255),@P9 int,@P10 int,@P11 money,@P12 money,@P13 varchar(10),@P14 bit,@P15 bit,@P16 int,@P17 int,@P18 int,@P19 int,@P20 varchar(50),@P21 varchar(100),@P22 varchar(100),@P23 int,@P24 int,@P25 int','2014-02-28 00:00:00','2014-02-28 00:00:00',2014,2,4,44,NULL,'测试数据001',0,2,$1.0000,$1.0000,NULL,0,0,16394,-1,-1,-1,NULL,NULL,NULL,183,0,1
```
#### 相关文件
- [ERP开发科目清理](http://t.cn/AiQSS7k0)
- [百盛数据字典](http://t.cn/AiQSoLTt)
- [K3凭证导入相关库表描述](http://t.cn/AiQS9bOC)
- [目前发现的缺失核算项目](http://t.cn/AiRdJ4TK)
---
#### 待处理事项
- 当不存在核算项目时(如供货商,仓库等),进行消息提示(客户需求)
- 单据日期目前使用的是单据抽取的实际日期,需要与客户协商
- 商店配货单在(2019-08-01 至 2019-08-31)发现一条分录数据为负,金额为-61.3
<file_sep>package org.spring.boot.multiple.ds.dao;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.springframework.stereotype.Component;
/**
* @author 刘世杰
* @date 2019/9/20
* 销货收款单金蝶dao
*/
@Component
public interface SalesReceiptKingDeeDao {
/**
* 查询新增前的最后一条凭证数据
* resolve: 无法获取自增主键
* @return
*/
Tvoucher selectLastVoucher();
/**
* 新增凭证数据
* @param tvoucher: 凭证数据
* @return
*/
void addVoucher(Tvoucher tvoucher);
}
<file_sep>package org.spring.boot.multiple.ds.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.boot.multiple.ds.TargetDataSource;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.spring.boot.multiple.ds.bean.TvoucherEntry;
import org.spring.boot.multiple.ds.bean.YmlProp;
import org.spring.boot.multiple.ds.dao.GoodsIntoReturnBSDao;
import org.spring.boot.multiple.ds.dao.GoodsIntoReturnKingDeeDao;
import org.spring.boot.multiple.ds.service.GoodsIntoReturnService;
import org.spring.boot.multiple.ds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author 刘世杰
* @date 2019/8/14
* 商品进退货impl
*/
@SuppressWarnings("unchecked")
@Service
public class GoodsIntoReturnServiceImpl implements GoodsIntoReturnService {
@Autowired
GoodsIntoReturnKingDeeDao goodsIntoReturnKingDeeDao;
@Autowired
GoodsIntoReturnBSDao goodsIntoReturnBsDao;
@Autowired
YmlProp ymlProp;
/**
* SLF4J
*/
Logger log = LoggerFactory.getLogger(getClass());
/**
* 查询凭证表所需数据-from:百盛
* @param date
*/
@TargetDataSource("dataSource")
@Override
public List<Tvoucher> goodsReceiptVoucher(DateInfo date) {
log.info("进入goodsReceiptVoucher方法,查询百盛商品进货单数据处理并生成单据集合");
//百盛
List<Object> list = goodsIntoReturnBsDao.generatePurchase(date);
DateInfo dateInfo = DateUtil.dateData();
//凭证日期-当前时间
String rq = dateInfo.getCurrentTime();
List<Tvoucher> tVoucherList = new ArrayList<>();
//插入tVoucher凭证
for (Object obj : list) {
Map<String,Object> map = (Map<String, Object>)obj;
Tvoucher voucher = new Tvoucher();
//凭证日期
voucher.setFDate(rq);
//业务日期
voucher.setFTransDate(rq);
//年份
voucher.setFYear(dateInfo.getCurrentYear());
//会计期间
voucher.setFPeriod(dateInfo.getCurrentMonth());
//摘要组内码
voucher.setFGroupID("1");
//摘要编码
voucher.setFNumber("44");
//参考信息
voucher.setFReference(null);
//摘要
voucher.setFExplanation("");
//附件张数
voucher.setFAttachments("0");
//分录数
voucher.setFEntryCount(String.valueOf(map.get("TOTAL")));
//借方金额合计
voucher.setFDebitTotal(String.valueOf(map.get("SJJE")));
//贷方金额合计
voucher.setFCreditTotal(String.valueOf(map.get("SJJE")));
//空-手工凭证,非空-机制凭证
voucher.setFInternalInd(null);
//0-未审核,1-已审核
voucher.setFChecked("0");
//0-未过账,1-已过账
voucher.setFPosted("0");
//制单人
voucher.setFPreparerID("16394");
//审核人
voucher.setFCheckerID("-1");
//记账人
voucher.setFPosterID("-1");
//出纳员
voucher.setFCashierID("-1");
//会计主管
voucher.setFHandler(null);
//其他系统传入凭证对象接口描述
voucher.setFObjectName(null);
//接口参数
voucher.setFParameter(null);
//凭证序号
voucher.setFSerialNum("183");
//单据类型
voucher.setFTranType("0");
//制单人所属工作组
voucher.setFOwnerGroupID("0");
//仓库名称
voucher.setCKMC((String)map.get("CKMC"));
//返回获取到的数据到金蝶
tVoucherList.add(voucher);
}
return tVoucherList;
}
/**
* 查询凭证表分录所需数据-from:百盛
* @return
* @param date
*/
@TargetDataSource("dataSource")
@Override
public List<TvoucherEntry> goodsReceiptVoucherEntry(DateInfo date) {
log.info("进入goodsReceiptVoucherEntry方法,查询百盛商品进货单数据处理并生成单据分录集合");
List<Object> list = goodsIntoReturnBsDao.selectEntry(date);
List<TvoucherEntry> tVoucherEntryList = new ArrayList<>();
for(Object obj : list) {
TvoucherEntry tvoucherEntry = new TvoucherEntry();
Map<String,Object> map = (Map<String, Object>)obj;
//摘要
tvoucherEntry.setFExplanation("");
//币别
tvoucherEntry.setFCurrencyID("1");
//费率类型
tvoucherEntry.setFExchangeRateType("1");
//费率
tvoucherEntry.setFExchangeRate("1");
//余额方向 0-贷方,1- 借方
tvoucherEntry.setFDC("0");
//金额(原币)
tvoucherEntry.setFAmountFor(String.valueOf(map.get("F6")));
//金额(本位币)
tvoucherEntry.setFAmount(String.valueOf(map.get("F6")));
//数量
tvoucherEntry.setFQuantity("0");
//单位内码
tvoucherEntry.setFMeasureUnitID("0");
//单价
tvoucherEntry.setFUnitPrice("0");
//机制凭证
tvoucherEntry.setFInternalInd(null);
//结算方式
tvoucherEntry.setFSettleTypeID("0");
//结算号
tvoucherEntry.setFSettleNo(null);
//现金流量 0-不是,1-是现金流量项目
tvoucherEntry.setFCashFlowItem("0");
//项目任务内码
tvoucherEntry.setFTaskID("0");
//项目资源ID
tvoucherEntry.setFResourceID("0");
//业务号
tvoucherEntry.setFTransNo(null);
//仓库名称
tvoucherEntry.setCKMC((String)map.get("CKMC"));
//供货商名称
tvoucherEntry.setGHSMC((String)map.get("GHSMC"));
tVoucherEntryList.add(tvoucherEntry);
}
return tVoucherEntryList;
}
/**
* 添加凭证数据到金蝶系统
* @param tVoucherList
* @param tVoucherEntryList
* @return
*/
@Transactional(rollbackFor = {Exception.class})
@TargetDataSource("ds1")
@Override
public int insertGoodsReceiptVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) {
log.info("进入insertGoodsReceiptVoucher方法,插入商品进货单数据到金蝶凭证");
for(Tvoucher tvoucher : tVoucherList) {
//查询最后插入的数据-没有自增主键,只能这么获取了
Tvoucher obj = goodsIntoReturnKingDeeDao.selectLastVoucher();
String FVoucherID;
if(obj == null) {
FVoucherID = "0";
} else {
FVoucherID = String.valueOf(Integer.parseInt(obj.getFVoucherID())+1);
}
tvoucher.setFVoucherID(FVoucherID);
tvoucher.setFNumber(FVoucherID);
tvoucher.setFSerialNum(FVoucherID);
//插入凭证数据到金蝶系统
goodsIntoReturnKingDeeDao.insertPurchase(tvoucher);
//用于生成分录号
int i = 0;
//贷方数据
TvoucherEntry tvoucherEntryTotal = new TvoucherEntry();
//根据仓库名称查询id,放入核算项目
Map<String,Object> ckId = (Map<String, Object>) goodsIntoReturnKingDeeDao.selectFNumber(tvoucher.getCKMC(),"5");
if(ckId == null || ckId.isEmpty()) {
//核算项目
tvoucherEntryTotal.setFDetailID("0");
} else {
//核算项目
tvoucherEntryTotal.setFDetailID(String.valueOf(ckId.get("FDetailID")));
}
//摘要
tvoucherEntryTotal.setFExplanation("");
//币别
tvoucherEntryTotal.setFCurrencyID("1");
//费率类型
tvoucherEntryTotal.setFExchangeRateType("1");
//费率
tvoucherEntryTotal.setFExchangeRate("1");
//余额方向 0-贷方,1- 借方
tvoucherEntryTotal.setFDC("1");
//金额(原币)
tvoucherEntryTotal.setFAmountFor(tvoucher.getFDebitTotal());
//金额(本位币)
tvoucherEntryTotal.setFAmount(tvoucher.getFDebitTotal());
//数量
tvoucherEntryTotal.setFQuantity("0");
//单位内码
tvoucherEntryTotal.setFMeasureUnitID("0");
//单价
tvoucherEntryTotal.setFUnitPrice("0");
//机制凭证
tvoucherEntryTotal.setFInternalInd(null);
//结算方式
tvoucherEntryTotal.setFSettleTypeID("0");
//结算号
tvoucherEntryTotal.setFSettleNo(null);
//现金流量 0-不是,1-是现金流量项目
tvoucherEntryTotal.setFCashFlowItem("0");
//项目任务内码
tvoucherEntryTotal.setFTaskID("0");
//项目资源ID
tvoucherEntryTotal.setFResourceID("0");
//业务号
tvoucherEntryTotal.setFTransNo(null);
//仓库名称
tvoucherEntryTotal.setCKMC(tvoucher.getCKMC());
//科目内码
tvoucherEntryTotal.setFAccountID(ymlProp.getSubjectStockGoods());
//对方科目
tvoucherEntryTotal.setFAccountID2(ymlProp.getSubjectAccountsPayable());
//凭证内码
tvoucherEntryTotal.setFVoucherID(FVoucherID);
//分录号
tvoucherEntryTotal.setFEntryID(String.valueOf(i));
goodsIntoReturnKingDeeDao.insertVoucherEntry(tvoucherEntryTotal);
i++;
for(TvoucherEntry tVoucherEntry : tVoucherEntryList) {
if(tvoucher.getCKMC().equals(tVoucherEntry.getCKMC())) {
//根据供货商名称查询id,放入核算项目
Map<String,Object> ghsId = (Map<String, Object>) goodsIntoReturnKingDeeDao.selectFNumber(tVoucherEntry.getGHSMC(),"8");
if(ghsId == null || ghsId.isEmpty()) {
//核算项目
tVoucherEntry.setFDetailID("0");
} else {
//核算项目
tVoucherEntry.setFDetailID(String.valueOf(ghsId.get("FDetailID")));
}
//科目内码
tVoucherEntry.setFAccountID(ymlProp.getSubjectAccountsPayable());
//对方科目
tVoucherEntry.setFAccountID2(ymlProp.getSubjectStockGoods());
//凭证内码
tVoucherEntry.setFVoucherID(FVoucherID);
//分录号
tVoucherEntry.setFEntryID(String.valueOf(i));
goodsIntoReturnKingDeeDao.insertVoucherEntry(tVoucherEntry);
i++;
}
}
}
return 0;
}
/**
* 查询凭证表所需数据-from:百盛
* @param date
*/
@TargetDataSource("dataSource")
@Override
public List<Tvoucher> goodsReturnReceiptVoucher(DateInfo date) {
log.info("进入goodsReturnReceiptVoucher方法,查询百盛商品退货单数据处理并生成单据集合");
//百盛--商品退货单
List<Object> list = goodsIntoReturnBsDao.returnGoodsVoucher(date);
List<Tvoucher> tVoucherList = new ArrayList<>();
DateInfo dateInfo = DateUtil.dateData();
//插入tVoucher凭证
for (Object obj : list) {
Map<String,Object> map = (Map<String, Object>)obj;
Tvoucher voucher = new Tvoucher();
//获取当前时间
String rq = dateInfo.getCurrentTime();
//凭证日期
voucher.setFDate(rq);
//业务日期
voucher.setFTransDate(rq);
//年份
voucher.setFYear(dateInfo.getCurrentYear());
//会计期间
voucher.setFPeriod(dateInfo.getCurrentMonth());
//摘要组内码
voucher.setFGroupID("1");
//摘要编码
voucher.setFNumber("44");
//参考信息
voucher.setFReference(null);
//摘要
voucher.setFExplanation("");
//附件张数
voucher.setFAttachments("0");
//分录数
voucher.setFEntryCount(String.valueOf(map.get("TOTAL")));
//借方金额合计
voucher.setFDebitTotal(String.valueOf(map.get("SJJE")));
//贷方金额合计
voucher.setFCreditTotal(String.valueOf(map.get("SJJE")));
//空-手工凭证,非空-机制凭证
voucher.setFInternalInd(null);
//0-未审核,1-已审核
voucher.setFChecked("0");
//0-未过账,1-已过账
voucher.setFPosted("0");
//制单人
voucher.setFPreparerID("16394");
//审核人
voucher.setFCheckerID("-1");
//记账人
voucher.setFPosterID("-1");
//出纳员
voucher.setFCashierID("-1");
//会计主管
voucher.setFHandler(null);
//其他系统传入凭证对象接口描述
voucher.setFObjectName(null);
//接口参数
voucher.setFParameter(null);
//凭证序号
voucher.setFSerialNum("183");
//单据类型
voucher.setFTranType("0");
//制单人所属工作组
voucher.setFOwnerGroupID("0");
//仓库名称
voucher.setCKMC((String)map.get("CKMC"));
//返回获取到的数据到金蝶
tVoucherList.add(voucher);
}
return tVoucherList;
}
/**
* 查询凭证表分录所需数据-from:百盛
* @param date
* @return
*/
@TargetDataSource("dataSource")
@Override
public List<TvoucherEntry> goodsReturnVoucherEntry(DateInfo date) {
log.info("进入goodsReturnVoucherEntry方法,查询百盛商品退货单数据处理并生成单据分录集合");
List<Object> list = goodsIntoReturnBsDao.returnGoodsVoucherEntry(date);
List<TvoucherEntry> tVoucherEntryList = new ArrayList<>();
for(Object obj : list) {
TvoucherEntry tvoucherEntry = new TvoucherEntry();
Map<String,Object> map = (Map<String, Object>)obj;
//摘要
tvoucherEntry.setFExplanation("");
//币别
tvoucherEntry.setFCurrencyID("1");
//费率类型
tvoucherEntry.setFExchangeRateType("1");
//费率
tvoucherEntry.setFExchangeRate("1");
//余额方向 0-贷方,1- 借方
tvoucherEntry.setFDC("0");
//金额(原币)
tvoucherEntry.setFAmountFor(String.valueOf(map.get("F6")));
//金额(本位币)
tvoucherEntry.setFAmount(String.valueOf(map.get("F6")));
//数量
tvoucherEntry.setFQuantity("0");
//单位内码
tvoucherEntry.setFMeasureUnitID("0");
//单价
tvoucherEntry.setFUnitPrice("0");
//机制凭证
tvoucherEntry.setFInternalInd(null);
//结算方式
tvoucherEntry.setFSettleTypeID("0");
//结算号
tvoucherEntry.setFSettleNo(null);
//现金流量 0-不是,1-是现金流量项目
tvoucherEntry.setFCashFlowItem("0");
//项目任务内码
tvoucherEntry.setFTaskID("0");
//项目资源ID
tvoucherEntry.setFResourceID("0");
//业务号
tvoucherEntry.setFTransNo(null);
//仓库名称
tvoucherEntry.setCKMC((String)map.get("CKMC"));
//供货商名称
tvoucherEntry.setGHSMC((String)map.get("GHSMC"));
tVoucherEntryList.add(tvoucherEntry);
}
return tVoucherEntryList;
}
/**
* 添加凭证数据到金蝶系统-商品退货单
* @param tVoucherList
* @param tVoucherEntryList
* @return
*/
@Transactional(rollbackFor = {Exception.class})
@TargetDataSource("ds1")
@Override
public void insertGoodsReturnReceiptVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) {
log.info("进入insertGoodsReturnReceiptVoucher方法,插入商品退货单数据到金蝶凭证");
for(Tvoucher tvoucher : tVoucherList) {
//查询最后插入的数据-没有自增主键,只能这么获取了
Tvoucher obj = goodsIntoReturnKingDeeDao.selectLastVoucher();
String FVoucherID;
if(obj == null) {
FVoucherID = "0";
} else {
FVoucherID = String.valueOf(Integer.parseInt(obj.getFVoucherID())+1);
}
tvoucher.setFVoucherID(FVoucherID);
tvoucher.setFNumber(FVoucherID);
tvoucher.setFSerialNum(FVoucherID);
//插入凭证数据到金蝶系统
goodsIntoReturnKingDeeDao.insertPurchase(tvoucher);
//更新刚才插入的凭证数据-折中方案,无法获取自增值,只能进行修改了
//用于生成分录号
int i = 0;
//贷方数据
TvoucherEntry tvoucherEntryTotal = new TvoucherEntry();
//根据仓库名称查询id,放入核算项目
Map<String,Object> ckId = (Map<String, Object>) goodsIntoReturnKingDeeDao.selectFNumber(tvoucher.getCKMC(),"5");
if(ckId == null || ckId.isEmpty()) {
//核算项目
tvoucherEntryTotal.setFDetailID("0");
} else {
//核算项目
tvoucherEntryTotal.setFDetailID(String.valueOf(ckId.get("FDetailID")));
}
//摘要
tvoucherEntryTotal.setFExplanation("");
//币别
tvoucherEntryTotal.setFCurrencyID("1");
//费率类型
tvoucherEntryTotal.setFExchangeRateType("1");
//费率
tvoucherEntryTotal.setFExchangeRate("1");
//余额方向 0-贷方,1- 借方
tvoucherEntryTotal.setFDC("1");
//金额(原币)
tvoucherEntryTotal.setFAmountFor(tvoucher.getFDebitTotal());
//金额(本位币)
tvoucherEntryTotal.setFAmount(tvoucher.getFDebitTotal());
//数量
tvoucherEntryTotal.setFQuantity("0");
//单位内码
tvoucherEntryTotal.setFMeasureUnitID("0");
//单价
tvoucherEntryTotal.setFUnitPrice("0");
//机制凭证
tvoucherEntryTotal.setFInternalInd(null);
//结算方式
tvoucherEntryTotal.setFSettleTypeID("0");
//结算号
tvoucherEntryTotal.setFSettleNo(null);
//现金流量 0-不是,1-是现金流量项目
tvoucherEntryTotal.setFCashFlowItem("0");
//项目任务内码
tvoucherEntryTotal.setFTaskID("0");
//项目资源ID
tvoucherEntryTotal.setFResourceID("0");
//业务号
tvoucherEntryTotal.setFTransNo(null);
//仓库名称
tvoucherEntryTotal.setCKMC(tvoucher.getCKMC());
//科目内码
tvoucherEntryTotal.setFAccountID(ymlProp.getSubjectStockGoods());
//对方科目
tvoucherEntryTotal.setFAccountID2(ymlProp.getSubjectAccountsPayable());
//凭证内码
tvoucherEntryTotal.setFVoucherID(FVoucherID);
//分录号
tvoucherEntryTotal.setFEntryID(String.valueOf(i));
goodsIntoReturnKingDeeDao.insertVoucherEntry(tvoucherEntryTotal);
i++;
for(TvoucherEntry tVoucherEntry : tVoucherEntryList) {
if(tvoucher.getCKMC().equals(tVoucherEntry.getCKMC())) {
//根据供货商名称查询id,放入核算项目
Map<String,Object> ghsId = (Map<String, Object>) goodsIntoReturnKingDeeDao.selectFNumber(tVoucherEntry.getGHSMC(),"8");
if(ghsId == null || ghsId.isEmpty()) {
//核算项目
tVoucherEntry.setFDetailID("0");
} else {
//核算项目
tVoucherEntry.setFDetailID(String.valueOf(ghsId.get("FDetailID")));
}
//科目内码
tVoucherEntry.setFAccountID(ymlProp.getSubjectAccountsPayable());
//对方科目
tVoucherEntry.setFAccountID2(ymlProp.getSubjectStockGoods());
//凭证内码
tVoucherEntry.setFVoucherID(FVoucherID);
//分录号
tVoucherEntry.setFEntryID(String.valueOf(i));
goodsIntoReturnKingDeeDao.insertVoucherEntry(tVoucherEntry);
i++;
}
}
}
}
}<file_sep>package org.spring.boot.multiple.ds.bean;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* 凭证分录表
* @author 刘世杰
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TvoucherEntry {
private String FVoucherID;
private String FEntryID;
private String FExplanation;
private String FAccountID;
private String FCurrencyID;
private String FExchangeRateType;
private String FExchangeRate;
private String FDC;
private String FAmountFor;
private String FAmount;
private String FQuantity;
private String FMeasureUnitID;
private String FUnitPrice;
private String FInternalInd;
private String FAccountID2;
private String FSettleTypeID;
private String FSettleNo;
private String FCashFlowItem;
private String FTaskID;
private String FResourceID;
private String FTransNo;
private String FDetailID;
/**
* add 2019/8/15
* CKMC: 仓库名称
* GHSMC: 供货商名称
*/
private String CKMC;
private String GHSMC;
/**
* add 2019/8/20
* debit: 借方
* credit: 贷方
*/
private String debit;
private String credit;
/**
* add 2019/8/30
* djbh: 通过单据编号将凭证List以及凭证分录List进行汇总
*/
private String djbh;
/**
* add 2019/8/30
* isSummary: 用于判断是否是汇总数据 0-否 1-是
*/
private String isSummary;
/**
* add 2019/9/20
* khmc: 客户名称
*/
private String khmc;
}
<file_sep>package org.spring.boot.multiple.ds.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.boot.multiple.ds.TargetDataSource;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.spring.boot.multiple.ds.bean.TvoucherEntry;
import org.spring.boot.multiple.ds.bean.YmlProp;
import org.spring.boot.multiple.ds.dao.ProductDistributionOrderBSDao;
import org.spring.boot.multiple.ds.dao.ProductDistributionOrderKingDeeDao;
import org.spring.boot.multiple.ds.service.ProductDistributionOrderService;
import org.spring.boot.multiple.ds.util.DateUtil;
import org.spring.boot.multiple.ds.util.VoucherUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author 刘世杰
* @date 2019/8/22
* 商店配货退货单
*/
@SuppressWarnings("unchecked")
@Service
public class ProductDistributionOrderServiceImpl implements ProductDistributionOrderService {
@Autowired
ProductDistributionOrderBSDao productDistributionOrderBSDao;
@Autowired
ProductDistributionOrderKingDeeDao productDistributionOrderKingDeeDao;
@Autowired
YmlProp ymlProp;
/**
* SLF4J
*/
Logger log = LoggerFactory.getLogger(getClass());
@TargetDataSource("dataSource")
@Override
public List<Tvoucher> productDistributionOrderVoucher(DateInfo date) throws Exception {
log.info("进入productDistributionOrderVoucher方法,查询百盛商店配货单数据处理并生成单据集合");
List<Object> list = productDistributionOrderBSDao.getVoucher(date);
DateInfo dateInfo = DateUtil.dateData();
List<Tvoucher> tVoucherList = new ArrayList<>();
for(Object obj : list) {
if(!ObjectUtils.isEmpty(obj)) {
Map<String,Object> map = (Map<String, Object>)obj;
Tvoucher voucher = VoucherUtil.getVoucher();
//凭证日期
voucher.setFDate(dateInfo.getCurrentTime());
//业务日期
voucher.setFTransDate(dateInfo.getCurrentTime());
//年份
voucher.setFYear(dateInfo.getCurrentYear());
//会计期间
voucher.setFPeriod(dateInfo.getCurrentMonth());
//摘要
voucher.setFExplanation("摘要");
//分录数
voucher.setFEntryCount(String.valueOf(map.get("TOTAL")));
//借方金额合计
voucher.setFDebitTotal(String.valueOf(map.get("CBJE")));
//贷方金额合计
voucher.setFCreditTotal(String.valueOf(map.get("CBJE")));
//贷方:CKMC
voucher.setCredit(String.valueOf(map.get("CKMC")));
//返回百盛获取到的数据
tVoucherList.add(voucher);
}
}
return tVoucherList;
}
@TargetDataSource("dataSource")
@Override
public List<TvoucherEntry> productDistributionOrderVoucherEntry(DateInfo date) throws Exception {
log.info("进入productDistributionOrderVoucherEntry方法,查询百盛商店配货单数据处理并生成单据分录集合");
List<Object> list = productDistributionOrderBSDao.getVoucherEntry(date);
List<TvoucherEntry> tVoucherEntryList = new ArrayList<>();
for(Object obj : list) {
if(!ObjectUtils.isEmpty(obj)) {
TvoucherEntry tvoucherEntry = VoucherUtil.getVoucherEntry();
Map<String, Object> map = (Map<String, Object>) obj;
//摘要
tvoucherEntry.setFExplanation("摘要");
//余额方向 0-贷方,1- 借方
tvoucherEntry.setFDC("1");
//金额(原币)
tvoucherEntry.setFAmountFor(String.valueOf(map.get("CBJE")));
//金额(本位币)
tvoucherEntry.setFAmount(String.valueOf(map.get("CBJE")));
//贷方:CKMC
tvoucherEntry.setCredit((String)map.get("CKMC"));
//借方:CKMC1
tvoucherEntry.setDebit((String)map.get("CKMC1"));
tVoucherEntryList.add(tvoucherEntry);
}
}
return tVoucherEntryList;
}
@Transactional(rollbackFor = {Exception.class})
@TargetDataSource("ds1")
@Override
public void insertProductDistributionOrderVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) throws Exception {
log.info("进入insertProductDistributionOrderVoucher方法,插入商品调仓单数据到金蝶凭证");
for(Tvoucher tvoucher : tVoucherList) {
Tvoucher obj = productDistributionOrderKingDeeDao.selectLastVoucher();
String FVoucherID = "0";
if (obj != null) {
FVoucherID = String.valueOf(Integer.parseInt(obj.getFVoucherID()) + 1);
}
tvoucher.setFVoucherID(FVoucherID);
tvoucher.setFNumber(FVoucherID);
tvoucher.setFSerialNum(FVoucherID);
//插入凭证数据到金蝶系统
productDistributionOrderKingDeeDao.addVoucher(tvoucher);
//用于生成分录号
int i = 0;
//贷方数据
TvoucherEntry tvoucherEntryTotal = VoucherUtil.getVoucherEntry();
//根据仓库名称CKMC查询对应的FItemID
Map<String,Object> fItemid = (Map<String, Object>) productDistributionOrderKingDeeDao.selectFItemID(tvoucher.getCredit());
if(fItemid == null || fItemid.isEmpty()) {
//核算项目
tvoucherEntryTotal.setFDetailID("0");
} else {
//核算项目
tvoucherEntryTotal.setFDetailID(String.valueOf(fItemid.get("FDetailID")));
}
//摘要
tvoucherEntryTotal.setFExplanation("摘要");
//金额(原币)
tvoucherEntryTotal.setFAmountFor(tvoucher.getFDebitTotal());
//金额(本位币)
tvoucherEntryTotal.setFAmount(tvoucher.getFDebitTotal());
//贷方-CKMC1
tvoucherEntryTotal.setCredit(tvoucher.getCredit());
//科目内码
tvoucherEntryTotal.setFAccountID(ymlProp.getSubjectStockGoods());
//对方科目
tvoucherEntryTotal.setFAccountID2(ymlProp.getSubjectStockGoods());
//凭证内码
tvoucherEntryTotal.setFVoucherID(FVoucherID);
//分录号
tvoucherEntryTotal.setFEntryID(String.valueOf(i));
//余额方向 0-贷方,1- 借方
tvoucherEntryTotal.setFDC("0");
productDistributionOrderKingDeeDao.addVoucherEntry(tvoucherEntryTotal);
i++;
for(TvoucherEntry tVoucherEntry : tVoucherEntryList) {
if(tvoucher.getCredit().equals(tVoucherEntry.getCredit())) {
//根据仓库名称CKMC查询对应的FItemID
Map<String,Object> ghsId = (Map<String, Object>) productDistributionOrderKingDeeDao.selectFItemID(tVoucherEntry.getDebit());
if(ghsId == null || ghsId.isEmpty()) {
//核算项目
tVoucherEntry.setFDetailID("0");
} else {
//核算项目
tVoucherEntry.setFDetailID(String.valueOf(ghsId.get("FDetailID")));
}
//科目内码
tVoucherEntry.setFAccountID(ymlProp.getSubjectStockGoods());
//对方科目
tVoucherEntry.setFAccountID2(ymlProp.getSubjectStockGoods());
//凭证内码
tVoucherEntry.setFVoucherID(FVoucherID);
//分录号
tVoucherEntry.setFEntryID(String.valueOf(i));
productDistributionOrderKingDeeDao.addVoucherEntry(tVoucherEntry);
i++;
}
}
}
}
@TargetDataSource("dataSource")
@Override
public List<Tvoucher> storeReturnOrderVoucher(DateInfo date) throws Exception {
log.info("进入productDistributionOrderVoucher方法,查询百盛商店配货单数据处理并生成单据集合");
List<Object> list = productDistributionOrderBSDao.getReturnVoucher(date);
DateInfo dateInfo = DateUtil.dateData();
List<Tvoucher> tVoucherList = new ArrayList<>();
for(Object obj : list) {
if(!ObjectUtils.isEmpty(obj)) {
Map<String,Object> map = (Map<String, Object>)obj;
Tvoucher voucher = VoucherUtil.getVoucher();
//凭证日期
voucher.setFDate(dateInfo.getCurrentTime());
//业务日期
voucher.setFTransDate(dateInfo.getCurrentTime());
//年份
voucher.setFYear(dateInfo.getCurrentYear());
//会计期间
voucher.setFPeriod(dateInfo.getCurrentMonth());
//摘要
voucher.setFExplanation("摘要");
//分录数
voucher.setFEntryCount(String.valueOf(map.get("TOTAL")));
//借方金额合计
voucher.setFDebitTotal(String.valueOf(map.get("CBJE")));
//贷方金额合计
voucher.setFCreditTotal(String.valueOf(map.get("CBJE")));
//贷方:CKMC
voucher.setCredit(String.valueOf(map.get("CKMC")));
//返回百盛获取到的数据
tVoucherList.add(voucher);
}
}
return tVoucherList;
}
@TargetDataSource("dataSource")
@Override
public List<TvoucherEntry> storeReturnOrderVoucherEntry(DateInfo date) throws Exception {
log.info("进入productDistributionOrderVoucherEntry方法,查询百盛商店配货单数据处理并生成单据分录集合");
List<Object> list = productDistributionOrderBSDao.getReturnVoucherEntry(date);
List<TvoucherEntry> tVoucherEntryList = new ArrayList<>();
for(Object obj : list) {
if(!ObjectUtils.isEmpty(obj)) {
TvoucherEntry tvoucherEntry = VoucherUtil.getVoucherEntry();
Map<String, Object> map = (Map<String, Object>) obj;
//摘要
tvoucherEntry.setFExplanation("摘要");
//余额方向 0-贷方,1- 借方
tvoucherEntry.setFDC("0");
//金额(原币)
tvoucherEntry.setFAmountFor(String.valueOf(map.get("CBJE")));
//金额(本位币)
tvoucherEntry.setFAmount(String.valueOf(map.get("CBJE")));
//贷方:CKMC
tvoucherEntry.setCredit((String)map.get("CKMC"));
//借方:CKMC1
tvoucherEntry.setDebit((String)map.get("CKMC1"));
tVoucherEntryList.add(tvoucherEntry);
}
}
return tVoucherEntryList;
}
@Transactional(rollbackFor = {Exception.class})
@TargetDataSource("ds1")
@Override
public void insertStoreReturnOrderVoucher(List<Tvoucher> tVoucherList, List<TvoucherEntry> tVoucherEntryList) throws Exception {
log.info("进入insertStoreReturnOrderVoucher方法,插入商店配货单数据到金蝶凭证");
for(Tvoucher tvoucher : tVoucherList) {
Tvoucher obj = productDistributionOrderKingDeeDao.selectLastVoucher();
String FVoucherID = "0";
if (obj != null) {
FVoucherID = String.valueOf(Integer.parseInt(obj.getFVoucherID()) + 1);
}
tvoucher.setFVoucherID(FVoucherID);
tvoucher.setFNumber(FVoucherID);
tvoucher.setFSerialNum(FVoucherID);
//插入凭证数据到金蝶系统
productDistributionOrderKingDeeDao.addVoucher(tvoucher);
//用于生成分录号
int i = 0;
//贷方数据
TvoucherEntry tvoucherEntryTotal = VoucherUtil.getVoucherEntry();
//根据仓库名称CKMC查询对应的FItemID
Map<String,Object> fItemid = (Map<String, Object>) productDistributionOrderKingDeeDao.selectFItemID(tvoucher.getCredit());
if(fItemid == null || fItemid.isEmpty()) {
//核算项目
tvoucherEntryTotal.setFDetailID("0");
} else {
//核算项目
tvoucherEntryTotal.setFDetailID(String.valueOf(fItemid.get("FDetailID")));
}
//摘要
tvoucherEntryTotal.setFExplanation("摘要");
//金额(原币)
tvoucherEntryTotal.setFAmountFor(tvoucher.getFDebitTotal());
//金额(本位币)
tvoucherEntryTotal.setFAmount(tvoucher.getFDebitTotal());
//贷方-CKMC1
tvoucherEntryTotal.setCredit(tvoucher.getCredit());
//科目内码
tvoucherEntryTotal.setFAccountID(ymlProp.getSubjectStockGoods());
//对方科目
tvoucherEntryTotal.setFAccountID2(ymlProp.getSubjectStockGoods());
//凭证内码
tvoucherEntryTotal.setFVoucherID(FVoucherID);
//分录号
tvoucherEntryTotal.setFEntryID(String.valueOf(i));
//余额方向 0-贷方,1- 借方
tvoucherEntryTotal.setFDC("1");
productDistributionOrderKingDeeDao.addVoucherEntry(tvoucherEntryTotal);
i++;
for(TvoucherEntry tVoucherEntry : tVoucherEntryList) {
if(tvoucher.getCredit().equals(tVoucherEntry.getCredit())) {
//根据仓库名称CKMC查询对应的FItemID
Map<String,Object> ghsId = (Map<String, Object>) productDistributionOrderKingDeeDao.selectFItemID(tVoucherEntry.getDebit());
if(ghsId == null || ghsId.isEmpty()) {
//核算项目
tVoucherEntry.setFDetailID("0");
} else {
//核算项目
tVoucherEntry.setFDetailID(String.valueOf(ghsId.get("FDetailID")));
}
//科目内码
tVoucherEntry.setFAccountID(ymlProp.getSubjectStockGoods());
//对方科目
tVoucherEntry.setFAccountID2(ymlProp.getSubjectStockGoods());
//凭证内码
tVoucherEntry.setFVoucherID(FVoucherID);
//分录号
tVoucherEntry.setFEntryID(String.valueOf(i));
productDistributionOrderKingDeeDao.addVoucherEntry(tVoucherEntry);
i++;
}
}
}
}
}
<file_sep>package org.spring.boot.multiple.ds.controller;
import org.spring.boot.multiple.ds.bean.DateInfo;
import org.spring.boot.multiple.ds.bean.Tvoucher;
import org.spring.boot.multiple.ds.bean.TvoucherEntry;
import org.spring.boot.multiple.ds.service.*;
import org.spring.boot.multiple.ds.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @author 刘世杰
* EnableScheduling:开启定时任务
* {@link #goodsReceiptVoucher()}:商品进货单据
* {@link #goodsReturnReceipt()}:商品退货单据
* {@link #merchandiseShiftVoucher()}:商品移仓单据(移入)
* {@link #merchandiseShiftOutVoucher()}:商品移仓单据(移出)
* {@link #productDistributionOrderVoucher()}:商店配货单据
* {@link #storeReturnOrderVoucher()}:商店退货单据
* {@link #incomingStatement()}:进货结算单
* <em>
* 商场销售抽取时间段: [上个月26日,本月25日]
* 商场销售外抽取时间段: [上个月1日,上个月最后1日]
* </em>
*/
@SuppressWarnings("unchecked")
@EnableScheduling
@RestController
public class YueTuController {
@Autowired
private GoodsIntoReturnService goodsIntoReturnService;
@Autowired
private MerchandiseShiftService merchandiseShiftService;
@Autowired
private ProductDistributionOrderService productDistributionOrderService;
@Autowired
private IsExtractService isExtractService;
@Autowired
private incomingStatementService incomingStatementService;
@Autowired
private SalesReceiptService salesReceiptService;
/**
* default msg
*/
private String msg = "SUCCESS";
/**
* 抽取商品进货单据
* 每月1日0时定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/goodsReceiptVoucher")
public String goodsReceiptVoucher() {
try {
Boolean isExtract = isExtract("商品进货单");
//单据未抽取才能进行单据抽取
if (isExtract) {
msg = "本月商品进货单据已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
List<Tvoucher> tVoucherList = goodsIntoReturnService.goodsReceiptVoucher(date);
List<TvoucherEntry> tVoucherEntryList = goodsIntoReturnService.goodsReceiptVoucherEntry(date);
goodsIntoReturnService.insertGoodsReceiptVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("商品进货单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取商品退货单据
* 每月1日0时定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/goodsReturnReceiptVoucher")
public String goodsReturnReceipt() {
Boolean isExtract = isExtract("商品退货单");
try {
//单据未抽取才能进行单据抽取
if (isExtract) {
msg = "本月商品退货单据已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
List<Tvoucher> tVoucherList = goodsIntoReturnService.goodsReturnReceiptVoucher(date);
List<TvoucherEntry> tVoucherEntryList = goodsIntoReturnService.goodsReturnVoucherEntry(date);
goodsIntoReturnService.insertGoodsReturnReceiptVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("商品退货单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取商品移仓单单据--移入
* 每月1日0时定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/merchandiseShiftVoucher")
public String merchandiseShiftVoucher() {
Boolean isExtract = isExtract("商品移仓单");
try {
//单据未抽取才能进行单据抽取
if (isExtract) {
msg = "本月商品移仓单据(移入)已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
List<Tvoucher> tVoucherList = merchandiseShiftService.merchandiseShiftVoucher(date);
List<TvoucherEntry> tVoucherEntryList = merchandiseShiftService.merchandiseShiftVoucherEntry(date);
merchandiseShiftService.insertMerchandiseShiftVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("商品移仓单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取商品移仓单单据--移出
* 每月1日0时定期执行-cron表达式
*/
@SuppressWarnings(value = "all")
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/merchandiseShiftOutVoucher")
public String merchandiseShiftOutVoucher() {
String msg = "success";
Boolean isExtract = isExtract("商品移仓单移出");
try {
//单据未抽取才能进行单据抽取
if (isExtract) {
return "本月商品移仓单据(移出)已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
List<Tvoucher> tVoucherList = merchandiseShiftService.merchandiseShiftOutVoucher(date);
List<TvoucherEntry> tVoucherEntryList = merchandiseShiftService.merchandiseShiftOutVoucherEntry(date);
merchandiseShiftService.insertMerchandiseShiftVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("商品移仓单移出");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取商店配货单单据
* 每月1日定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/productDistributionOrderVoucher")
public String productDistributionOrderVoucher() {
Boolean isExtract = isExtract("商店配货单");
try {
//单据未抽取才能进行单据抽取
if (isExtract) {
msg = "本月商店配货单单据已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
List<Tvoucher> tVoucherList = productDistributionOrderService.productDistributionOrderVoucher(date);
List<TvoucherEntry> tVoucherEntryList = productDistributionOrderService.productDistributionOrderVoucherEntry(date);
productDistributionOrderService.insertProductDistributionOrderVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("商店配货单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取商店退货单单据
* 每月1日0时定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/storeReturnOrderVoucher")
public String storeReturnOrderVoucher() {
Boolean isExtract = isExtract("商店退货单");
try {
//单据未抽取才能进行单据抽取
if (isExtract) {
msg = "本月商店退货单单据已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
List<Tvoucher> tVoucherList = productDistributionOrderService.storeReturnOrderVoucher(date);
List<TvoucherEntry> tVoucherEntryList = productDistributionOrderService.storeReturnOrderVoucherEntry(date);
productDistributionOrderService.insertStoreReturnOrderVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("商店退货单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取进货结算单
* 每月1日0时定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/incomingStatement")
public String incomingStatement() {
Boolean isExtract = isExtract("进货结算单");
try {
if (isExtract) {
msg = "本月商店退货单单据已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
Map<String, List<Object>> map = incomingStatementService.incomingStatementVoucher(date);
List<Tvoucher> tVoucherList = new ArrayList<>();
List<TvoucherEntry> tVoucherEntryList = new ArrayList<>();
List<Object> list01 = map.get("voucher");
List<Object> list02 = map.get("voucherEntry");
for (Object obj : list01) {
tVoucherList = (List<Tvoucher>) obj;
}
for(Object obj : list02) {
tVoucherEntryList = (List<TvoucherEntry>)obj;
}
incomingStatementService.insertIncomingStatementVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("进货结算单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 抽取销货收款单
* 每月1日0时定期执行-cron表达式
*/
@Scheduled(cron = "0 0 0 1 * ?")
@RequestMapping("/salesReceipt")
public String salesReceipt() {
Boolean isExtract = isExtract("销货收款单");
try {
if (isExtract) {
msg = "本月销货收款单单据已经抽取完成,不能重复抽取";
} else {
//日期相关数据
DateInfo date = DateUtil.dateData();
Map<String, List<Object>> map = salesReceiptService.salesReceiptVoucher(date);
List<Tvoucher> tVoucherList = new ArrayList<>();
List<TvoucherEntry> tVoucherEntryList = new ArrayList<>();
List<Object> list01 = map.get("voucher");
List<Object> list02 = map.get("voucherEntry");
for (Object obj : list01) {
tVoucherList = (List<Tvoucher>) obj;
}
for(Object obj : list02) {
tVoucherEntryList = (List<TvoucherEntry>)obj;
}
salesReceiptService.insertSalesReceiptVoucher(tVoucherList,tVoucherEntryList);
isExtractService.changeExtractStatus("销货收款单");
}
} catch (Exception e) {
msg = e.getMessage();
}
return msg;
}
/**
* 判断本月该类单据是否抽取完成
* <strong>"1":本次单据已经抽取;"0":本次单据未抽取</strong>
* @return
*/
private Boolean isExtract(String type) {
boolean isExtract = false;
try {
//判断单据是否存在表中
Object obj = isExtractService.isExtract(type);
if(obj != null) {
Map<String,String> map = (Map<String,String>)obj;
String str = map.get("isExtract");
if(Objects.equals("1",str.trim())) {
isExtract = true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return isExtract;
}
}
| ed49b4705e40299861f31e5c1aa5c10a40639fca | [
"Markdown",
"Java"
] | 16 | Java | sineava/com.yuetu.io | 9a7c54898640ef50d8430c94d34dd7181fe1cda7 | bcd450017b14370a995b00b94b9a5c48c0741abc |
refs/heads/master | <file_sep>import React from 'react';
import 'react-bootstrap';
import { Grid, Col } from 'react-bootstrap';
import HeaderComponent from '../header/headerComponent';
import FooterComponent from '../footer/footerComponent';
import Aux from '../hoc/aux';
import DashboardComponent from '../dashboard/dashboardConatiner';
const home = (props) => {
return (
<Aux>
<Grid fluid={true}>
<HeaderComponent />
<Col className="main-content" xs={12} md={12}>
<DashboardComponent />
</Col>
<FooterComponent />
</Grid>
</Aux>
)
}
export default home;
<file_sep>import React, { Component } from 'react';
import { Breadcrumb, Row, Col } from 'react-bootstrap';
import { connect } from 'react-redux';
import * as actionBuilder from "../actions/index";
import BrandsComponent from './components/brandComponent';
import QuickMarketComponent from './components/quickMarketComponent';
import MixTrendsComponent from './components/mixTrendsComponent';
import RxTrendsComponent from './components/rxTrendesComponent';
import CostMetricsComponent from './components/costMetricsComponents';
import MapComponent from './components/mapComponent';
class DashboardComponent extends Component {
state = {
brands: [],
dashboardData: []
}
componentDidMount() {
this.props.loadAllDashboardData()
}
componentWillReceiveProps(nextProps) {
this.setState({
dashboardData: nextProps.dashboardData, brands: nextProps.brands
})
}
render() {
return (
<div className="dashboard-container">
<Row>
<Col xs={6} md={6}>
<p className="margin-0">Market Dashboard - GLP -1</p>
<Breadcrumb> Home / Market</Breadcrumb>
</Col>
<Col xs={6} md={6}>
<div className="pull-right" >
<p className="margin-0">P12: Proir 12 months</p>
<p>R12: Recent 12 months</p>
</div>
</Col>
</Row>
{this.state.dashboardData.patients ? <QuickMarketComponent quickData={this.state.dashboardData.quick} /> : null}
<Col xs={6} md={6}>
<BrandsComponent brandsData={this.state.brands} />
</Col>
<Col xs={6} md={6}>
<MapComponent />
</Col>
<Row className="trends-container">
{this.state.dashboardData.patients ? <MixTrendsComponent patientsData={this.state.dashboardData.patients} /> : null}
{this.state.dashboardData.rx ? <RxTrendsComponent rxData={this.state.dashboardData.rx} /> : null}
{this.state.dashboardData.cost ? <CostMetricsComponent costData={this.state.dashboardData.cost} /> : null}
</Row>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
dashboardData: state.dashboardData.dashboard,
brands: state.dashboardData.brands
}
}
const mapDispatchToProps = (dispatch) => {
return {
loadAllDashboardData: () => dispatch(actionBuilder.loadDashboard())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DashboardComponent);
<file_sep>import React from 'react';
import { Panel, Table, Badge } from 'react-bootstrap';
const brandsComponent = (props) => {
const featuredData = props.brandsData.reduce(function (acc, val) {
if (acc.length === 0 || acc.current_rank > val.current_rank) {
acc.push(val);
}
return acc;
}, [])
let featuredTemplate = featuredData.map(item => {
return (
<tr className="border-1" key={item.name}>
<td><p>FEATURED BRAND</p>{item.name}</td>
<td className="text-right"><Badge>{item.previous_rank} %</Badge></td>
<td className="text-right"> {(item.current_rank > item.previous_rank) ? <span className="positive-arrow glyphicon glyphicon-arrow-up"></span> : <span className="negative-arrow glyphicon glyphicon-arrow-down"></span> }</td>
<td className="text-center"><Badge className={(item.current_rank > item.previous_rank) ? 'badge-positive' : 'badge-negitive'}>{item.current_rank} %</Badge></td>
</tr>
)
});
const otherBrands = props.brandsData.filter(brand => brand.current_rank !== featuredData[0].current_rank);
let brandsTemplate = otherBrands.map((item, index) => {
return (
<tr key={item.name}>
{index===0 ? <td> <p >Other Brands</p> {item.name}</td> : <td> {item.name}</td>}
<td className="text-right"><Badge>{item.previous_rank} %</Badge></td>
<td className="text-right">{(item.current_rank > item.previous_rank) ? <span className="positive-arrow glyphicon glyphicon-arrow-up"></span> : <span className="negative-arrow glyphicon glyphicon-arrow-down"></span> }</td>
<td className="text-center"><Badge className={(item.current_rank > item.previous_rank) ? 'badge-positive' : 'badge-negitive'}>{item.current_rank} %</Badge></td>
</tr>
)
});
return (
<Panel className="brands-container">
<Table>
<thead>
<tr>
<th className="text-left">GLP- 1 Brands</th>
<th colSpan="3" className="text-center">Patient Share</th>
</tr>
<tr>
<th></th>
<th className="text-right">P12</th>
<th></th>
<th className="text-center">R12</th>
</tr>
</thead>
<tbody>
{featuredTemplate}
{brandsTemplate}
</tbody>
</Table>
</Panel>
);
}
export default brandsComponent;<file_sep>import React from 'react';
import { Panel, Table } from 'react-bootstrap';
const TableViewComponent = (props) => {
return (
<Panel>
<Panel.Title >
{props.panelTitle}
</Panel.Title>
<Table>
<thead>
<tr>
<th colSpan="2"></th>
<th className="previous-label">P12</th>
<th>R12</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>{props.tableData}</tbody>
</Table>
</Panel>
);
}
export default TableViewComponent;<file_sep>import React, { Component } from 'react';
import { BrowserRouter as Router } from "react-router-dom";
import '../assets/css/styles.css';
import { connect } from 'react-redux';
import Home from './homecomponent';
import * as actionBuilder from "../actions/index";
class HomeComponent extends Component {
state = {
loggedIn:true
}
componentWillMount () {
this.props.loadBrands();
}
render() {
let content = null;
if (this.state.loggedIn) {
content = <Home />
} else {
content = "Login";
}
return (
<Router>
{content}
</Router>
);
}
}
const mapStateToProps = (state) => {
return {}
}
const mapDispatchToProps = (dispatch) => {
return {
loadBrands:() => dispatch(actionBuilder.loadBrands())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomeComponent);
<file_sep># analytics-dashboard-react
Analytics UI with ReactJS
<file_sep>import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router } from 'react-router-dom';
import Route from './routes';
import aytwStore from './store';
class AmpleApp extends Component {
render() {
return (
<Provider store={aytwStore}>
<Router>
<Route />
</Router>
</Provider>
);
}
}
export default AmpleApp;
<file_sep>import React from 'react';
import { Row, Jumbotron,Col } from 'react-bootstrap';
const QuickMarketComponent = (props) => {
let quickTemplate = props.quickData.map(item => {
return (
<Col key={item.name} xs={3} md={3}>
<Jumbotron className={item.name}>
<span> {item.name} </span>
<div className="quick-items">
<span className="pull-left"> {Math.floor(item.previous % 1000000 % 10) } M</span> / <span className="current-item"> { Math.floor(item.current % 1000000 % 10) } M </span>
{(item.current > item.previous) ? <span className="positive-arrow glyphicon glyphicon-arrow-up"></span> : <span className="negative-arrow glyphicon glyphicon-arrow-down"></span> }<span className=""> {Math.floor(Math.abs(item.previous - item.current) /100 % 10) } % </span></div>
<div className="sub-title"> <span className="pull-left"> PI2 </span> <span className="pull-right">RI2</span> </div>
</Jumbotron>
</Col>
)
});
return (
<Row className="quick-container">
{quickTemplate}
</Row>
);
}
export default QuickMarketComponent;<file_sep>import React from 'react';
import { Col } from 'react-bootstrap';
import TableViewComponent from '../../hoc/tableviewComponent';
const CostMetricsComponent = (props) => {
let costTemplate = props.costData.map(item => {
return (
<tr key={item.name}>
<td colSpan="2">{item.name}</td>
<td className="previous-label">{item.previous }</td>
<td>{item.current}</td>
<td>{(item.current > item.previous) ? <span className="positive-arrow glyphicon glyphicon-arrow-up"></span> : <span className="negative-arrow glyphicon glyphicon-arrow-down"></span> }</td>
<td className={(item.current > item.previous) ? 'number-positive' : 'number-negitive'}>{(Math.abs(item.previous - item.current)).toFixed(2)} %</td>
</tr>
)
});
return (
<Col xs={4} md={4}>
<TableViewComponent panelTitle={'Managed Care Metrics'} tableData={costTemplate} />
</Col>
);
}
export default CostMetricsComponent;<file_sep>export {
loadDashboard,
loadBrands,
loadPatients
} from './actionBuilder';<file_sep>
import axios from 'axios';
export const getBrandsData = () => {
return axios.get('/mockdata/data.json')
.then((response) => {
return response.data.top_brands;
})
.catch((err) => { })
}
export const getPatientsData = () => {
return axios.get('/mockdata/data.json')
.then((response) => {
return response.data.patients;
})
.catch((err) => { })
}
export const getDashboardData = () => {
return axios.get('/mockdata/data.json')
.then((response) => {
return response.data;
})
.catch((err) => { })
}
<file_sep>import * as actionDispatch from './actionDispatch';
import * as services from '../services';
export const loadBrands = () => {
return dispatch => {
services.getBrandsData()
.then(response => {
dispatch(actionDispatch.onLoadBrands(response));
})
}
}
export const loadPatients = () => {
return dispatch => {
services.getPatientsData()
.then(response => {
dispatch(actionDispatch.onLoadPatients(response));
})
}
}
export const loadDashboard = () => {
return dispatch => {
services.getDashboardData()
.then(response => {
dispatch(actionDispatch.onLoadDashboardData(response));
})
}
}
<file_sep>
import React from 'react';
import { Panel, Image, } from 'react-bootstrap';
import mapImage from '../../assets/images/map.png';
const MapComponent = (props) => {
return (
<Panel>
<Panel.Title >
GLP-1 Patient Distribution (Total Mapped 16M)
</Panel.Title>
<Panel.Body>
<Image src={mapImage} thumbnail />
</Panel.Body>
</Panel>
);
}
export default MapComponent;<file_sep>import React from 'react';
const FooterComponent = (props) => {
return(
<p className="pull-right">Powered by © Anyalytical Wizards.</p>
);
}
export default FooterComponent;<file_sep>import * as actionTypes from '../actions/actionTypes';
const intialState = {
dashboard: [],
brands:[],
patients:[]
}
const dashboardReducer = function (currentState = intialState, action) {
switch (action.type) {
case actionTypes.ON_LOAD_DASHBOARD:
return {
...currentState,
dashboard: action.payload
}
case actionTypes.ON_LOAD_BRANDS:
return {
...currentState,
brands: action.payload
}
case actionTypes.ON_LOAD_PATIENTS:
return {
...currentState,
patients: action.payload
}
default:
return currentState
}
}
export default dashboardReducer; | 9b1ad863187d1843df05e169463c958ab78bde51 | [
"JavaScript",
"Markdown"
] | 15 | JavaScript | spal0002/analytics-dashboard | ef916f1f7a2aa05eabcad953c0ba59a69e89a6e4 | e14ff6c8ad1805a1d2530a9f492e758e8754ab5e |
refs/heads/master | <repo_name>JianqingHe/netty-parent<file_sep>/netty-server/src/main/java/netty/server/http/HttpServerHandler.java
package netty.server.http;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.AsciiString;
import lombok.extern.slf4j.Slf4j;
import netty.server.http.entity.User;
import netty.server.http.serialize.SerializerImpl;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.codec.Charsets;
import org.springframework.http.MediaType;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
/**
* http拦截
*
* @author hejq
* @date 2019/7/16 16:56
*/
@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
private HttpHeaders headers;
private FullHttpRequest fullRequest;
private static final String FAVICON_ICO = "/favicon.ico";
private static final AsciiString CONTENT_TYPE = AsciiString.cached("Content-Type");
private static final AsciiString CONTENT_LENGTH = AsciiString.cached("Content-Length");
private static final AsciiString CONNECTION = AsciiString.cached("Connection");
private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive");
/**
* 建立连接,发送消息通知
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.write("It is " + LocalDateTime.now() + " now.\r\n");
log.info("[netty-process] connection success!!\r\n");
ctx.flush();
}
/**
* <strong>Please keep in mind that this method will be renamed to
* {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
* <p>
* Is called for each message of type {@link }.
*
* @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
* belongs to
* @param msg the message to handle
* @throws Exception is thrown if an error occurred
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
User user = new User("hejq");
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
headers = request.headers();
String uri = request.uri();
log.info("[http uri] {}", uri);
if (FAVICON_ICO.equals(uri)) {
return;
}
HttpMethod method = request.method();
if (HttpMethod.GET.equals(method)) {
QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, Charsets.toCharset(CharEncoding.UTF_8));
Map<String, List<String>> uriAttributes = queryDecoder.parameters();
//此处仅打印请求参数(你可以根据业务需求自定义处理)
for (Map.Entry<String, List<String>> attr : uriAttributes.entrySet()) {
for (String attrVal : attr.getValue()) {
log.info(attr.getKey() + "=" + attrVal);
}
}
user.setMethod("get");
} else if (HttpMethod.POST.equals(method)) {
//POST请求,由于你需要从消息体中获取数据,因此有必要把msg转换成FullHttpRequest
fullRequest = (FullHttpRequest)msg;
//根据不同的Content_Type处理body数据
dealWithContentType();
user.setMethod("post");
}
SerializerImpl serializer = new SerializerImpl();
byte[] content = serializer.serialize(user);
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(content));
response.headers().set(CONTENT_TYPE, "text/plain");
response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());
boolean keepAlive = HttpUtil.isKeepAlive(request);
if (!keepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, KEEP_ALIVE);
ctx.write(response);
}
}
}
/**
* 处理content-type
*/
private void dealWithContentType() {
String contentType = getContentType();
//可以使用HttpJsonDecoder
switch (contentType) {
case MediaType.APPLICATION_JSON_VALUE: {
String jsonStr = fullRequest.content().toString(Charsets.toCharset(CharEncoding.UTF_8));
JSONObject obj = JSON.parseObject(jsonStr);
for (Map.Entry<String, Object> item : obj.entrySet()) {
log.info("[msg] -> " + item.getKey() + "=" + item.getValue().toString());
}
break;
}
case MediaType.APPLICATION_FORM_URLENCODED_VALUE: {
//方式一:使用 QueryStringDecoder
String jsonStr = fullRequest.content().toString(Charsets.toCharset(CharEncoding.UTF_8));
QueryStringDecoder queryDecoder = new QueryStringDecoder(jsonStr, false);
Map<String, List<String>> uriAttributes = queryDecoder.parameters();
for (Map.Entry<String, List<String>> attr : uriAttributes.entrySet()) {
for (String attrVal : attr.getValue()) {
log.info("[msg] -> " + attr.getKey() + "=" + attrVal);
}
}
break;
}
case MediaType.MULTIPART_FORM_DATA_VALUE:
log.info("文件上传");
break;
default:
log.info("其他");
break;
}
}
/**
* 捕获异常
*
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
log.error(cause.getMessage());
cause.printStackTrace();
ctx.close();
}
/**
* 完成消息读取
*
* @param ctx
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
log.info("[netty-process] complete!!\r\n");
ctx.flush();
}
/**
* 获取contentType
*
* @return 参数content-type
*/
private String getContentType(){
String typeStr = headers.get("Content-Type");
String[] list = typeStr.split(";");
return list[0];
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/proto/DisConnect.java
package netty.iot.proto;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import netty.iot.entity.SessionStore;
import netty.iot.sevice.DupRepublishMessageStoreService;
import netty.iot.sevice.DupResendMessageStoreService;
import netty.iot.sevice.SessionStoreService;
import netty.iot.sevice.SubscribeStoreService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 关闭连接
*
* @author hejq
* @date 2019/7/19 9:59
*/
@Slf4j
public class DisConnect {
@Autowired
private SessionStoreService sessionStoreService;
@Autowired
private SubscribeStoreService subscribeStoreService;
@Autowired
private DupRepublishMessageStoreService republishMessageStoreService;
@Autowired
private DupResendMessageStoreService resendMessageStoreService;
/**
* 关闭连接
*
* @param channel 信道
*/
public void disConnect(Channel channel) {
String clientId = channel.attr(AttributeKey.valueOf("clientId")).get().toString();
SessionStore sessionStore = sessionStoreService.getByClientId(clientId);
if (null != sessionStore && sessionStore.isCleanSession()) {
subscribeStoreService.removeForClient(clientId);
republishMessageStoreService.removeByClient(clientId);
resendMessageStoreService.removeByClient(clientId);
log.info("DISCONNECT - clientId: {}, cleanSession: {}", clientId, sessionStore.isCleanSession());
}
sessionStoreService.removeByClientId(clientId);
channel.close();
}
public void processDisConnect(Channel channel,MqttMessage msg){
String clientId = (String) channel.attr(AttributeKey.valueOf("clientId")).get();
SessionStore sessionStore = sessionStoreService.getByClientId(clientId);
if (sessionStore!=null && sessionStore.isCleanSession()){
subscribeStoreService.removeForClient(clientId);
republishMessageStoreService.removeByClient(clientId);
resendMessageStoreService.removeByClient(clientId);
}
log.info("DISCONNECT - clientId: {}, cleanSession: {}", clientId, sessionStore.isCleanSession());
sessionStoreService.removeByClientId(clientId);
channel.close();
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/sevice/RetainMessageStoreService.java
package netty.iot.sevice;
import netty.iot.entity.RetainMessageStore;
/**
* 消息存储服务接口
*
* @author hejq
* @date 2019/7/18 17:05
*/
public interface RetainMessageStoreService {
/**
* 删除retain标志消息
*
* @param topic 主题
*/
void remove(String topic);
/**
* 存储retain标志消息
*
* @param topic 主题
* @param retainMessageStore 内部消息
*/
void put(String topic, RetainMessageStore retainMessageStore);
}
<file_sep>/netty-server/src/main/java/netty/server/http/serialize/SerializerImpl.java
package netty.server.http.serialize;
import com.alibaba.fastjson.JSON;
/**
* 序列化实现
*
* @author hejq
* @date 2019/7/16 17:00
*/
public class SerializerImpl implements Serializer {
/**
* java 对象转换成二进制
*
* @param object
*/
@Override
public byte[] serialize(Object object) {
return JSON.toJSONBytes(object);
}
/**
* 二进制转换成 java 对象
*
* @param clazz
* @param bytes
*/
@Override
public <T> T deserialize(Class<T> clazz, byte[] bytes) {
return JSON.parseObject(bytes, clazz);
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/sevice/MessageIdService.java
package netty.iot.sevice;
/**
* 生产报文id接口
*
* @author hejq
* @date 2019/7/18 17:05
*/
public interface MessageIdService {
/**
* 获取下一个报文标识符
*
* @return 下一个报文标识符
*/
int getNextMessageId();
}
<file_sep>/netty-iot/src/main/java/netty/iot/sevice/KafkaService.java
package netty.iot.sevice;
import netty.iot.entity.InternalMessage;
/**
* kafka接口
*
* @author hejq
* @date 2019/7/18 17:04
*/
public interface KafkaService {
/**
* kafka发送消息
*
* @param internalMessage 内部消息
*/
void send(InternalMessage internalMessage);
}
<file_sep>/netty-iot/src/main/java/netty/iot/server/MqttServer.java
package netty.iot.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.util.ResourceLeakDetector;
import lombok.extern.slf4j.Slf4j;
import netty.iot.handler.MqttTransportHandler;
import netty.iot.proto.ProtoProcess;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* mqtt server配置
*
* @author hejq
* @date 2019/7/19 14:45
*/
@Component
@Slf4j
public class MqttServer {
@Value("${mqtt.bind_address}")
private String host;
@Value("${mqtt.bind_port}")
private Integer port;
@Value("${mqtt.adaptor}")
private String adaptorName;
@Value("${mqtt.netty.leak_detector_level}")
private String leakDetectorLevel;
@Value("${mqtt.netty.boss_group_thread_count}")
private Integer bossGroupThreadCount;
@Value("${mqtt.netty.worker_group_thread_count}")
private Integer workerGroupThreadCount;
@Value("${mqtt.netty.max_payload_size}")
private Integer maxPayloadSize;
@Autowired
private ProtoProcess protoProcess;
private Channel serverChannel;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
/**
* 初始化netty服务器
*/
@PostConstruct
public void init() {
log.info("Setting resource leak detector level to {}", leakDetectorLevel);
ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));
log.info("Starting MQTT transport...");
bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
ServerBootstrap sp = new ServerBootstrap();
sp.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", new MqttDecoder(maxPayloadSize));
pipeline.addLast("encoder", MqttEncoder.INSTANCE);
MqttTransportHandler handler = new MqttTransportHandler(protoProcess);
pipeline.addLast(handler);
}
});
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/auth/AuthService.java
package netty.iot.auth;
/**
* 账户接口
*
* @author hejq
* @date 2019/7/18 16:19
*/
public interface AuthService {
/**
* 检验用户名密码
*
* @param userName 用户名
* @param password 密码
* @return 校验结果
*/
boolean checkAccount(String userName, String password);
}
<file_sep>/netty-iot/src/main/java/netty/iot/serializable/Serializer.java
package netty.iot.serializable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import netty.iot.entity.SessionStore;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* 序列化接口
*
* @author hejq
* @date 2019/7/18 17:08
*/
public class Serializer implements RedisSerializer<Object> {
private static Gson gson = new GsonBuilder().create();
/**
* 对象转二进制数据
*
* @param object 需要转换的数据
* @return 转换后的二进制数据
* @throws SerializationException 序列话转换异常
*/
@Override
public byte[] serialize(Object object) throws SerializationException {
return gson.toJson(object).getBytes();
}
/**
* 二进制转换成bean数据
*
* @param bytes 二进制数据
* @return bean数据
* @throws SerializationException 反序列化异常
*/
@Override
public Object deserialize(byte[] bytes) throws SerializationException {
return gson.fromJson(new String(bytes), SessionStore.class);
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/entity/SessionStore.java
package netty.iot.entity;
import java.io.Serializable;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import lombok.Data;
import lombok.NoArgsConstructor;
import io.netty.channel.Channel;
/**
* session存储
*
* @author hejq
* @date 2019/7/18 17:12
*/
@Data
@NoArgsConstructor
public class SessionStore implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 客户id
*/
private String clientId;
/**
* 通讯
*/
private Channel channel;
/**
* 是否清除缓存
*/
private boolean cleanSession;
/**
* mqtt发布消息
*/
private MqttPublishMessage willMessage;
public SessionStore(String clientId, Channel channel, boolean cleanSession, MqttPublishMessage willMessage) {
this.clientId = clientId;
this.channel = channel;
this.cleanSession = cleanSession;
this.willMessage = willMessage;
}
public SessionStore setClientId(String clientId) {
this.clientId = clientId;
return this;
}
public SessionStore setChannel(Channel channel) {
this.channel = channel;
return this;
}
public boolean isCleanSession() {
return cleanSession;
}
public SessionStore setCleanSession(boolean cleanSession) {
this.cleanSession = cleanSession;
return this;
}
public MqttPublishMessage getWillMessage() {
return willMessage;
}
public SessionStore setWillMessage(MqttPublishMessage willMessage) {
this.willMessage = willMessage;
return this;
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/sevice/impl/SessionStoreServiceImpl.java
package netty.iot.sevice.impl;
import netty.iot.entity.SessionStore;
import netty.iot.sevice.SessionStoreService;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 消息存储接口
*
* @author hejq
* @date 2019/7/19 15:39
*/
@Service
public class SessionStoreServiceImpl implements SessionStoreService {
private Map<String, SessionStore> sessionCache = new ConcurrentHashMap<>();
/**
* 存储消息
*
* @param clientId 客户id
* @param sessionStore session消息
*/
@Override
public void put(String clientId, SessionStore sessionStore) {
this.sessionCache.put(clientId, sessionStore);
}
/**
* 通过clientId查询session消息
*
* @param clientId clientId
* @return session消息
*/
@Override
public SessionStore getByClientId(String clientId) {
return sessionCache.get(clientId);
}
/**
* clientId的会话是否存在
*
* @param clientId clientId
* @return 是否存在
*/
@Override
public boolean containsKey(String clientId) {
return sessionCache.containsKey(clientId);
}
/**
* 删除会话
*
* @param clientId clientId
*/
@Override
public void removeByClientId(String clientId) {
this.sessionCache.remove(clientId);
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/proto/Connect.java
package netty.iot.proto;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.*;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import netty.iot.auth.AuthService;
import netty.iot.entity.DupRepublishMessageStore;
import netty.iot.entity.DupResendMessageStore;
import netty.iot.entity.SessionStore;
import netty.iot.sevice.DupRepublishMessageStoreService;
import netty.iot.sevice.DupResendMessageStoreService;
import netty.iot.sevice.SessionStoreService;
import netty.iot.sevice.SubscribeStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import java.util.List;
/**
* 连接
*
* @author hejq
* @date 2019/7/19 9:08
*/
@Slf4j
public class Connect {
@Autowired
private AuthService authService;
@Autowired
private SessionStoreService sessionStoreService;
@Autowired
private DupRepublishMessageStoreService republishMessageStoreService;
@Autowired
private DupResendMessageStoreService resendMessageStoreService;
@Autowired
private SubscribeStoreService subscribeStoreService;
/**
* 处理连接过程
*
* @param channel 信道
* @param connectMessage 连接信息
*/
public void processConnect(Channel channel, MqttConnectMessage connectMessage) {
// 消息解码异常
if (connectMessage.decoderResult().isFailure()) {
Throwable cause = connectMessage.decoderResult().cause();
if (cause instanceof MqttUnacceptableProtocolVersionException) {
// 不支持的协议版本
MqttConnAckMessage connAckMessage = (MqttConnAckMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION, false), null);
channel.writeAndFlush(connAckMessage);
} else if (cause instanceof MqttIdentifierRejectedException) {
// 不合格的clientId
MqttConnAckMessage connAckMessage = (MqttConnAckMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false), null);
channel.writeAndFlush(connAckMessage);
}
channel.close();
return;
}
// clientId为空或null的情况, 这里要求客户端必须提供clientId, 不管cleanSession是否为1, 此处没有参考标准协议实现
if (StringUtils.isEmpty(connectMessage.payload().clientIdentifier())) {
MqttConnAckMessage ackMessage = (MqttConnAckMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false), null);
channel.writeAndFlush(ackMessage);
return;
}
// 账户验证
String userName = connectMessage.payload().userName();
String password = connectMessage.payload().passwordInBytes() == null ? null : new String(connectMessage.payload().passwordInBytes(), CharsetUtil.UTF_8);
if (!authService.checkAccount(userName, password)) {
MqttConnAckMessage connAckMessage = (MqttConnAckMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD, false), null);
channel.writeAndFlush(connAckMessage);
channel.close();
return;
}
// 如果会话中已存储这个新连接的clientId, 就关闭之前该clientId的连接
if (sessionStoreService.containsKey(connectMessage.payload().clientIdentifier())) {
SessionStore sessionStore = sessionStoreService.getByClientId(connectMessage.payload().clientIdentifier());
Channel previous = sessionStore.getChannel();
Boolean cleanSession = sessionStore.isCleanSession();
if (cleanSession) {
sessionStoreService.removeByClientId(connectMessage.payload().clientIdentifier());
subscribeStoreService.removeForClient(connectMessage.payload().clientIdentifier());
republishMessageStoreService.removeByClient(connectMessage.payload().clientIdentifier());
resendMessageStoreService.removeByClient(connectMessage.payload().clientIdentifier());
}
previous.close();
}
//处理遗嘱信息
SessionStore sessionStore = new SessionStore(connectMessage.payload().clientIdentifier(), channel, connectMessage.variableHeader().isCleanSession(), null);
if (connectMessage.variableHeader().isWillFlag()) {
MqttPublishMessage willMessage = (MqttPublishMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.valueOf(connectMessage.variableHeader().willQos()), connectMessage.variableHeader().isWillRetain(), 0),
new MqttPublishVariableHeader(connectMessage.payload().willTopic(), 0),
Unpooled.buffer().writeBytes(connectMessage.payload().willMessageInBytes())
);
sessionStore.setWillMessage(willMessage);
}
//处理连接心跳包
if (connectMessage.variableHeader().keepAliveTimeSeconds() > 0) {
if (channel.pipeline().names().contains("idle")) {
channel.pipeline().remove("idle");
}
channel.pipeline().addFirst("idle", new IdleStateHandler(0, 0, Math.round(connectMessage.variableHeader().keepAliveTimeSeconds() * 1.5f)));
}
//至此存储会话消息及返回接受客户端连接
sessionStoreService.put(connectMessage.payload().clientIdentifier(), sessionStore);
//将clientId存储到channel的map中
channel.attr(AttributeKey.valueOf("clientId")).set(connectMessage.payload().clientIdentifier());
Boolean sessionPresent = sessionStoreService.containsKey(connectMessage.payload().clientIdentifier()) && !connectMessage.variableHeader().isCleanSession();
MqttConnAckMessage okResp = (MqttConnAckMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0),
new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, sessionPresent),
null
);
channel.writeAndFlush(okResp);
log.info("CONNECT - clientId: {}, cleanSession: {}", connectMessage.payload().clientIdentifier(), connectMessage.variableHeader().isCleanSession());
// 如果cleanSession为0, 需要重发同一clientId存储的未完成的QoS1和QoS2的DUP消息
if (!connectMessage.variableHeader().isCleanSession()) {
List<DupRepublishMessageStore> dupPublishMessageStoreList = republishMessageStoreService.getByClientId(connectMessage.payload().clientIdentifier());
dupPublishMessageStoreList.forEach(dupPublishMessageStore -> {
MqttPublishMessage publishMessage = (MqttPublishMessage) MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBLISH, true, MqttQoS.valueOf(dupPublishMessageStore.getMqttQos()), false, 0),
new MqttPublishVariableHeader(dupPublishMessageStore.getTopic(), dupPublishMessageStore.getMessageId()),
Unpooled.buffer().writeBytes(dupPublishMessageStore.getMessageBytes())
);
channel.writeAndFlush(publishMessage);
});
List<DupResendMessageStore> dupPubRelMessageStoreList = resendMessageStoreService.getByClientId(connectMessage.payload().clientIdentifier());
dupPubRelMessageStoreList.forEach(dupPubRelMessageStore -> {
MqttMessage pubRelMessage = MqttMessageFactory.newMessage(
new MqttFixedHeader(MqttMessageType.PUBREL, true, MqttQoS.AT_MOST_ONCE, false, 0),
MqttMessageIdVariableHeader.from(dupPubRelMessageStore.getMessageId()),
null
);
channel.writeAndFlush(pubRelMessage);
});
}
}
}
<file_sep>/netty-server/src/main/java/netty/server/ServerHandler.java
package netty.server;
import io.netty.channel.*;
import java.net.InetAddress;
import java.time.LocalDateTime;
/**
* 服务拦截
*
* @author hejq
* @date 2019/7/16 14:30
*/
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 建立连接,发送消息通知
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
ctx.write("It is " + LocalDateTime.now() + " now.\r\n");
ctx.flush();
}
/**
* 根据传入内容做出相应处理
*
* @param ctx 信道拦截
* @param request 传入的内容
* @throws Exception 异常
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String request) throws Exception {
String response;
boolean close = false;
if (request.isEmpty()) {
response = "please type something. \r\n";
} else if ("bye".equalsIgnoreCase(request)) {
response = "goodbye !! \r\n";
close = true;
} else {
response = LocalDateTime.now() + ": Did you say '" + request + "' ? \r\n";
}
ChannelFuture cf = ctx.write(response);
if (close) {
cf.addListener(ChannelFutureListener.CLOSE);
}
}
/**
* 消息读取完成操作
*
* @param ctx
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
/**
* 异常处理
* @param ctx
* @param e
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
e.printStackTrace();
ctx.flush();
}
}
<file_sep>/netty-iot/src/main/java/netty/iot/auth/AuthServiceImpl.java
package netty.iot.auth;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.util.StringUtils;
import java.security.interfaces.RSAPrivateKey;
/**
* 账户接口
*
* @author hejq
* @date 2019/7/18 16:19
*/
public class AuthServiceImpl implements AuthService {
private RSAPrivateKey privateKey;
/**
* 检验用户名密码
*
* @param userName 用户名
* @param password 密码
* @return 校验结果
*/
@Override
public boolean checkAccount(String userName, String password) {
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
return false;
}
RSA rsa = new RSA(privateKey, null);
String checkValue = rsa.encryptBcd(userName, KeyType.PrivateKey);
return checkValue.equals(password);
}
}
| bc13abb73ad96eb389d769856ea9c861b0b1def6 | [
"Java"
] | 14 | Java | JianqingHe/netty-parent | 34cefd0826b1485d0af125616f237b73f360b501 | 86c3f73fb6764f595f42c2af733477a82a2f3c9f |
refs/heads/master | <file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2019 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_M_FED_WELL_KNOWN_H
namespace ircd::m::fed::well_known
{
string_view fetch(const mutable_buffer &out, const string_view &origin);
string_view get(const mutable_buffer &out, const string_view &origin);
extern conf::item<size_t> fetch_redirects;
extern conf::item<seconds> fetch_timeout;
extern conf::item<seconds> cache_max;
extern conf::item<seconds> cache_error;
extern conf::item<seconds> cache_default;
}
<file_sep># This — is The **Construct**
[](https://matrix.to/#/#construct:zemos.net) []() []()
The community's own Matrix server. It is designed to be fast and highly scalable,
and to be developed by volunteer contributors over the internet. This mission
strives to make the software easy to understand, modify, audit, and extend.
Matrix is about giving you control over your communication; Construct is about
giving you control over Matrix. Your privacy and security matters. We encourage
you to contribute new ideas and are liberal in accepting experimental features.
## Installation
### Dependencies
- **Boost** library 1.66+
- **RocksDB** library 5.17.2+
- **Sodium** library for curve ed25519.
- **OpenSSL** library for HTTPS TLS / X.509.
- **Magic** library for MIME type recognition.
##### OPTIONAL
- **lz4** or **snappy** database compressions.
- **GraphicsMagick** for media thumbnails.
- **jemalloc** for dynamic memory.
- **ICU** for unicode tools.
##### BUILD TOOLS
- **GNU C++** compiler, ld.gold, automake, autoconf, autoconf2.13,
autoconf-archive, libtool.
- A platform capable of loading dynamic shared objects at runtime is required.
<!--
#### Platforms
[](https://github.com/jevolk/charybdis/tree/master)
| <sub> Continuously Integrated Host </sub> | <sub> Compiler </sub> | <sub> Third party </sub> | <sub> Status </sub> |
|:------------------------------------------- |:------------------------ |:------------------------ |:------------------- |
| <sub> Linux Ubuntu 16.04 Xenial </sub> | <sub> GCC 6 </sub> | <sub> Boost 1.66 </sub> | [](https://travis-ci.org/jevolk/charybdis) |
| <sub> Linux Ubuntu 16.04 Xenial </sub> | <sub> GCC 8 </sub> | <sub> Boost 1.66 </sub> | [](https://travis-ci.org/jevolk/charybdis) |
| <sub> Linux Ubuntu 18.04 Xenial </sub> | <sub> GCC 6 </sub> | <sub> Boost 1.66 </sub> | [](https://travis-ci.org/jevolk/charybdis) |
-->
### Getting Started
1. At this phase of development the best thing to do is pull the master branch
and use the latest head.
2. See the [BUILD](https://github.com/matrix-construct/construct/wiki/BUILD) instructions to compile Construct from source.
3. See the [SETUP](https://github.com/matrix-construct/construct/wiki/SETUP) instructions to run Construct for the first time.
4. See the [TUNING](https://github.com/matrix-construct/construct/wiki/TUNING) guide to optimize Construct for your deployment.
##### TROUBLESHOOTING
See the [TROUBLESHOOTING](https://github.com/matrix-construct/construct/wiki/Troubleshooting-problems) guide for solutions to possible
problems.
See the [FREQUENTLY ASKED QUESTIONS](https://github.com/matrix-construct/construct/wiki/FAQ) for answers to the most common
perplexities.
## Developers
##### DOCUMENTATION
Generate doxygen using `doxygen ./Doxyfile` the target
directory is `doc/html`. Browse to `doc/html/index.html`.
##### ARCHITECTURE GUIDE
See the [ARCHITECTURE](https://github.com/matrix-construct/construct/wiki/ARCHITECTURE) summary for design choices and
things to know when starting out.
##### DEVELOPMENT STYLE GUIDE
See the [STYLE](https://github.com/matrix-construct/construct/wiki/STYLE) guide for an admittedly tongue-in-cheek lecture on
the development approach.
## Roadmap
##### TECHNOLOGY
- [x] Phase Zero: **Core libircd**: Utils; Modules; Contexts; JSON; Database; HTTP; etc...
- [x] Phase One: **Matrix Protocol**: Core VM; Core modules; Protocol endpoints; etc...
- [ ] Phase Two: **Construct Cluster**: Kademlia sharding of events; Maymounkov's erasure codes.
##### DEPLOYMENT
```
Operating a Construct server which is open to public user registration is unsafe. Local users may
be able to exceed resource limitations and deny service to other users.
```
- [x] **Personal**: Dozens of users. Few default restrictions; higher log output.
- [ ] **Company**: Hundreds of users. Moderate default restrictions.
- [ ] **Public**: Thousands of users. Untrusting configuration defaults.
> Due to the breadth of the Matrix client/server protocol we can only endorse
production use of Construct gradually while local user restrictions are
developed. This notice applies to locally registered users connecting with
clients, it does not apply to federation.
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_SIMD_POPCNT_H
namespace ircd::simd
{
template<class T> T popmask(const T) noexcept;
template<class T> T boolmask(const T) noexcept;
template<class T> uint popcnt(const T) noexcept;
}
/// Convenience template. Unfortunately this drops to scalar until specific
/// targets and specializations are created.
template<class T>
inline uint
ircd::simd::popcnt(const T a)
noexcept
{
uint ret(0), i(0);
for(; i < lanes<T>(); ++i)
if constexpr(sizeof_lane<T>() <= sizeof(int))
ret += __builtin_popcount(a[i]);
else if constexpr(sizeof_lane<T>() <= sizeof(long))
ret += __builtin_popcountl(a[i]);
else
ret += __builtin_popcountll(a[i]);
return ret;
}
/// Convenience template. Extends a bool value where the lsb is 1 or 0 into a
/// mask value like the result of vector comparisons.
template<class T>
inline T
ircd::simd::boolmask(const T a)
noexcept
{
return ~(popmask(a) - 1);
}
/// Convenience template. Vector compare instructions yield 0xff on equal;
/// sometimes one might need an actual value of 1 for accumulators or maybe
/// some bool-type reason...
template<class T>
inline T
ircd::simd::popmask(const T a)
noexcept
{
return a & 1;
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_SIMD_H
#include "type.h"
#include "traits.h"
#include "lane_cast.h"
#include "broad_cast.h"
#include "shift.h"
#include "popcnt.h"
#include "lzcnt.h"
#include "tzcnt.h"
#include "print.h"
namespace ircd
{
using simd::lane_cast;
using simd::shl;
using simd::shr;
using simd::lzcnt;
using simd::tzcnt;
using simd::popcnt;
using simd::popmask;
using simd::boolmask;
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_SIMD_TZCNT_H
namespace ircd::simd
{
template<class T> uint tzcnt(const T) noexcept;
}
/// Convenience template. Unfortunately this drops to scalar until specific
/// targets and specializations are created.
template<class T>
inline uint
__attribute__((target("lzcnt")))
ircd::simd::tzcnt(const T a)
noexcept
{
// The behavior of lzcnt/tzcnt can differ among platforms; when false we
// lzcnt/tzcnt to fall back to bsr/bsf-like behavior.
constexpr auto bitscan
{
#ifdef __LZCNT__
false
#else
true
#endif
};
uint ret(0), i(lanes<T>()), mask(-1U); do
{
if constexpr(bitscan && sizeof_lane<T>() <= sizeof(u16))
ret += (15 - __lzcnt16(a[--i])) & mask;
else if constexpr(sizeof_lane<T>() <= sizeof(u16))
ret += __lzcnt16(a[--i]) & mask;
else if constexpr(bitscan && sizeof_lane<T>() <= sizeof(u32))
ret += (31 - __lzcnt32(a[--i])) & mask;
else if constexpr(sizeof_lane<T>() <= sizeof(u32))
ret += __lzcnt32(a[--i]) & mask;
else if constexpr(bitscan)
ret += (63 - __lzcnt64(a[--i])) & mask;
else
ret += __lzcnt64(a[--i]) & mask;
static const auto lane_bits(sizeof_lane<T>() * 8);
mask &= boolmask(uint(ret % lane_bits == 0));
mask &= boolmask(uint(ret != 0));
}
while(i);
return ret;
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_BUFFER_STREAM_H
namespace ircd::buffer
{
size_t stream_aligned(const mutable_buffer &dst, const const_buffer &src);
}
/// Non-temporal copy. This copies from an aligned source to an aligned
/// destination without the data cycling through the d-cache. The alignment
/// requirements are currently very strict. The source and destination buffers
/// must begin at a cache-line alignment and the size of the buffers must be
/// a multiple of something we'll call "register-file size" which is the size
/// of all named multimedia registers (256 for SSE, 512 for AVX, 2048 for
/// AVX512) so it's safe to say buffers should just be aligned and padded out
/// to 4K page-size to be safe. The size of the src argument itself can be an
/// arbitrary size and this function will return that size, but its backing
/// buffer must be padded out to alignment.
///
inline size_t
ircd::buffer::stream_aligned(const mutable_buffer &dst,
const const_buffer &src)
{
// Platforms that have non-temporal store support; this is all of x86_64
constexpr bool has_store
{
#if defined(__SSE2__) && !defined(RB_GENERIC)
true
#else
false
#endif
};
// Platforms that have non-temporal load support; sidenote SSE4.1 can do
// 16 byte loads and AVX2 can do 32 byte loads; SSE2 cannot do loads.
constexpr bool has_load
{
#if defined(__AVX__) && !defined(RB_GENERIC)
true
#else
false
#endif
};
// Use the AVX512 vector type unconditionally as it conveniently matches
// the cache-line size on the relevant platforms and simplifies our syntax
// below by being a single object. On those w/o AVX512 it uses an
// isomorphic configuration of the best available regs.
using block_type = u512x1;
// The number of cache lines we'll have "in flight" which is basically
// just a gimmick to unroll the loop such that each iteration covers
// the full register file. On SSE with 256 bytes of register file we can
// name 4 cache lines at once; on AVX with 512 bytes we can name 8, etc.
constexpr size_t file_lines
{
#if defined(__AVX512F__)
32
#elif defined(__AVX__)
8
#else
4
#endif
};
// Configurable magic number only relevant to SSE2 systems which don't have
// non-temporal load instructions. On these platforms we'll conduct a
// prefetch loop and mark the lines NTA.
constexpr size_t latency
{
16
};
// When the constexpr conditions aren't favorable we can fallback to
// normal copy here.
if constexpr(!has_store && !has_load)
return copy(dst, src);
// Assert valid arguments
assert(!overlap(src, dst));
assert(aligned(data(src), sizeof(block_type)));
assert(aligned(data(dst), sizeof(block_type)));
assert(size(dst) % (sizeof(block_type) * file_lines));
// Size in bytes to be copied
const size_t copy_size
{
std::min(size(src), size(dst))
};
// Number of lines to be copied.
const size_t copy_lines
{
(copy_size / sizeof(block_type)) + bool(copy_size % sizeof(block_type))
};
// destination base ptr
block_type *const __restrict__ out
{
reinterpret_cast<block_type *__restrict__>(data(dst))
};
// source base ptr
const block_type *const __restrict__ in
{
reinterpret_cast<const block_type *__restrict__>(data(src))
};
if constexpr(!has_load)
#pragma clang loop unroll(disable)
for(size_t i(0); i < latency; ++i)
__builtin_prefetch(in + i, 0, 0);
for(size_t i(0); i < copy_lines; i += file_lines)
{
if constexpr(!has_load)
for(size_t j(0); j < file_lines; ++j)
__builtin_prefetch(in + i + latency + j, 0, 0);
block_type block[file_lines];
for(size_t j(0); j < file_lines; ++j)
#if defined(__clang__)
block[j] = __builtin_nontemporal_load(in + i + j);
#else
block[j] = *(in + i + j); //TODO: XXX
#endif
for(size_t j(0); j < file_lines; ++j)
#if defined(__clang__)
__builtin_nontemporal_store(block[j], out + i + j);
#else
*(out + i + j) = block[j]; //TODO: XXX
#endif
}
if constexpr(has_store)
asm volatile ("sfence");
return copy_size;
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_SIMD_SHIFT_H
// xmmx shifter workarounds
namespace ircd::simd
{
template<int b,
class T>
typename std::enable_if<sizeof(T) == 16, T>::type
shl(const T a) noexcept;
template<int b,
class T>
typename std::enable_if<sizeof(T) == 32, T>::type
shl(const T a) noexcept;
template<int b,
class T>
typename std::enable_if<sizeof(T) == 16, T>::type
shr(const T a) noexcept;
template<int b,
class T>
typename std::enable_if<sizeof(T) == 32, T>::type
shr(const T a) noexcept;
}
#ifdef HAVE_X86INTRIN_H
template<int b,
class T>
[[using gnu: always_inline, gnu_inline, artificial]]
extern inline typename std::enable_if<sizeof(T) == 16, T>::type
ircd::simd::shr(const T a)
noexcept
{
static_assert
(
b % 8 == 0, "xmmx register only shifts right at bytewise resolution."
);
return T(_mm_bsrli_si128(u128x1(a), b / 8));
}
#endif
#ifdef HAVE_X86INTRIN_H
template<int b,
class T>
[[using gnu: always_inline, gnu_inline, artificial]]
extern inline typename std::enable_if<sizeof(T) == 16, T>::type
ircd::simd::shl(const T a)
noexcept
{
static_assert
(
b % 8 == 0, "xmmx register only shifts left at bytewise resolution."
);
return T(_mm_bslli_si128(u128x1(a), b / 8));
}
#endif
#if defined(HAVE_X86INTRIN_H) && defined(__AVX2__)
template<int b,
class T>
[[using gnu: always_inline, gnu_inline, artificial]]
extern inline typename std::enable_if<sizeof(T) == 32, T>::type
ircd::simd::shr(const T a)
noexcept
{
static_assert
(
b % 8 == 0, "ymmx register only shifts right at bytewise resolution."
);
return T(_mm256_srli_si256(u256x1(a), b / 8));
}
#endif
#if defined(HAVE_X86INTRIN_H) && defined(__AVX2__)
template<int b,
class T>
[[using gnu: always_inline, gnu_inline, artificial]]
extern inline typename std::enable_if<sizeof(T) == 32, T>::type
ircd::simd::shl(const T a)
noexcept
{
static_assert
(
b % 8 == 0, "ymmx register only shifts left at bytewise resolution."
);
return T(_mm256_slli_si256(u256x1(a), b / 8));
}
#endif
<file_sep>// Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2019 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
namespace ircd
{
template<class i8xN,
size_t N>
static size_t indexof(const string_view &, const string_view *const &) noexcept;
}
size_t
ircd::indexof(const string_view &s,
const string_views &tab)
noexcept
{
#if defined(__AVX__)
static const size_t N {32};
using i8xN = i8x32;
#elif defined(__SSE__)
static const size_t N {16};
using i8xN = i8x16;
#else
static const size_t N {1};
using i8xN = char __attribute__((vector_size(1)));
#endif
string_view a[N];
size_t i, j, ret;
for(i = 0; i < tab.size() / N; ++i)
{
for(j = 0; j < N; ++j)
a[j] = tab[i * N + j];
if((ret = indexof<i8xN, N>(s, a)) != N)
return i * N + ret;
}
for(j = 0; j < tab.size() % N; ++j)
a[j] = tab[i * N + j];
for(; j < N; ++j)
a[j] = string_view{};
ret = i * N + indexof<i8xN, N>(s, a);
return std::min(ret, tab.size());
}
template<class i8xN,
size_t N>
size_t
ircd::indexof(const string_view &s,
const string_view *const &st)
noexcept
{
i8xN ct, res;
size_t i, j, k;
for(i = 0; i < N; ++i)
res[i] = true;
const size_t max(s.size());
for(i = 0, j = 0; i < max; i = (j < N)? i + 1 : max)
{
#pragma clang loop unroll (disable)
for(k = 0; k < N; ++k)
{
res[k] &= size(st[k]) > i;
ct[k] = res[k]? st[k][i]: 0;
}
res &= ct == s[i];
while(j < N && !res[j])
++j;
}
for(i = 0; i < N && !res[i]; ++i);
return i;
}
ircd::string_view
ircd::toupper(const mutable_buffer &out,
const string_view &in)
noexcept
{
const auto stop
{
std::next(begin(in), std::min(size(in), size(out)))
};
const auto end
{
std::transform(begin(in), stop, begin(out), []
(auto&& c)
{
return std::toupper(c);
})
};
assert(intptr_t(begin(out)) <= intptr_t(end));
return string_view
{
data(out), size_t(std::distance(begin(out), end))
};
}
#if defined(__SSE2__)
ircd::string_view
ircd::tolower(const mutable_buffer &out,
const string_view &in)
noexcept
{
const auto stop
{
std::next(begin(in), std::min(size(in), size(out)))
};
const u128x1 *src_
{
reinterpret_cast<const u128x1 *>(begin(in))
};
u128x1 *dst
{
reinterpret_cast<u128x1 *>(begin(out))
};
while(intptr_t(src_) < intptr_t(stop) - ssize_t(sizeof(u128x1)))
{
const u128x1 lit_A1 { _mm_set1_epi8('A' - 1) };
const u128x1 lit_Z1 { _mm_set1_epi8('Z' + 1) };
const u128x1 addend { _mm_set1_epi8('a' - 'A') };
const u128x1 src { _mm_loadu_si128(src_++) };
const u128x1 gte_A { _mm_cmpgt_epi8(src, lit_A1) };
const u128x1 lte_Z { _mm_cmplt_epi8(src, lit_Z1) };
const u128x1 mask { _mm_and_si128(gte_A, lte_Z) };
const u128x1 ctrl_mask { _mm_and_si128(mask, addend) };
const u128x1 result { _mm_add_epi8(src, ctrl_mask) };
_mm_storeu_si128(dst++, result);
}
const auto end{std::transform
(
reinterpret_cast<const char *>(src_),
stop,
reinterpret_cast<char *>(dst),
::tolower
)};
assert(intptr_t(begin(out)) <= intptr_t(end));
return string_view{begin(out), end};
}
#else
ircd::string_view
ircd::tolower(const mutable_buffer &out,
const string_view &in)
noexcept
{
const auto stop
{
std::next(begin(in), std::min(size(in), size(out)))
};
const auto end
{
std::transform(begin(in), stop, begin(out), ::tolower)
};
assert(intptr_t(begin(out)) <= intptr_t(end));
return string_view
{
data(out), size_t(std::distance(begin(out), end))
};
}
#endif
std::string
ircd::replace(const string_view &s,
const char &before,
const string_view &after)
{
const uint32_t occurs
(
std::count(begin(s), end(s), before)
);
const size_t size
{
occurs? s.size() + (occurs * after.size()):
s.size() - occurs
};
return string(size, [&s, &before, &after]
(const mutable_buffer &buf)
{
char *p{begin(buf)};
std::for_each(begin(s), end(s), [&before, &after, &p]
(const char &c)
{
if(c == before)
{
memcpy(p, after.data(), after.size());
p += after.size();
}
else *p++ = c;
});
return std::distance(begin(buf), p);
});
}
<file_sep>// Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2018 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#include "db.h"
/// Dedicated logging facility for the database subsystem
decltype(ircd::db::log)
ircd::db::log
{
"db", 'D'
};
/// Dedicated logging facility for rocksdb's log callbacks
decltype(ircd::db::rog)
ircd::db::rog
{
"db.rocksdb"
};
decltype(ircd::db::version_api)
ircd::db::version_api
{
"RocksDB", info::versions::API, 0,
{
ROCKSDB_MAJOR, ROCKSDB_MINOR, ROCKSDB_PATCH,
}
};
extern "C" const char *
rocksdb_build_git_sha;
extern "C" const char *
rocksdb_build_compile_date;
decltype(ircd::db::version_abi)
ircd::db::version_abi
{
"RocksDB", info::versions::ABI, 0, {0}, []
(auto &, const mutable_buffer &buf)
{
fmt::sprintf
{
buf, "%s (%s)",
lstrip(rocksdb_build_git_sha, "rocksdb_build_git_sha:"),
rocksdb_build_compile_date,
};
}
};
ircd::conf::item<size_t>
ircd::db::request_pool_stack_size
{
{ "name", "ircd.db.request_pool.stack_size" },
{ "default", long(128_KiB) },
};
ircd::conf::item<size_t>
ircd::db::request_pool_size
{
{
{ "name", "ircd.db.request_pool.size" },
{ "default", 0L },
}, []
{
request.set(size_t(request_pool_size));
}
};
decltype(ircd::db::request_pool_opts)
ircd::db::request_pool_opts
{
size_t(request_pool_stack_size),
size_t(request_pool_size),
-1, // No hard limit
0, // Soft limit at any queued
true, // Yield before hitting soft limit
};
/// Concurrent request pool. Requests to seek may be executed on this
/// pool in cases where a single context would find it advantageous.
/// Some examples are a db::row seek, or asynchronous prefetching.
///
/// The number of workers in this pool should upper bound at the
/// number of concurrent AIO requests which are effective on this
/// system. This is a static pool shared by all databases.
decltype(ircd::db::request)
ircd::db::request
{
"db req", request_pool_opts
};
/// This mutex is necessary to serialize entry into rocksdb's write impl
/// otherwise there's a risk of a deadlock if their internal pthread
/// mutexes are contended. This is because a few parts of rocksdb are
/// incorrectly using std::mutex directly when they ought to be using their
/// rocksdb::port wrapper.
decltype(ircd::db::write_mutex)
ircd::db::write_mutex;
///////////////////////////////////////////////////////////////////////////////
//
// init
//
namespace ircd::db
{
extern const std::string direct_io_test_file_path;
}
decltype(ircd::db::direct_io_test_file_path)
ircd::db::direct_io_test_file_path
{
fs::path_string(fs::path_views
{
fs::base::db, "SUPPORTS_DIRECT_IO"_sv
})
};
ircd::db::init::init()
try
{
#ifdef IRCD_DB_HAS_ALLOCATOR
database::allocator::init();
#endif
compressions();
directory();
request_pool();
test_direct_io();
test_hw_crc32();
}
catch(const std::exception &e)
{
log::critical
{
log, "Cannot start database system :%s",
e.what()
};
throw;
}
ircd::db::init::~init()
noexcept
{
delete prefetcher;
prefetcher = nullptr;
if(request.active())
log::warning
{
log, "Terminating %zu active of %zu client request contexts; %zu pending; %zu queued",
request.active(),
request.size(),
request.pending(),
request.queued()
};
request.terminate();
log::debug
{
log, "Waiting for %zu active of %zu client request contexts; %zu pending; %zu queued",
request.active(),
request.size(),
request.pending(),
request.queued()
};
request.join();
log::debug
{
log, "All contexts joined; all requests are clear."
};
#ifdef IRCD_DB_HAS_ALLOCATOR
database::allocator::fini();
#endif
}
void
ircd::db::init::directory()
try
{
const string_view &dbdir
{
fs::base::db
};
if(!fs::is_dir(dbdir) && (ircd::read_only || ircd::write_avoid))
log::warning
{
log, "Not creating database directory `%s' in read-only/write-avoid mode.", dbdir
};
else if(fs::mkdir(dbdir))
log::notice
{
log, "Created new database directory at `%s'", dbdir
};
else
log::info
{
log, "Using database directory at `%s'", dbdir
};
}
catch(const fs::error &e)
{
log::error
{
log, "Database directory error: %s", e.what()
};
throw;
}
void
ircd::db::init::test_direct_io()
try
{
const auto &test_file_path
{
direct_io_test_file_path
};
if(fs::support::direct_io(test_file_path))
log::debug
{
log, "Detected Direct-IO works by opening test file at `%s'",
test_file_path
};
else
log::warning
{
log, "Direct-IO is not supported in the database directory `%s'"
"; Concurrent database queries will not be possible.",
string_view{fs::base::db}
};
}
catch(const std::exception &e)
{
log::error
{
log, "Failed to test if Direct-IO possible with test file `%s'"
"; Concurrent database queries will not be possible :%s",
direct_io_test_file_path,
e.what()
};
}
namespace rocksdb::crc32c
{
extern std::string IsFastCrc32Supported();
}
void
ircd::db::init::test_hw_crc32()
try
{
const auto supported_str
{
rocksdb::crc32c::IsFastCrc32Supported()
};
const bool supported
{
startswith(supported_str, "Supported")
};
assert(supported || startswith(supported_str, "Not supported"));
if(!supported)
log::warning
{
log, "crc32c hardware acceleration is not available on this platform."
};
}
catch(const std::exception &e)
{
log::error
{
log, "Failed to test crc32c hardware acceleration support :%s",
e.what()
};
}
decltype(ircd::db::compressions)
ircd::db::compressions;
void
ircd::db::init::compressions()
try
{
auto supported
{
rocksdb::GetSupportedCompressions()
};
size_t i(0);
for(const rocksdb::CompressionType &type_ : supported) try
{
auto &[string, type]
{
db::compressions.at(i++)
};
type = type_;
throw_on_error
{
rocksdb::GetStringFromCompressionType(&string, type_)
};
log::debug
{
log, "Detected supported compression #%zu type:%lu :%s",
i,
type,
string,
};
}
catch(const std::exception &e)
{
log::error
{
log, "Failed to identify compression type:%u :%s",
uint(type_),
e.what()
};
}
if(supported.empty())
log::warning
{
"No compression libraries have been linked with the DB."
" This is probably not what you want."
};
}
catch(const std::exception &e)
{
log::error
{
log, "Failed to initialize database compressions :%s",
e.what()
};
throw;
}
void
ircd::db::init::request_pool()
{
char buf[32];
const string_view value
{
conf::get(buf, "ircd.fs.aio.max_events")
};
const size_t aio_max_events
{
lex_castable<size_t>(value)?
lex_cast<size_t>(value):
0UL
};
const size_t new_size
{
size_t(request_pool_size)?
request_pool_size:
aio_max_events?
aio_max_events:
1UL
};
request_pool_size.set(lex_cast(new_size));
}
///////////////////////////////////////////////////////////////////////////////
//
// database
//
/// Conf item toggles if full database checksum verification should occur
/// when any database is opened.
decltype(ircd::db::open_check)
ircd::db::open_check
{
{ "name", "ircd.db.open.check" },
{ "default", false },
{ "persist", false },
};
/// Conf item determines the recovery mode to use when opening any database.
///
/// "absolute" - The default and is the same for an empty value. This means
/// any database corruptions are treated as an error on open and an exception
/// is thrown with nothing else done.
///
/// "point" - The database is rolled back to before any corruption. This will
/// lose some of the latest data last committed, but will open the database
/// and continue normally thereafter.
///
/// "skip" - The corrupted areas are skipped over and the database continues
/// normally with just those assets missing. This option is dangerous because
/// the database continues in a logically incoherent state which is only ok
/// for very specific applications.
///
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
///
/// IRCd's applications are NOT tolerant of skip recovery. You will create an
/// incoherent database. NEVER USE "skip" RECOVERY MODE.
///
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
///
decltype(ircd::db::open_recover)
ircd::db::open_recover
{
{ "name", "ircd.db.open.recover" },
{ "default", "absolute" },
{ "persist", false },
};
/// Conf item determines if database repair should occur (before open). This
/// mechanism can be used when SST file corruption occurs which is too deep
/// for log-based recovery. The affected blocks may be discarded; this risks
/// destabilizing an application expecting the data in those blocks to exist.
///
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
///
/// Use with caution.
///
/// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
///
decltype(ircd::db::open_repair)
ircd::db::open_repair
{
{ "name", "ircd.db.open.repair" },
{ "default", false },
{ "persist", false },
};
/// Conf item toggles whether automatic compaction is enabled or disabled for
/// all databases upon opening. This is useful for developers, debugging and
/// valgrind etc to prevent these background jobs from spawning when unwanted.
decltype(ircd::db::auto_compact)
ircd::db::auto_compact
{
{ "name", "ircd.db.compact.auto" },
{ "default", true },
{ "persist", false },
};
/// Conf item dictates whether databases will be opened in slave mode; this
/// is a recent feature of RocksDB which may not be available. It allows two
/// instances of a database, so long as only one is not opened as a slave.
decltype(ircd::db::open_slave)
ircd::db::open_slave
{
{ "name", "ircd.db.open.slave" },
{ "default", false },
{ "persist", false },
};
void
ircd::db::sync(database &d)
{
log::debug
{
log, "[%s] @%lu SYNC WAL",
name(d),
sequence(d)
};
throw_on_error
{
d.d->SyncWAL()
};
}
/// Flushes all columns. Note that if blocking=true, blocking may occur for
/// each column individually.
void
ircd::db::flush(database &d,
const bool &sync)
{
log::debug
{
log, "[%s] @%lu FLUSH WAL",
name(d),
sequence(d)
};
throw_on_error
{
d.d->FlushWAL(sync)
};
}
/// Moves memory structures to SST files for all columns. This doesn't
/// necessarily sort anything that wasn't previously sorted, but it may create
/// new SST files and shouldn't be confused with a typical fflush().
/// Note that if blocking=true, blocking may occur for each column individually.
void
ircd::db::sort(database &d,
const bool &blocking,
const bool &now)
{
for(const auto &c : d.columns)
{
db::column column{*c};
db::sort(column, blocking, now);
}
}
void
ircd::db::compact(database &d,
const compactor &cb)
{
static const std::pair<string_view, string_view> range
{
{}, {}
};
for(const auto &c : d.columns) try
{
db::column column{*c};
compact(column, range, -1, cb);
}
catch(const ctx::interrupted &)
{
throw;
}
catch(const std::exception &e)
{
assert(c);
log::error
{
log, "[%s] compact '%s' :%s",
name(d),
name(*c),
e.what(),
};
}
}
void
ircd::db::compact(database &d,
const std::pair<int, int> &level,
const compactor &cb)
{
for(const auto &c : d.columns) try
{
db::column column{*c};
compact(column, level, cb);
}
catch(const ctx::interrupted &)
{
throw;
}
catch(const std::exception &e)
{
assert(c);
log::error
{
log, "[%s] compact '%s' :%s",
name(d),
name(*c),
e.what(),
};
}
}
void
ircd::db::check(database &d)
{
assert(d.d);
throw_on_error
{
d.d->VerifyChecksum()
};
}
void
ircd::db::check(database &d,
const string_view &file)
{
assert(file);
assert(d.d);
const auto &opts
{
d.d->GetOptions()
};
const rocksdb::EnvOptions env_opts
{
opts
};
const bool absolute
{
fs::is_absolute(file)
};
const string_view parts[]
{
d.path, file
};
const std::string path
{
!absolute?
fs::path_string(parts):
std::string{file}
};
throw_on_error
{
rocksdb::VerifySstFileChecksum(opts, env_opts, path)
};
}
void
ircd::db::resume(database &d)
{
assert(d.d);
const ctx::uninterruptible::nothrow ui;
const std::lock_guard lock{write_mutex};
const auto errors
{
db::errors(d)
};
log::debug
{
log, "[%s] Attempting to resume from %zu errors @%lu",
name(d),
errors.size(),
sequence(d)
};
throw_on_error
{
d.d->Resume()
};
d.errors.clear();
log::info
{
log, "[%s] Resumed normal operation at sequence number %lu; cleared %zu errors",
name(d),
sequence(d),
errors.size()
};
}
void
ircd::db::refresh(database &d)
{
assert(d.d);
throw_on_error
{
#ifdef IRCD_DB_HAS_SECONDARY
d.d->TryCatchUpWithPrimary()
#else
rocksdb::Status::NotSupported(slice("Slave mode not supported by this RocksDB"_sv))
#endif
};
log::debug
{
log, "[%s] Caught up with primary database.",
name(d)
};
}
void
ircd::db::bgpause(database &d)
{
assert(d.d);
throw_on_error
{
d.d->PauseBackgroundWork()
};
log::debug
{
log, "[%s] Paused all background work",
name(d)
};
}
void
ircd::db::bgcontinue(database &d)
{
assert(d.d);
log::debug
{
log, "[%s] Continuing background work",
name(d)
};
throw_on_error
{
d.d->ContinueBackgroundWork()
};
}
void
ircd::db::bgcancel(database &d,
const bool &blocking)
{
assert(d.d);
log::debug
{
log, "[%s] Canceling all background work...",
name(d)
};
rocksdb::CancelAllBackgroundWork(d.d.get(), blocking);
if(!blocking)
return;
assert(d.env);
assert(d.env->st);
const ctx::uninterruptible::nothrow ui;
for(auto &pool : d.env->st->pool) if(pool)
{
log::debug
{
log, "[%s] Waiting for tasks:%zu queued:%zu active:%zu in pool '%s'",
name(d),
pool->tasks.size(),
pool->p.pending(),
pool->p.active(),
ctx::name(pool->p),
};
pool->wait();
}
const auto errors
{
property<uint64_t>(d, rocksdb::DB::Properties::kBackgroundErrors)
};
const auto level
{
errors? log::level::ERROR : log::level::DEBUG
};
log::logf
{
log, level,
"[%s] Canceled all background work; errors:%lu",
name(d),
errors
};
}
/// Writes a snapshot of this database to the directory specified. The
/// snapshot consists of hardlinks to the bulk data files of this db, but
/// copies the other stuff that usually gets corrupted. The directory can
/// then be opened as its own database either read-only or read-write.
/// Incremental backups and rollbacks can begin from this interface. Note
/// this may be an expensive blocking operation.
uint64_t
ircd::db::checkpoint(database &d)
{
if(!d.checkpointer)
throw error
{
"Checkpointing is not available for db(%p) '%s",
&d,
name(d)
};
const std::lock_guard lock{write_mutex};
const ctx::uninterruptible::nothrow ui;
const auto seqnum
{
sequence(d)
};
const std::string dir
{
db::path(name(d), seqnum)
};
throw_on_error
{
d.checkpointer->CreateCheckpoint(dir, 0)
};
log::debug
{
log, "[%s] Checkpoint at sequence %lu in `%s' complete",
name(d),
seqnum,
dir
};
return seqnum;
}
/// This wraps RocksDB's "File Deletions" which means after RocksDB
/// compresses some file it then destroys the uncompressed version;
/// setting this to false will disable that and retain both versions.
/// This is useful when a direct reference is being manually held by
/// us into the uncompressed version which must remain valid.
void
ircd::db::fdeletions(database &d,
const bool &enable,
const bool &force)
{
if(enable) throw_on_error
{
d.d->EnableFileDeletions(force)
};
else throw_on_error
{
d.d->DisableFileDeletions()
};
}
void
ircd::db::setopt(database &d,
const string_view &key,
const string_view &val)
{
const std::unordered_map<std::string, std::string> options
{
{ std::string{key}, std::string{val} }
};
throw_on_error
{
d.d->SetDBOptions(options)
};
}
/// Set the rdb logging level by translating our ircd::log::level to the
/// RocksDB enum. This translation is a reasonable convenience, as both
/// enums are similar enough.
void
ircd::db::loglevel(database &d,
const ircd::log::level &fac)
{
using ircd::log::level;
rocksdb::InfoLogLevel lev
{
rocksdb::WARN_LEVEL
};
switch(fac)
{
case level::CRITICAL: lev = rocksdb::FATAL_LEVEL; break;
case level::ERROR: lev = rocksdb::ERROR_LEVEL; break;
case level::WARNING:
case level::NOTICE: lev = rocksdb::WARN_LEVEL; break;
case level::INFO: lev = rocksdb::INFO_LEVEL; break;
case level::DERROR:
case level::DWARNING:
case level::DEBUG: lev = rocksdb::DEBUG_LEVEL; break;
case level::_NUM_: assert(0); break;
}
d.logger->SetInfoLogLevel(lev);
}
/// Set the rdb logging level by translating our ircd::log::level to the
/// RocksDB enum. This translation is a reasonable convenience, as both
/// enums are similar enough.
ircd::log::level
ircd::db::loglevel(const database &d)
{
const auto &level
{
d.logger->GetInfoLogLevel()
};
switch(level)
{
default:
case rocksdb::NUM_INFO_LOG_LEVELS:
assert(0);
case rocksdb::HEADER_LEVEL:
case rocksdb::FATAL_LEVEL: return log::level::CRITICAL;
case rocksdb::ERROR_LEVEL: return log::level::ERROR;
case rocksdb::WARN_LEVEL: return log::level::WARNING;
case rocksdb::INFO_LEVEL: return log::level::INFO;
case rocksdb::DEBUG_LEVEL: return log::level::DEBUG;
}
}
ircd::db::options
ircd::db::getopt(const database &d)
{
return options
{
d.d->GetDBOptions()
};
}
size_t
ircd::db::bytes(const database &d)
{
return std::accumulate(begin(d.columns), end(d.columns), size_t(0), []
(auto ret, const auto &colptr)
{
db::column c{*colptr};
return ret += db::bytes(c);
});
}
size_t
ircd::db::file_count(const database &d)
{
return std::accumulate(begin(d.columns), end(d.columns), size_t(0), []
(auto ret, const auto &colptr)
{
db::column c{*colptr};
return ret += db::file_count(c);
});
}
/// Get the list of WAL (Write Ahead Log) files.
std::vector<std::string>
ircd::db::wals(const database &cd)
{
auto &d
{
const_cast<database &>(cd)
};
std::vector<std::unique_ptr<rocksdb::LogFile>> vec;
throw_on_error
{
d.d->GetSortedWalFiles(vec)
};
std::vector<std::string> ret(vec.size());
std::transform(begin(vec), end(vec), begin(ret), []
(const auto &file)
{
return file->PathName();
});
return ret;
}
/// Get the live file list for db; see overlord documentation.
std::vector<std::string>
ircd::db::files(const database &d)
{
uint64_t ignored;
return files(d, ignored);
}
/// Get the live file list for database relative to the database's directory.
/// One of the files is a manifest file which is over-allocated and its used
/// size is returned in the integer passed to the `msz` argument.
///
/// This list may not be completely up to date. The reliable way to get the
/// most current list is to flush all columns first and ensure no database
/// activity took place between the flushing and this query.
std::vector<std::string>
ircd::db::files(const database &cd,
uint64_t &msz)
{
std::vector<std::string> ret;
auto &d(const_cast<database &>(cd));
throw_on_error
{
d.d->GetLiveFiles(ret, &msz, false)
};
return ret;
}
const std::vector<std::string> &
ircd::db::errors(const database &d)
{
return d.errors;
}
uint64_t
ircd::db::sequence(const database &cd)
{
database &d(const_cast<database &>(cd));
return d.d->GetLatestSequenceNumber();
}
rocksdb::Cache *
ircd::db::cache(database &d)
{
return d.row_cache.get();
}
const rocksdb::Cache *
ircd::db::cache(const database &d)
{
return d.row_cache.get();
}
template<>
ircd::db::prop_int
ircd::db::property(const database &cd,
const string_view &name)
{
uint64_t ret(0);
database &d(const_cast<database &>(cd));
if(!d.d->GetAggregatedIntProperty(slice(name), &ret))
throw not_found
{
"property '%s' for all columns in '%s' not found or not an integer.",
name,
db::name(d)
};
return ret;
}
std::shared_ptr<ircd::db::database::column>
ircd::db::shared_from(database::column &column)
{
return column.shared_from_this();
}
std::shared_ptr<const ircd::db::database::column>
ircd::db::shared_from(const database::column &column)
{
return column.shared_from_this();
}
const std::string &
ircd::db::uuid(const database &d)
{
return d.uuid;
}
const std::string &
ircd::db::name(const database &d)
{
return d.name;
}
//
// database
//
namespace ircd::db
{
extern const description default_description;
}
// Instance list linkage
template<>
decltype(ircd::util::instance_list<ircd::db::database>::allocator)
ircd::util::instance_list<ircd::db::database>::allocator
{};
template<>
decltype(ircd::util::instance_list<ircd::db::database>::list)
ircd::util::instance_list<ircd::db::database>::list
{
allocator
};
decltype(ircd::db::default_description)
ircd::db::default_description
{
/// Requirement of RocksDB going back to LevelDB. This column must
/// always exist in all descriptions and probably should be at idx[0].
{ "default" }
};
ircd::db::database &
ircd::db::database::get(column &column)
{
assert(column.d);
return *column.d;
}
const ircd::db::database &
ircd::db::database::get(const column &column)
{
assert(column.d);
return *column.d;
}
ircd::db::database &
ircd::db::database::get(const string_view &name)
{
const auto pair
{
namepoint(name)
};
return get(pair.first, pair.second);
}
ircd::db::database &
ircd::db::database::get(const string_view &name,
const uint64_t &checkpoint)
{
auto *const &d
{
get(std::nothrow, name, checkpoint)
};
if(likely(d))
return *d;
throw checkpoint == uint64_t(-1)?
std::out_of_range{"No database with that name exists"}:
std::out_of_range{"No database with that name at that checkpoint exists"};
}
ircd::db::database *
ircd::db::database::get(std::nothrow_t,
const string_view &name)
{
const auto pair
{
namepoint(name)
};
return get(std::nothrow, pair.first, pair.second);
}
ircd::db::database *
ircd::db::database::get(std::nothrow_t,
const string_view &name,
const uint64_t &checkpoint)
{
for(auto *const &d : list)
if(name == d->name)
if(checkpoint == uint64_t(-1) || checkpoint == d->checkpoint)
return d;
return nullptr;
}
//
// database::database
//
ircd::db::database::database(const string_view &name,
std::string optstr)
:database
{
name, std::move(optstr), default_description
}
{
}
ircd::db::database::database(const string_view &name,
std::string optstr,
description description)
:database
{
namepoint(name).first, namepoint(name).second, std::move(optstr), std::move(description)
}
{
}
ircd::db::database::database(const string_view &name,
const uint64_t &checkpoint,
std::string optstr,
description description)
try
:name
{
namepoint(name).first
}
,checkpoint
{
// a -1 may have been generated by the db::namepoint() util when the user
// supplied just a name without a checkpoint. In the context of database
// opening/creation -1 just defaults to 0.
checkpoint == uint64_t(-1)? 0 : checkpoint
}
,path
{
db::path(this->name, this->checkpoint)
}
,optstr
{
std::move(optstr)
}
,fsck
{
db::open_repair
}
,slave
{
db::open_slave
}
,read_only
{
ircd::read_only
}
,env
{
std::make_shared<struct env>(this)
}
,stats
{
std::make_shared<struct stats>(this)
}
,logger
{
std::make_shared<struct logger>(this)
}
,events
{
std::make_shared<struct events>(this)
}
,mergeop
{
std::make_shared<struct mergeop>(this)
}
,wal_filter
{
std::make_unique<struct wal_filter>(this)
}
,allocator
{
#ifdef IRCD_DB_HAS_ALLOCATOR
std::make_shared<struct allocator>(this, nullptr, database::allocator::cache_arena)
#endif
}
,ssts{rocksdb::NewSstFileManager
(
env.get(), // env
logger, // logger
{}, // trash_dir
0, // rate_bytes_per_sec
true, // delete_existing_trash
nullptr, // Status*
0.05, // max_trash_db_ratio 0.25
64_MiB // bytes_max_delete_chunk
)}
,row_cache
{
std::make_shared<database::cache>
(
this, this->stats, this->allocator, this->name, 16_MiB
)
}
,descriptors
{
std::move(description)
}
,opts{[this]
{
auto opts
{
std::make_unique<rocksdb::DBOptions>(make_dbopts(this->optstr, &this->optstr, &read_only, &fsck))
};
// Setup sundry
opts->create_if_missing = true;
opts->create_missing_column_families = true;
// Uses thread_local counters in rocksdb and probably useless for ircd::ctx.
opts->enable_thread_tracking = false;
// MUST be 0 or std::threads are spawned in rocksdb.
opts->max_file_opening_threads = 0;
// limit maxfdto prevent too many small files degrading read perf; too low is
// bad for write perf.
opts->max_open_files = fs::support::rlimit_nofile();
// TODO: Check if these values can be increased; RocksDB may keep
// thread_local state preventing values > 1.
opts->max_background_jobs = 16;
opts->max_background_flushes = 1;
opts->max_background_compactions = 1;
opts->max_total_wal_size = 96_MiB; //TODO: conf
opts->db_write_buffer_size = 96_MiB; //TODO: conf
//opts->max_log_file_size = 32_MiB; //TODO: conf
//TODO: range_sync
opts->bytes_per_sync = 0;
opts->wal_bytes_per_sync = 0;
// For the write-side of a compaction process: writes will be of approx
// this size. The compaction process is composing a buffer of this size
// between those writes. Too large a buffer will hog the CPU and starve
// other ircd::ctx's. Too small a buffer will be inefficient.
opts->writable_file_max_buffer_size = 4_MiB; //TODO: conf
// MUST be 1 (no subcompactions) or rocksdb spawns internal std::thread.
opts->max_subcompactions = 1;
// Disable noise
opts->stats_dump_period_sec = 0;
// Disables the timer to delete unused files; this operation occurs
// instead with our compaction operations so we don't need to complicate.
opts->delete_obsolete_files_period_micros = 0;
opts->keep_log_file_num = 16;
// These values prevent codepaths from being taken in rocksdb which may
// introduce issues for ircd::ctx. We should still fully investigate
// if any of these features can safely be used.
opts->allow_concurrent_memtable_write = true;
opts->enable_write_thread_adaptive_yield = false;
opts->enable_pipelined_write = false;
opts->write_thread_max_yield_usec = 0;
opts->write_thread_slow_yield_usec = 0;
// Detect if O_DIRECT is possible if db::init left a file in the
// database directory claiming such. User can force no direct io
// with program option at startup (i.e -nodirect).
opts->use_direct_reads = bool(fs::fd::opts::direct_io_enable)?
fs::exists(direct_io_test_file_path):
false;
// For the read-side of the compaction process.
opts->compaction_readahead_size = !opts->use_direct_reads?
512_KiB: //TODO: conf
0;
// Use the determined direct io value for writes as well.
//opts->use_direct_io_for_flush_and_compaction = opts->use_direct_reads;
// Doesn't appear to be in effect when direct io is used. Not supported by
// all filesystems so disabled for now.
// TODO: use fs::support::test_fallocate() test similar to direct_io_test_file.
opts->allow_fallocate = false;
#ifdef RB_DEBUG
opts->dump_malloc_stats = true;
#endif
// Default corruption tolerance is zero-tolerance; db fails to open with
// error by default to inform the user. The rest of the options are
// various relaxations for how to proceed.
opts->wal_recovery_mode = rocksdb::WALRecoveryMode::kAbsoluteConsistency;
// When corrupted after crash, the DB is rolled back before the first
// corruption and erases everything after it, giving a consistent
// state up at that point, though losing some recent data.
if(string_view(open_recover) == "point" || string_view(open_recover) == "recover")
opts->wal_recovery_mode = rocksdb::WALRecoveryMode::kPointInTimeRecovery;
// When corrupted after crash and PointInTimeRecovery does not work,
// this will drop more data, but consistently. RocksDB sez the WAL is not
// used at all in this mode.
#if ROCKSDB_MAJOR > 6 \
|| (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR >= 10)
if(string_view(open_recover) == "recover")
opts->best_efforts_recovery = true;
#endif
// Skipping corrupted records will create gaps in the DB timeline where the
// application (like a matrix timeline) cannot tolerate the unexpected gap.
if(string_view(open_recover) == "skip")
opts->wal_recovery_mode = rocksdb::WALRecoveryMode::kSkipAnyCorruptedRecords;
// Tolerating corrupted records is very last-ditch for getting the database to
// open in a catastrophe. We have no use for this option but should use it for
//TODO: emergency salvage-mode.
if(string_view(open_recover) == "tolerate")
opts->wal_recovery_mode = rocksdb::WALRecoveryMode::kTolerateCorruptedTailRecords;
// This prevents the creation of additional SST files and lots of I/O on
// either DB open and close.
opts->avoid_flush_during_recovery = true;
opts->avoid_flush_during_shutdown = true;
// Setup env
opts->env = env.get();
// Setup WAL filter
opts->wal_filter = this->wal_filter.get();
// Setup SST file mgmt
opts->sst_file_manager = this->ssts;
// Setup logging
logger->SetInfoLogLevel(ircd::debugmode? rocksdb::DEBUG_LEVEL : rocksdb::WARN_LEVEL);
opts->info_log_level = logger->GetInfoLogLevel();
opts->info_log = logger;
// Setup event and statistics callbacks
opts->listeners.emplace_back(this->events);
// Setup histogram collecting
#if ROCKSDB_MAJOR > 6 \
|| (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR >= 1)
//this->stats->set_stats_level(rocksdb::kExceptTimeForMutex);
this->stats->set_stats_level(rocksdb::kAll);
#else
//this->stats->stats_level_ = rocksdb::kExceptTimeForMutex;
this->stats->stats_level_ = rocksdb::kAll;
#endif
opts->statistics = this->stats;
// Setup performance metric options
//rocksdb::SetPerfLevel(rocksdb::PerfLevel::kDisable);
// Setup row cache.
opts->row_cache = this->row_cache;
return opts;
}()}
,column_names{[this]
{
// Existing columns at path. If any are left the descriptor set did not
// describe all of the columns found in the database at path.
const auto required
{
db::column_names(path, *opts)
};
// As we find descriptors for all of the columns on the disk we'll
// remove their names from this set. Anything remaining is undescribed
// and that's a fatal error.
std::set<string_view> existing
{
begin(required), end(required)
};
// The names of the columns extracted from the descriptor set
decltype(this->column_names) ret;
for(auto &descriptor : descriptors)
{
// Deprecated columns which have already been dropped won't appear
// in the existing (required) list. We don't need to construct those.
if(!existing.count(descriptor.name) && descriptor.drop)
continue;
// Construct the column instance and indicate that we have a description
// for it by removing it from existing.
ret.emplace(descriptor.name, std::make_shared<column>(*this, descriptor));
existing.erase(descriptor.name);
}
if(!existing.empty())
throw error
{
"Failed to describe existing column '%s' (and %zd others...)",
*begin(existing),
existing.size() - 1
};
return ret;
}()}
,d{[this]
{
std::vector<rocksdb::ColumnFamilyHandle *> handles; // filled by DB::Open()
std::vector<rocksdb::ColumnFamilyDescriptor> columns(this->column_names.size());
std::transform(begin(this->column_names), end(this->column_names), begin(columns), []
(const auto &pair)
{
const auto &column(*pair.second);
return static_cast<const rocksdb::ColumnFamilyDescriptor &>(column);
});
// NOTE: rocksdb sez RepairDB is broken; can't use now
if(fsck && fs::is_dir(path))
{
log::notice
{
log, "Checking database @ `%s' columns[%zu]", path, columns.size()
};
throw_on_error
{
rocksdb::RepairDB(path, *opts, columns)
};
log::info
{
log, "Database @ `%s' check complete", path
};
}
// If the directory does not exist, though rocksdb will create it, we can
// avoid scaring the user with an error log message if we just do that..
if(opts->create_if_missing && !fs::is_dir(path) && !ircd::write_avoid)
fs::mkdir(path);
// Announce attempt before usual point where exceptions are thrown
log::info
{
log, "Opening database \"%s\" @ `%s' with %zu columns...",
this->name,
path,
columns.size()
};
if(read_only)
log::warning
{
log, "Database \"%s\" @ `%s' will be opened in read-only mode.",
this->name,
path,
};
// Open DB into ptr
rocksdb::DB *ptr;
if(slave)
throw_on_error
{
#ifdef IRCD_DB_HAS_SECONDARY
rocksdb::DB::OpenAsSecondary(*opts, path, "/tmp/slave", columns, &handles, &ptr)
#else
rocksdb::Status::NotSupported(slice("Slave mode not supported by this RocksDB"_sv))
#endif
};
else if(read_only)
throw_on_error
{
rocksdb::DB::OpenForReadOnly(*opts, path, columns, &handles, &ptr)
};
else
throw_on_error
{
rocksdb::DB::Open(*opts, path, columns, &handles, &ptr)
};
std::unique_ptr<rocksdb::DB> ret
{
ptr
};
// Set the handles. We can't throw here so we just log an error.
for(const auto &handle : handles) try
{
this->column_names.at(handle->GetName())->handle.reset(handle);
}
catch(const std::exception &e)
{
log::critical
{
log, "[%s] Error finding described handle '%s' which RocksDB opened :%s",
this->name,
handle->GetName(),
e.what()
};
}
return ret;
}()}
,column_index{[this]
{
size_t size{0};
for(const auto &p : column_names)
{
const auto &column(*p.second);
if(db::id(column) + 1 > size)
size = db::id(column) + 1;
}
// This may have some gaps containing nullptrs where a CFID is unused.
decltype(this->column_index) ret(size);
for(const auto &p : column_names)
{
const auto &colptr(p.second);
ret.at(db::id(*colptr)) = colptr;
}
return ret;
}()}
,columns{[this]
{
// Skip the gaps in the column_index vector to make the columns list
// only contain active column instances.
decltype(this->columns) ret;
for(const auto &ptr : this->column_index)
if(ptr)
ret.emplace_back(ptr);
return ret;
}()}
,uuid{[this]
{
std::string ret;
throw_on_error
{
d->GetDbIdentity(ret)
};
return ret;
}()}
,checkpointer{[this]
{
rocksdb::Checkpoint *checkpointer{nullptr};
throw_on_error
{
rocksdb::Checkpoint::Create(this->d.get(), &checkpointer)
};
return checkpointer;
}()}
{
// Conduct drops from schema changes. The database must be fully opened
// as if they were not dropped first, then we conduct the drop operation
// here. The drop operation has no effects until the database is next
// closed; the dropped columns will still work during this instance.
for(const auto &colptr : columns)
if(describe(*colptr).drop)
db::drop(*colptr);
// Database integrity check branch.
if(bool(open_check))
{
log::notice
{
log, "[%s] Verifying database integrity. This may take several minutes...",
this->name
};
check(*this);
}
log::info
{
log, "[%s] Opened database @ `%s' with %zu columns at sequence number %lu.",
this->name,
path,
columns.size(),
d->GetLatestSequenceNumber()
};
}
catch(const error &e)
{
log::error
{
"Error opening db [%s] %s",
name,
e.what()
};
throw;
}
catch(const std::exception &e)
{
log::error
{
"Error opening db [%s] %s",
name,
e.what()
};
throw error
{
"Failed to open db [%s] %s",
name,
e.what()
};
}
ircd::db::database::~database()
noexcept try
{
const ctx::uninterruptible::nothrow ui;
const std::unique_lock lock{write_mutex};
log::info
{
log, "[%s] closing database @ `%s'...",
name,
path
};
if(likely(prefetcher))
{
const size_t canceled
{
prefetcher->cancel(*this)
};
log::debug
{
log, "[%s] canceled %zu queued prefetches; waiting for any pending ...",
name,
canceled,
};
// prefetcher::cancel() only removes requests from its queue, but if
// a prefetch request from this database is in flight that is bad; so
// we wait until the unit has completed its pending requests.
prefetcher->wait_pending();
}
bgcancel(*this, true);
log::debug
{
log, "[%s] closing columns...",
name
};
this->checkpointer.reset(nullptr);
this->column_names.clear();
this->column_index.clear();
this->columns.clear();
log::debug
{
log, "[%s] closed columns; flushing...",
name
};
if(!read_only)
flush(*this);
log::debug
{
log, "[%s] flushed; synchronizing...",
name
};
if(!read_only)
sync(*this);
log::debug
{
log, "[%s] synchronized with hardware.",
name
};
const auto sequence
{
d->GetLatestSequenceNumber()
};
throw_on_error
{
d->Close()
};
env->st.reset(nullptr);
log::info
{
log, "[%s] closed database @ `%s' at sequence number %lu.",
name,
path,
sequence
};
}
catch(const std::exception &e)
{
log::error
{
log, "Error closing database(%p) :%s",
this,
e.what()
};
return;
}
catch(...)
{
log::critical
{
log, "Unknown error closing database(%p)",
this
};
return;
}
void
ircd::db::database::operator()(const delta &delta)
{
operator()(sopts{}, delta);
}
void
ircd::db::database::operator()(const std::initializer_list<delta> &deltas)
{
operator()(sopts{}, deltas);
}
void
ircd::db::database::operator()(const delta *const &begin,
const delta *const &end)
{
operator()(sopts{}, begin, end);
}
void
ircd::db::database::operator()(const sopts &sopts,
const delta &delta)
{
operator()(sopts, &delta, &delta + 1);
}
void
ircd::db::database::operator()(const sopts &sopts,
const std::initializer_list<delta> &deltas)
{
operator()(sopts, std::begin(deltas), std::end(deltas));
}
void
ircd::db::database::operator()(const sopts &sopts,
const delta *const &begin,
const delta *const &end)
{
rocksdb::WriteBatch batch;
std::for_each(begin, end, [this, &batch]
(const delta &delta)
{
const auto &op(std::get<op>(delta));
const auto &col(std::get<1>(delta));
const auto &key(std::get<2>(delta));
const auto &val(std::get<3>(delta));
db::column column(operator[](col));
append(batch, column, db::column::delta
{
op,
key,
val
});
});
commit(*this, batch, sopts);
}
ircd::db::database::column &
ircd::db::database::operator[](const string_view &name)
{
return operator[](cfid(name));
}
ircd::db::database::column &
ircd::db::database::operator[](const uint32_t &id)
try
{
auto &ret(*column_index.at(id));
assert(db::id(ret) == id);
return ret;
}
catch(const std::out_of_range &e)
{
throw not_found
{
"[%s] column id[%u] is not available or specified in schema",
this->name,
id
};
}
const ircd::db::database::column &
ircd::db::database::operator[](const string_view &name)
const
{
return operator[](cfid(name));
}
const ircd::db::database::column &
ircd::db::database::operator[](const uint32_t &id)
const try
{
auto &ret(*column_index.at(id));
assert(db::id(ret) == id);
return ret;
}
catch(const std::out_of_range &e)
{
throw not_found
{
"[%s] column id[%u] is not available or specified in schema",
this->name,
id
};
}
uint32_t
ircd::db::database::cfid(const string_view &name)
const
{
const int32_t id
{
cfid(std::nothrow, name)
};
if(id < 0)
throw not_found
{
"[%s] column '%s' is not available or specified in schema",
this->name,
name
};
return id;
}
int32_t
ircd::db::database::cfid(const std::nothrow_t,
const string_view &name)
const
{
const auto it{column_names.find(name)};
return it != std::end(column_names)?
db::id(*it->second):
-1;
}
///////////////////////////////////////////////////////////////////////////////
//
// database::column
//
void
ircd::db::drop(database::column &c)
{
if(!c.handle)
return;
database &d(c);
log::debug
{
log, "[%s]'%s' @%lu DROPPING COLUMN",
name(d),
name(c),
sequence(d)
};
throw_on_error
{
c.d->d->DropColumnFamily(c.handle.get())
};
log::notice
{
log, "[%s]'%s' @%lu DROPPED COLUMN",
name(d),
name(c),
sequence(d)
};
}
bool
ircd::db::dropped(const database::column &c)
{
return c.descriptor?
c.descriptor->drop:
true;
}
uint32_t
ircd::db::id(const database::column &c)
{
if(!c.handle)
return -1;
return c.handle->GetID();
}
const std::string &
ircd::db::name(const database::column &c)
{
return c.name;
}
const ircd::db::descriptor &
ircd::db::describe(const database::column &c)
{
assert(c.descriptor);
return *c.descriptor;
}
//
// database::column
//
ircd::db::database::column::column(database &d,
db::descriptor &descriptor)
:rocksdb::ColumnFamilyDescriptor
(
descriptor.name, db::options{descriptor.options}
)
,d{&d}
,descriptor{&descriptor}
,key_type{this->descriptor->type.first}
,mapped_type{this->descriptor->type.second}
,cmp{this->d, this->descriptor->cmp}
,prefix{this->d, this->descriptor->prefix}
,cfilter{this, this->descriptor->compactor}
,stats
{
descriptor.name != "default"s?
std::make_shared<struct database::stats>(this->d, this):
this->d->stats
}
,allocator
{
#ifdef IRCD_DB_HAS_ALLOCATOR
std::make_shared<struct database::allocator>(this->d, this, database::allocator::cache_arena, descriptor.block_size)
#endif
}
,handle
{
nullptr, [&d](rocksdb::ColumnFamilyHandle *const handle)
{
assert(d.d);
if(handle && d.d)
d.d->DestroyColumnFamilyHandle(handle);
}
}
{
// If possible, deduce comparator based on type given in descriptor
if(!this->descriptor->cmp.less)
{
if(key_type == typeid(string_view))
this->cmp.user = cmp_string_view{};
else if(key_type == typeid(int64_t))
this->cmp.user = cmp_int64_t{};
else if(key_type == typeid(uint64_t))
this->cmp.user = cmp_uint64_t{};
else
throw error
{
"column '%s' key type[%s] requires user supplied comparator",
this->name,
key_type.name()
};
}
// Set the key comparator
this->options.comparator = &this->cmp;
// Set the prefix extractor
if(this->prefix.user.get && this->prefix.user.has)
this->options.prefix_extractor = std::shared_ptr<const rocksdb::SliceTransform>
{
&this->prefix, [](const rocksdb::SliceTransform *) {}
};
// Set the insert hint prefix extractor
if(this->options.prefix_extractor)
this->options.memtable_insert_with_hint_prefix_extractor = this->options.prefix_extractor;
// Set the compaction filter
this->options.compaction_filter = &this->cfilter;
//this->options.paranoid_file_checks = true;
// More stats reported by the rocksdb.stats property.
this->options.report_bg_io_stats = true;
// Set filter reductions for this column. This means we expect a key to exist.
this->options.optimize_filters_for_hits = this->descriptor->expect_queries_hit;
// Compression type
this->options.compression = find_supported_compression(this->descriptor->compression);
//this->options.compression = rocksdb::kNoCompression;
// Compression options
this->options.compression_opts.enabled = true;
this->options.compression_opts.max_dict_bytes = 0;//8_MiB;
// Mimic the above for bottommost compression.
//this->options.bottommost_compression = this->options.compression;
//this->options.bottommost_compression_opts = this->options.compression_opts;
//TODO: descriptor / conf
this->options.write_buffer_size = 4_MiB;
this->options.max_write_buffer_number = 8;
this->options.min_write_buffer_number_to_merge = 4;
this->options.max_write_buffer_number_to_maintain = 0;
// Conf item can be set to disable automatic compactions. For developers
// and debugging; good for valgrind.
this->options.disable_auto_compactions = !bool(db::auto_compact);
// Set the compaction style; we don't override this in the descriptor yet.
//this->options.compaction_style = rocksdb::kCompactionStyleNone;
this->options.compaction_style = rocksdb::kCompactionStyleLevel;
//this->options.compaction_style = rocksdb::kCompactionStyleUniversal;
// Set the compaction priority from string in the descriptor
this->options.compaction_pri =
this->descriptor->compaction_pri == "kByCompensatedSize"?
rocksdb::CompactionPri::kByCompensatedSize:
this->descriptor->compaction_pri == "kMinOverlappingRatio"?
rocksdb::CompactionPri::kMinOverlappingRatio:
this->descriptor->compaction_pri == "kOldestSmallestSeqFirst"?
rocksdb::CompactionPri::kOldestSmallestSeqFirst:
this->descriptor->compaction_pri == "kOldestLargestSeqFirst"?
rocksdb::CompactionPri::kOldestLargestSeqFirst:
rocksdb::CompactionPri::kOldestLargestSeqFirst;
this->options.num_levels = 7;
this->options.level0_file_num_compaction_trigger = 2;
this->options.level_compaction_dynamic_level_bytes = false;
this->options.ttl = 0;
#ifdef IRCD_DB_HAS_PERIODIC_COMPACTIONS
this->options.periodic_compaction_seconds = this->descriptor->compaction_period.count();
#endif
this->options.target_file_size_base = this->descriptor->target_file_size.base;
this->options.target_file_size_multiplier = this->descriptor->target_file_size.multiplier;
this->options.max_bytes_for_level_base = this->descriptor->max_bytes_for_level[0].base;
this->options.max_bytes_for_level_multiplier = this->descriptor->max_bytes_for_level[0].multiplier;
this->options.max_bytes_for_level_multiplier_additional = std::vector<int>(this->options.num_levels, 1);
{
auto &dst(this->options.max_bytes_for_level_multiplier_additional);
const auto &src(this->descriptor->max_bytes_for_level);
const size_t src_size(std::distance(begin(src) + 1, std::end(src)));
assert(src_size >= 1);
const auto end
{
begin(src) + 1 + std::min(dst.size(), src_size)
};
std::transform(begin(src) + 1, end, begin(dst), []
(const auto &mbfl)
{
return mbfl.multiplier;
});
}
// Universal compaction options; these are unused b/c we don't use this
// style; they are here for hacking an experimentation for now.
this->options.compaction_options_universal.size_ratio = 1;
this->options.compaction_options_universal.min_merge_width = 2;
this->options.compaction_options_universal.max_merge_width = UINT_MAX;
this->options.compaction_options_universal.max_size_amplification_percent = 200;
this->options.compaction_options_universal.compression_size_percent = -1;
this->options.compaction_options_universal.stop_style = rocksdb::kCompactionStopStyleTotalSize;
this->options.compaction_options_universal.allow_trivial_move = false;;
//
// Table options
//
// Block based table index type.
table_opts.format_version = 3; // RocksDB >= 5.15 compat only; otherwise use 2.
table_opts.index_type = rocksdb::BlockBasedTableOptions::kTwoLevelIndexSearch;
table_opts.index_block_restart_interval = 64;
table_opts.read_amp_bytes_per_bit = 8;
// Specify that index blocks should use the cache. If not, they will be
// pre-read into RAM by rocksdb internally. Because of the above
// TwoLevelIndex + partition_filters configuration on RocksDB v5.15 it's
// better to use pre-read except in the case of a massive database.
table_opts.cache_index_and_filter_blocks = true;
table_opts.cache_index_and_filter_blocks_with_high_priority = true;
table_opts.pin_top_level_index_and_filter = false;
table_opts.pin_l0_filter_and_index_blocks_in_cache = false;
table_opts.partition_filters = true;
table_opts.use_delta_encoding = false;
// Determine whether the index for this column should be compressed.
const bool is_string_index(this->descriptor->type.first == typeid(string_view));
const bool is_compression(this->options.compression != rocksdb::kNoCompression);
table_opts.enable_index_compression = is_compression; //&& is_string_index;
// Setup the block size
table_opts.block_size = this->descriptor->block_size;
table_opts.metadata_block_size = this->descriptor->meta_block_size;
table_opts.block_size_deviation = 50;
table_opts.block_restart_interval = 64;
//table_opts.data_block_index_type = rocksdb::BlockBasedTableOptions::kDataBlockBinaryAndHash;
//table_opts.data_block_hash_table_util_ratio = 0.75;
// Block alignment doesn't work if compression is enabled for this
// column. If not, we want block alignment for direct IO.
table_opts.block_align = this->options.compression == rocksdb::kNoCompression;
// Setup the cache for assets.
const auto &cache_size(this->descriptor->cache_size);
if(cache_size != 0)
table_opts.block_cache = std::make_shared<database::cache>(this->d, this->stats, this->allocator, this->name, cache_size);
// RocksDB will create an 8_MiB block_cache if we don't create our own.
// To honor the user's desire for a zero-size cache, this must be set.
if(!table_opts.block_cache)
{
table_opts.no_block_cache = true;
table_opts.cache_index_and_filter_blocks = false; // MBZ or error w/o block_cache
}
// Setup the cache for compressed assets.
const auto &cache_size_comp(this->descriptor->cache_size_comp);
if(cache_size_comp != 0)
table_opts.block_cache_compressed = std::make_shared<database::cache>(this->d, this->stats, this->allocator, this->name, cache_size_comp);
// Setup the bloom filter.
const auto &bloom_bits(this->descriptor->bloom_bits);
if(bloom_bits)
table_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(bloom_bits, false));
// Tickers::READ_AMP_TOTAL_READ_BYTES / Tickers::READ_AMP_ESTIMATE_USEFUL_BYTES
//table_opts.read_amp_bytes_per_bit = 8;
// Finally set the table options in the column options.
this->options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(table_opts));
log::debug
{
log, "schema '%s' column [%s => %s] cmp[%s] pfx[%s] lru:%s:%s bloom:%zu compression:%d %s",
db::name(d),
demangle(key_type.name()),
demangle(mapped_type.name()),
this->cmp.Name(),
this->options.prefix_extractor? this->prefix.Name() : "none",
cache_size? "YES": "NO",
cache_size_comp? "YES": "NO",
bloom_bits,
int(this->options.compression),
this->descriptor->name
};
}
ircd::db::database::column::~column()
noexcept
{
}
ircd::db::database::column::operator
database &()
{
return *d;
}
ircd::db::database::column::operator
rocksdb::ColumnFamilyHandle *()
{
return handle.get();
}
ircd::db::database::column::operator
const database &()
const
{
return *d;
}
ircd::db::database::column::operator
const rocksdb::ColumnFamilyHandle *()
const
{
return handle.get();
}
ircd::db::database::column::operator
const rocksdb::ColumnFamilyOptions &()
const
{
return options;
}
///////////////////////////////////////////////////////////////////////////////
//
// database::comparator
//
ircd::db::database::comparator::comparator(database *const &d,
db::comparator user)
:d{d}
,user
{
std::move(user)
}
{
}
const char *
ircd::db::database::comparator::Name()
const noexcept
{
assert(!user.name.empty());
return user.name.data();
}
bool
ircd::db::database::comparator::Equal(const Slice &a,
const Slice &b)
const noexcept
{
return user.equal?
user.equal(slice(a), slice(b)):
Compare(a, b) == 0;
}
int
ircd::db::database::comparator::Compare(const Slice &a,
const Slice &b)
const noexcept
{
assert(bool(user.less));
const auto sa{slice(a)};
const auto sb{slice(b)};
return user.less(sa, sb)? -1: // less[Y], equal[?], greater[?]
user.equal && user.equal(sa, sb)? 0: // less[N], equal[Y], greater[?]
user.equal? 1: // less[N], equal[N], greater[Y]
user.less(sb, sa)? 1: // less[N], equal[?], greater[Y]
0; // less[N], equal[Y], greater[N]
}
void
ircd::db::database::comparator::FindShortestSeparator(std::string *const key,
const Slice &limit)
const noexcept
{
assert(key != nullptr);
if(user.separator)
user.separator(*key, slice(limit));
}
void
ircd::db::database::comparator::FindShortSuccessor(std::string *const key)
const noexcept
{
assert(key != nullptr);
if(user.successor)
user.successor(*key);
}
bool
ircd::db::database::comparator::IsSameLengthImmediateSuccessor(const Slice &s,
const Slice &t)
const noexcept
{
return rocksdb::Comparator::IsSameLengthImmediateSuccessor(s, t);
}
bool
ircd::db::database::comparator::CanKeysWithDifferentByteContentsBeEqual()
const noexcept
{
// When keys with different byte contents can be equal the keys are
// not hashable.
return !user.hashable;
}
///////////////////////////////////////////////////////////////////////////////
//
// database::prefix_transform
//
const char *
ircd::db::database::prefix_transform::Name()
const noexcept
{
assert(!user.name.empty());
return user.name.c_str();
}
rocksdb::Slice
ircd::db::database::prefix_transform::Transform(const Slice &key)
const noexcept
{
assert(bool(user.get));
return slice(user.get(slice(key)));
}
bool
ircd::db::database::prefix_transform::InRange(const Slice &key)
const noexcept
{
return InDomain(key);
}
bool
ircd::db::database::prefix_transform::InDomain(const Slice &key)
const noexcept
{
assert(bool(user.has));
return user.has(slice(key));
}
///////////////////////////////////////////////////////////////////////////////
//
// database::snapshot
//
uint64_t
ircd::db::sequence(const database::snapshot &s)
{
const rocksdb::Snapshot *const rs(s);
return sequence(rs);
}
uint64_t
ircd::db::sequence(const rocksdb::Snapshot *const &rs)
{
return likely(rs)? rs->GetSequenceNumber() : 0ULL;
}
//
// snapshot::shapshot
//
ircd::db::database::snapshot::snapshot(database &d)
:s
{
d.d->GetSnapshot(),
[dp(weak_from(d))](const rocksdb::Snapshot *const s)
{
if(!s)
return;
const auto d(dp.lock());
d->d->ReleaseSnapshot(s);
}
}
{
}
ircd::db::database::snapshot::~snapshot()
noexcept
{
}
///////////////////////////////////////////////////////////////////////////////
//
// database::logger
//
ircd::db::database::logger::logger(database *const &d)
:rocksdb::Logger{}
,d{d}
{
}
ircd::db::database::logger::~logger()
noexcept
{
}
rocksdb::Status
ircd::db::database::logger::Close()
noexcept
{
return rocksdb::Status::NotSupported();
}
static
ircd::log::level
translate(const rocksdb::InfoLogLevel &level)
{
switch(level)
{
// Treat all infomational messages from rocksdb as debug here for now.
// We can clean them up and make better reports for our users eventually.
default:
case rocksdb::InfoLogLevel::DEBUG_LEVEL: return ircd::log::level::DEBUG;
case rocksdb::InfoLogLevel::INFO_LEVEL: return ircd::log::level::DEBUG;
case rocksdb::InfoLogLevel::WARN_LEVEL: return ircd::log::level::WARNING;
case rocksdb::InfoLogLevel::ERROR_LEVEL: return ircd::log::level::ERROR;
case rocksdb::InfoLogLevel::FATAL_LEVEL: return ircd::log::level::CRITICAL;
case rocksdb::InfoLogLevel::HEADER_LEVEL: return ircd::log::level::NOTICE;
}
}
void
ircd::db::database::logger::Logv(const char *const fmt,
va_list ap)
noexcept
{
Logv(rocksdb::InfoLogLevel::DEBUG_LEVEL, fmt, ap);
}
void
ircd::db::database::logger::LogHeader(const char *const fmt,
va_list ap)
noexcept
{
Logv(rocksdb::InfoLogLevel::DEBUG_LEVEL, fmt, ap);
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif __clang__
void
ircd::db::database::logger::Logv(const rocksdb::InfoLogLevel level_,
const char *const fmt,
va_list ap)
noexcept
{
if(level_ < GetInfoLogLevel())
return;
const log::level level
{
translate(level_)
};
if(level > RB_LOG_LEVEL)
return;
thread_local char buf[1024]; const auto len
{
vsnprintf(buf, sizeof(buf), fmt, ap)
};
const auto str
{
// RocksDB adds annoying leading whitespace to attempt to right-justify things and idc
lstrip(string_view{buf, size_t(len)}, ' ')
};
// Skip the options for now
if(startswith(str, "Options"))
return;
rog(level, "[%s] %s", d->name, str);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif __clang__
#pragma GCC diagnostic pop
///////////////////////////////////////////////////////////////////////////////
//
// database::mergeop
//
ircd::db::database::mergeop::mergeop(database *const &d,
merge_closure merger)
:d{d}
,merger
{
merger?
std::move(merger):
ircd::db::merge_operator
}
{
}
ircd::db::database::mergeop::~mergeop()
noexcept
{
}
const char *
ircd::db::database::mergeop::Name()
const noexcept
{
return "<unnamed>";
}
bool
ircd::db::database::mergeop::Merge(const rocksdb::Slice &_key,
const rocksdb::Slice *const _exist,
const rocksdb::Slice &_update,
std::string *const newval,
rocksdb::Logger *const)
const noexcept try
{
const string_view key
{
_key.data(), _key.size()
};
const string_view exist
{
_exist? string_view { _exist->data(), _exist->size() } : string_view{}
};
const string_view update
{
_update.data(), _update.size()
};
if(exist.empty())
{
*newval = std::string(update);
return true;
}
//XXX caching opportunity?
*newval = merger(key, {exist, update}); // call the user
return true;
}
catch(const std::bad_function_call &e)
{
log::critical
{
log, "merge: missing merge operator (%s)", e
};
return false;
}
catch(const std::exception &e)
{
log::error
{
log, "merge: %s", e
};
return false;
}
///////////////////////////////////////////////////////////////////////////////
//
// database::stats (db/database/stats.h) internal
//
namespace ircd::db
{
static thread_local char database_stats_name_buf[128];
}
//
// stats::stats
//
ircd::db::database::stats::stats(database *const &d,
database::column *const &c)
:d{d}
,c{c}
,get_copied
{
{ "name", make_name("get.copied") },
{ "desc", "Number of DB::Get() results violating zero-copy." },
}
,get_referenced
{
{ "name", make_name("get.referenced") },
{ "desc", "Number of DB::Get() results adhering to zero-copy." },
}
,multiget_copied
{
{ "name", make_name("multiget.copied") },
{ "desc", "Number of DB::MultiGet() results violating zero-copy." },
}
,multiget_referenced
{
{ "name", make_name("multiget.referenced") },
{ "desc", "Number of DB::MultiGet() results adhering to zero-copy." },
}
{
assert(item.size() == ticker.size());
for(size_t i(0); i < item.size(); ++i)
{
const auto &[id, ticker_name]
{
rocksdb::TickersNameMap[i]
};
assert(id == i);
new (item.data() + i) ircd::stats::item<uint64_t *>
{
std::addressof(ticker[i]), json::members
{
{ "name", make_name(ticker_name) },
{ "desc", "RocksDB library statistics counter." },
}
};
}
}
ircd::db::database::stats::~stats()
noexcept
{
}
rocksdb::Status
ircd::db::database::stats::Reset()
noexcept
{
ticker.fill(0);
histogram.fill({0.0});
return rocksdb::Status::OK();
}
bool
ircd::db::database::stats::HistEnabledForType(const uint32_t type)
const noexcept
{
return type < histogram.size();
}
void
ircd::db::database::stats::measureTime(const uint32_t type,
const uint64_t time)
noexcept
{
auto &data(histogram.at(type));
data.time += time;
data.hits++;
data.max = std::max(data.max, double(time));
data.avg = data.time / static_cast<long double>(data.hits);
}
void
ircd::db::database::stats::histogramData(const uint32_t type,
rocksdb::HistogramData *const data)
const noexcept
{
assert(data);
const auto &h
{
histogram.at(type)
};
data->median = h.median;
data->percentile95 = h.pct95;
data->percentile99 = h.pct99;
data->average = h.avg;
data->standard_deviation = h.stddev;
data->max = h.max;
}
void
ircd::db::database::stats::recordTick(const uint32_t type,
const uint64_t count)
noexcept
{
ticker.at(type) += count;
}
void
ircd::db::database::stats::setTickerCount(const uint32_t type,
const uint64_t count)
noexcept
{
ticker.at(type) = count;
}
uint64_t
ircd::db::database::stats::getAndResetTickerCount(const uint32_t type)
noexcept
{
const auto ret(getTickerCount(type));
setTickerCount(type, 0);
return ret;
}
uint64_t
ircd::db::database::stats::getTickerCount(const uint32_t type)
const noexcept
{
return ticker.at(type);
}
ircd::string_view
ircd::db::database::stats::make_name(const string_view &ticker_name)
const
{
assert(this->d);
return fmt::sprintf
{
database_stats_name_buf, "ircd.db.%s.%s.%s",
db::name(*d),
c? db::name(*c): "db"s,
ticker_name,
};
}
//
// database::stats::passthru
//
ircd::db::database::stats::passthru::passthru(rocksdb::Statistics *const &a,
rocksdb::Statistics *const &b)
:pass
{
{ a, b }
}
{
}
ircd::db::database::stats::passthru::~passthru()
noexcept
{
}
rocksdb::Status
__attribute__((noreturn))
ircd::db::database::stats::passthru::Reset()
noexcept
{
ircd::terminate
{
"Unavailable for passthru"
};
__builtin_unreachable();
}
void
ircd::db::database::stats::passthru::recordTick(const uint32_t tickerType,
const uint64_t count)
noexcept
{
for(auto *const &pass : this->pass)
pass->recordTick(tickerType, count);
}
void
ircd::db::database::stats::passthru::measureTime(const uint32_t histogramType,
const uint64_t time)
noexcept
{
for(auto *const &pass : this->pass)
pass->measureTime(histogramType, time);
}
bool
ircd::db::database::stats::passthru::HistEnabledForType(const uint32_t type)
const noexcept
{
return std::all_of(begin(pass), end(pass), [&type]
(const auto *const &pass)
{
return pass->HistEnabledForType(type);
});
}
uint64_t
__attribute__((noreturn))
ircd::db::database::stats::passthru::getTickerCount(const uint32_t tickerType)
const noexcept
{
ircd::terminate
{
"Unavailable for passthru"
};
__builtin_unreachable();
}
void
__attribute__((noreturn))
ircd::db::database::stats::passthru::setTickerCount(const uint32_t tickerType,
const uint64_t count)
noexcept
{
ircd::terminate
{
"Unavailable for passthru"
};
__builtin_unreachable();
}
void
__attribute__((noreturn))
ircd::db::database::stats::passthru::histogramData(const uint32_t type,
rocksdb::HistogramData *const data)
const noexcept
{
ircd::terminate
{
"Unavailable for passthru"
};
__builtin_unreachable();
}
uint64_t
__attribute__((noreturn))
ircd::db::database::stats::passthru::getAndResetTickerCount(const uint32_t tickerType)
noexcept
{
ircd::terminate
{
"Unavailable for passthru"
};
__builtin_unreachable();
}
///////////////////////////////////////////////////////////////////////////////
//
// database::events
//
void
ircd::db::database::events::OnFlushCompleted(rocksdb::DB *const db,
const rocksdb::FlushJobInfo &info)
noexcept
{
log::info
{
log, "[%s] job:%d ctx:%lu flush ended writes[slow:%d stop:%d] seq[%zu -> %zu] %s '%s' `%s'",
d->name,
info.job_id,
info.thread_id,
info.triggered_writes_slowdown,
info.triggered_writes_stop,
info.smallest_seqno,
info.largest_seqno,
reflect(info.flush_reason),
info.cf_name,
info.file_path,
};
assert(info.thread_id == ctx::id(*ctx::current));
}
void
ircd::db::database::events::OnFlushBegin(rocksdb::DB *const db,
const rocksdb::FlushJobInfo &info)
noexcept
{
log::info
{
log, "[%s] job:%d ctx:%lu flush start writes[slow:%d stop:%d] seq[%zu -> %zu] %s '%s'",
d->name,
info.job_id,
info.thread_id,
info.triggered_writes_slowdown,
info.triggered_writes_stop,
info.smallest_seqno,
info.largest_seqno,
reflect(info.flush_reason),
info.cf_name,
};
assert(info.thread_id == ctx::id(*ctx::current));
}
void
ircd::db::database::events::OnCompactionCompleted(rocksdb::DB *const db,
const rocksdb::CompactionJobInfo &info)
noexcept
{
const log::level level
{
info.status == rocksdb::Status::OK()?
log::level::INFO:
log::level::ERROR
};
log::logf
{
log, level,
"[%s] job:%d ctx:%lu compacted level[%d -> %d] files[%zu -> %zu] %s '%s' (%d): %s",
d->name,
info.job_id,
info.thread_id,
info.base_input_level,
info.output_level,
info.input_files.size(),
info.output_files.size(),
reflect(info.compaction_reason),
info.cf_name,
int(info.status.code()),
info.status.getState()?: "OK",
};
const bool bytes_same
{
info.stats.total_input_bytes == info.stats.total_output_bytes
};
log::debug
{
log, "[%s] job:%d keys[in:%zu out:%zu upd:%zu] bytes[%s -> %s] falloc:%s write:%s rsync:%s fsync:%s total:%s",
d->name,
info.job_id,
info.stats.num_input_records,
info.stats.num_output_records,
info.stats.num_records_replaced,
pretty(iec(info.stats.total_input_bytes)),
bytes_same? "same": pretty(iec(info.stats.total_output_bytes)),
pretty(nanoseconds(info.stats.file_prepare_write_nanos), true),
pretty(nanoseconds(info.stats.file_write_nanos), true),
pretty(nanoseconds(info.stats.file_range_sync_nanos), true),
pretty(nanoseconds(info.stats.file_fsync_nanos), true),
pretty(microseconds(info.stats.elapsed_micros), true),
};
if(info.stats.num_corrupt_keys > 0)
log::error
{
log, "[%s] job:%d reported %lu corrupt keys.",
d->name,
info.job_id,
info.stats.num_corrupt_keys
};
assert(info.thread_id == ctx::id(*ctx::current));
}
void
ircd::db::database::events::OnTableFileDeleted(const rocksdb::TableFileDeletionInfo &info)
noexcept
{
const log::level level
{
info.status == rocksdb::Status::OK()?
log::level::DEBUG:
log::level::ERROR
};
log::logf
{
log, level,
"[%s] job:%d table file delete [%s][%s] (%d): %s",
d->name,
info.job_id,
info.db_name,
lstrip(info.file_path, info.db_name),
int(info.status.code()),
info.status.getState()?: "OK",
};
}
void
ircd::db::database::events::OnTableFileCreated(const rocksdb::TableFileCreationInfo &info)
noexcept
{
const log::level level
{
info.status == rocksdb::Status::OK()?
log::level::DEBUG:
log::level::ERROR
};
log::logf
{
log, level,
"[%s] job:%d table file closed [%s][%s] size:%s '%s' (%d): %s",
d->name,
info.job_id,
info.db_name,
lstrip(info.file_path, info.db_name),
pretty(iec(info.file_size)),
info.cf_name,
int(info.status.code()),
info.status.getState()?: "OK",
};
log::debug
{
log, "[%s] job:%d head[%s] index[%s] filter[%s] data[%lu %s] keys[%lu %s] vals[%s] %s",
d->name,
info.job_id,
pretty(iec(info.table_properties.top_level_index_size)),
pretty(iec(info.table_properties.index_size)),
pretty(iec(info.table_properties.filter_size)),
info.table_properties.num_data_blocks,
pretty(iec(info.table_properties.data_size)),
info.table_properties.num_entries,
pretty(iec(info.table_properties.raw_key_size)),
pretty(iec(info.table_properties.raw_value_size)),
info.table_properties.compression_name
};
}
void
ircd::db::database::events::OnTableFileCreationStarted(const rocksdb::TableFileCreationBriefInfo &info)
noexcept
{
log::debug
{
log, "[%s] job:%d table file opened [%s][%s] '%s'",
d->name,
info.job_id,
info.db_name,
lstrip(info.file_path, info.db_name),
info.cf_name,
};
}
void
ircd::db::database::events::OnMemTableSealed(const rocksdb::MemTableInfo &info)
noexcept
{
log::debug
{
log, "[%s] memory table sealed '%s' entries:%lu deletes:%lu",
d->name,
info.cf_name,
info.num_entries,
info.num_deletes
};
}
void
ircd::db::database::events::OnColumnFamilyHandleDeletionStarted(rocksdb::ColumnFamilyHandle *const h)
noexcept
{
log::debug
{
log, "[%s] column[%s] handle closing @ %p",
d->name,
h->GetName(),
h
};
}
void
ircd::db::database::events::OnExternalFileIngested(rocksdb::DB *const d,
const rocksdb::ExternalFileIngestionInfo &info)
noexcept
{
log::notice
{
log, "[%s] external file ingested column[%s] external[%s] internal[%s] sequence:%lu",
this->d->name,
info.cf_name,
info.external_file_path,
info.internal_file_path,
info.global_seqno
};
}
void
ircd::db::database::events::OnBackgroundError(rocksdb::BackgroundErrorReason reason,
rocksdb::Status *const status)
noexcept
{
assert(d);
assert(status);
thread_local char buf[1024];
const string_view str{fmt::sprintf
{
buf, "%s error in %s :%s",
reflect(status->severity()),
reflect(reason),
status->ToString()
}};
// This is a legitimate when we want to use it. If the error is not
// suppressed the DB will enter read-only mode and will require a
// call to db::resume() to clear the error (i.e by admin at console).
const bool ignore
{
false
};
const log::level fac
{
ignore?
log::level::DERROR:
status->severity() == rocksdb::Status::kFatalError?
log::level::CRITICAL:
log::level::ERROR
};
log::logf
{
log, fac, "[%s] %s", d->name, str
};
if(ignore)
{
*status = rocksdb::Status::OK();
return;
}
// Downgrade select fatal errors to hard errors. If this downgrade
// does not occur then it can never be cleared by a db::resume() and
// the daemon must be restarted.
if(reason == rocksdb::BackgroundErrorReason::kCompaction)
if(status->severity() == rocksdb::Status::kFatalError)
*status = rocksdb::Status(*status, rocksdb::Status::kHardError);
// Save the error string to the database instance for later examination.
d->errors.emplace_back(str);
}
void
ircd::db::database::events::OnStallConditionsChanged(const rocksdb::WriteStallInfo &info)
noexcept
{
const auto level
{
info.condition.cur == rocksdb::WriteStallCondition::kNormal?
log::level::INFO:
log::level::WARNING
};
log::logf
{
log, level,
"'%s' stall condition column[%s] %s -> %s",
d->name,
info.cf_name,
reflect(info.condition.prev),
reflect(info.condition.cur)
};
}
///////////////////////////////////////////////////////////////////////////////
//
// database::cache (internal)
//
decltype(ircd::db::database::cache::DEFAULT_SHARD_BITS)
ircd::db::database::cache::DEFAULT_SHARD_BITS
(
std::log2(std::min(size_t(db::request_pool_size), 16UL))
);
decltype(ircd::db::database::cache::DEFAULT_STRICT)
ircd::db::database::cache::DEFAULT_STRICT
{
false
};
decltype(ircd::db::database::cache::DEFAULT_HI_PRIO)
ircd::db::database::cache::DEFAULT_HI_PRIO
{
0.25
};
//
// cache::cache
//
ircd::db::database::cache::cache(database *const &d,
std::shared_ptr<struct database::stats> stats,
std::shared_ptr<struct database::allocator> allocator,
std::string name,
const ssize_t &initial_capacity)
#ifdef IRCD_DB_HAS_ALLOCATOR
:rocksdb::Cache{allocator}
,d{d}
#else
:d{d}
#endif
,name{std::move(name)}
,stats{std::move(stats)}
,allocator{std::move(allocator)}
,c{rocksdb::NewLRUCache(rocksdb::LRUCacheOptions
{
size_t(std::max(initial_capacity, ssize_t(0)))
,DEFAULT_SHARD_BITS
,DEFAULT_STRICT
,DEFAULT_HI_PRIO
#ifdef IRCD_DB_HAS_ALLOCATOR
,this->allocator
#endif
})}
{
assert(bool(c));
#ifdef IRCD_DB_HAS_ALLOCATOR
assert(c->memory_allocator() == this->allocator.get());
#endif
}
ircd::db::database::cache::~cache()
noexcept
{
}
const char *
ircd::db::database::cache::Name()
const noexcept
{
return !empty(name)?
name.c_str():
c->Name();
}
rocksdb::Status
ircd::db::database::cache::Insert(const Slice &key,
void *const value,
size_t charge,
deleter del,
Handle **const handle,
Priority priority)
noexcept
{
assert(bool(c));
assert(bool(stats));
const rocksdb::Status &ret
{
c->Insert(key, value, charge, del, handle, priority)
};
stats->recordTick(rocksdb::Tickers::BLOCK_CACHE_ADD, ret.ok());
stats->recordTick(rocksdb::Tickers::BLOCK_CACHE_ADD_FAILURES, !ret.ok());
stats->recordTick(rocksdb::Tickers::BLOCK_CACHE_DATA_BYTES_INSERT, ret.ok()? charge : 0UL);
return ret;
}
rocksdb::Cache::Handle *
ircd::db::database::cache::Lookup(const Slice &key,
Statistics *const statistics)
noexcept
{
assert(bool(c));
assert(bool(this->stats));
database::stats::passthru passthru
{
this->stats.get(), statistics
};
rocksdb::Statistics *const s
{
statistics?
dynamic_cast<rocksdb::Statistics *>(&passthru):
dynamic_cast<rocksdb::Statistics *>(this->stats.get())
};
auto *const &ret
{
c->Lookup(key, s)
};
// Rocksdb's LRUCache stats are broke. The statistics ptr is null and
// passing it to Lookup() does nothing internally. We have to do this
// here ourselves :/
this->stats->recordTick(rocksdb::Tickers::BLOCK_CACHE_HIT, bool(ret));
this->stats->recordTick(rocksdb::Tickers::BLOCK_CACHE_MISS, !bool(ret));
return ret;
}
bool
ircd::db::database::cache::Ref(Handle *const handle)
noexcept
{
assert(bool(c));
return c->Ref(handle);
}
bool
ircd::db::database::cache::Release(Handle *const handle,
bool force_erase)
noexcept
{
assert(bool(c));
return c->Release(handle, force_erase);
}
void *
ircd::db::database::cache::Value(Handle *const handle)
noexcept
{
assert(bool(c));
return c->Value(handle);
}
void
ircd::db::database::cache::Erase(const Slice &key)
noexcept
{
assert(bool(c));
return c->Erase(key);
}
uint64_t
ircd::db::database::cache::NewId()
noexcept
{
assert(bool(c));
return c->NewId();
}
void
ircd::db::database::cache::SetCapacity(size_t capacity)
noexcept
{
assert(bool(c));
return c->SetCapacity(capacity);
}
void
ircd::db::database::cache::SetStrictCapacityLimit(bool strict_capacity_limit)
noexcept
{
assert(bool(c));
return c->SetStrictCapacityLimit(strict_capacity_limit);
}
bool
ircd::db::database::cache::HasStrictCapacityLimit()
const noexcept
{
assert(bool(c));
return c->HasStrictCapacityLimit();
}
size_t
ircd::db::database::cache::GetCapacity()
const noexcept
{
assert(bool(c));
return c->GetCapacity();
}
size_t
ircd::db::database::cache::GetUsage()
const noexcept
{
assert(bool(c));
return c->GetUsage();
}
size_t
ircd::db::database::cache::GetUsage(Handle *const handle)
const noexcept
{
assert(bool(c));
return c->GetUsage(handle);
}
size_t
ircd::db::database::cache::GetPinnedUsage()
const noexcept
{
assert(bool(c));
return c->GetPinnedUsage();
}
void
ircd::db::database::cache::DisownData()
noexcept
{
assert(bool(c));
return c->DisownData();
}
void
ircd::db::database::cache::ApplyToAllCacheEntries(callback cb,
bool thread_safe)
noexcept
{
assert(bool(c));
return c->ApplyToAllCacheEntries(cb, thread_safe);
}
void
ircd::db::database::cache::EraseUnRefEntries()
noexcept
{
assert(bool(c));
return c->EraseUnRefEntries();
}
std::string
ircd::db::database::cache::GetPrintableOptions()
const noexcept
{
assert(bool(c));
return c->GetPrintableOptions();
}
#ifdef IRCD_DB_HAS_CACHE_GETCHARGE
size_t
ircd::db::database::cache::GetCharge(Handle *const handle)
const noexcept
{
assert(bool(c));
return c->GetCharge(handle);
}
#endif
///////////////////////////////////////////////////////////////////////////////
//
// database::compaction_filter
//
ircd::db::database::compaction_filter::compaction_filter(column *const &c,
db::compactor user)
:c{c}
,d{c->d}
,user{std::move(user)}
{
}
ircd::db::database::compaction_filter::~compaction_filter()
noexcept
{
}
rocksdb::CompactionFilter::Decision
ircd::db::database::compaction_filter::FilterV2(const int level,
const Slice &key,
const ValueType type,
const Slice &oldval,
std::string *const newval,
std::string *const skip)
const noexcept
{
const ctx::uninterruptible::nothrow ui;
#ifdef RB_DEBUG_DB_ENV
const auto typestr
{
type == kValue?
"VALUE"_sv:
type == kMergeOperand?
"MERGE"_sv:
"BLOB"_sv
};
#endif
static const compactor::callback empty;
const db::compactor::callback &callback
{
type == ValueType::kValue && user.value?
user.value:
type == ValueType::kMergeOperand && user.merge?
user.merge:
empty
};
if(!callback)
return Decision::kKeep;
#ifdef RB_DEBUG_DB_ENV
log::debug
{
log, "[%s]'%s': compaction level:%d key:%zu@%p type:%s old:%zu@%p new:%p skip:%p",
d->name,
c->name,
level,
size(key),
data(key),
typestr,
size(oldval),
data(oldval),
(const void *)newval,
(const void *)skip
};
#endif
const compactor::args args
{
level, slice(key), slice(oldval), newval, skip
};
switch(callback(args))
{
default:
case db::op::GET: return Decision::kKeep;
case db::op::SET: return Decision::kChangeValue;
case db::op::DELETE: return Decision::kRemove;
case db::op::DELETE_RANGE: return Decision::kRemoveAndSkipUntil;
}
}
bool
ircd::db::database::compaction_filter::IgnoreSnapshots()
const noexcept
{
// RocksDB >= 6.0.0 sez this must no longer be false.
return true;
}
const char *
ircd::db::database::compaction_filter::Name()
const noexcept
{
assert(c);
return db::name(*c).c_str();
}
///////////////////////////////////////////////////////////////////////////////
//
// database::wal_filter
//
decltype(ircd::db::database::wal_filter::debug)
ircd::db::database::wal_filter::debug
{
{ "name", "ircd.db.wal.debug" },
{ "default", false },
{ "persist", false },
};
ircd::db::database::wal_filter::wal_filter(database *const &d)
:d{d}
{
}
ircd::db::database::wal_filter::~wal_filter()
noexcept
{
}
void
ircd::db::database::wal_filter::ColumnFamilyLogNumberMap(const log_number_map &log_number,
const name_id_map &name_id)
noexcept
{
assert(d);
this->log_number = log_number;
this->name_id = name_id;
log::debug
{
log, "[%s] WAL recovery mapping update: log_number:%zu name_id:%zu",
db::name(*d),
log_number.size(),
name_id.size(),
};
}
rocksdb::WalFilter::WalProcessingOption
ircd::db::database::wal_filter::LogRecordFound(unsigned long long log_nr,
const std::string &name,
const WriteBatch &wb,
WriteBatch *const replace,
bool *const replaced)
noexcept
{
assert(d && replace && replaced);
if(debug)
log::debug
{
log, "[%s] WAL recovery record log:%lu '%s' wb[count:%zu size:%zu]",
db::name(*d),
log_nr,
name,
wb.Count(),
wb.GetDataSize(),
};
*replaced = false;
return WalProcessingOption::kContinueProcessing;
}
rocksdb::WalFilter::WalProcessingOption
ircd::db::database::wal_filter::LogRecord(const WriteBatch &wb,
WriteBatch *const replace,
bool *const replaced)
const noexcept
{
return WalProcessingOption::kContinueProcessing;
}
const char *
ircd::db::database::wal_filter::Name()
const noexcept
{
assert(d);
return db::name(*d).c_str();
}
///////////////////////////////////////////////////////////////////////////////
//
// database::sst
//
void
ircd::db::database::sst::tool(const vector_view<const string_view> &args)
{
const ctx::uninterruptible::nothrow ui;
static const size_t arg_max {16};
static const size_t arg_max_len {256};
thread_local char arg[arg_max][arg_max_len]
{
"./sst_dump"
};
size_t i(0);
char *argv[arg_max] { arg[i++] };
for(; i < arg_max - 1 && i - 1 < args.size(); ++i)
{
strlcpy(arg[i], args.at(i - 1));
argv[i] = arg[i];
}
argv[i++] = nullptr;
assert(i <= arg_max);
rocksdb::SSTDumpTool tool;
const int ret
{
tool.Run(i, argv)
};
if(ret != 0)
throw error
{
"Error from SST dump tool: return value: %d", ret
};
}
//
// sst::dump::dump
//
ircd::db::database::sst::dump::dump(db::column column,
const key_range &range,
const string_view &path_)
{
database::column &c(column);
const database &d(column);
std::string path
{
path_
};
if(path.empty())
{
const string_view path_parts[]
{
fs::base::db, db::name(d), db::name(c)
};
path = fs::path_string(path_parts);
}
rocksdb::Options opts(d.d->GetOptions(c));
rocksdb::EnvOptions eopts(opts);
rocksdb::SstFileWriter writer
{
eopts, opts, c
};
throw_on_error
{
writer.Open(path)
};
size_t i(0);
for(auto it(column.begin()); it != column.end(); ++it, ++i)
throw_on_error
{
writer.Put(slice(it->first), slice(it->second))
};
rocksdb::ExternalSstFileInfo info;
if(i)
throw_on_error
{
writer.Finish(&info)
};
this->info.column = db::name(column);
this->info.path = std::move(info.file_path);
this->info.min_key = std::move(info.smallest_key);
this->info.max_key = std::move(info.largest_key);
this->info.min_seq = info.sequence_number;
this->info.max_seq = info.sequence_number;
this->info.size = info.file_size;
this->info.entries = info.num_entries;
this->info.version = info.version;
}
//
// sst::info::vector
//
ircd::db::database::sst::info::vector::vector(const database &d)
{
this->reserve(db::file_count(d));
for(const auto &c : d.columns)
{
db::column column{*c};
for(auto &&info : vector(column))
this->emplace_back(std::move(info));
}
}
ircd::db::database::sst::info::vector::vector(const db::column &column)
{
database::column &c(const_cast<db::column &>(column));
database &d(*c.d);
rocksdb::ColumnFamilyMetaData cfmd;
d.d->GetColumnFamilyMetaData(c, &cfmd);
rocksdb::TablePropertiesCollection tpc;
throw_on_error
{
d.d->GetPropertiesOfAllTables(c, &tpc)
};
size_t i(0);
this->resize(std::max(cfmd.file_count, tpc.size()));
for(rocksdb::LevelMetaData &level : cfmd.levels)
for(rocksdb::SstFileMetaData md : level.files)
{
auto &info(this->at(i++));
info.operator=(std::move(md));
info.level = level.level;
const auto path(info.path + info.name);
auto tp(*tpc.at(path));
info.operator=(std::move(tp));
tpc.erase(path);
}
for(auto &&kv : tpc)
{
auto &info(this->at(i++));
auto tp(*kv.second);
info.operator=(std::move(tp));
info.path = kv.first;
}
assert(i == this->size());
}
//
// sst::info::info
//
ircd::db::database::sst::info::info(const database &d_,
const string_view &filename)
{
auto &d(const_cast<database &>(d_));
const ctx::uninterruptible::nothrow ui;
std::vector<rocksdb::LiveFileMetaData> v;
d.d->GetLiveFilesMetaData(&v);
for(auto &md : v)
if(md.name == filename)
{
rocksdb::TablePropertiesCollection tpc;
throw_on_error
{
d.d->GetPropertiesOfAllTables(d[md.column_family_name], &tpc)
};
auto tp(*tpc.at(md.db_path + md.name));
this->operator=(std::move(md));
this->operator=(std::move(tp));
return;
}
throw not_found
{
"No file named '%s' is live in database '%s'",
filename,
d.name
};
}
ircd::db::database::sst::info &
ircd::db::database::sst::info::operator=(rocksdb::LiveFileMetaData &&md)
{
name = std::move(md.name);
path = std::move(md.db_path);
column = std::move(md.column_family_name);
size = std::move(md.size);
min_seq = std::move(md.smallest_seqno);
max_seq = std::move(md.largest_seqno);
min_key = std::move(md.smallestkey);
max_key = std::move(md.largestkey);
num_reads = std::move(md.num_reads_sampled);
level = std::move(md.level);
compacting = std::move(md.being_compacted);
return *this;
}
ircd::db::database::sst::info &
ircd::db::database::sst::info::operator=(rocksdb::SstFileMetaData &&md)
{
name = std::move(md.name);
path = std::move(md.db_path);
size = std::move(md.size);
min_seq = std::move(md.smallest_seqno);
max_seq = std::move(md.largest_seqno);
min_key = std::move(md.smallestkey);
max_key = std::move(md.largestkey);
num_reads = std::move(md.num_reads_sampled);
compacting = std::move(md.being_compacted);
return *this;
}
ircd::db::database::sst::info &
ircd::db::database::sst::info::operator=(rocksdb::TableProperties &&tp)
{
column = std::move(tp.column_family_name);
filter = std::move(tp.filter_policy_name);
comparator = std::move(tp.comparator_name);
merge_operator = std::move(tp.merge_operator_name);
prefix_extractor = std::move(tp.prefix_extractor_name);
compression = std::move(tp.compression_name);
format = std::move(tp.format_version);
cfid = std::move(tp.column_family_id);
data_size = std::move(tp.data_size);
index_size = std::move(tp.index_size);
top_index_size = std::move(tp.top_level_index_size);
filter_size = std::move(tp.filter_size);
keys_size = std::move(tp.raw_key_size);
values_size = std::move(tp.raw_value_size);
index_parts = std::move(tp.index_partitions);
data_blocks = std::move(tp.num_data_blocks);
entries = std::move(tp.num_entries);
range_deletes = std::move(tp.num_range_deletions);
fixed_key_len = std::move(tp.fixed_key_len);
created = std::move(tp.creation_time);
oldest_key = std::move(tp.oldest_key_time);
delta_encoding = std::move(tp.index_value_is_delta_encoded);
return *this;
}
///////////////////////////////////////////////////////////////////////////////
//
// database::wal
//
//
// wal::info::vector
//
ircd::db::database::wal::info::vector::vector(const database &d_)
{
auto &d{const_cast<database &>(d_)};
std::vector<std::unique_ptr<rocksdb::LogFile>> vec;
throw_on_error
{
d.d->GetSortedWalFiles(vec)
};
this->resize(vec.size());
for(size_t i(0); i < vec.size(); ++i)
this->at(i).operator=(*vec.at(i));
}
//
// wal::info::info
//
ircd::db::database::wal::info::info(const database &d_,
const string_view &filename)
{
auto &d{const_cast<database &>(d_)};
std::vector<std::unique_ptr<rocksdb::LogFile>> vec;
throw_on_error
{
d.d->GetSortedWalFiles(vec)
};
for(const auto &ptr : vec)
if(ptr->PathName() == filename)
{
this->operator=(*ptr);
return;
}
throw not_found
{
"No file named '%s' is live in database '%s'",
filename,
d.name
};
}
ircd::db::database::wal::info &
ircd::db::database::wal::info::operator=(const rocksdb::LogFile &lf)
{
name = lf.PathName();
number = lf.LogNumber();
seq = lf.StartSequence();
size = lf.SizeFileBytes();
alive = lf.Type() == rocksdb::WalFileType::kAliveLogFile;
return *this;
}
///////////////////////////////////////////////////////////////////////////////
//
// db/stats.h
//
std::string
ircd::db::string(const rocksdb::IOStatsContext &ic,
const bool &all)
{
const bool exclude_zeros(!all);
return ic.ToString(exclude_zeros);
}
const rocksdb::IOStatsContext &
ircd::db::iostats_current()
{
const auto *const &ret
{
rocksdb::get_iostats_context()
};
if(unlikely(!ret))
throw error
{
"IO counters are not available on this thread."
};
return *ret;
}
std::string
ircd::db::string(const rocksdb::PerfContext &pc,
const bool &all)
{
const bool exclude_zeros(!all);
return pc.ToString(exclude_zeros);
}
const rocksdb::PerfContext &
ircd::db::perf_current()
{
const auto *const &ret
{
rocksdb::get_perf_context()
};
if(unlikely(!ret))
throw error
{
"Performance counters are not available on this thread."
};
return *ret;
}
void
ircd::db::perf_level(const uint &level)
{
if(level >= rocksdb::PerfLevel::kOutOfBounds)
throw error
{
"Perf level of '%u' is invalid; maximum is '%u'",
level,
uint(rocksdb::PerfLevel::kOutOfBounds)
};
rocksdb::SetPerfLevel(rocksdb::PerfLevel(level));
}
uint
ircd::db::perf_level()
{
return rocksdb::GetPerfLevel();
}
//
// ticker
//
uint64_t
ircd::db::ticker(const database &d,
const string_view &key)
{
return ticker(d, ticker_id(key));
}
uint64_t
ircd::db::ticker(const database &d,
const uint32_t &id)
{
return d.stats->getTickerCount(id);
}
uint32_t
ircd::db::ticker_id(const string_view &key)
{
for(const auto &pair : rocksdb::TickersNameMap)
if(key == pair.second)
return pair.first;
throw std::out_of_range
{
"No ticker with that key"
};
}
ircd::string_view
ircd::db::ticker_id(const uint32_t &id)
{
for(const auto &pair : rocksdb::TickersNameMap)
if(id == pair.first)
return pair.second;
return {};
}
decltype(ircd::db::ticker_max)
ircd::db::ticker_max
{
rocksdb::TICKER_ENUM_MAX
};
//
// histogram
//
const struct ircd::db::histogram &
ircd::db::histogram(const database &d,
const string_view &key)
{
return histogram(d, histogram_id(key));
}
const struct ircd::db::histogram &
ircd::db::histogram(const database &d,
const uint32_t &id)
{
return d.stats->histogram.at(id);
}
uint32_t
ircd::db::histogram_id(const string_view &key)
{
for(const auto &pair : rocksdb::HistogramsNameMap)
if(key == pair.second)
return pair.first;
throw std::out_of_range
{
"No histogram with that key"
};
}
ircd::string_view
ircd::db::histogram_id(const uint32_t &id)
{
for(const auto &pair : rocksdb::HistogramsNameMap)
if(id == pair.first)
return pair.second;
return {};
}
decltype(ircd::db::histogram_max)
ircd::db::histogram_max
{
rocksdb::HISTOGRAM_ENUM_MAX
};
///////////////////////////////////////////////////////////////////////////////
//
// db/prefetcher.h
//
decltype(ircd::db::prefetcher)
ircd::db::prefetcher;
//
// db::prefetcher
//
ircd::db::prefetcher::prefetcher()
:ticker
{
std::make_unique<struct ticker>()
}
,context
{
"db.prefetcher",
128_KiB,
context::POST,
std::bind(&prefetcher::worker, this)
}
{
}
ircd::db::prefetcher::~prefetcher()
noexcept
{
while(!queue.empty())
{
log::warning
{
log, "Prefetcher waiting for %zu requests to clear...",
queue.size(),
};
dock.wait_for(seconds(5), [this]
{
return queue.empty();
});
}
assert(queue.empty());
}
bool
ircd::db::prefetcher::operator()(column &c,
const string_view &key,
const gopts &opts)
{
auto &d
{
static_cast<database &>(c)
};
assert(ticker);
ticker->queries++;
if(db::cached(c, key, opts))
{
ticker->rejects++;
return false;
}
queue.emplace_back(d, c, key);
queue.back().snd = now<steady_point>();
ticker->request++;
// Branch here based on whether it's not possible to directly dispatch
// a db::request worker. If all request workers are busy we notify our own
// prefetcher worker, and then it blocks on submitting to the request
// worker instead of us blocking here. This is done to avoid use and growth
// of any request pool queue, and allow for more direct submission.
if(db::request.wouldblock())
{
dock.notify_one();
// If the user sets NO_BLOCKING we honor their request to not
// context switch for a prefetch. However by default we want to
// control queue growth, so we insert voluntary yield here to allow
// prefetch operations to at least be processed before returning to
// the user submitting more prefetches.
if(likely(!test(opts, db::get::NO_BLOCKING)))
ctx::yield();
return true;
}
const ctx::critical_assertion ca;
ticker->directs++;
this->handle();
return true;
}
size_t
ircd::db::prefetcher::cancel(column &c)
{
return cancel([&c]
(const auto &request)
{
return request.cid == id(c);
});
}
size_t
ircd::db::prefetcher::cancel(database &d)
{
return cancel([&d]
(const auto &request)
{
return request.d == std::addressof(d);
});
}
size_t
ircd::db::prefetcher::cancel(const closure &closure)
{
size_t canceled(0);
for(auto &request : queue)
{
// already finished
if(request.fin != steady_point::min())
continue;
// in progress; can't cancel
if(request.req != steady_point::min())
continue;
// allow user to accept or reject
if(!closure(request))
continue;
// cancel by precociously setting the finish time.
request.fin = now<steady_point>();
++canceled;
}
if(canceled)
dock.notify_all();
assert(ticker);
ticker->cancels += canceled;
return canceled;
}
void
ircd::db::prefetcher::worker()
try
{
while(1)
{
dock.wait([this]
{
if(queue.empty())
return false;
assert(ticker);
if(ticker->request <= ticker->handles)
return false;
return true;
});
handle();
}
}
catch(const std::exception &e)
{
log::critical
{
log, "prefetcher worker: %s",
e.what()
};
}
void
ircd::db::prefetcher::handle()
{
auto handler
{
std::bind(&prefetcher::request_worker, this)
};
ticker->handles++;
db::request(std::move(handler));
ticker->handled++;
}
void
ircd::db::prefetcher::request_worker()
{
const ctx::scope_notify notify
{
this->dock
};
const scope_count request_workers
{
this->request_workers
};
// Garbage collection of the queue invoked unconditionally on unwind.
const unwind cleanup_on_leave
{
std::bind(&prefetcher::request_cleanup, this)
};
// GC the queue here to get rid of any cancelled requests which have
// arrived at the front so they don't become our request.
const size_t cleanup_on_enter
{
request_cleanup()
};
// Find the first request in the queue which does not have its req
// timestamp sent.
auto request
{
std::find_if(begin(queue), end(queue), []
(const auto &request)
{
return request.req == steady_point::min();
})
};
if(request == end(queue))
return;
assert(ticker);
assert(request->fin == steady_point::min());
request->req = now<steady_point>();
ticker->last_snd_req = duration_cast<microseconds>(request->req - request->snd);
ticker->accum_snd_req += ticker->last_snd_req;
ticker->fetches++;
request_handle(*request);
assert(request->fin != steady_point::min());
ticker->fetched++;
#ifdef IRCD_DB_DEBUG_PREFETCH
log::debug
{
log, "prefetcher reject:%zu request:%zu handle:%zu fetch:%zu direct:%zu cancel:%zu queue:%zu rw:%zu",
ticker->rejects,
ticker->request,
ticker->handles,
ticker->fetches,
ticker->directs,
ticker->cancels,
queue.size(),
this->request_workers,
};
#endif
}
size_t
ircd::db::prefetcher::request_cleanup()
noexcept
{
size_t removed(0);
const ctx::critical_assertion ca;
for(; !queue.empty() && queue.front().fin != steady_point::min(); ++removed)
queue.pop_front();
return removed;
}
void
ircd::db::prefetcher::request_handle(request &request)
try
{
assert(request.d);
db::column column
{
(*request.d)[request.cid]
};
const string_view key
{
request
};
const auto it
{
seek(column, key, gopts{})
};
const ctx::critical_assertion ca;
request.fin = now<steady_point>();
ticker->last_req_fin = duration_cast<microseconds>(request.fin - request.req);
ticker->accum_req_fin += ticker->last_req_fin;
const bool lte
{
valid_lte(*it, key)
};
if(likely(lte))
{
ticker->fetched_bytes_key += size(it->key());
ticker->fetched_bytes_val += size(it->value());
}
#ifdef IRCD_DB_DEBUG_PREFETCH
char pbuf[3][32];
log::debug
{
log, "[%s][%s] completed prefetch len:%zu lte:%b k:%zu v:%zu snd-req:%s req-fin:%s snd-fin:%s queue:%zu",
name(*request.d),
name(column),
size(key),
lte,
lte? size(it->key()) : 0UL,
lte? size(it->value()) : 0UL,
pretty(pbuf[0], request.req - request.snd, 1),
pretty(pbuf[1], request.fin - request.req, 1),
pretty(pbuf[2], request.fin - request.snd, 1),
queue.size(),
};
#endif
}
catch(const std::exception &e)
{
assert(request.d);
request.fin = now<steady_point>();
log::error
{
log, "[%s][%u] :%s",
name(*request.d),
request.cid,
e.what(),
};
}
catch(...)
{
request.fin = now<steady_point>();
throw;
}
size_t
ircd::db::prefetcher::wait_pending()
{
const size_t fetched_counter
{
ticker->fetched
};
const size_t fetched_target
{
fetched_counter + request_workers
};
dock.wait([this, &fetched_target]
{
return this->ticker->fetched >= fetched_target;
});
assert(fetched_target >= fetched_counter);
return fetched_target - fetched_counter;
}
//
// prefetcher::request
//
ircd::db::prefetcher::request::request(database &d,
const column &c,
const string_view &key)
noexcept
:d
{
std::addressof(d)
}
,cid
{
db::id(c)
}
,len
{
uint32_t(std::min(size(key), sizeof(this->key)))
}
,snd
{
steady_point::min()
}
,req
{
steady_point::min()
}
,fin
{
steady_point::min()
}
{
const size_t &len
{
buffer::copy(this->key, key)
};
assert(this->len == len);
}
ircd::db::prefetcher::request::operator
ircd::string_view()
const noexcept
{
return
{
key, len
};
}
///////////////////////////////////////////////////////////////////////////////
//
// db/txn.h
//
void
ircd::db::get(database &d,
const uint64_t &seq,
const seq_closure &closure)
{
for_each(d, seq, seq_closure_bool{[&closure]
(txn &txn, const uint64_t &seq)
{
closure(txn, seq);
return false;
}});
}
void
ircd::db::for_each(database &d,
const uint64_t &seq,
const seq_closure &closure)
{
for_each(d, seq, seq_closure_bool{[&closure]
(txn &txn, const uint64_t &seq)
{
closure(txn, seq);
return true;
}});
}
bool
ircd::db::for_each(database &d,
const uint64_t &seq,
const seq_closure_bool &closure)
{
std::unique_ptr<rocksdb::TransactionLogIterator> tit;
{
const ctx::uninterruptible ui;
throw_on_error
{
d.d->GetUpdatesSince(seq, &tit)
};
}
assert(bool(tit));
for(; tit->Valid(); tit->Next())
{
const ctx::uninterruptible ui;
auto batchres
{
tit->GetBatch()
};
throw_on_error
{
tit->status()
};
db::txn txn
{
d, std::move(batchres.writeBatchPtr)
};
assert(bool(txn.wb));
if(!closure(txn, batchres.sequence))
return false;
}
return true;
}
std::string
ircd::db::debug(const txn &t)
{
const rocksdb::WriteBatch &wb(t);
return db::debug(wb);
}
void
ircd::db::for_each(const txn &t,
const delta_closure &closure)
{
const auto re{[&closure]
(const delta &delta)
{
closure(delta);
return true;
}};
const database &d(t);
const rocksdb::WriteBatch &wb(t);
txn::handler h{d, re};
wb.Iterate(&h);
}
bool
ircd::db::for_each(const txn &t,
const delta_closure_bool &closure)
{
const database &d(t);
const rocksdb::WriteBatch &wb(t);
txn::handler h{d, closure};
wb.Iterate(&h);
return h._continue;
}
///
/// handler (db/database/txn.h)
///
rocksdb::Status
ircd::db::txn::handler::PutCF(const uint32_t cfid,
const Slice &key,
const Slice &val)
noexcept
{
return callback(cfid, op::SET, key, val);
}
rocksdb::Status
ircd::db::txn::handler::DeleteCF(const uint32_t cfid,
const Slice &key)
noexcept
{
return callback(cfid, op::DELETE, key, {});
}
rocksdb::Status
ircd::db::txn::handler::DeleteRangeCF(const uint32_t cfid,
const Slice &begin,
const Slice &end)
noexcept
{
return callback(cfid, op::DELETE_RANGE, begin, end);
}
rocksdb::Status
ircd::db::txn::handler::SingleDeleteCF(const uint32_t cfid,
const Slice &key)
noexcept
{
return callback(cfid, op::SINGLE_DELETE, key, {});
}
rocksdb::Status
ircd::db::txn::handler::MergeCF(const uint32_t cfid,
const Slice &key,
const Slice &value)
noexcept
{
return callback(cfid, op::MERGE, key, value);
}
rocksdb::Status
ircd::db::txn::handler::MarkBeginPrepare(bool b)
noexcept
{
ircd::not_implemented{};
return Status::OK();
}
rocksdb::Status
ircd::db::txn::handler::MarkEndPrepare(const Slice &xid)
noexcept
{
ircd::not_implemented{};
return Status::OK();
}
rocksdb::Status
ircd::db::txn::handler::MarkCommit(const Slice &xid)
noexcept
{
ircd::not_implemented{};
return Status::OK();
}
rocksdb::Status
ircd::db::txn::handler::MarkRollback(const Slice &xid)
noexcept
{
ircd::not_implemented{};
return Status::OK();
}
rocksdb::Status
ircd::db::txn::handler::callback(const uint32_t &cfid,
const op &op,
const Slice &a,
const Slice &b)
noexcept try
{
auto &c{d[cfid]};
const delta delta
{
op,
db::name(c),
slice(a),
slice(b)
};
return callback(delta);
}
catch(const std::exception &e)
{
_continue = false;
log::critical
{
log, "txn::handler: cfid[%u]: %s",
cfid,
e.what()
};
ircd::terminate();
__builtin_unreachable();
}
rocksdb::Status
ircd::db::txn::handler::callback(const delta &delta)
noexcept try
{
_continue = cb(delta);
return Status::OK();
}
catch(const std::exception &e)
{
_continue = false;
return Status::OK();
}
bool
ircd::db::txn::handler::Continue()
noexcept
{
return _continue;
}
//
// txn
//
ircd::db::txn::txn(database &d)
:txn{d, opts{}}
{
}
ircd::db::txn::txn(database &d,
const opts &opts)
:d{&d}
,wb
{
std::make_unique<rocksdb::WriteBatch>(opts.reserve_bytes, opts.max_bytes)
}
{
}
ircd::db::txn::txn(database &d,
std::unique_ptr<rocksdb::WriteBatch> &&wb)
:d{&d}
,wb{std::move(wb)}
{
}
ircd::db::txn::~txn()
noexcept
{
}
void
ircd::db::txn::operator()(const sopts &opts)
{
assert(bool(d));
operator()(*d, opts);
}
void
ircd::db::txn::operator()(database &d,
const sopts &opts)
{
assert(bool(wb));
assert(this->state == state::BUILD);
this->state = state::COMMIT;
commit(d, *wb, opts);
this->state = state::COMMITTED;
}
void
ircd::db::txn::clear()
{
assert(bool(wb));
wb->Clear();
this->state = state::BUILD;
}
size_t
ircd::db::txn::size()
const
{
assert(bool(wb));
return wb->Count();
}
size_t
ircd::db::txn::bytes()
const
{
assert(bool(wb));
return wb->GetDataSize();
}
bool
ircd::db::txn::has(const op &op)
const
{
assert(bool(wb));
switch(op)
{
case op::GET: assert(0); return false;
case op::SET: return wb->HasPut();
case op::MERGE: return wb->HasMerge();
case op::DELETE: return wb->HasDelete();
case op::DELETE_RANGE: return wb->HasDeleteRange();
case op::SINGLE_DELETE: return wb->HasSingleDelete();
}
return false;
}
bool
ircd::db::txn::has(const op &op,
const string_view &col)
const
{
return !for_each(*this, delta_closure_bool{[&op, &col]
(const auto &delta)
{
return std::get<delta::OP>(delta) != op &&
std::get<delta::COL>(delta) != col;
}});
}
void
ircd::db::txn::at(const op &op,
const string_view &col,
const delta_closure &closure)
const
{
if(!get(op, col, closure))
throw not_found
{
"db::txn::at(%s, %s): no matching delta in transaction",
reflect(op),
col
};
}
bool
ircd::db::txn::get(const op &op,
const string_view &col,
const delta_closure &closure)
const
{
return !for_each(*this, delta_closure_bool{[&op, &col, &closure]
(const delta &delta)
{
if(std::get<delta::OP>(delta) == op &&
std::get<delta::COL>(delta) == col)
{
closure(delta);
return false;
}
else return true;
}});
}
bool
ircd::db::txn::has(const op &op,
const string_view &col,
const string_view &key)
const
{
return !for_each(*this, delta_closure_bool{[&op, &col, &key]
(const auto &delta)
{
return std::get<delta::OP>(delta) != op &&
std::get<delta::COL>(delta) != col &&
std::get<delta::KEY>(delta) != key;
}});
}
void
ircd::db::txn::at(const op &op,
const string_view &col,
const string_view &key,
const value_closure &closure)
const
{
if(!get(op, col, key, closure))
throw not_found
{
"db::txn::at(%s, %s, %s): no matching delta in transaction",
reflect(op),
col,
key
};
}
bool
ircd::db::txn::get(const op &op,
const string_view &col,
const string_view &key,
const value_closure &closure)
const
{
return !for_each(*this, delta_closure_bool{[&op, &col, &key, &closure]
(const delta &delta)
{
if(std::get<delta::OP>(delta) == op &&
std::get<delta::COL>(delta) == col &&
std::get<delta::KEY>(delta) == key)
{
closure(std::get<delta::VAL>(delta));
return false;
}
else return true;
}});
}
ircd::db::txn::operator
ircd::db::database &()
{
assert(bool(d));
return *d;
}
ircd::db::txn::operator
rocksdb::WriteBatch &()
{
assert(bool(wb));
return *wb;
}
ircd::db::txn::operator
const ircd::db::database &()
const
{
assert(bool(d));
return *d;
}
ircd::db::txn::operator
const rocksdb::WriteBatch &()
const
{
assert(bool(wb));
return *wb;
}
//
// txn::checkpoint
//
ircd::db::txn::checkpoint::checkpoint(txn &t)
:t{t}
{
assert(bool(t.wb));
t.wb->SetSavePoint();
}
ircd::db::txn::checkpoint::~checkpoint()
noexcept
{
const ctx::uninterruptible ui;
if(likely(!std::uncaught_exceptions()))
throw_on_error { t.wb->PopSavePoint() };
else
throw_on_error { t.wb->RollbackToSavePoint() };
}
//
// txn::append
//
ircd::db::txn::append::append(txn &t,
const string_view &key,
const json::iov &iov)
{
std::for_each(std::begin(iov), std::end(iov), [&t, &key]
(const auto &member)
{
append
{
t, delta
{
member.first, // col
key, // key
member.second // val
}
};
});
}
ircd::db::txn::append::append(txn &t,
const delta &delta)
{
assert(bool(t.d));
append(t, *t.d, delta);
}
__attribute__((noreturn))
ircd::db::txn::append::append(txn &t,
const row::delta &delta)
{
throw ircd::not_implemented
{
"db::txn::append (row::delta)"
};
}
ircd::db::txn::append::append(txn &t,
const cell::delta &delta)
{
db::append(*t.wb, delta);
}
ircd::db::txn::append::append(txn &t,
column &c,
const column::delta &delta)
{
db::append(*t.wb, c, delta);
}
ircd::db::txn::append::append(txn &t,
database &d,
const delta &delta)
{
db::column c
{
d[std::get<1>(delta)]
};
db::append(*t.wb, c, db::column::delta
{
std::get<op>(delta),
std::get<2>(delta),
std::get<3>(delta)
});
}
///////////////////////////////////////////////////////////////////////////////
//
// db/row.h
//
namespace ircd::db
{
static std::vector<rocksdb::Iterator *>
_make_iterators(database &d,
database::column *const *const &columns,
const size_t &columns_size,
const rocksdb::ReadOptions &opts);
}
void
ircd::db::del(row &row,
const sopts &sopts)
{
write(row::delta{op::DELETE, row}, sopts);
}
void
ircd::db::write(const row::delta &delta,
const sopts &sopts)
{
write(&delta, &delta + 1, sopts);
}
void
ircd::db::write(const sopts &sopts,
const std::initializer_list<row::delta> &deltas)
{
write(deltas, sopts);
}
void
ircd::db::write(const std::initializer_list<row::delta> &deltas,
const sopts &sopts)
{
write(std::begin(deltas), std::end(deltas), sopts);
}
void
ircd::db::write(const row::delta *const &begin,
const row::delta *const &end,
const sopts &sopts)
{
// Count the total number of cells for this transaction.
const auto cells
{
std::accumulate(begin, end, size_t(0), []
(auto ret, const row::delta &delta)
{
const auto &row(std::get<row *>(delta));
return ret += row->size();
})
};
//TODO: allocator?
std::vector<cell::delta> deltas;
deltas.reserve(cells);
// Compose all of the cells from all of the rows into a single txn
std::for_each(begin, end, [&deltas]
(const auto &delta)
{
const auto &op(std::get<op>(delta));
const auto &row(std::get<row *>(delta));
std::for_each(std::begin(*row), std::end(*row), [&deltas, &op]
(auto &cell)
{
// For operations like DELETE which don't require a value in
// the delta, we can skip a potentially expensive load of the cell.
const auto value
{
value_required(op)? cell.val() : string_view{}
};
deltas.emplace_back(op, cell, value);
});
});
// Commitment
write(&deltas.front(), &deltas.front() + deltas.size(), sopts);
}
size_t
ircd::db::seek(row &r,
const string_view &key,
const gopts &opts)
{
// The following closure performs the seek() for a single cell in the row.
// It may be executed on another ircd::ctx if the data isn't cached and
// blocking IO is required. This frame can't be interrupted because it may
// have requests pending in the request pool which must synchronize back
// here.
size_t ret{0};
std::exception_ptr eptr;
ctx::latch latch{r.size()};
const ctx::uninterruptible ui;
const auto closure{[&opts, &latch, &ret, &key, &eptr]
(auto &cell) noexcept
{
// If there's a pending error from another cell by the time this
// closure is executed we don't perform the seek() unless the user
// specifies db::get::NO_THROW to suppress it.
if(!eptr || test(opts, get::NO_THROW)) try
{
if(!seek(cell, key))
{
// If the cell is not_found that's not a thrown exception here;
// the cell will just be !valid(). The user can specify
// get::THROW to propagate a not_found from the seek(row);
if(test(opts, get::THROW))
throw not_found
{
"column '%s' key '%s'", cell.col(), key
};
}
else ++ret;
}
catch(const not_found &e)
{
eptr = std::current_exception();
}
catch(const std::exception &e)
{
log::error
{
log, "row seek: column '%s' key '%s' :%s",
cell.col(),
key,
e.what()
};
eptr = std::make_exception_ptr(e);
}
// The latch must always be hit here. No exception should propagate
// to prevent this from being reached or beyond.
latch.count_down();
}};
#ifdef RB_DEBUG_DB_SEEK_ROW
const ircd::timer timer;
size_t submits{0};
#endif
// Submit all the requests
for(auto &cell : r)
{
db::column &column(cell);
const auto reclosure{[&closure, &cell]
() noexcept
{
closure(cell);
}};
// Whether to submit the request to another ctx or execute it here.
// Explicit option to prevent submitting must not be set. If there
// is a chance the data is already in the cache, we can avoid the
// context switching and occupation of the request pool.
//TODO: should check a bloom filter on the cache for this branch
//TODO: because right now double-querying the cache is gross.
const bool submit
{
r.size() > 1 &&
!test(opts, get::NO_PARALLEL) &&
!db::cached(column, key, opts)
};
#ifdef RB_DEBUG_DB_SEEK_ROW
submits += submit;
#endif
if(submit)
request(reclosure);
else
reclosure();
}
// Wait for responses.
latch.wait();
assert(ret <= r.size());
#ifdef RB_DEBUG_DB_SEEK_ROW
if(likely(!r.empty()))
{
const column &c(r[0]);
const database &d(c);
thread_local char tmbuf[32];
log::debug
{
log, "'%s' SEEK ROW seq:%lu:%-10lu cnt:%-2zu req:%-2zu ret:%-2zu in %s %s",
name(d),
sequence(d),
sequence(opts.snapshot),
r.size(),
submits,
ret,
pretty(tmbuf, timer.at<microseconds>(), true),
what(eptr)
};
}
#endif
if(eptr && !test(opts, get::NO_THROW))
std::rethrow_exception(eptr);
return ret;
}
//
// row
//
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstack-usage="
__attribute__((stack_protect))
ircd::db::row::row(database &d,
const string_view &key,
const vector_view<const string_view> &colnames,
const vector_view<cell> &buf,
gopts opts)
:vector_view<cell>{[&d, &colnames, &buf, &opts]
{
using std::end;
using std::begin;
if(!opts.snapshot)
opts.snapshot = database::snapshot(d);
const rocksdb::ReadOptions options
{
make_opts(opts)
};
assert(buf.size() >= colnames.size());
const size_t request_count
{
std::min(colnames.size(), buf.size())
};
size_t count(0);
database::column *colptr[request_count];
for(size_t i(0); i < request_count; ++i)
{
const auto cfid
{
d.cfid(std::nothrow, colnames.at(i))
};
if(cfid >= 0)
colptr[count++] = &d[cfid];
}
// All pointers returned by rocksdb in this vector must be free'd.
const auto iterators
{
_make_iterators(d, colptr, count, options)
};
assert(iterators.size() == count);
for(size_t i(0); i < iterators.size(); ++i)
{
std::unique_ptr<rocksdb::Iterator> it
{
iterators.at(i)
};
buf[i] = cell
{
*colptr[i], std::move(it), opts
};
}
return vector_view<cell>
{
buf.data(), iterators.size()
};
}()}
{
if(key)
seek(*this, key, opts);
}
#pragma GCC diagnostic pop
static std::vector<rocksdb::Iterator *>
ircd::db::_make_iterators(database &d,
database::column *const *const &column,
const size_t &column_count,
const rocksdb::ReadOptions &opts)
{
using rocksdb::Iterator;
using rocksdb::ColumnFamilyHandle;
assert(column_count <= d.columns.size());
//const ctx::critical_assertion ca;
// NewIterators() has been seen to lead to IO and block the ircd::ctx;
// specifically when background options are aggressive and shortly
// after db opens. It would be nice if we could maintain the
// critical_assertion for this function, as we could eliminate the
// vector allocation for ColumnFamilyHandle pointers.
std::vector<ColumnFamilyHandle *> handles(column_count);
std::transform(column, column + column_count, begin(handles), []
(database::column *const &ptr)
{
assert(ptr);
return ptr->handle.get();
});
std::vector<Iterator *> ret;
const ctx::stack_usage_assertion sua;
throw_on_error
{
d.d->NewIterators(opts, handles, &ret)
};
return ret;
}
void
ircd::db::row::operator()(const op &op,
const string_view &col,
const string_view &val,
const sopts &sopts)
{
write(cell::delta{op, (*this)[col], val}, sopts);
}
ircd::db::cell &
ircd::db::row::operator[](const string_view &column)
{
const auto it(find(column));
if(unlikely(it == end()))
throw not_found
{
"column '%s' not specified in the descriptor schema", column
};
return *it;
}
const ircd::db::cell &
ircd::db::row::operator[](const string_view &column)
const
{
const auto it(find(column));
if(unlikely(it == end()))
throw not_found
{
"column '%s' not specified in the descriptor schema", column
};
return *it;
}
ircd::db::row::iterator
ircd::db::row::find(const string_view &col)
{
return std::find_if(std::begin(*this), std::end(*this), [&col]
(const auto &cell)
{
return name(cell.c) == col;
});
}
ircd::db::row::const_iterator
ircd::db::row::find(const string_view &col)
const
{
return std::find_if(std::begin(*this), std::end(*this), [&col]
(const auto &cell)
{
return name(cell.c) == col;
});
}
bool
ircd::db::row::cached()
const
{
return std::all_of(std::begin(*this), std::end(*this), []
(const auto &cell)
{
db::column &column(const_cast<db::cell &>(cell));
return cell.valid() && db::cached(column, cell.key());
});
}
bool
ircd::db::row::cached(const string_view &key)
const
{
return std::all_of(std::begin(*this), std::end(*this), [&key]
(const auto &cell)
{
db::column &column(const_cast<db::cell &>(cell));
return db::cached(column, key);
});
}
bool
ircd::db::row::valid_all(const string_view &s)
const
{
return !empty() && std::all_of(std::begin(*this), std::end(*this), [&s]
(const auto &cell)
{
return cell.valid(s);
});
}
bool
ircd::db::row::valid(const string_view &s)
const
{
return std::any_of(std::begin(*this), std::end(*this), [&s]
(const auto &cell)
{
return cell.valid(s);
});
}
bool
ircd::db::row::valid_all()
const
{
return !empty() && std::all_of(std::begin(*this), std::end(*this), []
(const auto &cell)
{
return cell.valid();
});
}
bool
ircd::db::row::valid()
const
{
return std::any_of(std::begin(*this), std::end(*this), []
(const auto &cell)
{
return cell.valid();
});
}
///////////////////////////////////////////////////////////////////////////////
//
// db/cell.h
//
uint64_t
ircd::db::sequence(const cell &c)
{
const database::snapshot &ss(c);
return sequence(database::snapshot(c));
}
const std::string &
ircd::db::name(const cell &c)
{
return name(c.c);
}
void
ircd::db::write(const cell::delta &delta,
const sopts &sopts)
{
write(&delta, &delta + 1, sopts);
}
void
ircd::db::write(const sopts &sopts,
const std::initializer_list<cell::delta> &deltas)
{
write(deltas, sopts);
}
void
ircd::db::write(const std::initializer_list<cell::delta> &deltas,
const sopts &sopts)
{
write(std::begin(deltas), std::end(deltas), sopts);
}
void
ircd::db::write(const cell::delta *const &begin,
const cell::delta *const &end,
const sopts &sopts)
{
if(begin == end)
return;
// Find the database through one of the cell's columns. cell::deltas
// may come from different columns so we do nothing else with this.
auto &front(*begin);
column &c(std::get<cell *>(front)->c);
database &d(c);
rocksdb::WriteBatch batch;
std::for_each(begin, end, [&batch]
(const cell::delta &delta)
{
append(batch, delta);
});
commit(d, batch, sopts);
}
template<class pos>
bool
ircd::db::seek(cell &c,
const pos &p,
gopts opts)
{
column &cc(c);
database::column &dc(cc);
if(!opts.snapshot)
opts.snapshot = c.ss;
const auto ropts(make_opts(opts));
return seek(dc, p, ropts, c.it);
}
template bool ircd::db::seek<ircd::db::pos>(cell &, const pos &, gopts);
template bool ircd::db::seek<ircd::string_view>(cell &, const string_view &, gopts);
// Linkage for incomplete rocksdb::Iterator
ircd::db::cell::cell()
{
}
ircd::db::cell::cell(database &d,
const string_view &colname,
const gopts &opts)
:cell
{
column(d[colname]), std::unique_ptr<rocksdb::Iterator>{}, opts
}
{
}
ircd::db::cell::cell(database &d,
const string_view &colname,
const string_view &index,
const gopts &opts)
:cell
{
column(d[colname]), index, opts
}
{
}
ircd::db::cell::cell(column column,
const string_view &index,
const gopts &opts)
:c{std::move(column)}
,ss{opts.snapshot}
,it
{
!index.empty()?
seek(this->c, index, opts):
std::unique_ptr<rocksdb::Iterator>{}
}
{
if(bool(this->it))
if(!valid_eq(*this->it, index))
this->it.reset();
}
ircd::db::cell::cell(column column,
const string_view &index,
std::unique_ptr<rocksdb::Iterator> it,
const gopts &opts)
:c{std::move(column)}
,ss{opts.snapshot}
,it{std::move(it)}
{
if(index.empty())
return;
seek(*this, index, opts);
if(!valid_eq(*this->it, index))
this->it.reset();
}
ircd::db::cell::cell(column column,
std::unique_ptr<rocksdb::Iterator> it,
const gopts &opts)
:c{std::move(column)}
,ss{opts.snapshot}
,it{std::move(it)}
{
}
// Linkage for incomplete rocksdb::Iterator
ircd::db::cell::cell(cell &&o)
noexcept
:c{std::move(o.c)}
,ss{std::move(o.ss)}
,it{std::move(o.it)}
{
}
// Linkage for incomplete rocksdb::Iterator
ircd::db::cell &
ircd::db::cell::operator=(cell &&o)
noexcept
{
c = std::move(o.c);
ss = std::move(o.ss);
it = std::move(o.it);
return *this;
}
// Linkage for incomplete rocksdb::Iterator
ircd::db::cell::~cell()
noexcept
{
}
bool
ircd::db::cell::load(const string_view &index,
gopts opts)
{
database &d(c);
if(valid(index) && !opts.snapshot && sequence(ss) == sequence(d))
return true;
if(bool(opts.snapshot))
{
this->it.reset();
this->ss = std::move(opts.snapshot);
}
database::column &c(this->c);
const auto _opts
{
make_opts(opts)
};
if(!seek(c, index, _opts, this->it))
return false;
return valid(index);
}
ircd::db::cell &
ircd::db::cell::operator=(const string_view &s)
{
write(c, key(), s);
return *this;
}
void
ircd::db::cell::operator()(const op &op,
const string_view &val,
const sopts &sopts)
{
write(cell::delta{op, *this, val}, sopts);
}
ircd::db::cell::operator
string_view()
{
return val();
}
ircd::db::cell::operator
string_view()
const
{
return val();
}
ircd::string_view
ircd::db::cell::val()
{
if(!valid())
load();
return likely(valid())? db::val(*it) : string_view{};
}
ircd::string_view
ircd::db::cell::key()
{
if(!valid())
load();
return likely(valid())? db::key(*it) : string_view{};
}
ircd::string_view
ircd::db::cell::val()
const
{
return likely(valid())? db::val(*it) : string_view{};
}
ircd::string_view
ircd::db::cell::key()
const
{
return likely(valid())? db::key(*it) : string_view{};
}
bool
ircd::db::cell::valid(const string_view &s)
const
{
return valid() && db::valid_eq(*it, s);
}
bool
ircd::db::cell::valid_gt(const string_view &s)
const
{
return valid() && db::valid_gt(*it, s);
}
bool
ircd::db::cell::valid_lte(const string_view &s)
const
{
return valid() && db::valid_lte(*it, s);
}
bool
ircd::db::cell::valid()
const
{
return bool(it) && db::valid(*it);
}
///////////////////////////////////////////////////////////////////////////////
//
// db/domain.h
//
const ircd::db::gopts
ircd::db::domain::applied_opts
{
get::PREFIX
};
bool
ircd::db::seek(domain::const_iterator_base &it,
const pos &p)
{
switch(p)
{
case pos::BACK:
{
// This is inefficient as per RocksDB's prefix impl. unknown why
// a seek to NEXT is still needed after walking back one.
while(seek(it, pos::NEXT));
if(seek(it, pos::PREV))
seek(it, pos::NEXT);
return bool(it);
}
default:
break;
}
it.opts |= domain::applied_opts;
return seek(static_cast<column::const_iterator_base &>(it), p);
}
bool
ircd::db::seek(domain::const_iterator_base &it,
const string_view &p)
{
it.opts |= domain::applied_opts;
return seek(static_cast<column::const_iterator_base &>(it), p);
}
ircd::db::domain::const_iterator
ircd::db::domain::begin(const string_view &key,
gopts opts)
{
const_iterator ret
{
c, {}, std::move(opts)
};
seek(ret, key);
return ret;
}
ircd::db::domain::const_iterator
ircd::db::domain::end(const string_view &key,
gopts opts)
{
const_iterator ret
{
c, {}, std::move(opts)
};
if(seek(ret, key))
seek(ret, pos::END);
return ret;
}
/// NOTE: RocksDB says they don't support reverse iteration over a prefix range
/// This means we have to forward scan to the end and then walk back! Reverse
/// iterations of a domain should only be used for debugging and statistics! The
/// domain should be ordered the way it will be primarily accessed using the
/// comparator. If it will be accessed in different directions, make another
/// domain column.
ircd::db::domain::const_reverse_iterator
ircd::db::domain::rbegin(const string_view &key,
gopts opts)
{
const_reverse_iterator ret
{
c, {}, std::move(opts)
};
if(seek(ret, key))
seek(ret, pos::BACK);
return ret;
}
ircd::db::domain::const_reverse_iterator
ircd::db::domain::rend(const string_view &key,
gopts opts)
{
const_reverse_iterator ret
{
c, {}, std::move(opts)
};
if(seek(ret, key))
seek(ret, pos::END);
return ret;
}
//
// const_iterator
//
ircd::db::domain::const_iterator &
ircd::db::domain::const_iterator::operator--()
{
if(likely(bool(*this)))
seek(*this, pos::PREV);
else
seek(*this, pos::BACK);
return *this;
}
ircd::db::domain::const_iterator &
ircd::db::domain::const_iterator::operator++()
{
if(likely(bool(*this)))
seek(*this, pos::NEXT);
else
seek(*this, pos::FRONT);
return *this;
}
ircd::db::domain::const_reverse_iterator &
ircd::db::domain::const_reverse_iterator::operator--()
{
if(likely(bool(*this)))
seek(*this, pos::NEXT);
else
seek(*this, pos::FRONT);
return *this;
}
ircd::db::domain::const_reverse_iterator &
ircd::db::domain::const_reverse_iterator::operator++()
{
if(likely(bool(*this)))
seek(*this, pos::PREV);
else
seek(*this, pos::BACK);
return *this;
}
const ircd::db::domain::const_iterator_base::value_type &
ircd::db::domain::const_iterator_base::operator*()
const
{
const auto &prefix
{
describe(*c).prefix
};
// Fetch the full value like a standard column first
column::const_iterator_base::operator*();
string_view &key{val.first};
// When there's no prefixing this domain column is just
// like a normal column. Otherwise, we remove the prefix
// from the key the user will end up seeing.
if(prefix.has && prefix.has(key))
{
const auto &first(prefix.get(key));
const auto &second(key.substr(first.size()));
key = second;
}
return val;
}
const ircd::db::domain::const_iterator_base::value_type *
ircd::db::domain::const_iterator_base::operator->()
const
{
return &this->operator*();
}
///////////////////////////////////////////////////////////////////////////////
//
// db/column.h
//
std::string
ircd::db::read(column &column,
const string_view &key,
const gopts &gopts)
{
std::string ret;
const auto closure([&ret]
(const string_view &src)
{
ret.assign(begin(src), end(src));
});
column(key, closure, gopts);
return ret;
}
ircd::string_view
ircd::db::read(column &column,
const string_view &key,
const mutable_buffer &buf,
const gopts &gopts)
{
string_view ret;
const auto closure([&ret, &buf]
(const string_view &src)
{
ret = { data(buf), copy(buf, src) };
});
column(key, closure, gopts);
return ret;
}
std::string
ircd::db::read(column &column,
const string_view &key,
bool &found,
const gopts &gopts)
{
std::string ret;
const auto closure([&ret]
(const string_view &src)
{
ret.assign(begin(src), end(src));
});
found = column(key, std::nothrow, closure, gopts);
return ret;
}
ircd::string_view
ircd::db::read(column &column,
const string_view &key,
bool &found,
const mutable_buffer &buf,
const gopts &gopts)
{
string_view ret;
const auto closure([&buf, &ret]
(const string_view &src)
{
ret = { data(buf), copy(buf, src) };
});
found = column(key, std::nothrow, closure, gopts);
return ret;
}
rocksdb::Cache *
ircd::db::cache(column &column)
{
database::column &c(column);
return c.table_opts.block_cache.get();
}
rocksdb::Cache *
ircd::db::cache_compressed(column &column)
{
database::column &c(column);
return c.table_opts.block_cache_compressed.get();
}
const rocksdb::Cache *
ircd::db::cache(const column &column)
{
const database::column &c(column);
return c.table_opts.block_cache.get();
}
const rocksdb::Cache *
ircd::db::cache_compressed(const column &column)
{
const database::column &c(column);
return c.table_opts.block_cache_compressed.get();
}
template<>
ircd::db::prop_str
ircd::db::property(const column &column,
const string_view &name)
{
std::string ret;
database::column &c(const_cast<db::column &>(column));
database &d(const_cast<db::column &>(column));
if(!d.d->GetProperty(c, slice(name), &ret))
throw not_found
{
"'property '%s' for column '%s' in '%s' not found.",
name,
db::name(column),
db::name(d)
};
return ret;
}
template<>
ircd::db::prop_int
ircd::db::property(const column &column,
const string_view &name)
{
uint64_t ret(0);
database::column &c(const_cast<db::column &>(column));
database &d(const_cast<db::column &>(column));
if(!d.d->GetIntProperty(c, slice(name), &ret))
throw not_found
{
"property '%s' for column '%s' in '%s' not found or not an integer.",
name,
db::name(column),
db::name(d)
};
return ret;
}
template<>
ircd::db::prop_map
ircd::db::property(const column &column,
const string_view &name)
{
std::map<std::string, std::string> ret;
database::column &c(const_cast<db::column &>(column));
database &d(const_cast<db::column &>(column));
if(!d.d->GetMapProperty(c, slice(name), &ret))
ret.emplace(std::string{name}, property<std::string>(column, name));
return ret;
}
ircd::db::options
ircd::db::getopt(const column &column)
{
database &d(const_cast<db::column &>(column));
database::column &c(const_cast<db::column &>(column));
return options
{
static_cast<rocksdb::ColumnFamilyOptions>(d.d->GetOptions(c))
};
}
size_t
ircd::db::bytes(const column &column)
{
rocksdb::ColumnFamilyMetaData cfm;
database &d(const_cast<db::column &>(column));
database::column &c(const_cast<db::column &>(column));
assert(bool(c.handle));
d.d->GetColumnFamilyMetaData(c.handle.get(), &cfm);
return cfm.size;
}
size_t
ircd::db::file_count(const column &column)
{
rocksdb::ColumnFamilyMetaData cfm;
database &d(const_cast<db::column &>(column));
database::column &c(const_cast<db::column &>(column));
assert(bool(c.handle));
d.d->GetColumnFamilyMetaData(c.handle.get(), &cfm);
return cfm.file_count;
}
uint32_t
ircd::db::id(const column &column)
{
const database::column &c(column);
return id(c);
}
const std::string &
ircd::db::name(const column &column)
{
const database::column &c(column);
return name(c);
}
const ircd::db::descriptor &
ircd::db::describe(const column &column)
{
const database::column &c(column);
return describe(c);
}
std::vector<std::string>
ircd::db::files(const column &column)
{
database::column &c(const_cast<db::column &>(column));
database &d(*c.d);
rocksdb::ColumnFamilyMetaData cfmd;
d.d->GetColumnFamilyMetaData(c, &cfmd);
size_t count(0);
for(const auto &level : cfmd.levels)
count += level.files.size();
std::vector<std::string> ret;
ret.reserve(count);
for(auto &level : cfmd.levels)
for(auto &file : level.files)
ret.emplace_back(std::move(file.name));
return ret;
}
void
ircd::db::drop(column &column)
{
database::column &c(column);
drop(c);
}
void
ircd::db::check(column &column)
{
database &d(column);
const auto &files
{
db::files(column)
};
for(const auto &file : files)
{
const auto &path
{
// remove false leading slash; the rest is relative to db.
lstrip(file, '/')
};
db::check(d, path);
}
}
void
ircd::db::sort(column &column,
const bool &blocking,
const bool &now)
{
database::column &c(column);
database &d(*c.d);
rocksdb::FlushOptions opts;
opts.wait = blocking;
opts.allow_write_stall = now;
const ctx::uninterruptible::nothrow ui;
const std::lock_guard lock{write_mutex};
log::debug
{
log, "[%s]'%s' @%lu FLUSH (sort) %s %s",
name(d),
name(c),
sequence(d),
blocking? "blocking"_sv: "non-blocking"_sv,
now? "now"_sv: "later"_sv
};
throw_on_error
{
d.d->Flush(opts, c)
};
}
void
ircd::db::compact(column &column,
const std::pair<int, int> &level,
const compactor &cb)
{
database::column &c(column);
database &d(*c.d);
const auto &dst_level{level.second};
const auto &src_level{level.first};
rocksdb::ColumnFamilyMetaData cfmd;
d.d->GetColumnFamilyMetaData(c, &cfmd);
for(const auto &level : cfmd.levels)
{
if(src_level != -1 && src_level != level.level)
continue;
if(level.files.empty())
continue;
const ctx::uninterruptible ui;
const std::lock_guard lock
{
write_mutex
};
const auto &to_level
{
dst_level > -1? dst_level : level.level
};
rocksdb::CompactionOptions opts;
opts.output_file_size_limit = 1_GiB; //TODO: conf
// RocksDB sez that setting this to Disable means that the column's
// compression options are read instead. If we don't set this here,
// rocksdb defaults to "snappy" (which is strange).
opts.compression = rocksdb::kDisableCompressionOption;
std::vector<std::string> files(level.files.size());
std::transform(level.files.begin(), level.files.end(), files.begin(), []
(auto &metadata)
{
return std::move(metadata.name);
});
// Save and restore the existing filter callback so we can allow our
// caller to use theirs. Note that this manual compaction should be
// exclusive for this column (no background compaction should be
// occurring, at least one relying on this filter).
auto their_filter(std::move(c.cfilter.user));
const unwind unfilter{[&c, &their_filter]
{
c.cfilter.user = std::move(their_filter);
}};
c.cfilter.user = cb;
log::debug
{
log, "[%s]'%s' COMPACT L%d -> L%d files:%zu size:%zu",
name(d),
name(c),
level.level,
to_level,
level.files.size(),
level.size
};
throw_on_error
{
d.d->CompactFiles(opts, c, files, to_level)
};
}
}
void
ircd::db::compact(column &column,
const std::pair<string_view, string_view> &range,
const int &to_level,
const compactor &cb)
{
database &d(column);
database::column &c(column);
const ctx::uninterruptible ui;
const auto begin(slice(range.first));
const rocksdb::Slice *const b
{
empty(range.first)? nullptr : &begin
};
const auto end(slice(range.second));
const rocksdb::Slice *const e
{
empty(range.second)? nullptr : &end
};
rocksdb::CompactRangeOptions opts;
opts.exclusive_manual_compaction = true;
opts.allow_write_stall = true;
opts.change_level = true;
opts.target_level = std::max(to_level, -1);
opts.bottommost_level_compaction = rocksdb::BottommostLevelCompaction::kForce;
// Save and restore the existing filter callback so we can allow our
// caller to use theirs. Note that this manual compaction should be
// exclusive for this column (no background compaction should be
// occurring, at least one relying on this filter).
auto their_filter(std::move(c.cfilter.user));
const unwind unfilter{[&c, &their_filter]
{
c.cfilter.user = std::move(their_filter);
}};
c.cfilter.user = cb;
log::debug
{
log, "[%s]'%s' @%lu COMPACT [%s, %s] -> L:%d (Lmax:%d Lbase:%d)",
name(d),
name(c),
sequence(d),
range.first,
range.second,
opts.target_level,
d.d->NumberLevels(c),
d.d->MaxMemCompactionLevel(c),
};
throw_on_error
{
d.d->CompactRange(opts, c, b, e)
};
}
void
ircd::db::setopt(column &column,
const string_view &key,
const string_view &val)
{
database &d(column);
database::column &c(column);
const std::unordered_map<std::string, std::string> options
{
{ std::string{key}, std::string{val} }
};
throw_on_error
{
d.d->SetOptions(c, options)
};
}
void
ircd::db::ingest(column &column,
const string_view &path)
{
database &d(column);
database::column &c(column);
rocksdb::IngestExternalFileOptions opts;
opts.allow_global_seqno = true;
opts.allow_blocking_flush = true;
// Automatically determine if we can avoid issuing new sequence
// numbers by considering this ingestion as "backfill" of missing
// data which did actually exist but was physically removed.
const auto &copts{d.d->GetOptions(c)};
opts.ingest_behind = copts.allow_ingest_behind;
const std::vector<std::string> files
{
{ std::string{path} }
};
const std::lock_guard lock{write_mutex};
const ctx::uninterruptible::nothrow ui;
throw_on_error
{
d.d->IngestExternalFile(c, files, opts)
};
}
void
ircd::db::del(column &column,
const std::pair<string_view, string_view> &range,
const sopts &sopts)
{
database &d(column);
database::column &c(column);
auto opts(make_opts(sopts));
const std::lock_guard lock{write_mutex};
const ctx::uninterruptible::nothrow ui;
const ctx::stack_usage_assertion sua;
log::debug
{
log, "'%s' %lu '%s' RANGE DELETE",
name(d),
sequence(d),
name(c),
};
throw_on_error
{
d.d->DeleteRange(opts, c, slice(range.first), slice(range.second))
};
}
void
ircd::db::del(column &column,
const string_view &key,
const sopts &sopts)
{
database &d(column);
database::column &c(column);
auto opts(make_opts(sopts));
const std::lock_guard lock{write_mutex};
const ctx::uninterruptible::nothrow ui;
const ctx::stack_usage_assertion sua;
log::debug
{
log, "'%s' %lu '%s' DELETE key(%zu B)",
name(d),
sequence(d),
name(c),
key.size()
};
throw_on_error
{
d.d->Delete(opts, c, slice(key))
};
}
void
ircd::db::write(column &column,
const string_view &key,
const const_buffer &val,
const sopts &sopts)
{
database &d(column);
database::column &c(column);
auto opts(make_opts(sopts));
const std::lock_guard lock{write_mutex};
const ctx::uninterruptible::nothrow ui;
const ctx::stack_usage_assertion sua;
log::debug
{
log, "'%s' %lu '%s' PUT key(%zu B) val(%zu B)",
name(d),
sequence(d),
name(c),
size(key),
size(val)
};
throw_on_error
{
d.d->Put(opts, c, slice(key), slice(val))
};
}
size_t
ircd::db::bytes_value(column &column,
const string_view &key,
const gopts &gopts)
{
size_t ret{0};
column(key, std::nothrow, gopts, [&ret]
(const string_view &value)
{
ret = value.size();
});
return ret;
}
size_t
ircd::db::bytes(column &column,
const std::pair<string_view, string_view> &key,
const gopts &gopts)
{
database &d(column);
database::column &c(column);
const rocksdb::Range range[1]
{
{ slice(key.first), slice(key.second) }
};
uint64_t ret[1] {0};
d.d->GetApproximateSizes(c, range, 1, ret);
return ret[0];
}
//
// db::prefetch
//
bool
ircd::db::prefetch(column &column,
const string_view &key,
const gopts &gopts)
{
static construction instance
{
[] { prefetcher = new struct prefetcher(); }
};
assert(prefetcher);
return (*prefetcher)(column, key, gopts);
}
//
// db::cached
//
#if 0
bool
ircd::db::cached(column &column,
const string_view &key,
const gopts &gopts)
{
return exists(cache(column), key);
}
#endif
bool
ircd::db::cached(column &column,
const string_view &key,
const gopts &gopts)
{
database &d(column);
database::column &c(column);
auto opts(make_opts(gopts));
opts.read_tier = NON_BLOCKING;
opts.fill_cache = false;
std::unique_ptr<rocksdb::Iterator> it;
if(!seek(c, key, opts, it))
return false;
assert(bool(it));
return valid_eq(*it, key);
}
bool
ircd::db::has(column &column,
const string_view &key,
const gopts &gopts)
{
database &d(column);
database::column &c(column);
// Perform a co-RP query to the filtration
//
// NOTE disabled for rocksdb >= v5.15 due to a regression
// where rocksdb does not init SuperVersion data in the column
// family handle and this codepath triggers null derefs and ub.
//
// NOTE works on rocksdb 6.6.4 but unconditionally copies value.
auto opts(make_opts(gopts));
if(c.table_opts.filter_policy && (false))
{
auto opts(make_opts(gopts));
const scope_restore read_tier
{
opts.read_tier, NON_BLOCKING
};
const scope_restore fill_cache
{
opts.fill_cache, false
};
std::string discard;
bool value_found {false};
const bool key_may_exist
{
d.d->KeyMayExist(opts, c, slice(key), &discard, &value_found)
};
if(!key_may_exist)
return false;
if(value_found)
return true;
}
std::unique_ptr<rocksdb::Iterator> it;
if(!seek(c, key, opts, it))
return false;
assert(bool(it));
return valid_eq(*it, key);
}
uint64_t
ircd::db::has(column &column,
const vector_view<const string_view> &key,
const gopts &opts)
{
const size_t num(key.size());
return has({&column, 1}, key, opts);
}
uint64_t
ircd::db::has(const vector_view<column> &c,
const vector_view<const string_view> &key,
const gopts &gopts)
{
if(c.empty())
return 0UL;
const size_t num(key.size());
if(unlikely(!num || num > 64))
throw std::out_of_range
{
"db::has() :too many columns or vector size mismatch"
};
_read_op op[num];
for(size_t i(0); i < num; ++i)
op[i] =
{
c[std::min(c.size() - 1, i)], key[i]
};
uint64_t i(0), ret(0);
auto opts(make_opts(gopts));
_read({op, num}, opts, [&i, &ret, &opts]
(column &, const column::delta &, const rocksdb::Status &s)
{
uint64_t found {0};
found |= s.ok();
found |= s.IsIncomplete() & (opts.read_tier == NON_BLOCKING);
ret |= (found << i++);
return true;
});
return ret;
}
//
// column
//
ircd::db::column::column(database &d,
const string_view &column_name,
const std::nothrow_t)
:c{[&d, &column_name]
{
const int32_t cfid
{
d.cfid(std::nothrow, column_name)
};
return cfid >= 0?
&d[cfid]:
nullptr;
}()}
{
}
ircd::db::column::column(database &d,
const string_view &column_name)
:column
{
d[column_name]
}
{
}
ircd::db::column::column(database::column &c)
:c{&c}
{
}
void
ircd::db::column::operator()(const delta &delta,
const sopts &sopts)
{
operator()(&delta, &delta + 1, sopts);
}
void
ircd::db::column::operator()(const sopts &sopts,
const std::initializer_list<delta> &deltas)
{
operator()(deltas, sopts);
}
void
ircd::db::column::operator()(const std::initializer_list<delta> &deltas,
const sopts &sopts)
{
operator()(std::begin(deltas), std::end(deltas), sopts);
}
void
ircd::db::column::operator()(const delta *const &begin,
const delta *const &end,
const sopts &sopts)
{
database &d(*this);
rocksdb::WriteBatch batch;
std::for_each(begin, end, [this, &batch]
(const delta &delta)
{
append(batch, *this, delta);
});
commit(d, batch, sopts);
}
void
ircd::db::column::operator()(const string_view &key,
const gopts &gopts,
const view_closure &func)
{
return operator()(key, func, gopts);
}
void
ircd::db::column::operator()(const string_view &key,
const view_closure &func,
const gopts &gopts)
{
const auto it(seek(*this, key, gopts));
valid_eq_or_throw(*it, key);
func(val(*it));
}
bool
ircd::db::column::operator()(const string_view &key,
const std::nothrow_t,
const gopts &gopts,
const view_closure &func)
{
return operator()(key, std::nothrow, func, gopts);
}
bool
ircd::db::column::operator()(const string_view &key,
const std::nothrow_t,
const view_closure &func,
const gopts &gopts)
{
const auto it(seek(*this, key, gopts));
if(!valid_eq(*it, key))
return false;
func(val(*it));
return true;
}
ircd::db::cell
ircd::db::column::operator[](const string_view &key)
const
{
return { *this, key };
}
ircd::db::column::operator
bool()
const
{
return c?
!dropped(*c):
false;
}
ircd::db::column::operator
const descriptor &()
const
{
assert(c->descriptor);
return *c->descriptor;
}
//
// column::const_iterator
//
ircd::db::column::const_iterator
ircd::db::column::end(gopts gopts)
{
const_iterator ret
{
c, {}, std::move(gopts)
};
seek(ret, pos::END);
return ret;
}
ircd::db::column::const_iterator
ircd::db::column::last(gopts gopts)
{
const_iterator ret
{
c, {}, std::move(gopts)
};
seek(ret, pos::BACK);
return ret;
}
ircd::db::column::const_iterator
ircd::db::column::begin(gopts gopts)
{
const_iterator ret
{
c, {}, std::move(gopts)
};
seek(ret, pos::FRONT);
return ret;
}
ircd::db::column::const_reverse_iterator
ircd::db::column::rend(gopts gopts)
{
const_reverse_iterator ret
{
c, {}, std::move(gopts)
};
seek(ret, pos::END);
return ret;
}
ircd::db::column::const_reverse_iterator
ircd::db::column::rbegin(gopts gopts)
{
const_reverse_iterator ret
{
c, {}, std::move(gopts)
};
seek(ret, pos::BACK);
return ret;
}
ircd::db::column::const_iterator
ircd::db::column::upper_bound(const string_view &key,
gopts gopts)
{
auto it(lower_bound(key, std::move(gopts)));
if(it && it.it->key().compare(slice(key)) == 0)
++it;
return it;
}
ircd::db::column::const_iterator
ircd::db::column::find(const string_view &key,
gopts gopts)
{
auto it(lower_bound(key, gopts));
if(!it || it.it->key().compare(slice(key)) != 0)
return end(gopts);
return it;
}
ircd::db::column::const_iterator
ircd::db::column::lower_bound(const string_view &key,
gopts gopts)
{
const_iterator ret
{
c, {}, std::move(gopts)
};
seek(ret, key);
return ret;
}
ircd::db::column::const_iterator &
ircd::db::column::const_iterator::operator--()
{
if(likely(bool(*this)))
seek(*this, pos::PREV);
else
seek(*this, pos::BACK);
return *this;
}
ircd::db::column::const_iterator &
ircd::db::column::const_iterator::operator++()
{
if(likely(bool(*this)))
seek(*this, pos::NEXT);
else
seek(*this, pos::FRONT);
return *this;
}
ircd::db::column::const_reverse_iterator &
ircd::db::column::const_reverse_iterator::operator--()
{
if(likely(bool(*this)))
seek(*this, pos::NEXT);
else
seek(*this, pos::FRONT);
return *this;
}
ircd::db::column::const_reverse_iterator &
ircd::db::column::const_reverse_iterator::operator++()
{
if(likely(bool(*this)))
seek(*this, pos::PREV);
else
seek(*this, pos::BACK);
return *this;
}
ircd::db::column::const_iterator_base::const_iterator_base(const_iterator_base &&o)
noexcept
:c{std::move(o.c)}
,opts{std::move(o.opts)}
,it{std::move(o.it)}
,val{std::move(o.val)}
{
}
ircd::db::column::const_iterator_base &
ircd::db::column::const_iterator_base::operator=(const_iterator_base &&o)
noexcept
{
c = std::move(o.c);
opts = std::move(o.opts);
it = std::move(o.it);
val = std::move(o.val);
return *this;
}
// linkage for incmplete rocksdb::Iterator
ircd::db::column::const_iterator_base::const_iterator_base()
{
}
// linkage for incmplete rocksdb::Iterator
ircd::db::column::const_iterator_base::~const_iterator_base()
noexcept
{
}
ircd::db::column::const_iterator_base::const_iterator_base(database::column *const &c,
std::unique_ptr<rocksdb::Iterator> &&it,
gopts opts)
:c{c}
,opts{std::move(opts)}
,it{std::move(it)}
{
}
const ircd::db::column::const_iterator_base::value_type &
ircd::db::column::const_iterator_base::operator*()
const
{
assert(it && valid(*it));
val.first = db::key(*it);
val.second = db::val(*it);
return val;
}
const ircd::db::column::const_iterator_base::value_type *
ircd::db::column::const_iterator_base::operator->()
const
{
return &operator*();
}
bool
ircd::db::column::const_iterator_base::operator!()
const
{
return !static_cast<bool>(*this);
}
ircd::db::column::const_iterator_base::operator bool()
const
{
if(!it)
return false;
if(!valid(*it))
return false;
return true;
}
bool
ircd::db::operator!=(const column::const_iterator_base &a, const column::const_iterator_base &b)
{
return !(a == b);
}
bool
ircd::db::operator==(const column::const_iterator_base &a, const column::const_iterator_base &b)
{
if(a && b)
{
const auto &ak(a.it->key());
const auto &bk(b.it->key());
return ak.compare(bk) == 0;
}
if(!a && !b)
return true;
return false;
}
bool
ircd::db::operator>(const column::const_iterator_base &a, const column::const_iterator_base &b)
{
if(a && b)
{
const auto &ak(a.it->key());
const auto &bk(b.it->key());
return ak.compare(bk) == 1;
}
if(!a && b)
return true;
if(!a && !b)
return false;
assert(!a && b);
return false;
}
bool
ircd::db::operator<(const column::const_iterator_base &a, const column::const_iterator_base &b)
{
if(a && b)
{
const auto &ak(a.it->key());
const auto &bk(b.it->key());
return ak.compare(bk) == -1;
}
if(!a && b)
return false;
if(!a && !b)
return false;
assert(a && !b);
return true;
}
template<class pos>
bool
ircd::db::seek(column::const_iterator_base &it,
const pos &p)
{
database::column &c(it);
return seek(c, p, make_opts(it.opts), it.it);
}
template bool ircd::db::seek<ircd::db::pos>(column::const_iterator_base &, const pos &);
template bool ircd::db::seek<ircd::string_view>(column::const_iterator_base &, const string_view &);
///////////////////////////////////////////////////////////////////////////////
//
// opts.h
//
//
// options
//
ircd::db::options::options(const database &d)
:options{d.d->GetDBOptions()}
{
}
ircd::db::options::options(const database::column &c)
:options
{
rocksdb::ColumnFamilyOptions
{
c.d->d->GetOptions(c.handle.get())
}
}{}
ircd::db::options::options(const rocksdb::DBOptions &opts)
{
throw_on_error
{
rocksdb::GetStringFromDBOptions(this, opts)
};
}
ircd::db::options::options(const rocksdb::ColumnFamilyOptions &opts)
{
throw_on_error
{
rocksdb::GetStringFromColumnFamilyOptions(this, opts)
};
}
ircd::db::options::operator rocksdb::PlainTableOptions()
const
{
rocksdb::PlainTableOptions ret;
throw_on_error
{
rocksdb::GetPlainTableOptionsFromString(ret, *this, &ret)
};
return ret;
}
ircd::db::options::operator rocksdb::BlockBasedTableOptions()
const
{
rocksdb::BlockBasedTableOptions ret;
throw_on_error
{
rocksdb::GetBlockBasedTableOptionsFromString(ret, *this, &ret)
};
return ret;
}
ircd::db::options::operator rocksdb::ColumnFamilyOptions()
const
{
rocksdb::ColumnFamilyOptions ret;
throw_on_error
{
rocksdb::GetColumnFamilyOptionsFromString(ret, *this, &ret)
};
return ret;
}
ircd::db::options::operator rocksdb::DBOptions()
const
{
rocksdb::DBOptions ret;
throw_on_error
{
rocksdb::GetDBOptionsFromString(ret, *this, &ret)
};
return ret;
}
ircd::db::options::operator rocksdb::Options()
const
{
rocksdb::Options ret;
throw_on_error
{
rocksdb::GetOptionsFromString(ret, *this, &ret)
};
return ret;
}
//
// options::map
//
ircd::db::options::map::map(const options &o)
{
throw_on_error
{
rocksdb::StringToMap(o, this)
};
}
ircd::db::options::map::operator rocksdb::PlainTableOptions()
const
{
rocksdb::PlainTableOptions ret;
throw_on_error
{
rocksdb::GetPlainTableOptionsFromMap(ret, *this, &ret)
};
return ret;
}
ircd::db::options::map::operator rocksdb::BlockBasedTableOptions()
const
{
rocksdb::BlockBasedTableOptions ret;
throw_on_error
{
rocksdb::GetBlockBasedTableOptionsFromMap(ret, *this, &ret)
};
return ret;
}
ircd::db::options::map::operator rocksdb::ColumnFamilyOptions()
const
{
rocksdb::ColumnFamilyOptions ret;
throw_on_error
{
rocksdb::GetColumnFamilyOptionsFromMap(ret, *this, &ret)
};
return ret;
}
ircd::db::options::map::operator rocksdb::DBOptions()
const
{
rocksdb::DBOptions ret;
throw_on_error
{
rocksdb::GetDBOptionsFromMap(ret, *this, &ret)
};
return ret;
}
///////////////////////////////////////////////////////////////////////////////
//
// cache.h
//
void
ircd::db::clear(rocksdb::Cache &cache)
{
cache.EraseUnRefEntries();
}
bool
ircd::db::remove(rocksdb::Cache &cache,
const string_view &key)
{
cache.Erase(slice(key));
return true;
}
bool
ircd::db::insert(rocksdb::Cache &cache,
const string_view &key,
const string_view &value)
{
unique_buffer<const_buffer> buf
{
const_buffer{value}
};
return insert(cache, key, std::move(buf));
}
bool
ircd::db::insert(rocksdb::Cache &cache,
const string_view &key,
unique_buffer<const_buffer> &&value)
{
const size_t value_size
{
size(value)
};
static const auto deleter{[]
(const rocksdb::Slice &key, void *const value)
{
delete[] reinterpret_cast<const char *>(value);
}};
// Note that because of the nullptr handle argument below, rocksdb
// will run the deleter if the insert throws; just make sure
// the argument execution doesn't throw after release()
throw_on_error
{
cache.Insert(slice(key),
const_cast<char *>(data(value.release())),
value_size,
deleter,
nullptr)
};
return true;
}
void
ircd::db::for_each(const rocksdb::Cache &cache,
const cache_closure &closure)
{
// Due to the use of the global variables which are required when using a
// C-style callback for RocksDB, we have to make use of this function
// exclusive for different contexts.
thread_local ctx::mutex mutex;
const std::lock_guard lock{mutex};
thread_local rocksdb::Cache *_cache;
_cache = const_cast<rocksdb::Cache *>(&cache);
thread_local const cache_closure *_closure;
_closure = &closure;
_cache->ApplyToAllCacheEntries([]
(void *const value_buffer, const size_t buffer_size)
noexcept
{
assert(_cache);
assert(_closure);
const const_buffer buf
{
reinterpret_cast<const char *>(value_buffer), buffer_size
};
(*_closure)(buf);
},
true);
}
#ifdef IRCD_DB_HAS_CACHE_GETCHARGE
size_t
ircd::db::charge(const rocksdb::Cache &cache_,
const string_view &key)
{
auto &cache
{
const_cast<rocksdb::Cache &>(cache_)
};
const custom_ptr<rocksdb::Cache::Handle> handle
{
cache.Lookup(slice(key)), [&cache](auto *const &handle)
{
cache.Release(handle);
}
};
return cache.GetCharge(handle);
}
#else
size_t
ircd::db::charge(const rocksdb::Cache &cache,
const string_view &key)
{
return 0UL;
}
#endif
[[gnu::hot]]
bool
ircd::db::exists(const rocksdb::Cache &cache_,
const string_view &key)
{
auto &cache
{
const_cast<rocksdb::Cache &>(cache_)
};
const custom_ptr<rocksdb::Cache::Handle> handle
{
cache.Lookup(slice(key)), [&cache](auto *const &handle)
{
cache.Release(handle);
}
};
return bool(handle);
}
size_t
ircd::db::pinned(const rocksdb::Cache &cache)
{
return cache.GetPinnedUsage();
}
size_t
ircd::db::usage(const rocksdb::Cache &cache)
{
return cache.GetUsage();
}
void
ircd::db::capacity(rocksdb::Cache &cache,
const size_t &cap)
{
cache.SetCapacity(cap);
}
size_t
ircd::db::capacity(const rocksdb::Cache &cache)
{
return cache.GetCapacity();
}
const uint64_t &
ircd::db::ticker(const rocksdb::Cache &cache,
const uint32_t &ticker_id)
{
const auto &c
{
dynamic_cast<const database::cache &>(cache)
};
static const uint64_t &zero
{
0ULL
};
return c.stats?
c.stats->ticker.at(ticker_id):
zero;
}
///////////////////////////////////////////////////////////////////////////////
//
// error.h
//
//
// error::not_found
//
decltype(ircd::db::error::not_found::_not_found_)
ircd::db::error::not_found::_not_found_
{
rocksdb::Status::NotFound()
};
//
// error::not_found::not_found
//
ircd::db::error::not_found::not_found()
:error
{
generate_skip, _not_found_
}
{
strlcpy(buf, "NotFound");
}
//
// error
//
decltype(ircd::db::error::_no_code_)
ircd::db::error::_no_code_
{
rocksdb::Status::OK()
};
//
// error::error
//
ircd::db::error::error(internal_t,
const rocksdb::Status &s,
const string_view &fmt,
const va_rtti &ap)
:error
{
s
}
{
const string_view &msg{buf};
const mutable_buffer remain
{
buf + size(msg), sizeof(buf) - size(msg)
};
fmt::vsprintf
{
remain, fmt, ap
};
}
ircd::db::error::error(const rocksdb::Status &s)
:error
{
generate_skip, s
}
{
fmt::sprintf
{
buf, "(%u:%u:%u) %s %s :%s",
this->code,
this->subcode,
this->severity,
reflect(rocksdb::Status::Severity(this->severity)),
reflect(rocksdb::Status::Code(this->code)),
s.getState(),
};
}
ircd::db::error::error(generate_skip_t,
const rocksdb::Status &s)
:ircd::error
{
generate_skip
}
,code
{
s.code()
}
,subcode
{
s.subcode()
}
,severity
{
s.severity()?
s.severity():
code == rocksdb::Status::kCorruption?
rocksdb::Status::kHardError:
rocksdb::Status::kNoError
}
{
}
///////////////////////////////////////////////////////////////////////////////
//
// merge.h
//
std::string
__attribute__((noreturn))
ircd::db::merge_operator(const string_view &key,
const std::pair<string_view, string_view> &delta)
{
//ircd::json::index index{delta.first};
//index += delta.second;
//return index;
throw ircd::not_implemented
{
"db::merge_operator()"
};
}
///////////////////////////////////////////////////////////////////////////////
//
// comparator.h
//
//
// linkage placements for integer comparators so they all have the same addr
//
ircd::db::cmp_int64_t::cmp_int64_t()
{
}
ircd::db::cmp_int64_t::~cmp_int64_t()
noexcept
{
}
ircd::db::cmp_uint64_t::cmp_uint64_t()
{
}
ircd::db::cmp_uint64_t::~cmp_uint64_t()
noexcept
{
}
ircd::db::reverse_cmp_int64_t::reverse_cmp_int64_t()
{
}
ircd::db::reverse_cmp_int64_t::~reverse_cmp_int64_t()
noexcept
{
}
ircd::db::reverse_cmp_uint64_t::reverse_cmp_uint64_t()
{
}
ircd::db::reverse_cmp_uint64_t::~reverse_cmp_uint64_t()
noexcept
{
}
//
// cmp_string_view
//
ircd::db::cmp_string_view::cmp_string_view()
:db::comparator{"string_view", &less, &equal}
{
}
bool
ircd::db::cmp_string_view::less(const string_view &a,
const string_view &b)
{
return a < b;
}
bool
ircd::db::cmp_string_view::equal(const string_view &a,
const string_view &b)
{
return a == b;
}
//
// reverse_cmp_string_view
//
ircd::db::reverse_cmp_string_view::reverse_cmp_string_view()
:db::comparator{"reverse_string_view", &less, &equal}
{
}
bool
ircd::db::reverse_cmp_string_view::less(const string_view &a,
const string_view &b)
{
/// RocksDB sez things will not work correctly unless a shorter string
/// result returns less than a longer string even if one intends some
/// reverse ordering
if(a.size() < b.size())
return true;
/// Furthermore, b.size() < a.size() returning false from this function
/// appears to not be correct. The reversal also has to also come in
/// the form of a bytewise forward iteration.
return std::memcmp(a.data(), b.data(), std::min(a.size(), b.size())) > 0;
}
bool
ircd::db::reverse_cmp_string_view::equal(const string_view &a,
const string_view &b)
{
return a == b;
}
///////////////////////////////////////////////////////////////////////////////
//
// delta.h
//
bool
ircd::db::value_required(const op &op)
{
switch(op)
{
case op::SET:
case op::MERGE:
case op::DELETE_RANGE:
return true;
case op::GET:
case op::DELETE:
case op::SINGLE_DELETE:
return false;
}
assert(0);
return false;
}
///////////////////////////////////////////////////////////////////////////////
//
// db.h (internal)
//
//
// throw_on_error
//
ircd::db::throw_on_error::throw_on_error(const rocksdb::Status &status)
{
using rocksdb::Status;
switch(status.code())
{
case Status::kOk:
return;
case Status::kNotFound:
throw not_found{};
#ifdef RB_DEBUG
//case Status::kCorruption:
case Status::kNotSupported:
case Status::kInvalidArgument:
debugtrap();
[[fallthrough]];
#endif
default:
throw error
{
status
};
}
}
//
// error_to_status
//
ircd::db::error_to_status::error_to_status(const std::exception &e)
:rocksdb::Status
{
Status::Aborted(slice(string_view(e.what())))
}
{
}
ircd::db::error_to_status::error_to_status(const std::system_error &e)
:error_to_status{e.code()}
{
}
ircd::db::error_to_status::error_to_status(const std::error_code &e)
:rocksdb::Status{[&e]
{
using std::errc;
switch(e.value())
{
case 0:
return Status::OK();
case int(errc::no_such_file_or_directory):
return Status::NotFound();
case int(errc::not_supported):
return Status::NotSupported();
case int(errc::invalid_argument):
return Status::InvalidArgument();
case int(errc::io_error):
return Status::IOError();
case int(errc::timed_out):
return Status::TimedOut();
case int(errc::device_or_resource_busy):
return Status::Busy();
case int(errc::resource_unavailable_try_again):
return Status::TryAgain();
case int(errc::no_space_on_device):
return Status::NoSpace();
case int(errc::not_enough_memory):
return Status::MemoryLimit();
default:
return Status::Aborted(slice(string_view(e.message())));
}
}()}
{
}
//
// writebatch suite
//
void
ircd::db::append(rocksdb::WriteBatch &batch,
const cell::delta &delta)
{
auto &column
{
std::get<cell *>(delta)->c
};
append(batch, column, column::delta
{
std::get<op>(delta),
std::get<cell *>(delta)->key(),
std::get<string_view>(delta)
});
}
void
ircd::db::append(rocksdb::WriteBatch &batch,
column &column,
const column::delta &delta)
{
if(unlikely(!column))
{
// Note: Unknown at this time whether allowing attempts at writing
// to a null column should be erroneous or silently ignored. It's
// highly likely this log message will be removed soon to allow
// toggling database columns for optimization without touching calls.
log::critical
{
log, "Attempting to transact a delta for a null column"
};
return;
}
database::column &c(column);
const auto k(slice(std::get<1>(delta)));
const auto v(slice(std::get<2>(delta)));
switch(std::get<0>(delta))
{
case op::GET: assert(0); break;
case op::SET: batch.Put(c, k, v); break;
case op::MERGE: batch.Merge(c, k, v); break;
case op::DELETE: batch.Delete(c, k); break;
case op::DELETE_RANGE: batch.DeleteRange(c, k, v); break;
case op::SINGLE_DELETE: batch.SingleDelete(c, k); break;
}
}
void
ircd::db::commit(database &d,
rocksdb::WriteBatch &batch,
const sopts &sopts)
{
const auto opts(make_opts(sopts));
commit(d, batch, opts);
}
void
ircd::db::commit(database &d,
rocksdb::WriteBatch &batch,
const rocksdb::WriteOptions &opts)
{
#ifdef RB_DEBUG
ircd::timer timer;
#endif
const std::lock_guard lock{write_mutex};
const ctx::uninterruptible ui;
const ctx::stack_usage_assertion sua;
throw_on_error
{
d.d->Write(opts, &batch)
};
#ifdef RB_DEBUG
log::debug
{
log, "[%s] %lu COMMIT %s in %ld$us",
d.name,
sequence(d),
debug(batch),
timer.at<microseconds>().count()
};
#endif
}
std::string
ircd::db::debug(const rocksdb::WriteBatch &batch)
{
return ircd::string(512, [&batch]
(const mutable_buffer &ret)
{
return snprintf(data(ret), size(ret)+1,
"%d deltas; size:%zuB %s+%s+%s+%s+%s+%s+%s+%s+%s",
batch.Count(),
batch.GetDataSize(),
batch.HasPut()? "PUT" : "",
batch.HasDelete()? "DEL" : "",
batch.HasSingleDelete()? "SDL" : "",
batch.HasDeleteRange()? "DRG" : "",
batch.HasMerge()? "MRG" : "",
batch.HasBeginPrepare()? "BEG" : "",
batch.HasEndPrepare()? "END" : "",
batch.HasCommit()? "COM-" : "",
batch.HasRollback()? "RB^" : "");
});
}
bool
ircd::db::has(const rocksdb::WriteBatch &wb,
const op &op)
{
switch(op)
{
case op::GET: assert(0); return false;
case op::SET: return wb.HasPut();
case op::MERGE: return wb.HasMerge();
case op::DELETE: return wb.HasDelete();
case op::DELETE_RANGE: return wb.HasDeleteRange();
case op::SINGLE_DELETE: return wb.HasSingleDelete();
}
return false;
}
//
// read suite
//
namespace ircd::db
{
static rocksdb::Status _seek(database::column &, rocksdb::PinnableSlice &, const string_view &, const rocksdb::ReadOptions &);
}
rocksdb::Status
ircd::db::_read(column &column,
const string_view &key,
const rocksdb::ReadOptions &opts,
const column::view_closure &closure)
{
std::string buf;
rocksdb::PinnableSlice ps
{
&buf
};
database::column &c(column);
const rocksdb::Status ret
{
_seek(c, ps, key, opts)
};
if(!valid(ret))
return ret;
const string_view value
{
slice(ps)
};
if(likely(closure))
closure(value);
// Update stats about whether the pinnable slices we obtained have internal
// copies or referencing the cache copy.
database &d(column);
c.stats->get_referenced += buf.empty();
d.stats->get_referenced += buf.empty();
c.stats->get_copied += !buf.empty();
d.stats->get_copied += !buf.empty();
return ret;
}
rocksdb::Status
ircd::db::_seek(database::column &c,
rocksdb::PinnableSlice &s,
const string_view &key,
const rocksdb::ReadOptions &ropts)
{
const ctx::uninterruptible::nothrow ui;
const ctx::stack_usage_assertion sua;
rocksdb::ColumnFamilyHandle *const &cf(c);
database &d(*c.d);
#ifdef RB_DEBUG_DB_SEEK
const ircd::timer timer;
#endif
const rocksdb::Status ret
{
d.d->Get(ropts, cf, slice(key), &s)
};
#ifdef RB_DEBUG_DB_SEEK
log::debug
{
log, "[%s] %lu:%lu SEEK %s in %ld$us '%s'",
name(d),
sequence(d),
sequence(ropts.snapshot),
ret.ToString(),
timer.at<microseconds>().count(),
name(c)
};
#endif
return ret;
}
//
// parallel read suite
//
namespace ircd::db
{
static void _seek(const vector_view<_read_op> &, const vector_view<rocksdb::Status> &, const vector_view<rocksdb::PinnableSlice> &, const rocksdb::ReadOptions &);
}
bool
ircd::db::_read(const vector_view<_read_op> &op,
const rocksdb::ReadOptions &ropts,
const _read_closure &closure)
{
assert(op.size() >= 1);
assert(op.size() <= IOV_MAX);
const size_t &num
{
op.size()
};
std::string buf[num];
rocksdb::PinnableSlice val[num];
for(size_t i(0); i < num; ++i)
new (val + i) rocksdb::PinnableSlice
{
buf + i
};
const bool parallelize
{
#ifdef IRCD_DB_HAS_MULTIGET_DIRECT
true && num > 1
#else
false
#endif
};
rocksdb::Status status[num];
if(!parallelize)
for(size_t i(0); i < num; ++i)
{
database::column &column(std::get<column>(op[i]));
status[i] = _seek(column, val[i], std::get<1>(op[i]), ropts);
}
else
_seek(op, {status, num}, {val, num}, ropts);
bool ret(true);
if(closure)
for(size_t i(0); i < num && ret; ++i)
{
const column::delta delta(std::get<1>(op[i]), slice(val[i]));
ret = closure(std::get<column>(op[i]), delta, status[i]);
}
// Update stats about whether the pinnable slices we obtained have internal
// copies or referencing the cache copy.
for(size_t i(0); i < num; ++i)
{
database &d(std::get<column>(op[i]));
database::column &c(std::get<column>(op[i]));
// Find the correct stats to update, one for the specific column and
// one for the database total.
ircd::stats::item<uint64_t *> *item_[2]
{
parallelize && buf[i].empty()? &c.stats->multiget_referenced:
parallelize? &c.stats->multiget_copied:
buf[i].empty()? &c.stats->get_referenced:
&c.stats->get_copied,
parallelize && buf[i].empty()? &d.stats->multiget_referenced:
parallelize? &d.stats->multiget_copied:
buf[i].empty()? &d.stats->get_referenced:
&d.stats->get_copied,
};
for(auto *const &item : item_)
++(*item);
}
return ret;
}
void
ircd::db::_seek(const vector_view<_read_op> &op,
const vector_view<rocksdb::Status> &ret,
const vector_view<rocksdb::PinnableSlice> &val,
const rocksdb::ReadOptions &ropts)
{
assert(ret.size() == op.size());
assert(ret.size() == val.size());
const ctx::stack_usage_assertion sua;
const ctx::uninterruptible::nothrow ui;
assert(op.size() >= 1);
database &d(std::get<0>(op[0]));
const size_t &num
{
op.size()
};
rocksdb::Slice key[num];
std::transform(begin(op), end(op), key, []
(const auto &op)
{
return slice(std::get<1>(op));
});
rocksdb::ColumnFamilyHandle *cf[num];
std::transform(begin(op), end(op), cf, []
(auto &op_)
{
auto &op(const_cast<_read_op &>(op_));
database::column &c(std::get<column>(op));
return static_cast<rocksdb::ColumnFamilyHandle *>(c);
});
#ifdef RB_DEBUG_DB_SEEK
const ircd::timer timer;
#endif
#ifdef IRCD_DB_HAS_MULTIGET_BATCHED
d.d->MultiGet(ropts, num, cf, key, val.data(), ret.data());
#endif
#ifdef RB_DEBUG_DB_SEEK
log::debug
{
log, "[%s] %lu:%lu SEEK parallel:%zu ok:%zu nf:%zu inc:%zu in %ld$us",
name(d),
sequence(d),
sequence(ropts.snapshot),
ret.size(),
std::count_if(begin(ret), end(ret), [](auto&& s) { return s.ok(); }),
std::count_if(begin(ret), end(ret), [](auto&& s) { return s.IsNotFound(); }),
std::count_if(begin(ret), end(ret), [](auto&& s) { return s.IsIncomplete(); }),
timer.at<microseconds>().count(),
};
#endif
}
//
// iterator seek suite
//
namespace ircd::db
{
static rocksdb::Iterator &_seek_(rocksdb::Iterator &, const pos &);
static rocksdb::Iterator &_seek_(rocksdb::Iterator &, const string_view &);
static rocksdb::Iterator &_seek_lower_(rocksdb::Iterator &, const string_view &);
static rocksdb::Iterator &_seek_upper_(rocksdb::Iterator &, const string_view &);
static bool _seek(database::column &, const pos &, const rocksdb::ReadOptions &, rocksdb::Iterator &it);
static bool _seek(database::column &, const string_view &, const rocksdb::ReadOptions &, rocksdb::Iterator &it);
}
std::unique_ptr<rocksdb::Iterator>
ircd::db::seek(column &column,
const string_view &key,
const gopts &opts)
{
database &d(column);
database::column &c(column);
std::unique_ptr<rocksdb::Iterator> ret;
seek(c, key, make_opts(opts), ret);
return ret;
}
template<class pos>
bool
ircd::db::seek(database::column &c,
const pos &p,
const rocksdb::ReadOptions &opts,
std::unique_ptr<rocksdb::Iterator> &it)
{
if(!it)
{
const ctx::uninterruptible::nothrow ui;
database &d(*c.d);
rocksdb::ColumnFamilyHandle *const &cf(c);
it.reset(d.d->NewIterator(opts, cf));
}
return _seek(c, p, opts, *it);
}
bool
ircd::db::_seek(database::column &c,
const string_view &p,
const rocksdb::ReadOptions &opts,
rocksdb::Iterator &it)
try
{
const ctx::uninterruptible ui;
#ifdef RB_DEBUG_DB_SEEK
database &d(*c.d);
const ircd::timer timer;
#endif
_seek_(it, p);
#ifdef RB_DEBUG_DB_SEEK
log::debug
{
log, "[%s] %lu:%lu SEEK %s %s in %ld$us '%s'",
name(d),
sequence(d),
sequence(opts.snapshot),
valid(it)? "VALID" : "INVALID",
it.status().ToString(),
timer.at<microseconds>().count(),
name(c)
};
#endif
return valid(it);
}
catch(const error &e)
{
const database &d(*c.d);
log::critical
{
log, "[%s][%s] %lu:%lu SEEK key :%s",
name(d),
name(c),
sequence(d),
sequence(opts.snapshot),
e.what(),
};
throw;
}
bool
ircd::db::_seek(database::column &c,
const pos &p,
const rocksdb::ReadOptions &opts,
rocksdb::Iterator &it)
try
{
const ctx::stack_usage_assertion sua;
#ifdef RB_DEBUG_DB_SEEK
database &d(*c.d);
const ircd::timer timer;
const bool valid_it
{
valid(it)
};
#endif
_seek_(it, p);
#ifdef RB_DEBUG_DB_SEEK
log::debug
{
log, "[%s] %lu:%lu SEEK[%s] %s -> %s in %ld$us '%s'",
name(d),
sequence(d),
sequence(opts.snapshot),
reflect(p),
valid_it? "VALID" : "INVALID",
it.status().ToString(),
timer.at<microseconds>().count(),
name(c)
};
#endif
return valid(it);
}
catch(const error &e)
{
const database &d(*c.d);
log::critical
{
log, "[%s][%s] %lu:%lu SEEK %s %s :%s",
name(d),
name(c),
sequence(d),
sequence(opts.snapshot),
reflect(p),
it.Valid()? "VALID" : "INVALID",
e.what(),
};
throw;
}
/// Seek to entry NOT GREATER THAN key. That is, equal to or less than key
rocksdb::Iterator &
ircd::db::_seek_lower_(rocksdb::Iterator &it,
const string_view &sv)
{
it.SeekForPrev(slice(sv));
return it;
}
/// Seek to entry NOT LESS THAN key. That is, equal to or greater than key
rocksdb::Iterator &
ircd::db::_seek_upper_(rocksdb::Iterator &it,
const string_view &sv)
{
it.Seek(slice(sv));
return it;
}
/// Defaults to _seek_upper_ because it has better support from RocksDB.
rocksdb::Iterator &
ircd::db::_seek_(rocksdb::Iterator &it,
const string_view &sv)
{
return _seek_upper_(it, sv);
}
rocksdb::Iterator &
ircd::db::_seek_(rocksdb::Iterator &it,
const pos &p)
{
switch(p)
{
case pos::NEXT: it.Next(); break;
case pos::PREV: it.Prev(); break;
case pos::FRONT: it.SeekToFirst(); break;
case pos::BACK: it.SeekToLast(); break;
default:
case pos::END:
{
it.SeekToLast();
if(it.Valid())
it.Next();
break;
}
}
return it;
}
//
// validation suite
//
void
ircd::db::valid_eq_or_throw(const rocksdb::Iterator &it,
const string_view &sv)
{
assert(!empty(sv));
if(!valid_eq(it, sv))
{
throw_on_error(it.status());
throw not_found{};
}
}
void
ircd::db::valid_or_throw(const rocksdb::Iterator &it)
{
if(!valid(it))
{
throw_on_error(it.status());
throw not_found{};
//assert(0); // status == ok + !Valid() == ???
}
}
bool
ircd::db::valid_lte(const rocksdb::Iterator &it,
const string_view &sv)
{
return valid(it, [&sv](const auto &it)
{
return it.key().compare(slice(sv)) <= 0;
});
}
bool
ircd::db::valid_gt(const rocksdb::Iterator &it,
const string_view &sv)
{
return valid(it, [&sv](const auto &it)
{
return it.key().compare(slice(sv)) > 0;
});
}
bool
ircd::db::valid_eq(const rocksdb::Iterator &it,
const string_view &sv)
{
return valid(it, [&sv](const auto &it)
{
return it.key().compare(slice(sv)) == 0;
});
}
bool
ircd::db::valid(const rocksdb::Iterator &it,
const valid_proffer &proffer)
{
return valid(it)? proffer(it) : false;
}
bool
ircd::db::operator!(const rocksdb::Iterator &it)
{
return !valid(it);
}
bool
ircd::db::valid(const rocksdb::Iterator &it)
{
switch(it.status().code())
{
using rocksdb::Status;
case Status::kOk:
case Status::kNotFound:
case Status::kIncomplete:
return it.Valid();
default:
throw_on_error
{
it.status()
};
__builtin_unreachable();
}
}
bool
ircd::db::valid(const rocksdb::Status &s)
{
switch(s.code())
{
using rocksdb::Status;
case Status::kOk:
return true;
case Status::kNotFound:
case Status::kIncomplete:
return false;
default:
throw_on_error{s};
__builtin_unreachable();
}
}
//
// column_names
//
std::vector<std::string>
ircd::db::column_names(const std::string &path,
const std::string &options)
{
const rocksdb::DBOptions opts
{
db::options(options)
};
return column_names(path, opts);
}
/// Note that if there is no database found at path we still return a
/// vector containing the column name "default". This function is not
/// to be used as a test for whether the database exists. It returns
/// the columns required to be described at `path`. That will always
/// include the default column (RocksDB sez) even if database doesn't
/// exist yet.
std::vector<std::string>
ircd::db::column_names(const std::string &path,
const rocksdb::DBOptions &opts)
try
{
std::vector<std::string> ret;
throw_on_error
{
rocksdb::DB::ListColumnFamilies(opts, path, &ret)
};
return ret;
}
catch(const not_found &)
{
return // No database found at path.
{
{ rocksdb::kDefaultColumnFamilyName }
};
}
//
// Misc
//
rocksdb::CompressionType
ircd::db::find_supported_compression(const std::string &list)
{
rocksdb::CompressionType ret
{
rocksdb::kNoCompression
};
tokens(list, ';', [&ret]
(const string_view &requested)
{
if(ret != rocksdb::kNoCompression)
return;
for(const auto &[name, type] : db::compressions)
if(type != 0L && name == requested)
{
ret = rocksdb::CompressionType(type);
break;
}
});
return ret;
}
rocksdb::DBOptions
ircd::db::make_dbopts(std::string optstr,
std::string *const &out,
bool *const read_only,
bool *const fsck)
{
// RocksDB doesn't parse a read_only option, so we allow that to be added
// to open the database as read_only and then remove that from the string.
if(read_only)
*read_only |= optstr_find_and_remove(optstr, "read_only=true;"s);
else
optstr_find_and_remove(optstr, "read_only=true;"s);
// We also allow the user to specify fsck=true to run a repair operation on
// the db. This may be expensive to do by default every startup.
if(fsck)
*fsck |= optstr_find_and_remove(optstr, "fsck=true;"s);
else
optstr_find_and_remove(optstr, "fsck=true;"s);
// Generate RocksDB options from string
rocksdb::DBOptions opts
{
db::options(optstr)
};
if(out)
*out = std::move(optstr);
return opts;
}
bool
ircd::db::optstr_find_and_remove(std::string &optstr,
const std::string &what)
{
const auto pos(optstr.find(what));
if(pos == std::string::npos)
return false;
optstr.erase(pos, what.size());
return true;
}
/// Convert our options structure into RocksDB's options structure.
rocksdb::ReadOptions
ircd::db::make_opts(const gopts &opts)
{
rocksdb::ReadOptions ret;
assert(ret.fill_cache);
assert(ret.read_tier == BLOCKING);
// slice* for exclusive upper bound. when prefixes are used this value must
// have the same prefix because ordering is not guaranteed between prefixes
ret.iterate_lower_bound = opts.lower_bound;
ret.iterate_upper_bound = opts.upper_bound;
ret += opts;
return ret;
}
ircd::conf::item<bool>
read_checksum
{
{ "name", "ircd.db.read.checksum" },
{ "default", false }
};
/// Update a RocksDB options structure with our options structure. We use
/// operator+= for fun here; we can avoid reconstructing and returning a new
/// options structure in some cases by breaking out this function from
/// make_opts().
rocksdb::ReadOptions &
ircd::db::operator+=(rocksdb::ReadOptions &ret,
const gopts &opts)
{
ret.pin_data = test(opts, get::PIN);
ret.fill_cache |= test(opts, get::CACHE);
ret.fill_cache &= !test(opts, get::NO_CACHE);
ret.tailing = test(opts, get::NO_SNAPSHOT);
ret.prefix_same_as_start = test(opts, get::PREFIX);
ret.total_order_seek = test(opts, get::ORDERED);
ret.verify_checksums = bool(read_checksum);
ret.verify_checksums |= test(opts, get::CHECKSUM);
ret.verify_checksums &= !test(opts, get::NO_CHECKSUM);
ret.readahead_size = opts.readahead;
ret.iter_start_seqnum = opts.seqnum;
ret.read_tier = test(opts, get::NO_BLOCKING)?
rocksdb::ReadTier::kBlockCacheTier:
rocksdb::ReadTier::kReadAllTier;
if(opts.snapshot && !test(opts, get::NO_SNAPSHOT))
ret.snapshot = opts.snapshot;
return ret;
}
rocksdb::WriteOptions
ircd::db::make_opts(const sopts &opts)
{
rocksdb::WriteOptions ret;
//ret.no_slowdown = true; // read_tier = NON_BLOCKING for writes
ret += opts;
return ret;
}
rocksdb::WriteOptions &
ircd::db::operator+=(rocksdb::WriteOptions &ret,
const sopts &opts)
{
ret.sync = test(opts, set::FSYNC);
ret.disableWAL = test(opts, set::NO_JOURNAL);
ret.ignore_missing_column_families = test(opts, set::NO_COLUMN_ERR);
ret.no_slowdown = test(opts, set::NO_BLOCKING);
ret.low_pri = test(opts, set::PRIO_LOW);
return ret;
}
//
//
//
std::vector<std::string>
ircd::db::available()
{
const string_view &prefix
{
fs::base::db
};
const auto dirs
{
fs::ls(prefix)
};
std::vector<std::string> ret;
for(const auto &dir : dirs)
{
if(!fs::is_dir(dir))
continue;
const auto name
{
lstrip(dir, prefix)
};
const auto checkpoints
{
fs::ls(dir)
};
for(const auto &cpdir : checkpoints) try
{
const auto checkpoint
{
lstrip(lstrip(cpdir, dir), '/') //TODO: x-platform
};
auto path
{
db::path(name, lex_cast<uint64_t>(checkpoint))
};
ret.emplace_back(std::move(path));
}
catch(const bad_lex_cast &e)
{
continue;
}
}
return ret;
}
std::string
ircd::db::path(const string_view &name)
{
const auto pair
{
namepoint(name)
};
return path(pair.first, pair.second);
}
std::string
ircd::db::path(const string_view &name,
const uint64_t &checkpoint)
{
const auto &prefix
{
fs::base::db
};
const string_view parts[]
{
prefix, name, lex_cast(checkpoint)
};
return fs::path_string(parts);
}
std::pair<ircd::string_view, uint64_t>
ircd::db::namepoint(const string_view &name_)
{
const auto s
{
split(name_, ':')
};
return
{
s.first,
s.second? lex_cast<uint64_t>(s.second) : uint64_t(-1)
};
}
std::string
ircd::db::namepoint(const string_view &name,
const uint64_t &checkpoint)
{
return std::string{name} + ':' + std::string{lex_cast(checkpoint)};
}
//
// Iterator
//
std::pair<ircd::string_view, ircd::string_view>
ircd::db::operator*(const rocksdb::Iterator &it)
{
return { key(it), val(it) };
}
ircd::string_view
ircd::db::key(const rocksdb::Iterator &it)
{
return slice(it.key());
}
ircd::string_view
ircd::db::val(const rocksdb::Iterator &it)
{
return slice(it.value());
}
//
// PinnableSlice
//
size_t
ircd::db::size(const rocksdb::PinnableSlice &ps)
{
return size(static_cast<const rocksdb::Slice &>(ps));
}
const char *
ircd::db::data(const rocksdb::PinnableSlice &ps)
{
return data(static_cast<const rocksdb::Slice &>(ps));
}
ircd::string_view
ircd::db::slice(const rocksdb::PinnableSlice &ps)
{
return slice(static_cast<const rocksdb::Slice &>(ps));
}
//
// Slice
//
size_t
ircd::db::size(const rocksdb::Slice &slice)
{
return slice.size();
}
const char *
ircd::db::data(const rocksdb::Slice &slice)
{
return slice.data();
}
rocksdb::Slice
ircd::db::slice(const string_view &sv)
{
return { sv.data(), sv.size() };
}
ircd::string_view
ircd::db::slice(const rocksdb::Slice &sk)
{
return { sk.data(), sk.size() };
}
//
// reflect
//
const std::string &
ircd::db::reflect(const rocksdb::Tickers &type)
{
const auto &names(rocksdb::TickersNameMap);
const auto it(std::find_if(begin(names), end(names), [&type]
(const auto &pair)
{
return pair.first == type;
}));
static const auto empty{"<ticker>?????"s};
return it != end(names)? it->second : empty;
}
const std::string &
ircd::db::reflect(const rocksdb::Histograms &type)
{
const auto &names(rocksdb::HistogramsNameMap);
const auto it(std::find_if(begin(names), end(names), [&type]
(const auto &pair)
{
return pair.first == type;
}));
static const auto empty{"<histogram>?????"s};
return it != end(names)? it->second : empty;
}
ircd::string_view
ircd::db::reflect(const pos &pos)
{
switch(pos)
{
case pos::NEXT: return "NEXT";
case pos::PREV: return "PREV";
case pos::FRONT: return "FRONT";
case pos::BACK: return "BACK";
case pos::END: return "END";
}
return "?????";
}
ircd::string_view
ircd::db::reflect(const op &op)
{
switch(op)
{
case op::GET: return "GET";
case op::SET: return "SET";
case op::MERGE: return "MERGE";
case op::DELETE_RANGE: return "DELETE_RANGE";
case op::DELETE: return "DELETE";
case op::SINGLE_DELETE: return "SINGLE_DELETE";
}
return "?????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::FlushReason &r)
{
using FlushReason = rocksdb::FlushReason;
switch(r)
{
case FlushReason::kOthers: return "Others";
case FlushReason::kGetLiveFiles: return "GetLiveFiles";
case FlushReason::kShutDown: return "ShutDown";
case FlushReason::kExternalFileIngestion: return "ExternalFileIngestion";
case FlushReason::kManualCompaction: return "ManualCompaction";
case FlushReason::kWriteBufferManager: return "WriteBufferManager";
case FlushReason::kWriteBufferFull: return "WriteBufferFull";
case FlushReason::kTest: return "Test";
case FlushReason::kDeleteFiles: return "DeleteFiles";
case FlushReason::kAutoCompaction: return "AutoCompaction";
case FlushReason::kManualFlush: return "ManualFlush";
case FlushReason::kErrorRecovery: return "kErrorRecovery";
}
return "??????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::CompactionReason &r)
{
using CompactionReason = rocksdb::CompactionReason;
switch(r)
{
case CompactionReason::kUnknown: return "Unknown";
case CompactionReason::kLevelL0FilesNum: return "LevelL0FilesNum";
case CompactionReason::kLevelMaxLevelSize: return "LevelMaxLevelSize";
case CompactionReason::kUniversalSizeAmplification: return "UniversalSizeAmplification";
case CompactionReason::kUniversalSizeRatio: return "UniversalSizeRatio";
case CompactionReason::kUniversalSortedRunNum: return "UniversalSortedRunNum";
case CompactionReason::kFIFOMaxSize: return "FIFOMaxSize";
case CompactionReason::kFIFOReduceNumFiles: return "FIFOReduceNumFiles";
case CompactionReason::kFIFOTtl: return "FIFOTtl";
case CompactionReason::kManualCompaction: return "ManualCompaction";
case CompactionReason::kFilesMarkedForCompaction: return "FilesMarkedForCompaction";
case CompactionReason::kBottommostFiles: return "BottommostFiles";
case CompactionReason::kTtl: return "Ttl";
case CompactionReason::kFlush: return "Flush";
case CompactionReason::kExternalSstIngestion: return "ExternalSstIngestion";
#ifdef IRCD_DB_HAS_PERIODIC_COMPACTIONS
case CompactionReason::kPeriodicCompaction: return "kPeriodicCompaction";
#endif
case CompactionReason::kNumOfReasons:
break;
}
return "??????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::BackgroundErrorReason &r)
{
using rocksdb::BackgroundErrorReason;
switch(r)
{
case BackgroundErrorReason::kFlush: return "FLUSH";
case BackgroundErrorReason::kCompaction: return "COMPACTION";
case BackgroundErrorReason::kWriteCallback: return "WRITE";
case BackgroundErrorReason::kMemTable: return "MEMTABLE";
#if 0 // unreleased
case BackgroundErrorReason::kManifestWrite: return "MANIFESTWRITE";
#endif
}
return "??????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::WriteStallCondition &c)
{
using rocksdb::WriteStallCondition;
switch(c)
{
case WriteStallCondition::kNormal: return "NORMAL";
case WriteStallCondition::kDelayed: return "DELAYED";
case WriteStallCondition::kStopped: return "STOPPED";
}
return "??????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::Env::Priority &p)
{
switch(p)
{
case rocksdb::Env::Priority::BOTTOM: return "BOTTOM"_sv;
case rocksdb::Env::Priority::LOW: return "LOW"_sv;
case rocksdb::Env::Priority::HIGH: return "HIGH"_sv;
#ifdef IRCD_DB_HAS_ENV_PRIO_USER
case rocksdb::Env::Priority::USER: return "USER"_sv;
#endif
case rocksdb::Env::Priority::TOTAL: assert(0); break;
}
return "????"_sv;
}
ircd::string_view
ircd::db::reflect(const rocksdb::Env::IOPriority &p)
{
switch(p)
{
case rocksdb::Env::IOPriority::IO_LOW: return "IO_LOW"_sv;
case rocksdb::Env::IOPriority::IO_HIGH: return "IO_HIGH"_sv;
case rocksdb::Env::IOPriority::IO_TOTAL: assert(0); break;
}
return "IO_????"_sv;
}
ircd::string_view
ircd::db::reflect(const rocksdb::Env::WriteLifeTimeHint &h)
{
using WriteLifeTimeHint = rocksdb::Env::WriteLifeTimeHint;
switch(h)
{
case WriteLifeTimeHint::WLTH_NOT_SET: return "NOT_SET";
case WriteLifeTimeHint::WLTH_NONE: return "NONE";
case WriteLifeTimeHint::WLTH_SHORT: return "SHORT";
case WriteLifeTimeHint::WLTH_MEDIUM: return "MEDIUM";
case WriteLifeTimeHint::WLTH_LONG: return "LONG";
case WriteLifeTimeHint::WLTH_EXTREME: return "EXTREME";
}
return "WLTH_????"_sv;
}
ircd::string_view
ircd::db::reflect(const rocksdb::Status::Severity &s)
{
using Severity = rocksdb::Status::Severity;
switch(s)
{
case Severity::kNoError: return "NONE";
case Severity::kSoftError: return "SOFT";
case Severity::kHardError: return "HARD";
case Severity::kFatalError: return "FATAL";
case Severity::kUnrecoverableError: return "UNRECOVERABLE";
case Severity::kMaxSeverity: break;
}
return "?????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::Status::Code &s)
{
using Code = rocksdb::Status::Code;
switch(s)
{
case Code::kOk: return "Ok";
case Code::kNotFound: return "NotFound";
case Code::kCorruption: return "Corruption";
case Code::kNotSupported: return "NotSupported";
case Code::kInvalidArgument: return "InvalidArgument";
case Code::kIOError: return "IOError";
case Code::kMergeInProgress: return "MergeInProgress";
case Code::kIncomplete: return "Incomplete";
case Code::kShutdownInProgress: return "ShutdownInProgress";
case Code::kTimedOut: return "TimedOut";
case Code::kAborted: return "Aborted";
case Code::kBusy: return "Busy";
case Code::kExpired: return "Expired";
case Code::kTryAgain: return "TryAgain";
case Code::kCompactionTooLarge: return "CompactionTooLarge";
#if ROCKSDB_MAJOR > 6 \
|| (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR > 3) \
|| (ROCKSDB_MAJOR == 6 && ROCKSDB_MINOR == 3 && ROCKSDB_PATCH >= 6)
case Code::kColumnFamilyDropped: return "ColumnFamilyDropped";
case Code::kMaxCode: break;
#endif
}
return "?????";
}
ircd::string_view
ircd::db::reflect(const rocksdb::RandomAccessFile::AccessPattern &p)
{
switch(p)
{
case rocksdb::RandomAccessFile::AccessPattern::NORMAL: return "NORMAL"_sv;
case rocksdb::RandomAccessFile::AccessPattern::RANDOM: return "RANDOM"_sv;
case rocksdb::RandomAccessFile::AccessPattern::SEQUENTIAL: return "SEQUENTIAL"_sv;
case rocksdb::RandomAccessFile::AccessPattern::WILLNEED: return "WILLNEED"_sv;
case rocksdb::RandomAccessFile::AccessPattern::DONTNEED: return "DONTNEED"_sv;
}
return "??????"_sv;
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_SIMD_TYPE_H
//
// scalar
//
namespace ircd
{
typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef int128_t i128;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef uint128_t u128;
typedef float f32;
typedef double f64;
typedef long double f128;
}
//
// unsigned
//
#ifdef HAVE_X86INTRIN_H
namespace ircd
{
typedef __v64qu u8x64; // [
typedef __v32qu u8x32; // [0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|
typedef __v16qu u8x16; // [0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|
typedef __v32hu u16x32; // [
typedef __v16hu u16x16; // [_0_|_1_|_2_|_3_|_4_|_5_|_6_|_7_|_8_|_9_|_a_|_b_|_c_|_d_|_e_|_f_|
typedef __v8hu u16x8; // [_0_|_1_|_2_|_3_|_4_|_5_|_6_|_7_|
typedef __v16su u32x16; // [
typedef __v8su u32x8; // [__0__|__1__|__2__|__3__|__4__|__5__|__6__|__7__|
typedef __v4su u32x4; // [__0__|__1__|__2__|__3__|
typedef __v8du u64x8; // [
typedef __v4du u64x4; // [____0____|____1____|____2____|____3____|
typedef __v2du u64x2; // [____0____|____1____|
typedef __m128i u128x1; // [________0________|
typedef __m128i_u u128x1_u; // unaligned
typedef __m256i u256x1; // [________________0________________|
typedef __m256i_u u256x1_u; // unaligned
typedef __m512i u512x1; // [_______________________________0________________________________|
typedef __m512i_u u512x1_u; // unaligned
}
#endif
//
// signed
//
#ifdef HAVE_X86INTRIN_H
namespace ircd
{
typedef __v64qi i8x64; // [
typedef __v32qi i8x32; // [0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|
typedef __v16qi i8x16; // [0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|
typedef __v32hi i16x32; // [
typedef __v16hi i16x16; // [_0_|_1_|_2_|_3_|_4_|_5_|_6_|_7_|_8_|_9_|_a_|_b_|_c_|_d_|_e_|_f_|
typedef __v8hi i16x8; // [_0_|_1_|_2_|_3_|_4_|_5_|_6_|_7_|
typedef __v16si i32x16; // [
typedef __v8si i32x8; // [__0__|__1__|__2__|__3__|__4__|__5__|__6__|__7__|
typedef __v4si i32x4; // [__0__|__1__|__2__|__3__|
typedef __v8di i64x8; // [
typedef __v4di i64x4; // [____0____|____1____|____2____|____3____|
typedef __v2di i64x2; // [____0____|____1____|
typedef __m128i i128x1; // [________0________]
typedef __m128i_u i128x1_u; // unaligned
typedef __m256i i256x1; // [________________0________________|
typedef __m256i_u i256x1_u; // unaligned
typedef __m512i i512x1; // [_______________________________0________________________________|
typedef __m512i_u i512x1_u; // unaligned
}
#endif
//
// single precision
//
#ifdef HAVE_X86INTRIN_H
namespace ircd
{
typedef __v16qs f8x16; // [0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|
typedef __v16sf f32x16; // [
typedef __v8sf f32x8; // [__0__|__1__|__2__|__3__|__4__|__5__|__6__|__7__|
typedef __v4sf f32x4; // [__0__|__1__|__2__|__3__|
typedef __m128 f128x1; // [____|____0____|____|
typedef __m128_u f128x1_u; // unaligned
typedef __m256 f256x1; // [________________0________________|
typedef __m256_u f256x1_u; // unaligned
typedef __m512 f512x1; // [_______________________________0________________________________|
typedef __m512_u f512x1_u; // unaligned
}
#endif
//
// double precision
//
#ifdef HAVE_X86INTRIN_H
namespace ircd
{
typedef __v8df f64x8; // [
typedef __v4df f64x4; // [____0____|____1____|____2____|____3____|
typedef __v2df f64x2; // [____0____|____1____|
typedef __m128d d128x1; // [________0________]
typedef __m128d_u d128x1_u; // unaligned
typedef __m256d d256x1; // [________________0________________|
typedef __m256d_u d256x1_u; // unaligned
typedef __m512d d512x1; // [_______________________________0________________________________|
typedef __m512d_u d512x1_u; // unaligned
}
#endif
//
// other words
//
namespace ircd::simd
{
struct pshuf_imm8;
}
/// Shuffle control structure. This represents an 8-bit immediate operand;
/// note it can only be used if constexprs are allowed in your definition unit.
struct ircd::simd::pshuf_imm8
{
u8 dst3 : 2; // set src idx for word 3
u8 dst2 : 2; // set src idx for word 2
u8 dst1 : 2; // set src idx for word 1
u8 dst0 : 2; // set src idx for word 0
};
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_FPE_H
namespace ircd::fpe
{
struct errors_handle;
string_view reflect_sicode(const int &);
string_view reflect(const ushort &flag);
string_view reflect(const mutable_buffer &, const ushort &flags);
[[noreturn]] void _throw_errors(const ushort &flags);
void throw_errors(const ushort &flags);
std::fexcept_t set(const ushort &flag);
}
/// Perform a single floating point operation at a time within the scope
/// of fpe::errors_handle. After each operation check the floating point
/// unit for an error status flag and throw a C++ exception.
struct ircd::fpe::errors_handle
{
std::fexcept_t theirs;
public:
ushort pending() const;
void throw_pending() const;
void clear_pending();
errors_handle();
~errors_handle() noexcept(false);
};
[[gnu::always_inline]] inline
ircd::fpe::errors_handle::errors_handle()
{
syscall(std::fegetexceptflag, &theirs, FE_ALL_EXCEPT);
clear_pending();
}
[[gnu::always_inline]] inline
ircd::fpe::errors_handle::~errors_handle()
noexcept(false)
{
const unwind reset{[this]
{
syscall(std::fesetexceptflag, &theirs, FE_ALL_EXCEPT);
}};
throw_pending();
}
inline void
ircd::fpe::errors_handle::clear_pending()
{
syscall(std::feclearexcept, FE_ALL_EXCEPT);
}
inline void
ircd::fpe::errors_handle::throw_pending()
const
{
const auto pending
{
this->pending()
};
if(unlikely(pending))
_throw_errors(pending);
}
inline ushort
ircd::fpe::errors_handle::pending()
const
{
return std::fetestexcept(FE_ALL_EXCEPT);
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#pragma once
#define HAVE_IRCD_SIMD_LZCNT_H
namespace ircd::simd
{
template<class T> uint lzcnt(const T) noexcept;
}
/// Convenience template. Unfortunately this drops to scalar until specific
/// targets and specializations are created.
template<class T>
inline uint
__attribute__((target("lzcnt")))
ircd::simd::lzcnt(const T a)
noexcept
{
// The behavior of lzcnt can differ among platforms; when true we expect
// lzcnt to fall back to bsr-like behavior.
constexpr auto bitscan
{
#ifdef __LZCNT__
false
#else
true
#endif
};
uint ret(0), i(0); do
{
const auto mask
{
boolmask(uint(ret == sizeof_lane<T>() * 8 * i))
};
if constexpr(bitscan && sizeof_lane<T>() <= sizeof(u16))
ret += (15 - __lzcnt16(__builtin_bswap16(a[i++]))) & mask;
else if constexpr(sizeof_lane<T>() <= sizeof(u16))
ret += __lzcnt16(__builtin_bswap16(a[i++])) & mask;
else if constexpr(bitscan && sizeof_lane<T>() <= sizeof(u32))
ret += (31 - __lzcnt32(__builtin_bswap32(a[i++]))) & mask;
else if constexpr(sizeof_lane<T>() <= sizeof(u32))
ret += __lzcnt32(__builtin_bswap32(a[i++])) & mask;
else if constexpr(bitscan)
ret += (63 - __lzcnt64(__builtin_bswap64(a[i++]))) & mask;
else
ret += __lzcnt64(__builtin_bswap64(a[i++])) & mask;
}
while(i < lanes<T>());
return ret;
}
<file_sep>// The Construct
//
// Copyright (C) The Construct Developers, Authors & Contributors
// Copyright (C) 2016-2020 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
namespace ircd::m::fed::well_known
{
static std::tuple<ircd::http::code, ircd::string_view, ircd::string_view>
fetch(const mutable_buffer &,
const net::hostport &,
const string_view &url);
extern log::log log;
}
decltype(ircd::m::fed::well_known::log)
ircd::m::fed::well_known::log
{
"m.well-known"
};
decltype(ircd::m::fed::well_known::cache_default)
ircd::m::fed::well_known::cache_default
{
{ "name", "ircd.m.fed.well-known.cache.default" },
{ "default", 24 * 60 * 60L },
};
decltype(ircd::m::fed::well_known::cache_error)
ircd::m::fed::well_known::cache_error
{
{ "name", "ircd.m.fed.well-known.cache.error" },
{ "default", 36 * 60 * 60L },
};
///NOTE: not yet used until HTTP cache headers in response are respected.
decltype(ircd::m::fed::well_known::cache_max)
ircd::m::fed::well_known::cache_max
{
{ "name", "ircd.m.fed.well-known.cache.max" },
{ "default", 48 * 60 * 60L },
};
decltype(ircd::m::fed::well_known::fetch_timeout)
ircd::m::fed::well_known::fetch_timeout
{
{ "name", "ircd.m.fed.well-known.fetch.timeout" },
{ "default", 15L },
};
decltype(ircd::m::fed::well_known::fetch_redirects)
ircd::m::fed::well_known::fetch_redirects
{
{ "name", "ircd.m.fed.well-known.fetch.redirects" },
{ "default", 2L },
};
ircd::string_view
ircd::m::fed::well_known::get(const mutable_buffer &buf,
const string_view &origin)
try
{
static const string_view type
{
"well-known.matrix.server"
};
const m::room::id::buf room_id
{
"dns", m::my_host()
};
const m::room room
{
room_id
};
const m::event::idx event_idx
{
room.get(std::nothrow, type, origin)
};
const milliseconds origin_server_ts
{
m::get<time_t>(std::nothrow, event_idx, "origin_server_ts", time_t(0))
};
const json::object content
{
origin_server_ts > 0ms?
m::get(std::nothrow, event_idx, "content", buf):
const_buffer{}
};
const seconds ttl
{
content.get<time_t>("ttl", time_t(86400))
};
const string_view cached
{
data(buf), move(buf, json::string(content["m.server"]))
};
const system_point expires
{
origin_server_ts + ttl
};
const bool expired
{
ircd::now<system_point>() > expires
};
const bool valid
{
!empty(cached)
};
// Crucial value that will provide us with a return string for this
// function in any case. This is obtained by either using the value
// found in cache or making a network query for a new value. expired=true
// when a network query needs to be made, otherwise we can return the
// cached value. If the network query fails, this value is still defaulted
// as the origin string to return and we'll also cache that too.
const string_view delegated
{
expired || !valid?
fetch(buf + size(cached), origin):
cached
};
// Branch on valid cache hit to return result.
if(valid && !expired)
{
char tmbuf[48];
log::debug
{
log, "%s found in cache delegated to %s event_idx:%u expires %s",
origin,
cached,
event_idx,
timef(tmbuf, expires, localtime),
};
return delegated;
}
// Conditions for valid expired cache hit w/ failure to reacquire.
const bool fallback
{
valid
&& expired
&& cached != delegated
&& origin == delegated
&& now<system_point>() < expires + seconds(cache_max)
};
if(fallback)
{
char tmbuf[48];
log::debug
{
log, "%s found in cache delegated to %s event_idx:%u expired %s",
origin,
cached,
event_idx,
timef(tmbuf, expires, localtime),
};
return cached;
}
// Any time the well-known result is the same as the origin (that
// includes legitimate errors where fetch_well_known() returns the
// origin to default) we consider that an error and use the error
// TTL value. Sorry, no exponential backoff implemented yet.
const auto cache_ttl
{
origin == delegated?
seconds(cache_error).count():
seconds(cache_default).count()
};
// Write our record to the cache room; note that this doesn't really
// match the format of other DNS records in this room since it's a bit
// simpler, but we don't share the ircd.dns.rr type prefix anyway.
const auto cache_id
{
m::send(room, m::me(), type, origin, json::members
{
{ "ttl", cache_ttl },
{ "m.server", delegated },
})
};
log::debug
{
log, "%s caching delegation to %s to cache in %s",
origin,
delegated,
string_view{cache_id},
};
return delegated;
}
catch(const ctx::interrupted &)
{
throw;
}
catch(const std::exception &e)
{
log::error
{
log, "%s :%s",
origin,
e.what(),
};
return string_view
{
data(buf), move(buf, origin)
};
}
ircd::string_view
ircd::m::fed::well_known::fetch(const mutable_buffer &user_buf,
const string_view &origin)
try
{
static const string_view path
{
"/.well-known/matrix/server"
};
// If the supplied buffer isn't large enough to make the full
// HTTP request, allocate one that is.
const unique_mutable_buffer req_buf
{
size(user_buf) < 8_KiB? 8_KiB: 0UL
};
const mutable_buffer buf
{
req_buf? req_buf: user_buf
};
rfc3986::uri uri;
uri.remote = origin;
uri.path = path;
json::object response;
unique_mutable_buffer carry;
for(size_t i(0); i < fetch_redirects; ++i)
{
const auto &[code, location, content]
{
fetch(buf, uri.remote, uri.path)
};
// Successful error; bail
if(code >= 400)
return string_view
{
data(user_buf), move(user_buf, origin)
};
// Successful result; response content handled after loop.
if(code < 300)
{
response = content;
break;
}
// Indirection code, but no location response header
if(!location)
return string_view
{
data(user_buf), move(user_buf, origin)
};
// Redirection; carry over the new target by copying it because it's
// in the buffer which we'll be overwriting for the new request.
carry = unique_mutable_buffer{location};
uri = string_view{carry};
// Indirection code, bad location header.
if(!uri.path || !uri.remote)
return string_view
{
data(user_buf), move(user_buf, origin)
};
}
const json::string &m_server
{
response["m.server"]
};
if(!m_server)
return string_view
{
data(user_buf), move(user_buf, origin)
};
// This construction validates we didn't get a junk string
volatile const net::hostport ret
{
m_server
};
log::debug
{
log, "%s query to %s found delegation to %s",
origin,
uri.remote,
m_server,
};
// Move the returned string to the front of the buffer; this overwrites
// any other incoming content to focus on just the unquoted string.
return string_view
{
data(user_buf), move(user_buf, m_server)
};
}
catch(const ctx::interrupted &)
{
throw;
}
catch(const std::exception &e)
{
log::derror
{
log, "%s in network query :%s",
origin,
e.what(),
};
return string_view
{
data(user_buf), move(user_buf, origin)
};
}
/// Return a tuple of the HTTP code, any Location header, and the response
/// content. These values are unconditional if this function doesn't throw,
/// but if there's no Location header and/or content then those will be empty
/// string_view's. This function is intended to be run in a loop by the caller
/// to chase redirection. No HTTP codes will throw from here; server and
/// network errors (and others) will.
std::tuple<ircd::http::code, ircd::string_view, ircd::string_view>
ircd::m::fed::well_known::fetch(const mutable_buffer &buf,
const net::hostport &remote,
const string_view &url)
{
// Hard target https service; do not inherit any matrix service from remote.
const net::hostport target
{
host(remote), "https", port(remote)
};
window_buffer wb
{
buf
};
const http::header headers[]
{
{ "User-Agent", info::user_agent },
};
http::request
{
wb, host(target), "GET", url, 0, {}, headers
};
const const_buffer out_head
{
wb.completed()
};
// Remaining space in buffer is used for received head; note that below
// we specify this same buffer for in.content, but that's a trick
// recognized by ircd::server to place received content directly after
// head in this buffer without any additional dynamic allocation.
const mutable_buffer in_head
{
buf + size(out_head)
};
server::request::opts opts;
opts.http_exceptions = false; // 3xx/4xx/5xx response won't throw.
server::request request
{
target,
{ out_head },
{ in_head, in_head },
&opts
};
const auto code
{
request.get(seconds(fetch_timeout))
};
thread_local char rembuf[rfc3986::DOMAIN_BUFSIZE * 2];
log::debug
{
log, "fetch from %s %s :%u %s",
string(rembuf, target),
url,
uint(code),
http::status(code)
};
const http::response::head head
{
request.in.gethead(request)
};
return
{
code,
head.location,
request.in.content,
};
}
<file_sep>// Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2018 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
#ifndef HAVE_IRCD_SPIRIT_H
#define HAVE_IRCD_SPIRIT_H
/// This file is not part of the IRCd standard include list (stdinc.h) because
/// it involves extremely expensive boost headers for creating formal spirit
/// grammars. Include this in a definition file which defines such grammars.
///
/// Note that directly sharing elements of a grammar between two compilation
/// units can be achieved with forward declarations in `ircd/grammar.h`.
// ircd.h is included here so that it can be compiled into this header. Then
// this becomes the single leading precompiled header.
#include <ircd/ircd.h>
// Disables asserts in spirit headers even when we're NDEBUG due to
// some false asserts around boolean character tests in spirit.
#define BOOST_DISABLE_ASSERTS
// This prevents spirit grammar rules from generating a very large and/or deep
// call-graph where rules compose together using wrapped indirect calls through
// boost::function -- this is higly inefficient as the grammar's logic ends up
// being a fraction of the generated code and the rest is invocation related
// overhead. By force-flattening here we can allow each entry-point into
// spirit to compose rules at once and eliminate the wrapping complex.
#pragma clang attribute push ([[gnu::always_inline]], apply_to = function)
#pragma clang attribute push ([[gnu::flatten]], apply_to = function)
#include <boost/config.hpp>
#include <boost/function.hpp>
#pragma GCC visibility push (internal)
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/iterator.hpp>
#include <boost/fusion/adapted.hpp>
#include <boost/fusion/functional.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/repository/include/qi_seek.hpp>
#include <boost/spirit/repository/include/qi_subrule.hpp>
#pragma GCC visibility pop
#pragma clang attribute pop
#pragma clang attribute pop
namespace ircd {
namespace spirit
__attribute__((visibility("default")))
{
template<class parent_error> struct expectation_failure;
IRCD_EXCEPTION(ircd::error, error);
IRCD_EXCEPTION(error, generator_error);
IRCD_EXCEPTION(generator_error, buffer_overrun);
}}
namespace ircd {
namespace spirit
__attribute__((visibility("internal")))
{
namespace phx = boost::phoenix;
namespace fusion = boost::fusion;
namespace spirit = boost::spirit;
namespace ascii = spirit::ascii;
namespace karma = spirit::karma;
namespace qi = spirit::qi;
using _val_type = phx::actor<spirit::attribute<0>>;
using _r0_type = phx::actor<spirit::attribute<0>>;
using _r1_type = phx::actor<spirit::attribute<1>>;
using _r2_type = phx::actor<spirit::attribute<2>>;
using _r3_type = phx::actor<spirit::attribute<3>>;
using spirit::unused_type;
using spirit::auto_;
using spirit::_pass;
using spirit::_val;
using qi::locals;
using qi::_a;
using qi::_a_type;
using qi::_r1_type;
using qi::raw;
using qi::omit;
using qi::matches;
using qi::hold;
using qi::eoi;
using qi::eps;
using qi::expect;
using qi::attr;
using qi::attr_cast;
using qi::repeat;
using qi::lit;
using qi::char_;
using qi::byte_;
using qi::string;
using qi::short_;
using qi::ushort_;
using qi::word;
using qi::big_word;
using qi::little_word;
using qi::int_;
using qi::uint_;
using qi::dword;
using qi::big_dword;
using qi::little_dword;
using qi::long_;
using qi::ulong_;
using qi::qword;
using qi::big_qword;
using qi::little_qword;
using qi::float_;
using qi::bin_float;
using qi::big_bin_float;
using qi::little_bin_float;
using qi::double_;
using qi::bin_double;
using qi::big_bin_double;
using qi::little_bin_double;
using spirit::repository::qi::seek;
using karma::lit;
using karma::char_;
using karma::long_;
using karma::double_;
using karma::bool_;
using karma::eps;
using karma::attr_cast;
using karma::maxwidth;
using karma::buffer;
using karma::skip;
using prop_mask = mpl_::int_
<
karma::generator_properties::no_properties
| karma::generator_properties::buffering
| karma::generator_properties::counting
| karma::generator_properties::tracking
| karma::generator_properties::disabling
>;
using sink_type = karma::detail::output_iterator<char *, prop_mask, unused_type>;
template<size_t idx,
class semantic_context>
auto &
attr_at(semantic_context&&);
template<size_t idx,
class semantic_context>
auto &
local_at(semantic_context&&);
}}
namespace ircd::spirit::local
{
using qi::_0;
using qi::_1;
using qi::_2;
using qi::_3;
}
namespace ircd {
namespace spirit
__attribute__((visibility("default")))
{
// parse.cc
extern thread_local char rule_buffer[64];
extern thread_local struct generator_state *generator_state;
}}
namespace ircd {
namespace spirit
__attribute__((visibility("internal")))
{
struct substring_view;
struct custom_parser;
BOOST_SPIRIT_TERMINAL(custom);
template<class gen,
class... attr>
bool parse(const char *&start, const char *const &stop, gen&&, attr&&...);
template<class parent_error,
size_t error_show_max = 48,
class gen,
class... attr>
bool parse(const char *&start, const char *const &stop, gen&&, attr&&...);
template<bool truncation = false,
class gen,
class... attr>
bool generate(mutable_buffer &out, gen&&, attr&&...);
}}
namespace ircd
{
using spirit::generate;
using spirit::parse;
}
namespace boost {
namespace spirit
__attribute__((visibility("internal")))
{
namespace qi
{
template<class modifiers>
struct make_primitive<ircd::spirit::tag::custom, modifiers>;
}
template<>
struct use_terminal<qi::domain, ircd::spirit::tag::custom>
:mpl::true_
{};
}}
struct [[gnu::visibility("internal")]]
ircd::spirit::custom_parser
:qi::primitive_parser<custom_parser>
{
template<class context,
class iterator>
struct attribute
{
using type = iterator;
};
template<class context>
boost::spirit::info what(context &) const
{
return boost::spirit::info("custom");
}
template<class iterator,
class context,
class skipper,
class attr>
bool parse(iterator &, const iterator &, context &, const skipper &, attr &) const;
};
template<class modifiers>
struct [[gnu::visibility("internal")]]
boost::spirit::qi::make_primitive<ircd::spirit::tag::custom, modifiers>
{
using result_type = ircd::spirit::custom_parser;
result_type operator()(unused_type, unused_type) const
{
return result_type{};
}
};
struct ircd::spirit::substring_view
:ircd::string_view
{
using _iterator = boost::spirit::karma::detail::indirect_iterator<const char *>;
using _iterator_range = boost::iterator_range<_iterator>;
using ircd::string_view::string_view;
explicit substring_view(const _iterator_range &range)
:ircd::string_view
{
std::addressof(*range.begin()), std::addressof(*range.end())
}
{}
};
template<class parent_error>
struct __attribute__((visibility("default")))
ircd::spirit::expectation_failure
:parent_error
{
template<class it = const char *>
expectation_failure(const qi::expectation_failure<it> &e,
const ssize_t &show_max = 64);
template<class it = const char *>
expectation_failure(const qi::expectation_failure<it> &e,
const it &start,
const ssize_t &show_max = 64);
};
template<class parent>
template<class it>
ircd::spirit::expectation_failure<parent>::expectation_failure(const qi::expectation_failure<it> &e,
const ssize_t &show_max)
:parent
{
"Expected %s. You input %zd invalid characters :%s",
ircd::string(rule_buffer, e.what_),
std::distance(e.first, e.last),
string_view{e.first, e.first + std::min(std::distance(e.first, e.last), show_max)}
}
{}
template<class parent>
template<class it>
ircd::spirit::expectation_failure<parent>::expectation_failure(const qi::expectation_failure<it> &e,
const it &start,
const ssize_t &show_max)
:parent
{
"Expected %s. You input %zd invalid characters somewhere between position %zd and %zd :%s",
ircd::string(rule_buffer, e.what_),
std::distance(e.first, e.last),
std::distance(start, e.first),
std::distance(start, e.last),
string_view{e.first, e.first + std::min(std::distance(e.first, e.last), show_max)}
}
{}
struct [[gnu::visibility("hidden")]]
ircd::spirit::generator_state
{
/// Destination buffer (used like window_buffer).
mutable_buffer &out;
/// Current consumption count of the destination buffer.
ssize_t consumed {0};
/// The number of attemtped generated characters to the destination. This
/// can be larger than the consumed counter to indicate the destination
/// buffer is insufficient. Note that characters are otherwise quietly
/// discarded when the destination (out) is full.
ssize_t generated {0};
/// Internal state for buffer_sink::copy()
ssize_t last_generated {0}, last_width {0};
/// Count of rejected from the destination buffer.
ssize_t overflow {0};
};
template<bool truncation,
class gen,
class... attr>
[[using gnu: always_inline, gnu_inline]]
extern inline bool
ircd::spirit::generate(mutable_buffer &out,
gen&& g,
attr&&... a)
{
const auto max(size(out));
const auto start(data(out));
struct generator_state state
{
out
};
const scope_restore _state
{
generator_state, &state
};
sink_type sink
{
begin(out)
};
const auto ret
{
karma::generate(sink, std::forward<gen>(g), std::forward<attr>(a)...)
};
if constexpr(truncation)
{
assert(begin(out) <= end(out));
begin(out) = state.overflow? end(out): begin(out);
assert(!state.overflow || begin(out) == end(out));
assert(begin(out) <= end(out));
return ret;
}
if(unlikely(state.overflow || begin(out) > end(out)))
{
char pbuf[2][48];
const auto required
{
max + state.overflow?:
std::distance(start, begin(out))
};
assert(begin(out) <= end(out));
throw buffer_overrun
{
"Insufficient buffer of %s; required at least %s",
pretty(pbuf[0], iec(max)),
pretty(pbuf[1], iec(required)),
};
}
assert(begin(out) >= end(out) - max);
assert(begin(out) <= end(out));
return ret;
}
template<class parent_error,
size_t error_show_max,
class gen,
class... attr>
[[using gnu: always_inline, gnu_inline, artificial]]
extern inline bool
ircd::spirit::parse(const char *&start,
const char *const &stop,
gen&& g,
attr&&... a)
try
{
return qi::parse(start, stop, std::forward<gen>(g), std::forward<attr>(a)...);
}
catch(const qi::expectation_failure<const char *> &e)
{
throw expectation_failure<parent_error>
{
e, start, error_show_max
};
}
template<class gen,
class... attr>
[[using gnu: always_inline, gnu_inline, artificial]]
extern inline bool
ircd::spirit::parse(const char *&start,
const char *const &stop,
gen&& g,
attr&&... a)
{
return qi::parse(start, stop, std::forward<gen>(g), std::forward<attr>(a)...);
}
template<size_t idx,
class semantic_context>
inline auto &
ircd::spirit::local_at(semantic_context&& c)
{
return boost::fusion::at_c<idx>(c.locals);
}
template<size_t idx,
class semantic_context>
inline auto &
ircd::spirit::attr_at(semantic_context&& c)
{
return boost::fusion::at_c<idx>(c.attributes);
}
namespace boost::spirit::karma::detail
{
template<> bool buffer_sink::copy(ircd::spirit::sink_type &, size_t maxwidth) const;
template<> void buffer_sink::output(const char &);
}
template<>
inline void
boost::spirit::karma::detail::position_policy::output(const char &value)
{
}
#if 0
template<>
template<>
inline void
boost::spirit::karma::detail::counting_policy<ircd::spirit::sink_type>::output(const char &value)
{
}
#endif
#if 0
template<>
inline bool
boost::spirit::karma::detail::buffering_policy::output(const char &value)
{
if(likely(this->buffer != nullptr))
{
this->buffer->output(value);
return false;
}
else return true;
}
#endif
template<>
inline void
boost::spirit::karma::detail::buffer_sink::output(const char &value)
{
assert(ircd::spirit::generator_state);
#if __has_builtin(__builtin_assume)
__builtin_assume(ircd::spirit::generator_state != nullptr);
#endif
auto &state
{
*ircd::spirit::generator_state
};
const auto &consumed
{
ircd::consume(state.out, ircd::copy(state.out, value))
};
assert(consumed <= 1UL);
this->width += consumed;
state.overflow += !consumed;
state.generated++;
}
template<>
inline bool
boost::spirit::karma::detail::buffer_sink::copy(ircd::spirit::sink_type &sink,
size_t maxwidth)
const
{
assert(ircd::spirit::generator_state);
#if __has_builtin(__builtin_assume)
__builtin_assume(ircd::spirit::generator_state != nullptr);
#endif
auto &state
{
*ircd::spirit::generator_state
};
assert(state.last_generated >= 0);
assert(state.generated >= state.last_generated);
const auto &width_diff
{
state.last_generated == state.generated?
ssize_t(this->width) - state.last_width:
ssize_t(this->width)
};
assert(width_diff >= -state.consumed);
assert(state.generated >= state.consumed);
state.consumed += width_diff;
assert(state.consumed >= 0);
const auto &rewind_count
{
state.generated - state.consumed
};
const auto &rewind
{
rewind_count >= 0L?
std::min(rewind_count, state.generated):
0L
};
assert(rewind >= 0L);
assert(rewind <= state.generated);
std::get<0>(state.out) -= rewind;
state.generated -= rewind;
assert(state.generated >= 0);
state.last_generated = state.generated;
state.last_width = this->width;
return true; //sink.good();
}
template<>
inline bool
boost::spirit::karma::detail::buffer_sink::copy_rest(ircd::spirit::sink_type &sink,
size_t start_at)
const
{
assert(false);
return true; //sink.good();
}
template<>
inline bool
ircd::spirit::sink_type::good()
const
{
return true;
}
#endif // HAVE_IRCD_SPIRIT_H
<file_sep>// Matrix Construct
//
// Copyright (C) Matrix Construct Developers, Authors & Contributors
// Copyright (C) 2016-2019 <NAME> <<EMAIL>>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice is present in all copies. The
// full license for this software is available in the LICENSE file.
/// Given a buffer of CBOR this function parses the head data and maintains
/// a const_buffer span of the head. The span includes the leading head byte
/// and one or more integer bytes following the leading byte. If the major
/// type found in this head has a data payload which is not a following-integer
/// then that data starts directly after this head buffer ends.
///
/// The argument buffer must be at least one byte and must at least cover the
/// following-integer bytes (and can also be as large as possible).
///
ircd::cbor::head::head(const const_buffer &buf)
:const_buffer{[&buf]
{
if(unlikely(size(buf) < sizeof(uint8_t)))
throw buffer_underrun
{
"Item buffer is too small to contain a header"
};
const uint8_t &leading
{
*reinterpret_cast<const uint8_t *>(data(buf))
};
return const_buffer
{
data(buf), length(leading)
};
}()}
{
if(unlikely(size(*this) > size(buf)))
throw buffer_underrun
{
"Item buffer is too small to contain full header"
};
}
/// Pun a reference to the integer contained by the bytes following the head.
/// If there are no bytes following the head because the integer is contained
/// as bits packed into the leading head byte, this function will throw.
///
template<class T>
const T &
ircd::cbor::head::following()
const
{
if(unlikely(size(following()) < sizeof(T)))
throw buffer_underrun
{
"Buffer following header is too small (%zu) for type requiring %zu",
size(following()),
sizeof(T)
};
return *reinterpret_cast<const T *>(data(following()));
}
/// Return buffer spanning the integer bytes following this head. This may be
/// an empty buffer if the integer byte is packed into bits of the leading
/// byte (denoted by minor()).
ircd::const_buffer
ircd::cbor::head::following()
const
{
return { data(*this) + 1, length() - 1 };
}
/// Extract the length of the head from the buffer (requires 1 byte of buffer)
size_t
ircd::cbor::head::length()
const
{
return length(leading());
}
/// Extract the minor type from the reference to the leading byte in the head.
enum ircd::cbor::minor
ircd::cbor::head::minor()
const
{
return static_cast<enum minor>(minor(leading()));
}
/// Extract the major type from the reference to the leading byte in the head.
enum ircd::cbor::major
ircd::cbor::head::major()
const
{
return static_cast<enum major>(major(leading()));
}
/// Reference the leading byte of the head.
const uint8_t &
ircd::cbor::head::leading()
const
{
assert(size(*this) >= sizeof(uint8_t));
return *reinterpret_cast<const uint8_t *>(data(*this));
}
/// Extract length of head from leading head byte (arg); this is the length of
/// the integer following the leading head byte plus the one leading head
/// byte. This length covers all bytes which come before item payload bytes
/// (when such a payload exists). If this length is 1 then no integer bytes
/// are following the leading head byte. The length/returned value is never 0.
size_t
ircd::cbor::head::length(const uint8_t &a)
{
switch(major(a))
{
case POSITIVE:
case NEGATIVE:
case BINARY:
case STRING:
case ARRAY:
case OBJECT:
case TAG:
{
if(minor(a) > 23) switch(minor(a))
{
case minor::U8: return 2;
case minor::U16: return 3;
case minor::U32: return 5;
case minor::U64: return 9;
default: throw type_error
{
"Unknown minor type (%u); length of header unknown", minor(a)
};
}
else return 1;
}
case PRIMITIVE:
{
if(minor(a) > 23) switch(minor(a))
{
case FALSE:
case TRUE:
case NUL:
case UD: return 1;
case minor::F16: return 3;
case minor::F32: return 5;
case minor::F64: return 9;
default: throw type_error
{
"Unknown primitive minor type (%u); length of header unknown", minor(a)
};
}
else return 1;
}
default: throw type_error
{
"Unknown major type; length of header unknown"
};
}
}
/// Extract major type from leading head byte (arg)
uint8_t
ircd::cbor::head::major(const uint8_t &a)
{
// shift for higher 3 bits only
static const auto shift(5);
return a >> shift;
}
/// Extract minor type from leading head byte (arg)
uint8_t
ircd::cbor::head::minor(const uint8_t &a)
{
// mask of lower 5 bits only
static const uint8_t mask
{
uint8_t(0xFF) >> 3
};
return a & mask;
}
//
// cbor.h
//
enum ircd::cbor::major
ircd::cbor::major(const const_buffer &buf)
{
const head head(buf);
return head.major();
}
ircd::string_view
ircd::cbor::reflect(const enum major &major)
{
switch(major)
{
case major::POSITIVE: return "POSITIVE";
case major::NEGATIVE: return "NEGATIVE";
case major::BINARY: return "BINARY";
case major::STRING: return "STRING";
case major::ARRAY: return "ARRAY";
case major::OBJECT: return "OBJECT";
case major::TAG: return "TAG";
case major::PRIMITIVE: return "PRIMITIVE";
}
return "??????";
}
| 1088578cf78dc8cdc4c05adebfc922cb15637d3f | [
"Markdown",
"C++"
] | 15 | C++ | refaqtor/construct | dd17ba9decb3177edf6e8182ffaf760505cc05b3 | 25dbd267349815733fe41e60ef5d1e9eb4d5f270 |
refs/heads/master | <repo_name>STr355/Circle<file_sep>/main.py
import pygame
import random
pygame.init()
windowWidth = 2560
windowHeight = 1380
BLACK = [0, 0, 0]
window = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
window.fill(BLACK)
pygame.display.flip()
pygame.display.set_caption("Snake")
run = True
class Circle:
def __init__(self, window, xPos, yPos, radius):
self.window = window
self.xPos = xPos
self.yPos = yPos
self.color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
self.radius = radius
self.xDir = 0
self.yDir = 0
self.velocity = 0
self.generateDirection()
def draw(self):
pygame.draw.circle(self.window, self.color, (self.xPos, self.yPos), self.radius)
def generateNewColor(self):
red = random.randint(0, 255)
green = random.randint(0, 255)
blue = random.randint(0, 255)
self.color = [red, green, blue]
def increaseRadius(self):
if self.radius < windowHeight / 8:
self.radius += 5
def reduceRadius(self):
if self.radius > 20:
self.radius -= 5
def generateDirection(self):
self.xDir = random.randint(-2, 2)
self.yDir = random.randint(-2, 2)
self.vel = self.xDir * self.yDir
if self.xDir == 0 and self.yDir == 0:
self.generateDirection()
def move(self):
self.xPos += self.xDir
self.yPos += self.yDir
if self.xPos - self.radius <= 0:
self.bounceOffWall(0)
if self.xPos + self.radius >= windowWidth:
self.bounceOffWall(2)
if self.yPos - self.radius <= 0:
self.bounceOffWall(1)
if self.yPos + self.radius >= windowHeight:
self.bounceOffWall(3)
def bounceOffWall(self, border):
if border == 0:
self.xDir = random.randint(1, 2)
self.yDir = random.randint(-2, 2)
elif border == 1:
self.yDir = random.randint(1, 2)
self.xDir = random.randint(-2, 2)
elif border == 2:
self.xDir = random.randint(-2, -1)
self.yDir = random.randint(-2, 2)
elif border == 3:
self.yDir = random.randint(-2, -1)
self.xDir = random.randint(-2, 2)
self.generateNewColor()
def bounceOffCircle(self):
pass
circles = []
circle = Circle(window, windowWidth / 2, windowHeight / 2, random.randint(10, 50))
circles.append(circle)
while run:
if random.randint(1, 1000) > 990:
circles.append(
Circle(window, random.randint(0, windowWidth), random.randint(0, windowHeight), random.randint(10, 150)))
if len(circles) > 200:
circles.pop()
pygame.time.delay(5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
circle.generateNewColor()
elif keys[pygame.K_UP]:
circle.increaseRadius()
elif keys[pygame.K_DOWN]:
circle.reduceRadius()
elif keys[pygame.K_ESCAPE]:
run = False
window.fill(BLACK)
for circle in circles:
circle.draw()
circle.move()
pygame.display.update()
pygame.quit()
| 4be1e71ef8b306e759510e214d7c3d6f9ef02e6e | [
"Python"
] | 1 | Python | STr355/Circle | 6943c9aabecb40c83f70c87962057c92c0943bd2 | 8864122b7b1f97b714fd6ac80f9ebadde330c76c |
refs/heads/master | <repo_name>praveenkrjha/HackApp<file_sep>/IndoorNavigation/IndoorNavigation/Services/RestService.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace IndoorNavigation.Services
{
public class RestService
{
private static string responseString;
private static string inputDataString;
public async Task<string> PostRequestRaw(string url, string data)
{
try
{
var client = new System.Net.Http.HttpClient();
responseString = null;
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpResponseMessage response;
request.ContentType = "application/json";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
request.Headers.Add("RequestToken", AppConstants.RequestToken);
inputDataString = data;
//client.DefaultRequestHeaders.Add("Authorization", AppConstants.user_id);
var content = new StringContent(data, Encoding.UTF8, "application/json");
response = await client.PostAsync(new Uri(url), content);
var placesJson = response.Content.ReadAsStringAsync().Result;
return placesJson;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data1 = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
var ErrorResponse = reader.ReadToEnd();
}
}
return null;
}
catch (Exception ex)
{
return null;
}
//return responseString;
}
public string GetRequestRaw(string url)
{
try
{
responseString = null;
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpResponseMessage response;
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "GET";
//request.Headers.Add("Authorization", AppConstants.user_id);
Stream resStream = request.GetResponse().GetResponseStream();
StreamReader streamRead = new StreamReader(resStream);
responseString = streamRead.ReadToEnd();
return responseString;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
}
return null;
}
catch (Exception ex)
{
return null;
}
//return responseString;
}
public async Task<string> GetRequestRawAsync(string url)
{
try
{
HttpClient wc = new HttpClient();
wc.DefaultRequestHeaders.Add("RequestToken", AppConstants.RequestToken);
wc.DefaultRequestHeaders.Add("Content-Type", "application/json");
try
{
var resp = await wc.GetStringAsync(url);
return resp;
}
catch (Exception ex)
{
return null;
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
}
return null;
}
catch (Exception ex)
{
return null;
}
//return responseString;
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/RestClient/RestClient.cs
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace IndoorNavigation
{
public class RestClient : IRestClient, IDisposable
{
enum HttpVerbs
{
Get,
Post,
Put,
Delete
}
private const string UserInfoHeader = "UserInfo";
private const string RequestToken = "RequestToken";
private const string SecurityToken = "SecurityToken";
private const string RequestTokenValue = "B7A6A1F06D8A48BE826BBD184D0BBE17F224C661DABBD9B581ADAA7F2D56A375";
//private const string RequestTokenValue = "<KEY>";
private string baseUrl;
private readonly HttpClient RestHttpClient;
public RestClient()
{
RestHttpClient = new HttpClient();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Gets or sets the base URL.
/// </summary>
/// <value>The base URL.</value>
public string BaseUrl
{
get { return baseUrl; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("base url is not defined");
}
baseUrl = value;
}
}
#region Private Methods
private string AddHeadersAndGetRestUrl(string url, params object[] args)
{
return string.Format(BaseUrl + string.Format(url, args));
}
/// <summary>
/// function to handle the exceptions thrown by the api
/// </summary>
/// <returns>exception</returns>
private Exception HandleException(string restUrl, Exception ex)
{
if (!(ex is HttpRequestException))
return ex;
var message = new StringBuilder($"Request Failed: {restUrl}");
if (ex.InnerException == null)
{
message.Append($"\n {ex.Message}");
return new HttpRequestException(message.ToString(), ex);
}
message.Append($"\n {ex.InnerException.Message}");
return new HttpRequestException(message.ToString(), ex.InnerException);
}
private async Task<HttpResponseMessage> GetHttpResponse(HttpVerbs httpVerb, string restUrl, object objectPayLoad, params object[] args)
{
RestHttpClient.DefaultRequestHeaders.Clear();
RestHttpClient.DefaultRequestHeaders.Add(RequestToken, RequestTokenValue);
string securityToken = string.Empty;
if (App.Current.Properties.ContainsKey("SecurityToken"))
{
securityToken = Convert.ToString(App.Current.Properties["SecurityToken"]);
}
if (!string.IsNullOrEmpty(securityToken))
RestHttpClient.DefaultRequestHeaders.Add(SecurityToken, securityToken);
var response = new HttpResponseMessage();
// var payLoad = objectPayLoad == null ? string.Empty : JsonConvert.SerializeObject(objectPayLoad);
try
{
response = await RestHttpClient.GetAsync(restUrl);
response.EnsureSuccessStatusCodeEx();
}
catch (Exception ex)
{
throw HandleException(restUrl, ex);
}
return response;
}
private async Task<HttpResponseMessage> GetHttpResponse<T>(HttpVerbs httpVerb, string restUrl, T payLoad, params object[] args)
{
var response = new HttpResponseMessage();
RestHttpClient.DefaultRequestHeaders.Clear();
RestHttpClient.DefaultRequestHeaders.Add(RequestToken, RequestTokenValue);
string securityToken = string.Empty;
if (App.Current.Properties.ContainsKey("SecurityToken"))
{
securityToken = Convert.ToString(App.Current.Properties["SecurityToken"]);
}
if (!string.IsNullOrEmpty(securityToken))
RestHttpClient.DefaultRequestHeaders.Add(SecurityToken, securityToken);
RestHttpClient.Timeout = TimeSpan.FromSeconds(30);
try
{
HttpMethod httpMethod;
switch (httpVerb)
{
case HttpVerbs.Get:
httpMethod = HttpMethod.Get;
break;
case HttpVerbs.Post:
httpMethod = HttpMethod.Post;
break;
case HttpVerbs.Put:
httpMethod = HttpMethod.Put;
break;
case HttpVerbs.Delete:
httpMethod = HttpMethod.Delete;
break;
default:
throw new ArgumentOutOfRangeException(nameof(httpVerb), httpVerb, null);
}
var myContent = JsonConvert.SerializeObject(payLoad);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
var requestMessage = new HttpRequestMessage(httpMethod, restUrl);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
requestMessage.Content = byteContent;
response = await RestHttpClient.SendAsync(requestMessage).ConfigureAwait(false);
}
catch (Exception ex)
{
throw HandleException(restUrl, ex);
}
response.EnsureSuccessStatusCodeEx();
return response;
}
#endregion
/// <summary>
/// GetAsync method for generic return types like class,enumerable etc.21
/// Exception in this method need to be handled by calling method.
/// </summary>
public async Task<T> GetAsync<T>(string url, params object[] args)
{
var json = await GetAsync(url, args);
var serializedObject = JsonConvert.DeserializeObject<T>(json);
return serializedObject;
}
/// <summary>
/// GetAsync method for type void.
/// </summary>
/// <param name="url"></param>
/// <param name="args"></param>
/// <returns></returns>
public async Task<string> GetAsync(string url, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Get, restUrl, null, args);
var jsonResult = await response.Content.ReadAsStringAsync();
return jsonResult;
}
/// <summary>
/// DeleteASync method.
/// </summary>
/// <param name="url">URL</param>
/// <param name="args">Arguments</param>
/// <returns></returns>
public async Task DeleteAsync(string url, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
await GetHttpResponse(HttpVerbs.Delete, restUrl, null, args);
}
/// <summary>
/// Call DELETE method of Rest Api with Payload of type TPayload and expecting result of type TResult
/// </summary>
/// <param name="url">Url of the Rest Resource with placeholders for argument</param>
/// <param name="payload">Payload to be posted to Rest api</param>
/// <param name="args">Values for placeholder arguments</param>
/// <returns>Value of type TResult</returns>
public async Task<string> DeleteAsync(string url, object payload, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Delete, restUrl, payload, args);
return await response.Content.ReadAsStringAsync();
}
/// <summary>
/// Call DELETE method of Rest Api with Payload of type TPayload and expecting result of type TResult
/// </summary>
/// <typeparam name="TPayload">Type of Payload</typeparam>
/// <typeparam name="TResult">Type of Result</typeparam>
/// <param name="url">Url of the Rest Resource with placeholders for argument</param>
/// <param name="payload">Payload to be posted to Rest api</param>
/// <param name="args">Values for placeholder arguments</param>
/// <returns>Value of type TResult</returns>
public async Task<TResult> DeleteAsync<TPayload, TResult>(string url, TPayload payload, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Delete, restUrl, payload, args);
var json = await response.Content.ReadAsStringAsync();
var serializer = JsonConvert.DeserializeObject<TResult>(json);
return serializer;
}
/// <summary>
/// Call DELETE method of Rest Api with Payload of type T
/// </summary>
/// <typeparam name="T">Type of Payload</typeparam>
/// <param name="url">Url of the Rest Resource with placeholders for argument</param>
/// <param name="payload">Payload to be posted to Rest api</param>
/// <param name="args">Values for placeholder arguments</param>
/// <returns></returns>
public async Task DeleteAsync<T>(string url, T payload, params object[] args)
{
try
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Delete, restUrl, payload, args);
}
catch (Exception ex)
{
var errorMessage = ex.Message;
}
}
/// <summary>
/// </summary>
/// <param name="url"></param>
/// <param name="payload"></param>
/// <param name="args"></param>
/// <returns></returns>
public async Task<string> PostAsync(string url, object payload, params object[] args)
{
try
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Post, restUrl, payload, args);
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
var errorMessage = ex.Message;
return null;
}
}
/// <summary>
/// Call POST method of Rest Api with Payload of type TPayload and expecting result of type TResult
/// </summary>
/// <typeparam name="TPayload">Type of Payload</typeparam>
/// <typeparam name="TResult">Type of Result</typeparam>
/// <param name="url">Url of the Rest Resource with placeholders for argument</param>
/// <param name="payload">Payload to be posted to Rest api</param>
/// <param name="args">Values for placeholder arguments</param>
/// <returns>Value of type TResult</returns>
public async Task<TResult> PostAsync<TPayload, TResult>(string url, TPayload payload, params object[] args)
{
try
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Post, restUrl, payload, args);
var json = await response.Content.ReadAsStringAsync();
var serializer = JsonConvert.DeserializeObject<TResult>(json);
return serializer;
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// Call POST method of Rest Api with Payload of type T
/// </summary>
/// <typeparam name="T">Type of Payload</typeparam>
/// <param name="url">Url of the Rest Resource with placeholders for argument</param>
/// <param name="payload">Payload to be posted to Rest api</param>
/// <param name="args">Values for placeholder arguments</param>
/// <returns></returns>
public async Task PostAsync<T>(string url, T payload, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
await GetHttpResponse(HttpVerbs.Post, restUrl, payload, args);
}
/// <summary>
/// </summary>
/// <param name="url"></param>
/// <param name="payload"></param>
/// <param name="args"></param>
/// <returns></returns>
public async Task<string> PutAsync(string url, object payload, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Put, restUrl, payload, args);
return await response.Content.ReadAsStringAsync();
}
/// <summary>
/// PostAsync method for sending post request
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">Post URL</param>
/// <param name="payload">Arguments to be sent in post body</param>
/// <param name="args">Arguments to be sent in query string</param>
/// <returns></returns>
public async Task PutAsync<T>(string url, T payload, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
await GetHttpResponse(HttpVerbs.Put, restUrl, payload, args);
}
/// <summary>
/// PostAsync method for sending post request
/// </summary>
/// <param name="url">Post URL</param>
/// <param name="payload">Arguments to be sent in post body</param>
/// <param name="args">Arguments to be sent in query string</param>
/// <returns></returns>
public async Task<TResult> PutAsync<TPayload, TResult>(string url, TPayload payload, params object[] args)
{
var restUrl = AddHeadersAndGetRestUrl(url, args);
var response = await GetHttpResponse(HttpVerbs.Put, restUrl, payload, args);
var json = await response.Content.ReadAsStringAsync();
var serializer = JsonConvert.DeserializeObject<TResult>(json);
return serializer;
}
// The bulk of the clean-up code is implemented in Dispose(bool)
protected virtual void Dispose(bool disposing)
{
if (disposing && RestHttpClient != null)
{
RestHttpClient.Dispose();
}
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/ItemListViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using Xamarin.Forms;
using JDA.Entities.Response;
using System.Collections.ObjectModel;
using IndoorNavigation.Helpers;
namespace IndoorNavigation
{
public class ItemListViewModel : INotifyPropertyChanged
{
private ObservableCollection<MyProducts> _Products;
private ObservableCollection<MyProducts> _Facilities;
private MyProducts _SelectedFacilitate;
public MyProducts SelectedFacilitate
{
get
{
return _SelectedFacilitate;
}
set
{
_SelectedFacilitate = value;
OnPropertyChanged("SelectedFacilitate");
if (_SelectedFacilitate != null)
{
}
}
}
private MyProducts _SelectedProduct;
public MyProducts SelectedProduct
{
get
{
return _SelectedProduct;
}
set
{
_SelectedProduct = value;
OnPropertyChanged("SelectedProduct");
if(_SelectedProduct != null)
{
}
}
}
public ObservableCollection<MyProducts> Products
{
get
{
return _Products;
}
set
{
_Products = value;
OnPropertyChanged("Products");
}
}
public ObservableCollection<MyProducts> Facilities
{
get
{
return _Facilities;
}
set
{
_Facilities = value;
OnPropertyChanged("Facilities");
}
}
public ItemListViewModel()
{
LoadItems();
}
private void LoadItems()
{
Device.BeginInvokeOnMainThread(async () =>
{
try
{
var restClient = new RestClient();
var resp = await restClient.GetAsync<ServiceResponse<ProductsAndFacilities>>(AppConstants.BaseUrl + "Product");
if (resp.IsSuccess && resp.Data != null)
{
Products = new ObservableCollection<MyProducts>();
foreach(var item in resp.Data.Products)
{
var pd = new MyProducts
{
Id = item.Id,
Name = item.Name,
Description = item.Description,
LocationX = item.LocationX,
LocationY = item.LocationY,
};
switch(pd.Name)
{
case "Water Bottle":
pd.Source = "waterbottle.png";
break;
case "Fridge":
pd.Source = "fridge.png";
break;
case "TV":
pd.Source = "tv.png";
break;
default:
break;
}
Products.Add(pd);
}
Facilities = new ObservableCollection<MyProducts>();
foreach (var item in resp.Data.Facilities)
{
var pd = new MyProducts
{
Id = item.Id,
Name = item.Name,
Description = item.Description,
LocationX = item.LocationX,
LocationY = item.LocationY,
};
switch (pd.Name)
{
case "Entry":
pd.Source = "openeddoor.png";
break;
case "Exit":
pd.Source = "closeddoor.png";
break;
default:
break;
}
Facilities.Add(pd);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/LocateItemPage.xaml.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace IndoorNavigation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LocateItemPage : ContentPage
{
private Timer timer;
private Timer myTimer;
//public static ConcurrentBag<BeaconModel> FoundBeacons = new ConcurrentBag<BeaconModel>();
bool flag = false;
void TimerCallback(object obj)
{
var frmNew = abs.Children[1] as Frame;
if (!flag)
frmNew.ScaleTo(0, 1000, Easing.CubicIn);
else
frmNew.ScaleTo(1, 1000, Easing.CubicIn);
flag = !flag;
}
private void MyTimerCallback(object state)
{
if (IndoorLayout.FoundBeacons.Count >= 3)
{
myTimer.Change(Timeout.Infinite, Timeout.Infinite);
var e = IndoorLayout.FoundBeacons.ToList();
foreach (var item in e)
{
item.Rssi = (int)Utilities.CalcMedianRssi(item.Rssis);
}
IndoorLayout.FoundBeacons = new ConcurrentBag<BeaconModel>();
//Add your logic to draw the location
Device.BeginInvokeOnMainThread(() =>
{
try
{
if (abs.Children.Count > 2)
abs.Children.RemoveAt(2);
var point = IndoorLayout.GetMedianPoint(e[0], e[1], (e.Count == 3 ? e[2] : null));
if (e.Count == 2)
AppConstants.PositionHeight = 50;
else if (e.Count >= 3)
AppConstants.PositionHeight = 30;
//var yPer = ((point.Y / 720) * 100);
//var y = (yPer / 100) * (AppConstants.FloorLength - 10);
//var xPer = ((point.X / 1650) * 100);
//var x = (xPer / 100) * (AppConstants.FloorWidth - 10);
var yPer = ((point.Y / 720) * 100);
var y = (yPer / 100) * (246);
var xPer = ((point.X / 1650) * 100);
var x = (xPer / 100) * (570);
Frame frmNew = new Frame();
frmNew.HeightRequest = AppConstants.PositionHeight;
frmNew.WidthRequest = AppConstants.PositionHeight;
frmNew.CornerRadius = (float)AppConstants.PositionHeight / 2;
frmNew.BackgroundColor = AppConstants.PositionColor;
abs.Children.Add(frmNew, new Rectangle(y, x, AppConstants.PositionHeight, AppConstants.PositionHeight));
}
catch
{
}
});
}
myTimer.Change(2000, 2000);
}
public LocateItemPage (int xCoordinate, int yCoordinate)
{
timer = new Timer(TimerCallback, null, 1000, 1000);
myTimer = new Timer(MyTimerCallback, null, 2000, 2000);
InitializeComponent ();
double xPlace = xCoordinate;
double yPlace = yCoordinate;
var yPer = ((yPlace / 720) * 100);
var y = (yPer / 100) * (246);
var xPer = ((xPlace / 1650) * 100);
var x = (xPer / 100) * (570);
var frmNew = new Frame();
frmNew.HeightRequest = 30;
frmNew.WidthRequest = 30;
frmNew.CornerRadius = 15;
frmNew.BackgroundColor = Color.Gold;
abs.Children.Add(frmNew, new Rectangle(y, x, 30, 30));
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation.Android/RangeNotifier.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using RadiusNetworks.IBeaconAndroid;
namespace IndoorNavigation.Droid
{
public class RangeEventArgs : EventArgs
{
public Region Region { get; set; }
public ICollection<IBeacon> Beacons { get; set; }
}
public class RangeNotifier : Java.Lang.Object, IRangeNotifier
{
public event EventHandler<RangeEventArgs> DidRangeBeaconsInRegionComplete;
public void DidRangeBeaconsInRegion(ICollection<IBeacon> beacons, Region region)
{
OnDidRangeBeaconsInRegion(beacons, region);
}
private void OnDidRangeBeaconsInRegion(ICollection<IBeacon> beacons, Region region)
{
if (DidRangeBeaconsInRegionComplete != null)
{
DidRangeBeaconsInRegionComplete(this, new RangeEventArgs { Beacons = beacons, Region = region });
}
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation.Android/CustomRenderer/EntryRenderer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using IndoorNavigation.Droid.CustomRenderer;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Entry), typeof(BorderEntryRenderer))]
namespace IndoorNavigation.Droid.CustomRenderer
{
public class BorderEntryRenderer : EntryRenderer
{
public BorderEntryRenderer(Context context)
: base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
var nativeEditText = (EditText)Control;
nativeEditText.TextAlignment = Android.Views.TextAlignment.Center;
var shape = new ShapeDrawable(new Android.Graphics.Drawables.Shapes.OvalShape());
shape.Paint.Color = Xamarin.Forms.Color.Black.ToAndroid();
shape.Paint.SetStyle(Paint.Style.Stroke);
nativeEditText.Background = shape;
GradientDrawable gd = new GradientDrawable();
gd.SetColor(Android.Graphics.Color.White);
gd.SetCornerRadius(20);
gd.SetStroke(2, Android.Graphics.Color.LightGray);
//nativeEditText.SetPadding(10, 15, 3, 15);
nativeEditText.SetBackground(gd);
}
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/Utilities.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace IndoorNavigation
{
public class Utilities
{
public static string GetSha256Hash(string text)
{
using (var sha256 = SHA256.Create())
{
var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(text));
// Get the hashed string.
var strBuilder = new StringBuilder();
foreach (byte x in hashedBytes)
{
strBuilder.Append(string.Format("{0:x2}", x));
}
return strBuilder.ToString();
}
}
public static PointF GetLocationWithCenterOfGravity(PointF a, PointF b, PointF c, double dA, double dB, double dC)
{
var METERS_IN_COORDINATE_UNITS_RATIO = 1.0f;
//Find Center of Gravity
var cogX = (a.X + b.X + c.X) / 3;
var cogY = (a.Y + b.Y + c.Y) / 3;
var cog = new PointF(cogX, cogY);
//Nearest Beacon
PointF nearestBeacon;
double shortestDistanceInMeters;
if (dA <= dB && dA <= dC)
{
nearestBeacon = a;
shortestDistanceInMeters = dA;
}
else if (dB < dC)
{
nearestBeacon = b;
shortestDistanceInMeters = dB;
}
else
{
nearestBeacon = c;
shortestDistanceInMeters = dC;
}
//http://www.mathplanet.com/education/algebra-2/conic-sections/distance-between-two-points-and-the-midpoint
//Distance between nearest beacon and COG
var distanceToCog = (float)(Math.Sqrt(Math.Pow(cog.X - nearestBeacon.X, 2)
+ Math.Pow(cog.Y - nearestBeacon.Y, 2)));
//Convert shortest distance in meters into coordinates units.
var shortestDistanceInCoordinationUnits = shortestDistanceInMeters * METERS_IN_COORDINATE_UNITS_RATIO;
//http://math.stackexchange.com/questions/46527/coordinates-of-point-on-a-line-defined-by-two-other-points-with-a-known-distance?rq=1
//On the line between Nearest Beacon and COG find shortestDistance point apart from Nearest Beacon
var t = shortestDistanceInCoordinationUnits / distanceToCog;
var pointsDiff = new PointF(cog.X - nearestBeacon.X, cog.Y - nearestBeacon.Y);
var tTimesDiff = new PointF(pointsDiff.X * t, pointsDiff.Y * t);
//Add t times diff with nearestBeacon to find coordinates at a distance from nearest beacon in line to COG.
var userLocation = new PointF(nearestBeacon.X + tTimesDiff.X, nearestBeacon.Y + tTimesDiff.Y);
return userLocation;
}
public static double CalculateDistanceFromRssi(int rssi)
{
return Math.Pow(10, ((float)(rssi + 65) * -1) / 40) * 100;
}
public static double CalcMedianRssi(List<int> rssis)
{
int numberCount = rssis.Count();
int halfIndex = rssis.Count() / 2;
var sortedNumbers = rssis.OrderBy(n => n);
double median;
if ((numberCount % 2) == 0)
{
median = ((sortedNumbers.ElementAt(halfIndex) + sortedNumbers.ElementAt(halfIndex - 1)) / 2);
//median = ((sortedNumbers.ElementAt(halfIndex) + sortedNumbers.ElementAt(2)));
}
else
{
median = sortedNumbers.ElementAt(halfIndex);
}
return median;
}
public static PointF GetLocationWithCenterOfGravity(PointF a, PointF b, double dA, double dB)
{
var METERS_IN_COORDINATE_UNITS_RATIO = 1.0f;
//Find Center of Gravity
var cogX = (a.X + b.X) / 2;
var cogY = (a.Y + b.Y) / 2;
var cog = new PointF(cogX, cogY);
//Nearest Beacon
PointF nearestBeacon;
double shortestDistanceInMeters;
if (dA <= dB)
{
nearestBeacon = a;
shortestDistanceInMeters = dA;
}
else
{
nearestBeacon = b;
shortestDistanceInMeters = dB;
}
//http://www.mathplanet.com/education/algebra-2/conic-sections/distance-between-two-points-and-the-midpoint
//Distance between nearest beacon and COG
var distanceToCog = (float)(Math.Sqrt(Math.Pow(cog.X - nearestBeacon.X, 2)
+ Math.Pow(cog.Y - nearestBeacon.Y, 2)));
//Convert shortest distance in meters into coordinates units.
var shortestDistanceInCoordinationUnits = shortestDistanceInMeters * METERS_IN_COORDINATE_UNITS_RATIO;
//http://math.stackexchange.com/questions/46527/coordinates-of-point-on-a-line-defined-by-two-other-points-with-a-known-distance?rq=1
//On the line between Nearest Beacon and COG find shortestDistance point apart from Nearest Beacon
var t = shortestDistanceInCoordinationUnits / distanceToCog;
var pointsDiff = new PointF(cog.X - nearestBeacon.X, cog.Y - nearestBeacon.Y);
var tTimesDiff = new PointF(pointsDiff.X * t, pointsDiff.Y * t);
//Add t times diff with nearestBeacon to find coordinates at a distance from nearest beacon in line to COG.
var userLocation = new PointF(nearestBeacon.X + tTimesDiff.X, nearestBeacon.Y + tTimesDiff.Y);
return userLocation;
}
}
public class PointF
{
public double X { get; set; }
public double Y { get; set; }
public PointF(double x, double y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return "X : " + this.X + " ; Y : " + this.Y;
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/Services/APIManager.cs
using Newtonsoft.Json;
using System.Threading.Tasks;
namespace IndoorNavigation.Services
{
class APIManager
{
public static RestService restService = new RestService();
//public async static Task<string> ValidateUser(ValidateUserInput ValidateUserInput)
//{
// try
// {
// var validateUserJson = JsonConvert.SerializeObject(ValidateUserInput);
// return await restService.PostRequestRaw(AppConstants.BaseUrl + "ValidateUser", validateUserJson);
// }
// catch
// {
// return null;
// }
//}
public async static Task<string> RegisterUser(string PassKey)
{
try
{
return await restService.GetRequestRawAsync(AppConstants.BaseUrl + "ValidateUser");
}
catch
{
return null;
}
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/IndoorLayout.xaml.cs
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace IndoorNavigation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class IndoorLayout : ContentPage
{
private Timer timer;
public static ConcurrentBag<BeaconModel> FoundBeacons = new ConcurrentBag<BeaconModel>();
public static double CalculateDistanceFromRssi(int rssi)
{
return Math.Pow(10, ((float)(rssi + 65) * -1) / 40) * 100;
}
private double CalcMedianRssi(List<int> rssis)
{
int numberCount = rssis.Count();
int halfIndex = rssis.Count() / 2;
var sortedNumbers = rssis.OrderBy(n => n);
double median;
if ((numberCount % 2) == 0)
{
median = ((sortedNumbers.ElementAt(halfIndex) + sortedNumbers.ElementAt(halfIndex - 1))/2);
//median = ((sortedNumbers.ElementAt(halfIndex) + sortedNumbers.ElementAt(2)));
}
else
{
median = sortedNumbers.ElementAt(halfIndex);
}
return median;
}
public static PointF GetMedianPoint(BeaconModel a, BeaconModel b, BeaconModel c = null)
{
PointF point = null;
if (c == null)
{
var dist1 = CalculateDistanceFromRssi(a.Rssi);
var dist2 = CalculateDistanceFromRssi(b.Rssi);
point = Utilities.GetLocationWithCenterOfGravity(new PointF(a.Major, a.Minor), new PointF(b.Major, b.Minor)
, dist1, dist2);
}
else
{
var dist1 = CalculateDistanceFromRssi(a.Rssi);
var dist2 = CalculateDistanceFromRssi(b.Rssi);
var dist3 = CalculateDistanceFromRssi(c.Rssi);
point = Utilities.GetLocationWithCenterOfGravity(new PointF(a.Major, a.Minor), new PointF(b.Major, b.Minor)
, new PointF(c.Major, c.Minor), dist1, dist2, dist3);
}
return point;
}
private void TimerCallback(object state)
{
if (FoundBeacons.Count >= 2)
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
//timer = new Timer(TimerCallback, null, Timeout.Infinite, Timeout.Infinite);
var e = FoundBeacons.ToList();
foreach(var item in e)
{
item.Rssi = (int)CalcMedianRssi(item.Rssis);
}
FoundBeacons = new ConcurrentBag<BeaconModel>();
//Add your logic to draw the location
Device.BeginInvokeOnMainThread(() =>
{
try
{
if(abs.Children.Count > 1)
abs.Children.RemoveAt(1);
var point = GetMedianPoint(e[0], e[1], (e.Count == 3 ? e[2] : null));
if (e.Count == 2)
AppConstants.PositionHeight = 50;
else if(e.Count >= 3)
AppConstants.PositionHeight = 30;
var yPer = ((point.Y / 720) * 100);
var y = (yPer / 100) * (240 - 10);
var xPer = ((point.X / 1650) * 100);
var x = (xPer / 100) * (552 - 10);
//var yPer = ((point.Y / 720) * 100);
//var y = (yPer / 100) * (AppConstants.FloorLength - 10);
// var xPer = ((point.X / 1650) * 100);
//var x = (xPer / 100) * (AppConstants.FloorWidth - 10);
Frame frmNew = new Frame();
frmNew.HeightRequest = AppConstants.PositionHeight;
frmNew.WidthRequest = AppConstants.PositionHeight;
frmNew.CornerRadius = (float)AppConstants.PositionHeight/2;
frmNew.BackgroundColor = AppConstants.PositionColor;
abs.Children.Add(frmNew, new Rectangle(y, x, AppConstants.PositionHeight, AppConstants.PositionHeight));
}
catch
{
}
});
}
timer.Change(3000, 3000);
//timer = new Timer(TimerCallback, null, 2000, 2000);
}
public IndoorLayout ()
{
timer = new Timer(TimerCallback, null, 3000, 3000);
InitializeComponent ();
//PointF point = Utilities.GetLocationWithCenterOfGravity(new PointF(829, 0), new PointF(414, 720), new PointF(1244, 720), 60, 100, 100);
//var yPer = ((point.Y / 150) * 100);
//var y = (yPer / 100) * (Application.Current.MainPage.Height - 10);
//var xPer = ((point.X / 150) * 100);
//var x = (xPer / 100) * (Application.Current.MainPage.Width - 10);
//Frame frmNew = new Frame();
//frmNew.HeightRequest = 10;
//frmNew.WidthRequest = 10;
//frmNew.CornerRadius = 5;
//frmNew.BackgroundColor = Color.Blue;
//abs.Children.Add(frmNew, new Rectangle(x, y, 10, 10));
//point = Utilities.GetLocationWithCenterOfGravity(new PointF(829, 0), new PointF(829, 720), new PointF(1244, 720), 600, 400, 150);
//yPer = ((point.Y / 720) * 100);
//y = (yPer / 100) * (552 - 10);
//xPer = ((point.X / 1650) * 100);
//x = (xPer / 100) * (240 - 10);
//frmNew = new Frame();
//frmNew.HeightRequest = 30;
//frmNew.WidthRequest = 30;
//frmNew.CornerRadius = 15;
//frmNew.BackgroundColor = Color.FromHex("#106DE9");
//abs.Children.Add(frmNew, new Rectangle(x, y, 30, 30));
//MessagingCenter.Subscribe<LstBeacons, List<BeaconModel>>(this, "Data", (s, e) =>
// {
// Device.BeginInvokeOnMainThread(() =>
// {
// try
// {
// abs.Children.RemoveAt(1);
// point = Utilities.GetLocationWithCenterOfGravity(new PointF(e[0].Major, e[0].Minor), new PointF(e[1].Major, e[1].Minor)
// , new PointF(e[2].Major, e[2].Minor), e[0].Distance, e[1].Distance, e[2].Distance);
// yPer = ((point.Y / 720) * 100);
// y = (yPer / 100) * (552 - 10);
// xPer = ((point.X / 1650) * 100);
// x = (xPer / 100) * (240 - 10);
// frmNew = new Frame();
// frmNew.HeightRequest = 10;
// frmNew.WidthRequest = 10;
// frmNew.CornerRadius = 5;
// frmNew.BackgroundColor = Color.Blue;
// abs.Children.Add(frmNew, new Rectangle(x, y, 10, 10));
// }
// catch
// {
// }
// });
//});
}
void ChangeLoc(double Dist1, double Dist2, double Dist3)
{
var point= Utilities.GetLocationWithCenterOfGravity(new PointF(829, 0), new PointF(414, 720), new PointF(1244, 720),Dist1, Dist2, Dist3);
var yPer = ((point.Y / 150) * 100);
var y = (yPer / 100) * (Application.Current.MainPage.Height - 10);
var xPer = ((point.X / 150) * 100);
var x = (xPer / 100) * (Application.Current.MainPage.Width - 10);
Frame frmNew = new Frame();
frmNew.HeightRequest = 10;
frmNew.WidthRequest = 10;
frmNew.CornerRadius = 5;
frmNew.BackgroundColor = Color.Blue;
abs.Children.Add(frmNew, new Rectangle(x, y, 10, 10));
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/DistanceModel.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace IndoorNavigation
{
public class DistanceModel
{
public double Dist1 { get; set; }
public double Dist2 { get; set; }
public double Dist3 { get; set; }
public double total
{
get { return Dist1 + Dist2 + Dist3; }
set
{
MessagingCenter.Send(this, "Data", Dist1 + "," + Dist2 + "," + Dist3);
}
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/RestClient/HttpClientEx.cs
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace IndoorNavigation
{
public static class HttpClientEx
{
/// <summary>
/// Method is responsible to catch the Restclient errors, make the custom exception as RestClientFailureException
/// and set the all required parameters
/// </summary>
/// <param name="sender">HttpResponseMessage </param>
public static void EnsureSuccessStatusCodeEx(this HttpResponseMessage sender)
{
if (sender.StatusCode == HttpStatusCode.OK)
return;
//Get the message from the sender which is used to forward the error message
var message = sender.ReasonPhrase;
throw new Exception(message);
}
private static async Task<HttpResponseMessage> GetHttpResponse(HttpMethod method, string url,
string payloadAsJson, HttpClient httpClient)
{
var request = new HttpRequestMessage(method, url);
if (string.IsNullOrEmpty(payloadAsJson))
return await httpClient.SendAsync(request);
request.Content = new StringContent(payloadAsJson);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return await httpClient.SendAsync(request);
}
public static async Task<HttpResponseMessage> DeleteAsJsonAsync(this HttpClient httpClient, string url,
string payloadAsJson)
{
return await GetHttpResponse(HttpMethod.Delete, url, payloadAsJson, httpClient);
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/MenuPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace IndoorNavigation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MenuPage : ContentPage
{
public MenuPage()
{
InitializeComponent();
try
{
lblUser.Text = "Welcome " + App.Current.Properties["User"].ToString();
}
catch { }
}
private async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
try
{
const int _animationTime = 20;
await OuterStk.ScaleTo(1.2, _animationTime);
await OuterStk.ScaleTo(1, _animationTime);
await Navigation.PushAsync(new LocatedItemsPage());
}
catch (Exception ez)
{
ez.Message.ToString();
}
}
private async void TapGestureRecognizer_Tapped_1(object sender, EventArgs e)
{
try
{
const int _animationTime = 20;
await WhereamiStk.ScaleTo(1.2, _animationTime);
await WhereamiStk.ScaleTo(1, _animationTime);
await Navigation.PushAsync(new IndoorLayout());
}
catch
{
}
}
private async void TapGestureRecognizer_Tapped_2(object sender, EventArgs e)
{
try
{
const int _animationTime = 20;
await MarkAttendance.ScaleTo(1.2, _animationTime);
await MarkAttendance.ScaleTo(1, _animationTime);
await Navigation.PushAsync(new MarkAttendancePage());
}
catch
{
}
}
private async void TapGestureRecognizer_Tapped_3(object sender, EventArgs e)
{
try
{
const int _animationTime = 20;
await ViewAttendance.ScaleTo(1.2, _animationTime);
await ViewAttendance.ScaleTo(1, _animationTime);
await Navigation.PushAsync(new AttendancePage());
}
catch { }
}
private void TapGestureRecognizer_Tapped_4(object sender, EventArgs e)
{
try
{
App.Current.Properties.Clear();
App.Current.MainPage = new NavigationPage(new MainPage());
}
catch { }
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/LocatedItemsPage.xaml.cs
using IndoorNavigation.Helpers;
using JDA.Entities.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace IndoorNavigation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LocatedItemsPage : ContentPage
{
ItemListViewModel Vm;
public LocatedItemsPage()
{
InitializeComponent();
Vm = new ItemListViewModel();
this.BindingContext = Vm;
if(Vm != null && Vm.Products != null && Vm.Products.Count>0)
{
LstView.HeightRequest = Vm.Products.Count * 80;
}
else
{
//LstView.HeightRequest = 0;
}
if (Vm != null && Vm.Facilities != null && Vm.Facilities.Count > 0)
{
LstView1.HeightRequest = Vm.Facilities.Count * 80;
}
else
{
//LstView1.HeightRequest = 0;
}
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var item = ((sender as Grid).BindingContext as MyProducts);
Navigation.PushAsync(new LocateItemPage(item.LocationX, item.LocationY));
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation.Android/MainActivity.cs
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android;
using Plugin.Permissions;
using RadiusNetworks.IBeaconAndroid;
using Android.Support.V4.App;
using Android.Content;
using System.Drawing;
using System.Linq;
using System.Collections.Generic;
namespace IndoorNavigation.Droid
{
[Activity(Label = "IndoorNavigation", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IBeaconConsumer
{
readonly string[] PermissionsLocation =
{
Manifest.Permission.AccessCoarseLocation,
Manifest.Permission.AccessFineLocation,Manifest.Permission.UseFingerprint
};
const int RequestLocationId = 0;
int _previousProximity;
private const string UUID = "c42da800-1afb-450c-9a50-5322f762cc4c";
private const string beaconApp = "JDA-Hack";
bool _paused;
View _view;
IBeaconManager _iBeaconManager;
MonitorNotifier _monitorNotifier;
RangeNotifier _rangeNotifier;
Region _monitoringRegion;
Region _rangingRegion;
public MainActivity()
{
_iBeaconManager = IBeaconManager.GetInstanceForApplication(this);
_monitorNotifier = new MonitorNotifier();
_rangeNotifier = new RangeNotifier();
_monitoringRegion = new Region(beaconApp, UUID, null, null);
_rangingRegion = new Region(beaconApp, UUID, null, null);
}
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
AndroidEnvironment.UnhandledExceptionRaiser += HandleAndroidException;
base.OnCreate(savedInstanceState);
Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);
RequestPermissions(PermissionsLocation, RequestLocationId);
_iBeaconManager.Bind(this);
_monitorNotifier.EnterRegionComplete += EnteredRegion;
_monitorNotifier.ExitRegionComplete += ExitedRegion;
_rangeNotifier.DidRangeBeaconsInRegionComplete += RangingBeaconsInRegion;
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
void HandleAndroidException(object sender, RaiseThrowableEventArgs e)
{
e.Handled = true;
Console.Write("HANDLED EXCEPTION");
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
protected override void OnResume()
{
base.OnResume();
_paused = false;
}
protected override void OnPause()
{
base.OnPause();
_paused = true;
}
void EnteredRegion(object sender, MonitorEventArgs e)
{
if (_paused)
{
ShowNotification();
}
}
void ExitedRegion(object sender, MonitorEventArgs e)
{
}
void RangingBeaconsInRegion(object sender, RangeEventArgs e)
{
Console.WriteLine("Found beacons :" + e.Beacons.Count);
foreach (var item in e.Beacons)
{
Console.WriteLine(" Beacon Major : " + item.Major + " Minor : " + item.Minor);
//var dist = Math.Pow(10, ((float)(item.Rssi + 65) * -1) / 40) * 100;
var beaconItem = IndoorLayout.FoundBeacons.FirstOrDefault(x => x.Major == item.Major && x.Minor == item.Minor);
if (beaconItem != null)
{
if(beaconItem.Rssis == null)
{
beaconItem.Rssis = new List<int>();
}
//if (item.Rssi > beaconItem.Rssi)
{
beaconItem.Rssis.Add(item.Rssi);
//beaconItem.Distance = dist;
}
}
else
{
IndoorLayout.FoundBeacons.Add(new BeaconModel
{
Major = item.Major,
Minor = item.Minor,
Rssis = new List<int>() { item.Rssi },
// Distance = dist,
DetectTime = DateTime.Now
});
}
}
//if (e.Beacons.Count < 3)
//{
// Console.WriteLine("Did not find enoough beacons.");
//}
//else
//{
// var beacon = e.Beacons.FirstOrDefault();
// var message = string.Empty;
// var rssi = beacon.Rssi;
// var distance1 = Math.Pow(10, ((float)(rssi + 65) * -1) / 20);
// LstBeacons lstBeacons = new LstBeacons();
// lstBeacons.beaconModels = new List<BeaconModel>();
// foreach (var beac in e.Beacons)
// {
// BeaconModel beaconModel = new BeaconModel();
// beaconModel.Minor = beac.Minor;
// beaconModel.Major = beac.Major;
// beaconModel.Distance = Math.Pow(10, ((float)(beac.Rssi + 65) * -1) / 20) * 100;
// lstBeacons.beaconModels.Add(beaconModel);
// }
// lstBeacons.Flag = 1;
// //DistanceModel distance = new DistanceModel();
// //foreach (var beac in e.Beacons)
// //{
// // if (beac.Major == 829 && beac.Minor == 0)
// // {
// // distance.Dist1 = Math.Pow(10, ((float)(beac.Rssi + 65) * -1) / 20) * 100;
// // }
// // else if (beac.Major == 829 && beac.Minor == 720)
// // {
// // distance.Dist2 = Math.Pow(10, ((float)(beac.Rssi + 65) * -1) / 20) * 100;
// // }
// // else if (beac.Major == 1244 && beac.Minor == 720)
// // {
// // distance.Dist3 = Math.Pow(10, ((float)(beac.Rssi + 65) * -1) / 20) * 100;
// // }
// //}
// //distance.total = distance.Dist1 + distance.Dist2 + distance.Dist3;
// switch ((ProximityType)beacon.Proximity)
// {
// case ProximityType.Immediate:
// UpdateDisplay("You found the monkey!", Color.Green);
// break;
// case ProximityType.Near:
// UpdateDisplay("You're getting warmer", Color.Yellow);
// break;
// case ProximityType.Far:
// UpdateDisplay("You're freezing cold", Color.Blue);
// break;
// case ProximityType.Unknown:
// UpdateDisplay("I'm not sure how close you are to the monkey", Color.Red);
// break;
// }
// _previousProximity = beacon.Proximity;
//}
}
#region IBeaconConsumer impl
public void OnIBeaconServiceConnect()
{
_iBeaconManager.SetMonitorNotifier(_monitorNotifier);
_iBeaconManager.SetRangeNotifier(_rangeNotifier);
_iBeaconManager.StartMonitoringBeaconsInRegion(_monitoringRegion);
_iBeaconManager.StartRangingBeaconsInRegion(_rangingRegion);
}
#endregion
private void UpdateDisplay(string message, Color color)
{
RunOnUiThread(() =>
{
});
}
private void ShowNotification()
{
var resultIntent = new Intent(this, typeof(MainActivity));
resultIntent.AddFlags(ActivityFlags.ReorderToFront);
var pendingIntent = PendingIntent.GetActivity(this, 0, resultIntent, PendingIntentFlags.UpdateCurrent);
var notificationId = 1234;
var builder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Mipmap.icon)
.SetContentTitle("Indoor Navigation")
.SetContentText("Notification")
.SetContentIntent(pendingIntent)
.SetAutoCancel(true);
var notification = builder.Build();
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(notificationId, notification);
}
protected override void OnDestroy()
{
base.OnDestroy();
_monitorNotifier.EnterRegionComplete -= EnteredRegion;
_monitorNotifier.ExitRegionComplete -= ExitedRegion;
_rangeNotifier.DidRangeBeaconsInRegionComplete -= RangingBeaconsInRegion;
_iBeaconManager.StopMonitoringBeaconsInRegion(_monitoringRegion);
_iBeaconManager.StopRangingBeaconsInRegion(_rangingRegion);
_iBeaconManager.UnBind(this);
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/ItemListModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using Xamarin.Forms;
namespace IndoorNavigation
{
public class ItemListModel
{
public string ItemName { get; set; }
public ImageSource Source { get; set; }
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/AttendancePage.xaml.cs
using JDA.Entities.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace IndoorNavigation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AttendancePage : ContentPage
{
public AttendancePage ()
{
InitializeComponent ();
var restClient = new RestClient();
Device.BeginInvokeOnMainThread(async() =>
{
try
{
var resp = await restClient.GetAsync<ServiceResponse<List<AttendenceData>>>(AppConstants.BaseUrl + "Attendance");
lstAttendance.ItemsSource = resp.Data;
}
catch
{
await DisplayAlert("", "Failed to reach server", "Ok");
}
});
lstAttendance.RefreshCommand = new Command(async() => {
//Do your stuff.
try
{
lstAttendance.ItemsSource = null;
var resp = await restClient.GetAsync<ServiceResponse<List<AttendenceData>>>(AppConstants.BaseUrl + "Attendance");
lstAttendance.ItemsSource = resp.Data;
lstAttendance.IsRefreshing = false;
}
catch
{
await DisplayAlert("", "Failed to reach server", "Ok");
}
});
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/FingerprintHandler.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace IndoorNavigation
{
class FingerprintHandler
{
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/MainPage.xaml.cs
using JDA.Entities.Request;
using JDA.Entities.Response;
using System;
using Xamarin.Forms;
namespace IndoorNavigation
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
stkPwd.ScaleTo(0);
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
}
private void Username_Focussed(object sender, FocusEventArgs e)
{
}
private void Password_Focussed(object sender, FocusEventArgs e)
{
}
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
var restClient = new RestClient();
if (!stkPwd.IsVisible)
{
if (string.IsNullOrEmpty(UsernameEntry.Text))
{
await DisplayAlert("", "Enter User name", "Ok");
return;
}
var resp = await restClient.PostAsync<ValidateUserRequest, ServiceResponse<ValidateUserResponse>>(AppConstants.BaseUrl + "ValidateUser", new ValidateUserRequest { EmailId = UsernameEntry.Text });
if (resp != null)
{
if (resp.IsSuccess)
{
await stkUName.ScaleTo(0, 1000, Easing.BounceIn);
stkUName.IsVisible = false;
stkPwd.IsVisible = true;
await stkPwd.ScaleTo(1, 1000, Easing.BounceOut);
if (App.Current.Properties.ContainsKey("SecurityToken"))
{
App.Current.Properties["SecurityToken"] = resp.Data.SecurityToken;
}
else
{
App.Current.Properties.Add("SecurityToken", resp.Data.SecurityToken);
}
}
}
}
else
{
if (string.IsNullOrEmpty(PasswordEntry.Text))
{
await DisplayAlert("", "Enter Password", "Ok");
}
var resp = await restClient.PostAsync<RegisterUserRequest, ServiceResponse<RegisterUserResponse>>(AppConstants.BaseUrl + "RegisterUser", new RegisterUserRequest { EmailId = UsernameEntry.Text, Password = Utilities.GetSha256Hash(PasswordEntry.Text) });
if (resp != null)
{
if (resp.IsSuccess)
{
if (App.Current.Properties.ContainsKey("User"))
{
App.Current.Properties["User"] = resp.Data.UserDetails.FirstName + " " + resp.Data.UserDetails.LastName;
}
else
{
App.Current.Properties.Add("User", resp.Data.UserDetails.FirstName + " " + resp.Data.UserDetails.LastName);
}
App.Current.MainPage = new NavigationPage(new MenuPage());
}
else
{
await DisplayAlert("", "Invalid password", "Ok");
}
}
}
}
catch
{
await DisplayAlert("", "Failed to reach server", "Ok");
}
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/IFingerprint.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace IndoorNavigation
{
public interface IFingerprint
{
void Authenticate();
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/BeaconModel.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace IndoorNavigation
{
public class BeaconModel
{
public int Major { get; set; }
public int Minor { get; set; }
// public double Distance { get; set; }
public List<int> Rssis { get; set; }
public int Rssi { get; set; }
public DateTime DetectTime { get; set; }
}
public class LstBeacons
{
public List<BeaconModel> beaconModels { get; set; }
public int Flag
{
get { return 0; }
set { MessagingCenter.Send(this, "Data", beaconModels); }
}
}
}
<file_sep>/IndoorNavigation/IndoorNavigation/AppConstants.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace IndoorNavigation
{
public class AppConstants
{
public static string BaseUrl = "http://10.104.15.107:53532/api/";
public static string RequestToken = "B7A6A1F06D8A48BE826BBD184D0BBE17F224C661DABBD9B581ADAA7F2D56A375";
public static int FloorLength = 552;
public static int FloorWidth = 240;
public static double PositionHeight = 30;
public static Color PositionColor = Color.FromHex("#106DE9");
}
}
<file_sep>/IndoorNavigation/IndoorNavigation.Android/CustomRenderer/FingerprintHandler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android;
using Android.App;
using Android.Content;
using Android.Hardware.Fingerprints;
using Android.OS;
using Android.Runtime;
using Android.Security.Keystore;
using Android.Support.V4.App;
using Android.Views;
using Android.Widget;
using IndoorNavigation.Droid.CustomRenderer;
using Java.Security;
using Javax.Crypto;
using Xamarin.Forms;
[assembly: Dependency(typeof(FingerprintHandler))]
namespace IndoorNavigation.Droid.CustomRenderer
{
internal class FingerprintHandler : FingerprintManager.AuthenticationCallback, IFingerprint
{
private Context mainActivity; private KeyStore keyStore; private Cipher cipher; private string KEY_NAME = "AutoCloud"; public FingerprintHandler() { this.mainActivity = Forms.Context; }
public override void OnAuthenticationFailed()
{
Toast.MakeText(mainActivity, "Fingerprint Authentication failed!", ToastLength.Long).Show();
}
public override void OnAuthenticationSucceeded(FingerprintManager.AuthenticationResult result)
{
FModel fModel = new FModel();
fModel.flag = true;
Toast.MakeText(mainActivity, "Fingerprint Authentication Successful!", ToastLength.Long).Show();
//MarkAttendancePage.FPNavigate();
}
private bool CipherInit()
{
try
{
cipher = Cipher.GetInstance(KeyProperties.KeyAlgorithmAes + "/" + KeyProperties.BlockModeCbc + "/" + KeyProperties.EncryptionPaddingPkcs7); keyStore.Load(null); IKey key = (IKey)keyStore.GetKey(KEY_NAME, null); cipher.Init(CipherMode.EncryptMode, key); return true;
}
catch (Exception ex)
{
return false;
}
}
private void GenKey()
{
keyStore = KeyStore.GetInstance("AndroidKeyStore");
KeyGenerator keyGenerator = null;
keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");
keyStore.Load(null);
keyGenerator.Init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt).SetBlockModes(KeyProperties.BlockModeCbc).SetUserAuthenticationRequired(true).SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7).Build());
keyGenerator.GenerateKey();
}
internal void StartAuthentication(FingerprintManager fingerprintManager, FingerprintManager.CryptoObject cryptoObject)
{
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.CheckSelfPermission(mainActivity, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted)
return;
fingerprintManager.Authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
public void Authenticate()
{
KeyguardManager keyguardManager = (KeyguardManager)Forms.Context.GetSystemService("keyguard");
FingerprintManager fingerprintManager = (FingerprintManager)Forms.Context.GetSystemService("fingerprint");
if (ActivityCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.UseFingerprint) != (int)Android.Content.PM.Permission.Granted)
return;
if (!fingerprintManager.IsHardwareDetected) Toast.MakeText(Forms.Context, "FingerPrint authentication permission not enable", ToastLength.Short).Show();
else
{
if (!fingerprintManager.HasEnrolledFingerprints)
Toast.MakeText(Forms.Context, "Register at least one fingerprint in Settings", ToastLength.Short).Show();
else
{
if (!keyguardManager.IsKeyguardSecure)
Toast.MakeText(Forms.Context, "Lock screen security not enable in Settings", ToastLength.Short).Show();
else GenKey();
if (CipherInit())
{
FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
StartAuthentication(fingerprintManager, cryptoObject);
}
}
}
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/MarkAttendancePage.xaml.cs
using JDA.Entities.Request;
using JDA.Entities.Response;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace IndoorNavigation
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MarkAttendancePage : ContentPage
{
public MarkAttendancePage()
{
InitializeComponent();
DependencyService.Get<IFingerprint>().Authenticate();
MessagingCenter.Subscribe<FModel>(this, "Hello", async(s) =>
{
MessagingCenter.Unsubscribe<FModel>(this, "Hello");
try
{
bool resp = await MarkAttendance();
if (resp)
{
await DisplayAlert("Info", "Attendance marked", "Ok");
}
else
{
await DisplayAlert("Alert", "Attendance not marked", "OK");
}
await Navigation.PopAsync();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
}
private async Task<bool> MarkAttendance()
{
try
{
var restClient = new RestClient();
var resp = await restClient.PostAsync<BlankRequest, ServiceResponse<string>>(AppConstants.BaseUrl + "Attendance", new BlankRequest { Id = 1 });
return resp.IsSuccess;
}
catch
{
await DisplayAlert("", "Failed to reach server", "Ok");
return false;
}
}
public static void FPNavigate()
{
//await Navigation.PopAsync();
}
}
public class FModel
{
public bool flag
{
get { return true; }
set
{
MessagingCenter.Send(this, "Hello");
}
}
}
}<file_sep>/IndoorNavigation/IndoorNavigation/Helpers/MyProducts.cs
using JDA.Entities.Response;
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace IndoorNavigation.Helpers
{
public class MyProducts : ProductDetail
{
public string Source { get; set; }
}
}
| 3423d5ff9b829e7790a71486d28d4feb38408885 | [
"C#"
] | 24 | C# | praveenkrjha/HackApp | 1d20ea03e949093954fa20c375a5cc304b4e54fd | b6098b79ebef17971bd585ffa35b278a72fd572b |
refs/heads/master | <file_sep>json.extract! bet_player, :id, :participant_id, :player_id, :stage, :score, :created_at, :updated_at
json.url bet_player_url(bet_player, format: :json)
<file_sep>json.array! @bet_topscorers, partial: "bet_topscorers/bet_topscorer", as: :bet_topscorer
<file_sep>json.extract! bet_game, :id, :game_id, :home, :away, :created_at, :updated_at
json.url bet_game_url(bet_game, format: :json)
<file_sep>json.array! @bet_games, partial: "bet_games/bet_game", as: :bet_game
<file_sep>json.extract! bet_topscorer, :id, :participant_id, :player_id, :created_at, :updated_at
json.url bet_topscorer_url(bet_topscorer, format: :json)
<file_sep>require "application_system_test_case"
class Bet::PlayersTest < ApplicationSystemTestCase
setup do
@bet_player = bet_players(:one)
end
test "visiting the index" do
visit bet_players_url
assert_selector "h1", text: "Bet/Players"
end
test "creating a Player" do
visit bet_players_url
click_on "New Bet/Player"
fill_in "Participant", with: @bet_player.participant_id
fill_in "Player", with: @bet_player.player_id
fill_in "Score", with: @bet_player.score
fill_in "Stage", with: @bet_player.stage
click_on "Create Player"
assert_text "Player was successfully created"
click_on "Back"
end
test "updating a Player" do
visit bet_players_url
click_on "Edit", match: :first
fill_in "Participant", with: @bet_player.participant_id
fill_in "Player", with: @bet_player.player_id
fill_in "Score", with: @bet_player.score
fill_in "Stage", with: @bet_player.stage
click_on "Update Player"
assert_text "Player was successfully updated"
click_on "Back"
end
test "destroying a Player" do
visit bet_players_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Player was successfully destroyed"
end
end
<file_sep>class GamesController < ApplicationController
before_action :set_game, only: %i[ show edit update destroy calculate reset_scores]
# GET /games or /games.json
def index
@games = Game.includes(:games, :away, :home).group_by{|x| x.stage_before_type_cast}.sort_by{|k,v| k}
end
# GET /games/1 or /games/1.json
def show
end
# GET /games/new
def new
@game = Game.new
end
# GET /games/1/edit
def edit
end
def calculate
@game.calculate
redirect_to games_url
end
def reset_scores
@game.reset_scores
redirect_to games_url
end
def calculate_stage_scores
Game.calculate_stage_scores(params[:stage])
redirect_to games_url
end
def reset_stage_scores
Game.reset_stage_scores(params[:stage])
redirect_to games_url
end
# POST /games or /games.json
def create
@game = Game.new(game_params)
respond_to do |format|
if @game.save
format.html { redirect_to games_url, notice: "Game was successfully created." }
format.json { render :show, status: :created, location: @game }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @game.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /games/1 or /games/1.json
def update
respond_to do |format|
if @game.update(game_params)
format.html { redirect_to games_url, notice: "Game was successfully updated." }
format.json { render :show, status: :ok, location: @game }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @game.errors, status: :unprocessable_entity }
end
end
end
# DELETE /games/1 or /games/1.json
def destroy
@game.destroy
respond_to do |format|
format.html { redirect_to games_url, notice: "Game was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_game
@game = Game.find(params[:id])
end
# Only allow a list of trusted parameters through.
def game_params
params.require(:game).permit(:nr, :date, :home_id, :away_id, :score_home, :score_away)
end
end
<file_sep>Rails.application.routes.draw do
resources :scores
resources :participants
resources :players do
member do
get :calculate_topplayer
get :calculate_topscorer
get :reset_topplayer_scores
get :reset_topscorer_scores
end
collection do
get :edit_many_topplayers
post :update_many_topplayers
get :edit_many_topscorers
post :update_many_topscorers
end
end
resources :games do
member do
get :calculate
get :reset_scores
end
collection do
get :calculate_stage_scores
get :reset_stage_scores
end
end
resources :teams do
member do
get :calculate_winner
get :calculate_redcard
get :reset_winner_scores
get :reset_redcard_scores
end
collection do
get :edit_many_redcards
post :update_many_redcards
get :edit_many_winners
post :update_many_winners
end
end
namespace :bet do
resources :teams
resources :players
resources :games
end
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
<file_sep>class AddStageToGame < ActiveRecord::Migration[6.1]
def change
add_column :games, :stage, :integer
add_index :games, :stage
end
end
<file_sep>require "application_system_test_case"
class Bet::TeamsTest < ApplicationSystemTestCase
setup do
@bet_team = bet_teams(:one)
end
test "visiting the index" do
visit bet_teams_url
assert_selector "h1", text: "Bet/Teams"
end
test "creating a Team" do
visit bet_teams_url
click_on "New Bet/Team"
fill_in "Participant", with: @bet_team.participant_id
fill_in "Stage", with: @bet_team.stage
fill_in "Team", with: @bet_team.team_id
click_on "Create Team"
assert_text "Team was successfully created"
click_on "Back"
end
test "updating a Team" do
visit bet_teams_url
click_on "Edit", match: :first
fill_in "Participant", with: @bet_team.participant_id
fill_in "Stage", with: @bet_team.stage
fill_in "Team", with: @bet_team.team_id
click_on "Update Team"
assert_text "Team was successfully updated"
click_on "Back"
end
test "destroying a Team" do
visit bet_teams_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Team was successfully destroyed"
end
end
<file_sep>module Pdf::ParticipantHelper
include ::ParticipantsHelper
def print_participant_page(participant)
print_participant_header(participant)
print_games(participant)
h -601
print_eigthfinalists(participant)
print_quarterfinalists(participant)
print_semifinalists(participant)
print_finalists(participant)
print_winner(participant)
print_topplayer(participant)
print_topscorer(participant)
print_redcard(participant)
h 50
print_score(participant)
end
def print_participant_header(participant)
arr = participant_header_array(participant)
pdf.table( arr, :column_widths => [100, 125], :cell_style=>cellstyle , position: 0) do
column(1).style :align => :right
end
h 20
end
def print_games(participant)
arr = games_array(participant)
pdf.table( arr, :column_widths => [60,10,60,10, 25, 10, 25, 25], :cell_style=>cellstyle , position: 0) do
column(7).style :align => :right
rows([0,7,14,21,28,35,42]).style :font_style=> :bold
end
end
def print_eigthfinalists(participant)
arr = eigthfinalists_array(participant)
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
row(-1).style :font_style=> :bold
end
end
def print_quarterfinalists(participant)
arr = quarterfinalists_array(participant)
h 10
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
row(-1).style :font_style=> :bold
end
end
def print_semifinalists(participant)
arr = semifinalists_array(participant)
h 10
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
row(-1).style :font_style=> :bold
end
end
def print_finalists(participant)
arr = finalists_array(participant)
h 10
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
row(-1).style :font_style=> :bold
end
end
def print_winner(participant)
arr = winner_array(participant)
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
end
end
def print_topplayer(participant)
arr = topplayer_array(participant)
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
end
end
def print_topscorer(participant)
arr = []
player = participant.players.find{|x| x.stage=="topscorer"}
arr << ["topscorer",player.player.name, player.score.to_s]
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
end
end
def print_redcard(participant)
arr = redcard_array(participant)
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
column(0).style :font_style=> :bold
end
end
def print_score(participant)
arr = score_array(participant)
pdf.table( arr, :column_widths => [80, 80, 25], :cell_style=>cellstyle , position: 300) do
column(2).style :align => :right
row(0).style :font_style=> :bold
end
end
end<file_sep>json.partial! "bet_games/bet_game", bet_game: @bet_game
<file_sep>module Bet
def self.table_name_prefix
'bet_'
end
end
<file_sep>class ScoresController < ApplicationController
def index
# @participants = Participant.includes(:games, :teams, :players).sort_by{|x| x.score_total}.reverse
@ranking = Participant.ranked
respond_to do |format|
format.pdf {
pdf = Pdf::Scores.new(@ranking)
send_data pdf.pdf.render, :filename=>"scores.pdf",:disposition => 'inline'
}
format.html
end
end
end<file_sep>class Pdf::Participants
include Pdf::PrintPdf
include Pdf::ParticipantHelper
attr_reader :pdf, :printed_on, :participants, :rank
def initialize(participants)
@participants = participants.sort_by{|x| x.score_total}.reverse
@printed_on = nldt(Time.now)
@ranking = @participants.group_by{|x| x.score_total}.sort.reverse.map{|k,v| [k, @participants.index(v.first)+1,v.map(&:id)]}
@pdf = Prawn::Document.new(defaults)
print_participants
footer_with_page_numbers
end
def print_participants
participants.each_with_index do |participant, i|
@rank = @ranking.find{|x| x[2].include?( participant.id )}[1]
print_participant_page(participant)
pdf.start_new_page unless i==participants.size-1
end
end
end
<file_sep>require 'roo'
class ImportFile
attr_accessor :file, :participant
def initialize
@file = Roo::Spreadsheet.open('app/excel/totaal_pool.xlsx')
end
def import_participants
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
part = sheet.cell(3,3)
email = sheet.cell(4,3)
@participant = Participant.new(name: part, email: email)
import_games(sheet)
import_teams(sheet, (9..24), "eightfinal",16)
import_teams(sheet, (29..36), "quarterfinal", 16)
import_teams(sheet, (41..44), "semifinal", 16)
import_teams(sheet, (49..50), "finale",16)
import_teams(sheet, (55..55), "winner",16)
import_teams(sheet, (63..63), "redcard",11)
import_players(sheet)
@participant.save
end
end
def import_games(sheet)
[(9..14), (17..22) ,(25..30), (33..38), (41..46), (49..54)].each do |arr|
arr.to_a.each do |x|
home_id = Team.find_by(name: return_official_team_name(sheet.cell(x,7).strip.downcase ) )&.id
away_id = Team.find_by(name: return_official_team_name(sheet.cell(x,9).strip.downcase ) )&.id
game = Game.find_by(home_id: home_id, away_id: away_id, stage: "pool")
unless game
byebug
end
home = sheet.cell(x,10)
away = sheet.cell(x,12)
@participant.games.build(game_id: game.id, home: home, away: away)
end
end
end
def import_teams(sheet, range, stage, column)
# [(9..24),16], [(29..36),8] ,[(41..44),4], [(49..50),2], [(55..55),1]]
range.to_a.each do |x|
name = sheet.cell(x,column).strip.downcase
name = return_official_team_name(name)
team_id = Team.find_by(name: name )&.id
unless team_id
byebug
end
@participant.teams.build(stage: stage, team_id: team_id)
end
end
def import_players(sheet)
# [(9..24),16], [(29..36),8] ,[(41..44),4], [(49..50),2], [(55..55),1]]
toppscorer = sheet.cell(59,11).strip.downcase
toppscorer = return_official_player_name(toppscorer)
player_id = Player.find_by(name: toppscorer )&.id
unless player_id
byebug
end
@participant.players.build(player_id: player_id, stage: "topscorer")
topplayer = sheet.cell(61,11).strip.downcase
topplayer = return_official_player_name(topplayer)
player_id = Player.find_by(name: topplayer )&.id
unless player_id
byebug
end
@participant.players.build(player_id: player_id, stage: "topplayer")
end
# def import_8_finalists(sheet)
# # [(9..24),16], [(29..36),8] ,[(41..44),4], [(49..50),2], [(55..55),1]]
# (9..24).to_a.each do |x|
# name = sheet.cell(x,16).strip.downcase
# name = return_official_team_name(name)
# team_id = Team.find_by(name: name )&.id
# unless team_id
# byebug
# end
# @participant.teams.build(stage: "eightfinal", team_id: team_id)
# end
# end
def test_participant_names
names = []
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
part = sheet.cell(3,3) || ""
if part.blank?
byebug
else
part = part.strip.downcase
names.push part
end
end
names.map{|x| x.strip.downcase}.uniq.sort
end
def test_participant_email
names = []
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
part = sheet.cell(4,3) || ""
if part.blank?
byebug
else
part = part.strip.downcase
names.push part
end
end
names.map{|x| x.strip.downcase}.uniq.sort
end
def test_games
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
[(9..14), (17..22) ,(25..30), (33..38), (41..46), (49..54)].each do |arr|
a = []
arr.each do |x|
a.push sheet.cell(x,10)
a.push sheet.cell(x,12)
end
if a.compact.size !=12
byebug
end
end
end
end
def test_teams
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
[[(9..24),16], [(29..36),8] ,[(41..44),4], [(49..50),2], [(55..55),1]].each do |arr|
a = []
arr[0].to_a.each do |x|
a.push sheet.cell(x,16)
end
p a.size
if a.size !=arr[1]
byebug
end
if a.compact.size !=arr[1]
byebug
end
end
end
end
def test_team_names
names = []
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
[[(9..24),16], [(29..36),8] ,[(41..44),4], [(49..50),2], [(55..55),1]].each do |arr|
arr[0].to_a.each do |x|
names.push sheet.cell(x,16)
end
end
end
names.map{|x| x.strip.downcase}.uniq.sort
end
def test_red_card
names = []
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
country = sheet.cell(63,11) || ""
if country
country = country.strip.downcase
end
names.push country
unless return_official_team_name(country)
byebug
end
end
names.map{|x| x.strip.downcase}.uniq.sort
end
def test_topscorer
names = []
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
player = sheet.cell(59,11) || ""
if player
player = player.strip.downcase
end
names.push player
unless return_official_player_name(player)
byebug
end
end
names.map{|x| x.strip.downcase}.uniq.sort
end
def test_topplayer
names = []
file.each_with_pagename do |name, sheet|
next if name =~/Totaal/
player = sheet.cell(61,11) || ""
if player
player = player.strip.downcase
end
names.push player
unless return_official_player_name(player)
byebug
end
end
names.map{|x| x.strip.downcase}.uniq.sort
end
# first find all name-entrys, stripped, downcased and uniq as returned by method test_team_names
# list the 24 official names from the database
# try to match each entry by the first 1-2-3-4 letters to only one of an official name
# return the official name
def return_official_team_name(entry)
case entry
when /^au|^oo/
"austria"
when /^be/
"belgium"
when /^ch|^cz|^tj|^ts/
"chech republic"
when /^cr|^kr/
"croatia"
when /^de/
"denmark"
when /^en/
"england"
when /^fi/
"finland"
when /^fr/
"france"
when /^du|^ge/
"germany"
when /^ho/
"hongarije"
when /^it/
"italy"
when /^ma/
"macedonie"
when /^ne/
"netherlands"
when /^pol/
"poland"
when /^por|pot/
"portugal"
when /^ru/
"russia"
when /^sc/
"schotland"
when /^sl/
"slowakije"
when /^sp/
"spain"
when /^swe|^zwe/
"sweden"
when /^swi|^zwi/
"switzerland"
when /^tu/
"turkey"
when /^oe|^uk/
"ukraine"
when /^wa/
"wales"
end
end
end
# first find all player-entrys, stripped, downcased and uniq as returned by method test_topscorer or test_topplayer
# list the 24 official player-names from the database
# try to match each entry by the first 1-2-3-4 letters to only one of an official name
# return the official name
def return_official_player_name(entry)
case entry
when /benz/
"benzema"
when /brui|bruy/
"bruyne"
when /cour/
"courtois"
when /jong/
"de jong"
when /ligt/
"de ligt"
when /depa/
"depay"
when /gnab/
"gnabri"
when /grav/
"gravenberg"
when /hav/
"havertz"
when /immo/
"immobile"
when /ins/
"insigne"
when /kane/
"kane"
when /kant/
"kante"
when /lewa/
"lewandowski"
when /luk/
"lukaku"
when /mba|mapp|mpab/
"mbappe"
when /mor/
"morata"
when /moun/
"mount"
when /rash/
"rashford"
when /rona/
"ronaldo"
when /san/
"sane"
end
end
#player-entrys
# "<NAME>"
# "benzema"
# "<NAME>"
# "<NAME>"
# "depay"
# "<NAME>"
# "havertz"
# "<NAME>"
# "kane"
# "<NAME>"
# "<NAME>"
# "<NAME>"
# "<NAME>"
# "lewandowski"
# "lukaku"
# "mappee"
# "mbappe"
# "mbappé"
# "mpabbe"
# "rashford"
# "<NAME>"
# "<NAME>"
# "courtois"
# "<NAME>"
# "<NAME>"
# "<NAME>"
# "gravenberg"
# "<NAME>"
# "<NAME>"
# "<NAME>)"
# "<NAME>"
# "<NAME>"
# "<NAME>"
# "lewandovski"
# "<NAME>"
# "lukaku"
# "mappee"
# "<NAME>"
# "mbape"
# "mbappe"
# "mbappé"
# "<NAME>"
# "<NAME>"
# "ronaldo"
#entries:
# "austria"
# "begie"
# "belgie"
# "belgium"
# "belgië"
# "chech rep"
# "chech republic"
# "chechrepublic"
# "croatia"
# "croatie"
# "croatië"
# "czech republic"
# "denemarken"
# "denmark"
# "duitsland"
# "duitslang"
# "engeland"
# "engelend"
# "england"
# "finland"
# "france"
# "frankrijk"
# "germany"
# "hongarije"
# "italie"
# "italië"
# "italy"
# "kroatie"
# "kroatië"
# "macedonie"
# "nederland"
# "netherlands"
# "oekraiene"
# "oekraine"
# "oekraïne"
# "oostenrijk"
# "poland"
# "polen"
# "portugal"
# "potugal"
# "rusland"
# "russia"
# "schotland"
# "slowakije"
# "spain"
# "spanje"
# "sweden"
# "switserland"
# "switzerland"
# "tjechie"
# "tjechië"
# "tsjechie"
# "turkey"
# "turkije"
# "turkijke"
# "ukraine"
# "wales"
# "zweden"
# "zwisterland"
# "zwitersland"
# "zwitserland"
<file_sep>class Bet::Team < ApplicationRecord
enum stage: {winner: 6, finale: 5, semifinal: 4, quarterfinal: 3, eightfinal: 2, pool: 1, redcard: 99}
belongs_to :participant
belongs_to :team, class_name: "::Team", optional: true
end
<file_sep>class Bet::Player < ApplicationRecord
enum stage: {topscorer: 1, topplayer: 2}
belongs_to :participant
belongs_to :player, class_name: "::Player", optional: true
end
<file_sep>json.array! @bet_topplayers, partial: "bet_topplayers/bet_topplayer", as: :bet_topplayer
<file_sep>require "application_system_test_case"
class Bet::GamesTest < ApplicationSystemTestCase
setup do
@bet_game = bet_games(:one)
end
test "visiting the index" do
visit bet_games_url
assert_selector "h1", text: "Bet/Games"
end
test "creating a Game" do
visit bet_games_url
click_on "New Bet/Game"
fill_in "Away", with: @bet_game.away
fill_in "Game", with: @bet_game.game_id
fill_in "Home", with: @bet_game.home
click_on "Create Game"
assert_text "Game was successfully created"
click_on "Back"
end
test "updating a Game" do
visit bet_games_url
click_on "Edit", match: :first
fill_in "Away", with: @bet_game.away
fill_in "Game", with: @bet_game.game_id
fill_in "Home", with: @bet_game.home
click_on "Update Game"
assert_text "Game was successfully updated"
click_on "Back"
end
test "destroying a Game" do
visit bet_games_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Game was successfully destroyed"
end
end
<file_sep>json.partial! "bet_topscorers/bet_topscorer", bet_topscorer: @bet_topscorer
<file_sep>json.array! @bet_teams, partial: "bet_teams/bet_team", as: :bet_team
<file_sep>class CreateBetGames < ActiveRecord::Migration[6.1]
def change
create_table :bet_games do |t|
t.integer :participant_id
t.integer :game_id
t.integer :home
t.integer :away
t.integer :score
t.timestamps
end
add_index :bet_games, :participant_id
end
end
<file_sep>require 'prawn'
require 'prawn/table'
require 'prawn/icon'
module Pdf::PrintPdf
Prawn::Font::AFM.hide_m17n_warning = true
include ActiveSupport::NumberHelper
include ApplicationHelper
attr_reader :pdf
# Prawn.debug = true
def defaults
{
:page_size=>'A4',
:page_layout=>:portrait,# or :landscape
:left_margin=>60,
:right_margin=>60,
:top_margin =>50,
:bottom_margin=>60,
:font_size=> 7
}
# :margin,
# :skip_page_creation,
# :compress,
# :background,
# :info,
# :text_formatter,
# :print_scaling
end
def h(options=nil)
pdf.move_down options.to_i
pdf.cursor
end
def logo2014
Rails.root.join('app/assets/images/logo_trans_2014.png')
end
def save
pdf.render_file name
end
def footerlogo
pdf.repeat(:all) do
pdf.image logo2014 ,width: 30, height: 6, :at=>[20,0]
pdf.draw_text "\u00A9", :at => [0, -5], :size=>6
pdf.draw_text "verzorgd door l-plan", :at => [200, -5], :size=>6
end
end
def page_numbers
string = "pagina <page> van <total>"
options = { :at => [pdf.bounds.right - 150, 0],
:width => 150,
:align => :right,
# :page_filter => (1..7),
:start_count_at => 1,
# :color => "007700"
:size=>6
}
pdf.number_pages string, options
end
def footer_with_page_numbers
page_numbers
footerlogo
end
private
def cellstyle
{:height=> 14, :padding => [0, 0, 0, 5], :border_width=> 0, :size => 7 }
end
def reference_style
{:font_style=> :italic, :size=>7 , :height=>20, :border_width=> 0 }
end
def bold_style
{:font_style=> :bold, :size=>7 , :height=>20, :border_width=> 0 }
end
def bolder_style
{:font_style=> :bold, :size=>9 , :height=>25, :border_width=> 0 }
end
def smaller_style
{ :size=>6 , :height=>20, :border_width=> 0 }
end
def vertical_style
{:size=>7 , :valign => :bottom, :rotate => 90, :align=> :left, :height=> 50, :border_width=> 0}
end
end
<file_sep>class Participant < ApplicationRecord
has_many :games, class_name: "Bet::Game", inverse_of: :participant
has_many :teams, class_name: "Bet::Team", inverse_of: :participant
has_many :players, class_name: "Bet::Player", inverse_of: :participant
has_one :redcard, -> { redcard }, class_name: 'Bet::Team', inverse_of: :participant
has_one :winner, -> { winner }, class_name: 'Bet::Team', inverse_of: :participant
has_many :finalists, -> { finale }, class_name: 'Bet::Team', inverse_of: :participant
has_many :semifinalists, -> { semifinal }, class_name: 'Bet::Team', inverse_of: :participant
has_many :quarterfinalists, -> { quarterfinal }, class_name: 'Bet::Team', inverse_of: :participant
has_many :eightfinalists, -> { eightfinal }, class_name: 'Bet::Team', inverse_of: :participant
has_one :topplayer, -> { topplayer }, class_name: 'Bet::Player', inverse_of: :participant
has_one :topscorer, -> { topscorer }, class_name: 'Bet::Player', inverse_of: :participant
scope :sorted, -> {includes(games: {game: [:home, :away] }, teams: :team, players: :player).sort_by{|x| x.score_total}.reverse}
def self.ranking
sorted.map{|x| {x.id => x.score_total} }
end
def self.ranked
includes(games: {game: [:home, :away] }, teams: :team, players: :player).group_by{|x| x.score_total}.sort.reverse.inject({}){|hsh,(pnt,a)| r=hsh.size+1; a.each{|x| hsh[x] = [r, pnt] } ;hsh}
end
def score_winner
winner&.score || 0
end
def score_redcard
redcard&.score || 0
end
def score_games
games.map(&:score).compact.sum
end
def score_finalists
finalists.map(&:score).compact.sum
end
def score_finalists
finalists.map(&:score).compact.sum
end
def score_semifinalists
semifinalists.map(&:score).compact.sum
end
def score_quarterfinalists
quarterfinalists.map(&:score).compact.sum
end
def score_eightfinalists
eightfinalists.map(&:score).compact.sum
end
def score_topplayer
topplayer&.score || 0
end
def score_topscorer
topscorer&.score || 0
end
def score_total
( games.map(&:score) + teams.map(&:score) + players.map(&:score) ).compact.sum
end
end
<file_sep>json.extract! bet_topplayer, :id, :participant_id, :player_id, :created_at, :updated_at
json.url bet_topplayer_url(bet_topplayer, format: :json)
<file_sep>require "test_helper"
class Bet::TeamsControllerTest < ActionDispatch::IntegrationTest
setup do
@bet_team = bet_teams(:one)
end
test "should get index" do
get bet_teams_url
assert_response :success
end
test "should get new" do
get new_bet_team_url
assert_response :success
end
test "should create bet_team" do
assert_difference('Bet::Team.count') do
post bet_teams_url, params: { bet_team: { participant_id: @bet_team.participant_id, stage: @bet_team.stage, team_id: @bet_team.team_id } }
end
assert_redirected_to bet_team_url(Bet::Team.last)
end
test "should show bet_team" do
get bet_team_url(@bet_team)
assert_response :success
end
test "should get edit" do
get edit_bet_team_url(@bet_team)
assert_response :success
end
test "should update bet_team" do
patch bet_team_url(@bet_team), params: { bet_team: { participant_id: @bet_team.participant_id, stage: @bet_team.stage, team_id: @bet_team.team_id } }
assert_redirected_to bet_team_url(@bet_team)
end
test "should destroy bet_team" do
assert_difference('Bet::Team.count', -1) do
delete bet_team_url(@bet_team)
end
assert_redirected_to bet_teams_url
end
end
<file_sep>class Bet::Game < ApplicationRecord
belongs_to :participant
belongs_to :game, class_name: "::Game", optional: true
def home?
home > away
end
def away?
away > home
end
def draw?
home == away
end
def exact?
home == game.score_home and away == game.score_away
end
end
<file_sep>json.extract! game, :id, :nr, :date, :home_id, :away_id, :score_home, :score_away, :created_at, :updated_at
json.url game_url(game, format: :json)
<file_sep>class Bet::GamesController < ApplicationController
before_action :set_bet_game, only: %i[ show edit update destroy ]
# GET /bet/games or /bet/games.json
def index
@bet_games = Bet::Game.all
end
# GET /bet/games/1 or /bet/games/1.json
def show
end
# GET /bet/games/new
def new
@bet_game = Bet::Game.new
end
# GET /bet/games/1/edit
def edit
end
# POST /bet/games or /bet/games.json
def create
@bet_game = Bet::Game.new(bet_game_params)
respond_to do |format|
if @bet_game.save
format.html { redirect_to @bet_game, notice: "Game was successfully created." }
format.json { render :show, status: :created, location: @bet_game }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @bet_game.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /bet/games/1 or /bet/games/1.json
def update
respond_to do |format|
if @bet_game.update(bet_game_params)
format.html { redirect_to @bet_game, notice: "Game was successfully updated." }
format.json { render :show, status: :ok, location: @bet_game }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @bet_game.errors, status: :unprocessable_entity }
end
end
end
# DELETE /bet/games/1 or /bet/games/1.json
def destroy
@bet_game.destroy
respond_to do |format|
format.html { redirect_to bet_games_url, notice: "Game was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_bet_game
@bet_game = Bet::Game.find(params[:id])
end
# Only allow a list of trusted parameters through.
def bet_game_params
params.require(:bet_game).permit(:participant_id, :game_id, :home, :away)
end
end
<file_sep>json.partial! "bet_topplayers/bet_topplayer", bet_topplayer: @bet_topplayer
<file_sep>json.array! @bet_players, partial: "bet_players/bet_player", as: :bet_player
<file_sep>class PlayersController < ApplicationController
before_action :set_player, only: %i[ show edit update destroy calculate_topplayer reset_topplayer_scores calculate_topscorer reset_topscorer_scores]
# GET /players or /players.json
def index
@players = Player.all
end
# GET /players/1 or /players/1.json
def show
end
# GET /players/new
def new
@player = Player.new
end
# GET /players/1/edit
def edit
end
# POST /players or /players.json
def create
@player = Player.new(player_params)
respond_to do |format|
if @player.save
format.html { redirect_to @player, notice: "Player was successfully created." }
format.json { render :show, status: :created, location: @player }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /players/1 or /players/1.json
def update
respond_to do |format|
if @player.update(player_params)
format.html { redirect_to @player, notice: "Player was successfully updated." }
format.json { render :show, status: :ok, location: @player }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
# DELETE /players/1 or /players/1.json
def destroy
@player.destroy
respond_to do |format|
format.html { redirect_to players_url, notice: "Player was successfully destroyed." }
format.json { head :no_content }
end
end
def edit_many_topscorers
@topscorers = Player.joins(:topscorers)
end
def update_many_topscorers
if Player.topscorer
Player.topscorer.reset_topscorer_scores
Player.topscorer.update_attribute(:top, nil)
end
unless params[:id].blank?
@topscorer = Player.find(params[:id])
@topscorer.update_attribute(:top, true)
@topscorer.topscorers.each{|x| x.update_attribute(:score, 5)}
end
redirect_to games_url
end
def edit_many_topplayers
@topplayers = Player.joins(:topplayers)
end
def update_many_topplayers
if Player.topplayer
Player.topplayer.reset_topplayer_scores
Player.topplayer.update_attribute(:best, nil)
end
unless params[:id].blank?
@topplayer = Player.find(params[:id])
@topplayer.update_attribute(:best, true)
@topplayer.topplayers.each{|x| x.update_attribute(:score, 5)}
end
redirect_to games_url
end
def calculate_topplayer
@player.calculate_topplayer
redirect_to games_url
end
def reset_topplayer_scores
@player.reset_topplayer_scores
redirect_to games_url
end
def calculate_topscorer
@player.calculate_topscorer
redirect_to games_url
end
def reset_topscorer_scores
@player.reset_topscorer_scores
redirect_to games_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_player
@player = Player.find(params[:id])
end
# Only allow a list of trusted parameters through.
def player_params
params.require(:player).permit(:name, :initials, :team_id)
end
end
<file_sep>json.extract! bet_team, :id, :participant_id, :stage, :team_id, :created_at, :updated_at
json.url bet_team_url(bet_team, format: :json)
<file_sep>module ApplicationHelper
def nld(date)
date.strftime( '%d %b %Y') if date
end
def nldt(datetime)
datetime.strftime( '%d %b %Y %H:%M') if datetime
end
alias :nldate :nld
def nlt(time)
time.strftime( '%H:%M') if time
end
def dayt(datetime)
datetime.strftime( '%a %d %b %H:%M') if datetime
end
end
<file_sep>class Bet::TeamsController < ApplicationController
before_action :set_bet_team, only: %i[ show edit update destroy ]
# GET /bet/teams or /bet/teams.json
def index
@bet_teams = Bet::Team.all
end
# GET /bet/teams/1 or /bet/teams/1.json
def show
end
# GET /bet/teams/new
def new
@bet_team = Bet::Team.new
end
# GET /bet/teams/1/edit
def edit
end
# POST /bet/teams or /bet/teams.json
def create
@bet_team = Bet::Team.new(bet_team_params)
respond_to do |format|
if @bet_team.save
format.html { redirect_to @bet_team, notice: "Team was successfully created." }
format.json { render :show, status: :created, location: @bet_team }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @bet_team.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /bet/teams/1 or /bet/teams/1.json
def update
respond_to do |format|
if @bet_team.update(bet_team_params)
format.html { redirect_to @bet_team, notice: "Team was successfully updated." }
format.json { render :show, status: :ok, location: @bet_team }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @bet_team.errors, status: :unprocessable_entity }
end
end
end
# DELETE /bet/teams/1 or /bet/teams/1.json
def destroy
@bet_team.destroy
respond_to do |format|
format.html { redirect_to bet_teams_url, notice: "Team was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_bet_team
@bet_team = Bet::Team.find(params[:id])
end
# Only allow a list of trusted parameters through.
def bet_team_params
params.require(:bet_team).permit(:participant_id, :stage, :team_id)
end
end
<file_sep>require "application_system_test_case"
class Bet::TopplayersTest < ApplicationSystemTestCase
setup do
@bet_topplayer = bet_topplayers(:one)
end
test "visiting the index" do
visit bet_topplayers_url
assert_selector "h1", text: "Bet/Topplayers"
end
test "creating a Topplayer" do
visit bet_topplayers_url
click_on "New Bet/Topplayer"
fill_in "Participant", with: @bet_topplayer.participant_id
fill_in "Player", with: @bet_topplayer.player_id
click_on "Create Topplayer"
assert_text "Topplayer was successfully created"
click_on "Back"
end
test "updating a Topplayer" do
visit bet_topplayers_url
click_on "Edit", match: :first
fill_in "Participant", with: @bet_topplayer.participant_id
fill_in "Player", with: @bet_topplayer.player_id
click_on "Update Topplayer"
assert_text "Topplayer was successfully updated"
click_on "Back"
end
test "destroying a Topplayer" do
visit bet_topplayers_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Topplayer was successfully destroyed"
end
end
<file_sep>class CreateBetTeams < ActiveRecord::Migration[6.1]
def change
create_table :bet_teams do |t|
t.integer :participant_id
t.integer :stage
t.integer :team_id
t.integer :score
t.timestamps
end
add_index :bet_teams, :participant_id
add_index :bet_teams, :team_id
add_index :bet_teams, :stage
end
end
<file_sep>class Pdf::Participant
include Pdf::PrintPdf
include Pdf::ParticipantHelper
attr_reader :pdf, :participant, :printed_on, :rank
def initialize(participant)
@participant = participant
@printed_on = nldt(Time.now)
@participants = Participant.includes({games: {game: [:home, :away] }}, {teams: [:team]}, players: :player).sort_by{|x| x.score_total}.reverse
@ranking = @participants.group_by{|x| x.score_total}.sort.reverse.map{|k,v| [k, @participants.index(v.first)+1,v.map(&:id)]}
@rank = @ranking.find{|x| x[2].include?( @participant.id )}[1]
@pdf = Prawn::Document.new(defaults)
print_participant_page(participant)
footer_with_page_numbers
end
end
<file_sep>json.partial! "bet_teams/bet_team", bet_team: @bet_team
<file_sep>class CreateGames < ActiveRecord::Migration[6.1]
def change
create_table :games do |t|
t.integer :nr
t.datetime :date
t.integer :home_id
t.integer :away_id
t.integer :score_home
t.integer :score_away
t.timestamps
end
add_index :games, :nr
add_index :games, :date
add_index :games, :home_id
add_index :games, :away_id
end
end
<file_sep>class ParticipantsController < ApplicationController
before_action :set_participant, only: %i[ show edit update destroy ]
# GET /participants or /participants.json
def index
# @participants = Participant.includes(:games, :teams, :players)
@participants = Participant.includes({games: {game: [:home, :away] }}, {teams: [:team]}, players: :player)
respond_to do |format|
format.pdf {
pdf = Pdf::Participants.new(@participants)
send_data pdf.pdf.render, :filename=>"participants.pdf",:disposition => 'inline'
}
format.html
end
end
# GET /participants/1 or /participants/1.json
def show
respond_to do |format|
format.pdf {
pdf = Pdf::Participant.new(@participant)
send_data pdf.pdf.render, :filename=>"participant.pdf",:disposition => 'inline'
}
format.html
end
end
# GET /participants/new
def new
@participant = Participant.new
end
# GET /participants/1/edit
def edit
end
# POST /participants or /participants.json
def create
@participant = Participant.new(participant_params)
respond_to do |format|
if @participant.save
format.html { redirect_to @participant, notice: "Participant was successfully created." }
format.json { render :show, status: :created, location: @participant }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @participant.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /participants/1 or /participants/1.json
def update
respond_to do |format|
if @participant.update(participant_params)
format.html { redirect_to @participant, notice: "Participant was successfully updated." }
format.json { render :show, status: :ok, location: @participant }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @participant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /participants/1 or /participants/1.json
def destroy
@participant.destroy
respond_to do |format|
format.html { redirect_to participants_url, notice: "Participant was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_participant
@participant = Participant.includes({games: {game: [:home, :away] }}, {teams: [:team]}, players: :player).find(params[:id])
end
# Only allow a list of trusted parameters through.
def participant_params
params.require(:participant).permit(:name, :email)
end
end
<file_sep>class Game < ApplicationRecord
enum stage: {winner: 6, finale: 5, semifinal: 4, quarterfinal: 3, eightfinal: 2, pool: 1, redcard: 99}
belongs_to :home, class_name: "Team", optional: true
belongs_to :away, class_name: "Team", optional: true
has_many :games, class_name: "Bet::Game"
# has_many :teams, class_name: "Bet::Team",
# has_many :teams, -> { Bet::Team.where(stage: "eightfinal", team_id: [1,2]) }
def teams
Bet::Team.where(stage: stage, team_id: [home&.id, away&.id])
end
def calculate
send("calculate_#{stage}")
end
def reset_scores
send("reset_scores_#{stage}")
end
def calculate_pool
return unless score_home and score_away
games.each do |game|
p = 0
if home? and game.home?
p = 3
end
if away? and game.away?
p = 3
end
if draw? and game.draw?
p = 3
end
if game.exact?
p+=2
end
game.update_attribute(:score, p)
end
end
def self.calculate_stage_scores(stage)
if stage == "pool"
self.calculate_pool_scores
else
self.calculate_team_scores(stage)
end
end
def self.reset_stage_scores(stage)
if stage == "pool"
self.reset_scores_pool
else
self.reset_scores_teams(stage)
end
end
def self.calculate_pool_scores
self.pool.each do |game|
game.calculate_pool
end
end
def self.calculate_team_scores(stage)
self.send(stage).each do |game|
game.send("calculate_#{stage}")
end
end
def self.reset_scores_pool
self.pool.each do |game|
game.reset_scores_pool
end
end
def self.reset_scores_teams(stage)
self.send(stage).each do |game|
game.send("reset_scores_#{stage}")
end
end
def self.stage_scores(stage)
if stage == "pool"
Bet::Game.all.map(&:score).compact.sum
else
Bet::Team.send(stage).map(&:score).compact.sum
end
end
def reset_scores_pool
games.each{|x| x.update_attribute(:score, nil)}
end
def calculate_eightfinal
teams.each do |team|
team.update_attribute(:score, 2)
end
end
def reset_scores_eightfinal
teams.each do |team|
team.update_attribute(:score, nil)
end
end
def calculate_quarterfinal
teams.each do |team|
team.update_attribute(:score, 4) if team.team_id
end
end
def reset_scores_quarterfinal
teams.each do |team|
team.update_attribute(:score, nil)
end
end
def calculate_semifinal
teams.each do |team|
team.update_attribute(:score, 6)
end
end
def reset_scores_semifinal
teams.each do |team|
team.update_attribute(:score, nil)
end
end
def calculate_finale
teams.each do |team|
team.update_attribute(:score, 8)
end
end
def reset_scores_finale
teams.each do |team|
team.update_attribute(:score, nil)
end
end
# def calculate_winner
# teams.each do |team|
# team.update_attribute(:score, nil)
# end
# end
# def reset_scores_winner
# teams.each do |team|
# team.update_attribute(:score, nil)
# end
# end
def home?
return unless score_home and score_away
score_home > score_away
end
def away?
return unless score_home and score_away
score_away > score_home
end
def draw?
return unless score_home and score_away
score_home == score_away
end
def score
if stage == "pool"
return unless (home_id and away_id)
games.map(&:score).compact.sum
else
return unless (home_id or away_id)
teams.map(&:score).compact.sum
end
end
end
# Puntentelling
# - Heb je de toto uitslag van een groepswedstrijd goed dan verdien je 3 punten.
# Is de uitslag helemaal juist dan verdien je 5 punten
# - Voor elke goed voorspelde ploeg in de 8e finale verdien je 2 punten
# - Voor elke goed voorspelde ploeg in de 4e finale verdien je 4 punten
# - Voor elke goed voorspelde ploeg in de halve finale verdien je 6 punten
# - Voor elke goed voorspelde ploeg in de finale verdien je 8 punten
# - Voorspel je de winnaar goed dan verdien je 15 punten
# - Voor elke juist beantwoorde bonusvraag verdien je 5 punten <file_sep>json.partial! "bet_players/bet_player", bet_player: @bet_player
<file_sep>class Pdf::Scores
include Pdf::PrintPdf
attr_reader :pdf, :ranking
def initialize(ranking)
@ranking = ranking
@pdf = Prawn::Document.new(defaults)
print_header
print_ranking
footer_with_page_numbers
end
def print_header
pdf.text "freeks poule bijgewerkt t/m #{nldt(Time.now)}"
h 20
arr = [%w(rank name games eightfinal quarterfinal semifinal finale winner redcard topplayer topscorer total)]
pdf.table( arr, :column_widths => [50,100,30,30,30,30,30, 30, 30, 30, 30, 30], :cell_style=> vertical_style)
end
def print_ranking
arr = []
prev = 0
# arr << %w(rank name games eightfinal quarterfinal semifinal finale winner redcard topplayer topscorer total)
ranking.each do |part, v|
rank = v[0]
score = v[1]
(score == prev) ? print_rank = "" : print_rank = rank
g = part.games.map(&:score).compact.sum
e = part.teams.select{|x| x.stage == 'eightfinal'}.map(&:score).compact.sum
q = part.teams.select{|x| x.stage == 'quarterfinal'}.map(&:score).compact.sum
s = part.teams.select{|x| x.stage == 'semifinal'}.map(&:score).compact.sum
f = part.teams.select{|x| x.stage == 'finale'}.map(&:score).compact.sum
w = part.teams.select{|x| x.stage == 'winner'}.map(&:score).compact.sum
r = part.teams.select{|x| x.stage == 'redcard'}.map(&:score).compact.sum
tp = part.players.select{|x| x.stage == 'topplayer'}.map(&:score).compact.sum
ts = part.players.select{|x| x.stage == 'topscorer'}.map(&:score).compact.sum
arr << [print_rank, part.name, g,e,q,s,f,w,r,tp, ts, score ]
prev = score
end
pdf.table( arr, :column_widths => [50,100,30,30,30,30,30, 30, 30, 30, 30, 30], :cell_style=>cellstyle ) do
# row(0).style :rotate => 90, :height=> 100, :valign => :bottom
end
end
private
def start_new_page?(lines,hight)
(lines.size * 12 + 15 ) > h.to_i-20 #(lines-size + line-header) is too big for page with footer...
end
end
<file_sep>class Player < ApplicationRecord
has_many :topplayers, -> { topplayer }, class_name: "Bet::Player", inverse_of: :player
has_many :topscorers, -> { topscorer }, class_name: "Bet::Player", inverse_of: :player
def self.topplayer
self.find_by(best: true)
end
def self.topscorer
self.find_by(top: true)
end
def calculate_topplayer
topplayers.each{|x| x.update_attribute(:score, 15)}
end
def reset_topplayer_scores
topplayers.each{|x| x.update_attribute(:score, nil)}
end
def calculate_topscorer
topscorers.each{|x| x.update_attribute(:score, 5)}
end
def reset_topscorer_scores
topscorers.each{|x| x.update_attribute(:score, nil)}
end
end
<file_sep>class Team < ApplicationRecord
has_many :winners, -> { winner }, class_name: "Bet::Team", inverse_of: :team
has_many :redcards, -> { redcard }, class_name: "Bet::Team", inverse_of: :team
has_many :finalists, -> { finale }, class_name: 'Bet::Team', inverse_of: :team
has_many :semifinalists, -> { semifinal }, class_name: 'Bet::Team', inverse_of: :team
has_many :quarterfinalists, -> { quarterfinal }, class_name: 'Bet::Team', inverse_of: :team
has_many :eightfinalists, -> { eightfinal }, class_name: 'Bet::Team', inverse_of: :team
def self.winner
Team.find_by(winner: true)
end
def self.redcard
Team.find_by(red: true)
end
def calculate_winner
winners.each{|x| x.update_attribute(:score, 15)}
end
def reset_winner_scores
winners.each{|x| x.update_attribute(:score, nil)}
end
def calculate_redcard
redcards.each{|x| x.update_attribute(:score, 5)}
end
def reset_redcard_scores
redcards.each{|x| x.update_attribute(:score, nil)}
end
end
<file_sep>class AddTopWinnerBestToPlayersAndTeams < ActiveRecord::Migration[6.1]
def change
add_column :teams, :winner, :boolean
add_column :teams, :red, :boolean
add_column :players, :top, :boolean
add_column :players, :best, :boolean
end
end
<file_sep>require "application_system_test_case"
class Bet::TopscorersTest < ApplicationSystemTestCase
setup do
@bet_topscorer = bet_topscorers(:one)
end
test "visiting the index" do
visit bet_topscorers_url
assert_selector "h1", text: "Bet/Topscorers"
end
test "creating a Topscorer" do
visit bet_topscorers_url
click_on "New Bet/Topscorer"
fill_in "Participant", with: @bet_topscorer.participant_id
fill_in "Player", with: @bet_topscorer.player_id
click_on "Create Topscorer"
assert_text "Topscorer was successfully created"
click_on "Back"
end
test "updating a Topscorer" do
visit bet_topscorers_url
click_on "Edit", match: :first
fill_in "Participant", with: @bet_topscorer.participant_id
fill_in "Player", with: @bet_topscorer.player_id
click_on "Update Topscorer"
assert_text "Topscorer was successfully updated"
click_on "Back"
end
test "destroying a Topscorer" do
visit bet_topscorers_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Topscorer was successfully destroyed"
end
end
<file_sep>require "test_helper"
class Bet::GamesControllerTest < ActionDispatch::IntegrationTest
setup do
@bet_game = bet_games(:one)
end
test "should get index" do
get bet_games_url
assert_response :success
end
test "should get new" do
get new_bet_game_url
assert_response :success
end
test "should create bet_game" do
assert_difference('Bet::Game.count') do
post bet_games_url, params: { bet_game: { away: @bet_game.away, game_id: @bet_game.game_id, home: @bet_game.home } }
end
assert_redirected_to bet_game_url(Bet::Game.last)
end
test "should show bet_game" do
get bet_game_url(@bet_game)
assert_response :success
end
test "should get edit" do
get edit_bet_game_url(@bet_game)
assert_response :success
end
test "should update bet_game" do
patch bet_game_url(@bet_game), params: { bet_game: { away: @bet_game.away, game_id: @bet_game.game_id, home: @bet_game.home } }
assert_redirected_to bet_game_url(@bet_game)
end
test "should destroy bet_game" do
assert_difference('Bet::Game.count', -1) do
delete bet_game_url(@bet_game)
end
assert_redirected_to bet_games_url
end
end
<file_sep>class Bet::PlayersController < ApplicationController
before_action :set_bet_player, only: %i[ show edit update destroy ]
# GET /bet/players or /bet/players.json
def index
@bet_players = Bet::Player.all
end
# GET /bet/players/1 or /bet/players/1.json
def show
end
# GET /bet/players/new
def new
@bet_player = Bet::Player.new
end
# GET /bet/players/1/edit
def edit
end
# POST /bet/players or /bet/players.json
def create
@bet_player = Bet::Player.new(bet_player_params)
respond_to do |format|
if @bet_player.save
format.html { redirect_to @bet_player, notice: "Player was successfully created." }
format.json { render :show, status: :created, location: @bet_player }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @bet_player.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /bet/players/1 or /bet/players/1.json
def update
respond_to do |format|
if @bet_player.update(bet_player_params)
format.html { redirect_to @bet_player, notice: "Player was successfully updated." }
format.json { render :show, status: :ok, location: @bet_player }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @bet_player.errors, status: :unprocessable_entity }
end
end
end
# DELETE /bet/players/1 or /bet/players/1.json
def destroy
@bet_player.destroy
respond_to do |format|
format.html { redirect_to bet_players_url, notice: "Player was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_bet_player
@bet_player = Bet::Player.find(params[:id])
end
# Only allow a list of trusted parameters through.
def bet_player_params
params.require(:bet_player).permit(:participant_id, :player_id, :stage, :score)
end
end
<file_sep>require "test_helper"
class Bet::PlayersControllerTest < ActionDispatch::IntegrationTest
setup do
@bet_player = bet_players(:one)
end
test "should get index" do
get bet_players_url
assert_response :success
end
test "should get new" do
get new_bet_player_url
assert_response :success
end
test "should create bet_player" do
assert_difference('Bet::Player.count') do
post bet_players_url, params: { bet_player: { participant_id: @bet_player.participant_id, player_id: @bet_player.player_id, score: @bet_player.score, stage: @bet_player.stage } }
end
assert_redirected_to bet_player_url(Bet::Player.last)
end
test "should show bet_player" do
get bet_player_url(@bet_player)
assert_response :success
end
test "should get edit" do
get edit_bet_player_url(@bet_player)
assert_response :success
end
test "should update bet_player" do
patch bet_player_url(@bet_player), params: { bet_player: { participant_id: @bet_player.participant_id, player_id: @bet_player.player_id, score: @bet_player.score, stage: @bet_player.stage } }
assert_redirected_to bet_player_url(@bet_player)
end
test "should destroy bet_player" do
assert_difference('Bet::Player.count', -1) do
delete bet_player_url(@bet_player)
end
assert_redirected_to bet_players_url
end
end
<file_sep>class CreateBetPlayers < ActiveRecord::Migration[6.1]
def change
create_table :bet_players do |t|
t.integer :participant_id
t.integer :player_id
t.integer :stage
t.integer :score
t.timestamps
end
add_index :bet_players, :participant_id
end
end
<file_sep>module ParticipantsHelper
def print_participant_page(participant)
print_participant_header(participant)
h 20
print_games(participant)
h -601
print_eigthfinalists(participant)
print_quarterfinalists(participant)
print_semifinalists(participant)
print_finalists(participant)
print_winner(participant)
print_topplayer(participant)
print_topscorer(participant)
print_redcard(participant)
h 50
print_score(participant)
end
def participant_header_array(participant)
arr = []
arr << ["bijgewerkt op", "#{printed_on}"]
arr << [ 'rank' ,rank.to_s]
arr << [ 'naam' ,participant.name]
arr << [ 'email',participant.email]
arr
end
def games_array(participant)
arr = []
gamez = participant.games
poule = %w(A B C D E F )
gamez.each_slice(6).with_index do |games, i|
arr << ["poule #{poule[i]}"]
games.each do |game|
arr<< [game.game.home.name, '-', game.game.away.name, nil, "#{game.home} - #{game.away}",nil, "(#{game.game.score_home} - #{game.game.score_away})", game.score.to_s]
end
end
arr << [nil,nil,nil, nil,nil,nil,nil, gamez.map(&:score).compact.sum]
end
def eigthfinalists_array(participant)
arr = []
eigthfinalists = participant.teams.select{|x| x.stage=="eightfinal"}.sort_by{|x| x.team.name}
eigthfinalists.each do |team|
arr << [nil, team.team.name, team.score.to_s]
end
arr[0][0] = "eightfinal"
arr << [nil, nil,eigthfinalists.map(&:score).compact.sum]
end
def quarterfinalists_array(participant)
arr = []
quarterfinalists = participant.teams.select{|x| x.stage=="quarterfinal"}.sort_by{|x| x.team&.name||""}
quarterfinalists.each do |team|
arr << [nil, team.team&.name|| "", team.score.to_s]
end
arr[0][0] = "quarterfinal"
arr << [nil, nil,quarterfinalists.map(&:score).compact.sum]
end
def semifinalists_array(participant)
arr = []
semifinalists = participant.teams.select{|x| x.stage=="semifinal"}.sort_by{|x| x.team.name}
semifinalists.each do |team|
arr << [nil, team.team.name, team.score.to_s]
end
arr[0][0] = "semifinal"
arr << [nil, nil,semifinalists.map(&:score).compact.sum]
end
def finalists_array(participant)
arr = []
finalists = participant.teams.select{|x| x.stage=="finale"}.sort_by{|x| x.team.name}
finalists.each do |team|
arr << [nil, team.team.name, team.score.to_s]
end
arr[0][0] = "finale"
arr << [nil, nil,finalists.map(&:score).compact.sum]
end
def winner_array(participant)
arr = []
winner = participant.teams.find{|x| x.stage=="winner"}
arr << ["winner",winner.team.name, winner.score.to_s]
end
def topplayer_array(participant)
arr = []
player = participant.players.find{|x| x.stage=="topplayer"}
arr << ["topplayer",player.player.name, player.score.to_s]
end
def topscorer_array(participant)
arr = []
player = participant.players.find{|x| x.stage=="topscorer"}
arr << ["topscorer",player.player.name, player.score.to_s]
end
def redcard_array(participant)
arr = []
team = participant.teams.find{|x| x.stage=="redcard"}
arr << ["redcard",team.team.name, team.score.to_s]
end
def score_array(participant)
arr = []
arr << ["totaal",nil, participant.score_total.to_s]
end
end | 4e4b6abae5921858fb84090e60a5130a100692bf | [
"Ruby"
] | 54 | Ruby | l-plan/soccer_bet | f453ace174b5b7b65a64fc9a7435074e9158e63d | 9206c04cc02abe7dab0b4c720e5851aff9ceb598 |
refs/heads/main | <file_sep># fio
- The purpose of the repository to save how to use [fio](https://github.com/axboe/fio) for benchmark test.
## Sample Scripts
- There are sample scripts.
- [Sequential write](script/seq/run-fio-md-seq.sh)
- [Random write](script/ran/run-fio-md-ran.sh)
<file_sep>#!/bin/bash
# Script file for sequential write performance
# Block size
BSIZE[0]="1K"
BSIZE[1]="2K"
BSIZE[2]="4K"
BSIZE[3]="8K"
BSIZE[4]="16K"
BSIZE[5]="32K"
BSIZE[6]="64K"
BSIZE[7]="128K"
BSIZE[8]="256K"
BSIZE[9]="512K"
BSIZE[10]="1M"
BSIZE[11]="2M"
BSIZE[12]="4M"
BSIZE[13]="8M"
BSIZE[14]="16M"
BSIZE[15]="32M"
BSIZE[16]="64M"
BSIZE[17]="128M"
BSIZE[18]="256M"
BSIZE[19]="512M"
# Parameters
# File name
FNAME="/mnt/md01/fio-benchmark"
# Type
RW="write"
# File size
FSIZE="8G"
# Runtime
RUNTIME="60"
# Job name
JOB=md
# Run fio
for bsize in ${BSIZE[@]}
do
echo $bsize
fio -filename=${FNAME} -direct=1 -rw=${RW} -bs=$bsize -size=${FSIZE} -runtime=${RUNTIME} -name=${JOB}-$bsize
done
| b5c387e65d9db92dade24344aa87581a68693789 | [
"Markdown",
"Shell"
] | 2 | Markdown | fukunagt/fio | 55e8cb466bda189019b001570b7da0869da8fc2e | 112bc9e42ee39593ed9bc83e5fefaa34fc60fa31 |
refs/heads/master | <repo_name>ryanliu1021/blackie-test-project<file_sep>/projects/demo_01_create_ucc/create_ucc.py
print("Create UCC") | 771e258794be744dba2630bcae8a7a0421a3366f | [
"Python"
] | 1 | Python | ryanliu1021/blackie-test-project | 7a1d1f9d339f57a0cf9afffedec3d7df3f29ca92 | b5eca4c4518168745b8da1743a2659b7b8a251ed |
refs/heads/master | <repo_name>Phongnn570/StudentManager<file_sep>/Podfile
platform :ios , '7.0'
pod 'JSONModel', '~> 0.12.0'
pod 'AsyncImageView', '~> 1.5.1'
pod 'MagicalRecord', '~> 2.2'
pod 'AFNetworkActivityLogger', '~> 2.0.1' | 62754c4d7bf104cca0f6ae36184d424eccf91d7d | [
"Ruby"
] | 1 | Ruby | Phongnn570/StudentManager | 56d34d3b291b3a74c69e21398d09bab0942eff8c | 57e608ce74b801f64d12c6410430552beddf0292 |
refs/heads/master | <repo_name>SameerPujji/breezy-weather<file_sep>/public/script.js
var convert = function(e) {
e.preventDefault();
var currentTemp = $("#temp").text();
var lastChar = currentTemp[currentTemp.length - 1];
if (lastChar === "C") {
var tempC = parseFloat(currentTemp.split(" ")[0]);
var tempF = Number(((tempC * 9) / 5 + 32).toFixed(3));
$("#convert").html(
"<a href = '' onclick = 'convert(event)' id='temp' >" +
tempF +
" ° F</a>"
);
} else if (lastChar === "F") {
var tempF = parseFloat(currentTemp.split(" ")[0]);
var tempC = Number((((tempF - 32) * 5) / 9).toFixed(3));
$("#convert").html(
"<a href = '' onclick = 'convert(event)' id='temp' >" +
tempC +
" ° C</a>"
);
} else {
console.log("error");
}
};
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var requestString =
"https://breezyweather.herokuapp.com/getWeather/" +
position.coords.latitude +
"," +
position.coords.longitude;
$.ajax({
url: requestString,
success: function(data) {
var weatherData = JSON.parse(data);
console.log(weatherData);
$("#convert").html(
"<a href = '' onclick = 'convert(event)' id='temp' >" +
weatherData.currently.temperature +
" ° C</a>"
);
$("#summary").text(weatherData.currently.summary);
$("#description").text(weatherData.daily.summary);
$("#weatherIcon").attr("alt", "Weather Icon");
if (weatherData.currently.icon === "clear-day") {
$("#weatherIcon").attr("src", "/public/clear.png");
$(".bg-circle").addClass("clearDay");
$(" header.masthead").addClass("clearDay");
$("a").addClass("black");
$("h5").addClass("black");
$("h6").addClass("black");
} else if (weatherData.currently.icon === "clear-night") {
$("#weatherIcon").attr("src", "/public/night.png");
$(".bg-circle").addClass("clearNight");
$(" header.masthead").addClass("clearNight");
} else if (weatherData.currently.icon === "rain") {
$("#weatherIcon").attr("src", "/public/rain.png");
$(".bg-circle").addClass("rain");
$(" header.masthead").addClass("rain");
$("a").addClass("black");
$("h5").addClass("black");
$("h6").addClass("black");
} else if (
weatherData.currently.icon === "snow" ||
weatherData.currently.icon === "sleet"
) {
$("#weatherIcon").attr("src", "/public/snow.png");
$(".bg-circle").addClass("snow");
$(" header.masthead").addClass("snow");
$("a").addClass("black");
$("h5").addClass("black");
$("h6").addClass("black");
} else if (weatherData.currently.icon === "wind") {
$("#weatherIcon").attr("src", "/public/windy.png");
$(".bg-circle").addClass("rain");
$(" header.masthead").addClass("rain");
$("a").addClass("black");
$("h5").addClass("black");
$("h6").addClass("black");
} else if (weatherData.currently.icon === "fog") {
$("#weatherIcon").attr("src", "/public/fog.png");
$(".bg-circle").addClass("rain");
$(" header.masthead").addClass("rain");
$("a").addClass("black");
$("h5").addClass("black");
$("h6").addClass("black");
} else if (weatherData.currently.icon === "cloudy") {
$("#weatherIcon").attr("src", "/public/cloud.png");
$(".bg-circle").addClass("rain");
$(" header.masthead").addClass("rain");
$("a").addClass("black");
$("h6").addClass("black");
$("h5").addClass("black");
} else if (weatherData.currently.icon === "partly-cloudy-day") {
$("#weatherIcon").attr("src", "/public/partly cloudy.png");
$(".bg-circle").addClass("cloudyDay");
$(" header.masthead").addClass("cloudyDay");
$("a").addClass("black");
$("h5").addClass("black");
$("h6").addClass("black");
} else if (weatherData.currently.icon === "partly-cloudy-night") {
$("#weatherIcon").attr("src", "/public/cloudy night.png");
$(".bg-circle").addClass("cloudyNight");
$(" header.masthead").addClass("cloudyNight");
} else {
$("#weatherIcon").attr("src", "/public/weather.png");
}
},
error: function() {
$("#convert").html("<h1>Error... Please try again</h1>");
}
});
});
}
});
| 1d4b3e340feec2500d71523e3a9a36c01c3ddd0e | [
"JavaScript"
] | 1 | JavaScript | SameerPujji/breezy-weather | 91208ef7a68820204ff3e5f7c34bd18ea488cfd6 | 5e20c05d05e9996b27b81cff3d97afdaa629c109 |
refs/heads/master | <file_sep>package main
import (
"syscall/js"
"strconv"
)
func main() {
c := make(chan struct{}, 0)
println("WASM Go Initialized")
// register functions
registerCallbacks()
<-c
}
func registerCallbacks() {
js.Global().Set("add", js.NewCallback(add))
js.Global().Set("subtract", js.NewCallback(subtract))
}
func add(i []js.Value) {
val1 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
val2 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()
i1, _ := strconv.Atoi(val1)
i2, _ := strconv.Atoi(val2)
a1 := i1 + i2
println(a1)
js.Global().Get("document").Call("getElementById", i[2].String()).Set("innerHTML", a1)
}
func subtract(i []js.Value) {
val3 := js.Global().Get("document").Call("getElementById", i[0].String()).Get("value").String()
val4 := js.Global().Get("document").Call("getElementById", i[1].String()).Get("value").String()
i3, _ := strconv.Atoi(val3)
i4, _ := strconv.Atoi(val4)
a2 := i3 - i4
println(a2)
js.Global().Get("document").Call("getElementById", i[2].String()).Set("innerHTML", a2)
}<file_sep># go-wasm
WebAssembly implementation by Golang.
[Official tutorial](https://github.com/golang/go/wiki/WebAssembly)
## build
```
GOOS=js GOARCH=wasm go build -o main.wasm
```
## run
```go
goexec 'http.ListenAndServe(":8080", http.FileServer(http.Dir(".")))'
``` | db6ddff439cdf7f60bf85e492b06a2294ffd1a74 | [
"Markdown",
"Go"
] | 2 | Go | ef-ryusx/go-wasm | 68397b4614e5df30c98d4910cf9d360dee8118fd | abb4f521c94c36f3b42eb9bd11035958826e120e |
refs/heads/master | <repo_name>Toklio-project/mytokl-app-js<file_sep>/build/installer.sh
!macro customInstall
DetailPrint "Register tokl URI Handler"
DeleteRegKey HKCR "toklio"
WriteRegStr HKCR "toklio" "" "URL:toklio"
WriteRegStr HKCR "toklio" "URL Protocol" ""
WriteRegStr HKCR "toklio\DefaultIcon" "" "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
WriteRegStr HKCR "toklio\shell" "" ""
WriteRegStr HKCR "toklio\shell\Open" "" ""
WriteRegStr HKCR "toklio\shell\Open\command" "" "$INSTDIR\${APP_EXECUTABLE_FILENAME} %1"
!macroend<file_sep>/local_modules/HostedMoneroAPIClient/config__MyMonero.js
module.exports =
{
API__authority: "172.16.58.3:1985"
} | 79fcf8615c849b0b5cb2b92d7cdfeae8dcf58078 | [
"JavaScript",
"Shell"
] | 2 | Shell | Toklio-project/mytokl-app-js | ad69285ed7558daafa94fd90a87859f67847712c | 80fc5192f933911cac21548127da7ffa013833c8 |
refs/heads/master | <file_sep>CC = g++
CF = -fpermissive -w -O3
I = -I../Include
RANLIB = ranlib
ARCHIVE = $(AR) $(ARFLAGS)
all: libcsparse.a
CS = cs_add.o cs_amd.o cs_chol.o cs_cholsol.o cs_counts.o cs_cumsum.o \
cs_droptol.o cs_dropzeros.o cs_dupl.o cs_entry.o \
cs_etree.o cs_fkeep.o cs_gaxpy.o cs_happly.o cs_house.o cs_ipvec.o \
cs_lsolve.o cs_ltsolve.o cs_lu.o cs_lusol.o cs_util.o cs_multiply.o \
cs_permute.o cs_pinv.o cs_post.o cs_pvec.o cs_qr.o cs_qrsol.o \
cs_scatter.o cs_schol.o cs_sqr.o cs_symperm.o cs_tdfs.o cs_malloc.o \
cs_transpose.o cs_compress.o cs_usolve.o cs_utsolve.o cs_scc.o \
cs_maxtrans.o cs_dmperm.o cs_updown.o cs_print.o cs_norm.o cs_load.o \
cs_dfs.o cs_reach.o cs_spsolve.o cs_ereach.o cs_leaf.o cs_randperm.o
$(CS): ../Include/cs.h Makefile
%.o: ../Source/%.cpp ../Include/cs.h
$(CC) $(CF) $(I) -c $<
libcsparse.a: $(CS)
$(ARCHIVE) libcsparse.a $(CS)
- $(RANLIB) libcsparse.a
clean:
- $(RM) *.o
purge: distclean
distclean: clean
- $(RM) *.a *.obj *.dll
<file_sep>#include "DataStruct.h"
DataStructure::DataStructure(char* fname) {
ifstream ReadFile;
ReadFile.open(fname);
ReadFile >> Nverts >> Ntris;
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
tris = new int*[Ntris];
neigh = new int*[Nverts];
verts = new double*[Nverts];
area = new double[Ntris];
for(int i = 0; i < Nverts; i++)
verts[i] = new double[3];
for(int i = 0; i < Ntris; i++)
tris[i] = new int[3];
for(int i = 0; i < Nverts; i++) {
for(int j = 0; j < 3; j++)
ReadFile >> verts[i][j];
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < Ntris; i++) {
for(int j = 0; j < 3; j++)
ReadFile >> tris[i][j];
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < Nverts; i++) {
int length;
ReadFile >> length;
neigh[i] = new int[length+1];
neigh[i][0] = length;
for(int j = 1; j <= neigh[i][0]; j++)
ReadFile >> neigh[i][j];
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < Ntris; i++) {
double x1 = verts[tris[i][0]][0],
x2 = verts[tris[i][1]][0],
x3 = verts[tris[i][2]][0],
y1 = verts[tris[i][0]][1],
y2 = verts[tris[i][1]][1],
y3 = verts[tris[i][2]][1];
area[i] = 0.5*fabs( x1*y2 - x2*y1 - x1*y3 + x3*y1 + x2*y3 - x3*y2 );
}
}
<file_sep>#include "Main.h"
#pragma once
#ifndef VECTOR_H
#define VECTOR_H
template <typename Type>
class Vector
{
protected:
Type *vec;
int length;
public:
Type* GetAddress() { return vec; }
void Allocate(int, Type);
/*** Constructors ***/
Vector(int, Type a = 0.0);
Vector(const Vector &);
Vector(int, Type*);
Vector() {}
/*** Access Ops ***/
int GetLength() const { return length; }
Type& operator()(int i) const;
Vector<Type> operator()(const int i, const int j);
template<typename T>
friend ostream& operator<<(ostream& out, Vector<T>& p);
Vector<Type>& operator()(Vector<Type>& p ,const int i, const int j);
void Write(char* fname);
/*** Scalar Ops ***/
Vector<Type>& operator*=(Type scalar);
Vector<Type>& operator+=(Type scalar);
Vector<Type>& operator-=(Type scalar);
Vector<Type>& operator/=(Type scalar);
Vector<Type> operator-();
Vector<Type> operator+();
Vector<Type> test();
template<typename T>
friend Vector<T> pow(Vector<T>& p, double n);
Type operator&&(Vector<Type>);
Type Trapezoidal(Vector<Type>&);
Type Amax();
Type Amin();
Type Amean();
Type max();
Type min();
Type Norm();
int Imax() ;
template<typename T>
friend Vector<T> operator*(T, Vector<T>);
template<typename T>
friend Vector<T> operator+(T, Vector<T>);
template<typename T>
friend Vector<T> operator-(T, Vector<T>);
template<typename T>
friend Vector<T> operator/(T, Vector<T>);
template<typename T>
friend Vector<T> operator+(Vector<T>,T);
template<typename T>
friend Vector<T> operator-(Vector<T>, T);
template<typename T>
friend Vector<T> operator*(Vector<T>, T);
template<typename T>
friend Vector<T> operator/(Vector<T>, T);
/*** Vector Ops ***/
template<typename T>
friend Vector<T> operator+(Vector<T>, Vector<T>);
template<typename T>
friend Vector<T> operator-(Vector<T>, Vector<T>);
template<typename T>
friend Vector<T> operator*(Vector<T>, Vector<T>);
template<typename T>
friend Vector<T> operator/(Vector<T>, Vector<T>);
Vector<Type> diff();
Vector<Type>& operator+=(Vector<Type>);
Vector<Type>& operator-=(Vector<Type>);
Vector<Type>& operator*=(Vector<Type>);
Vector<Type>& operator/=(Vector<Type>);
Vector<Type>& operator=(Vector<Type>);
Vector<Type>& operator=(Type);
~Vector() { delete[] vec; }
};
#endif
template<typename Type>
void Vector<Type>::Allocate(int n, Type a) {
vec = new Type[n];
length = n;
(*this) = a;
}
template<typename Type>
Vector<Type> Vector<Type>::operator-() {
Vector<Type> v = *this;
for(int i = 0; i < length; i++)
v(i) = - vec[i];
return v;
}
template<typename Type>
Vector<Type> Vector<Type>::operator+() {
Vector<Type> v = *this;
return v;
}
/*** Scalar Ops ***/
template<typename Type>
Vector<Type>& Vector<Type>::operator+=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] += scalar;
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator/=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] /= scalar;
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator-=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] -= scalar;
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator*=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] *= scalar;
return *this;
}
template<typename Type>
Type Vector<Type>::Amax() {
Type max = - pow(10.0,20.0);
for(int i = 0; i < length; i++)
max = max < fabs(vec[i]) ? fabs(vec[i]) : max;
return max;
}
template<typename Type>
Type Vector<Type>::max() {
Type max = - pow(10.0,20.0);
for(int i = 0; i < length; i++)
max = max < vec[i] ? vec[i] : max;
return max;
}
template<typename Type>
Type Vector<Type>::min() {
Type min = pow(10.0,20.0);
for(int i = 0; i < length; i++)
min = min > vec[i] ? vec[i] : min;
return min;
}
template<typename Type>
Type Vector<Type>::Amin() {
Type min = pow(10.0,20.0);
for(int i = 0; i < length; i++)
min = min > fabs(vec[i]) ? fabs(vec[i]) : min;
return min;
}
template<typename Type>
Type Vector<Type>::Amean() {
Type mean = 0.0;
for(int i = 0; i < length; i++)
mean += fabs(vec[i]);
return mean/length;
}
template<typename Type>
int Vector<Type>::Imax() {
Type max = 0.0;
int j = 0;
for(int i = 0; i < length; i++) {
j = max < fabs(vec[i]) ? i : j;
max = max < fabs(vec[i]) ? fabs(vec[i]) : max;
}
return j;
}
template<typename Type>
Type Vector<Type>::Norm() {
Type norm = 0.0;
for(int i = 0; i < length; i++)
norm += pow(vec[i],2.0);
return sqrt(norm);
}
/// Friend Operators ///
template<typename T>
Vector<T> operator+(T scalar, Vector<T> p) {
T* temp = new T[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) + scalar;
return Vector<T>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator+(Vector<Type> p, Type scalar) {
Type *temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) + scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator/(Type scalar, Vector<Type> p) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = scalar / p(i);
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator/(Vector<Type> p, Type scalar) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) / scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator-(Type scalar, Vector<Type> p) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = - p(i) + scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator-(Vector<Type> p, Type scalar) {
Type *temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) - scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator*(Type scalar, Vector<Type> p) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) * scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator*(Vector<Type> p, Type scalar) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) * scalar;
return Vector<Type>(p.GetLength(),temp);
}
/// Dot Product ///
template<typename Type>
Type Vector<Type>::operator&&(Vector<Type> p) {
assert(p.GetLength() == length);
Type output = 0;
for(int i = 0; i < length; i++)
output += p(i) * vec[i];
return output;
}
/// Integration Int ///
template<typename Type>
Type Vector<Type>::Trapezoidal(Vector<Type> &p) {
assert(p.GetLength() == length);
Type output = 0;
for(int i = 0; i < length - 1; i++)
output += (p(i) + p(i+1)) * vec[i];
return 0.5 * output;
}
/*** Vectors Ops ***/
template<typename Type>
Vector<Type> operator+(Vector<Type> p, Vector<Type> u) {
assert(p.GetLength() == u.GetLength());
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) + u(i);
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator-(Vector<Type> p, Vector<Type> u) {
assert(p.GetLength() == u.GetLength());
Type* temp = new Type[p.length];
for(int i = 0; i < p.length; i++)
temp[i] = p(i) - u(i);
return Vector<Type>(p.length,temp);
}
template<typename Type>
Vector<Type> operator*(Vector<Type> p, Vector<Type> u) {
int size = p.GetLength();
assert(size == u.GetLength());
Type* temp = new Type[size];
for(int i = 0; i < size; i++)
temp[i] = p(i) * u(i);
return Vector<Type>(size,temp);
}
template<typename Type>
Vector<Type> operator/(Vector<Type> p, Vector<Type> u) {
int size = p.GetLength();
assert(size == u.GetLength());
Type* temp = new Type[size];
for(int i = 0; i < size; i++)
temp[i] = p(i) / u(i);
return Vector<Type>(size,temp);
}
template<typename Type>
Vector<Type>& Vector<Type>::operator+=(Vector<Type> p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] += p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator-=(Vector<Type> p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] -= p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator*=(Vector<Type> p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] *= p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator/=(Vector<Type> p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] /= p(i);
return *this;
}
template<typename Type>
Vector<Type> Vector<Type>::diff() {
Vector<Type> p(length - 1,.0);
for(int i = 0; i < length - 1; i++)
p(i) = vec[i+1] - vec[i];
return p;
}
/*** Constructors ***/
template<typename Type>
Vector<Type>::Vector(int dim, Type a) : length(dim), vec(dim ? new Type[dim] : 0) {
for(int i = 0; i < length; i++)
vec[i] = a;
}
template<typename Type>
Vector<Type>::Vector(const Vector<Type> &p) : length(p.GetLength()),
vec(p.GetLength() ? new Type[p.GetLength()] : 0) {
assert(&p != this);
for(int i = 0; i < p.GetLength(); i++)
vec[i] = p(i);
}
template<typename Type>
Vector<Type>::Vector(int dim, Type* p) : length(dim) {
vec = p;
}
/*** ***/
template<typename Type>
Vector<Type>& Vector<Type>::operator=(Vector<Type> p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] = p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator=(Type a) {
for(int i = 0; i < length; i++)
vec[i] = a;
return *this;
}
/*** Access operator ***/
template<typename Type>
Type& Vector<Type>::operator()(int i) const{
assert(i >=0 && i <length);
return vec[i];
}
template<typename Type>
Vector<Type> Vector<Type>::operator()(const int i, const int j) {
const int N_temp = j - i + 1;
Vector<Type> p(N_temp,.0);
for(int k = 0; k < N_temp; k++)
p(k) = vec[i+k];
return p;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator()(Vector<Type>& p ,const int i, const int j) {
int count = 0;
for(int k = i; k <= j; k++) {
vec[k] = p(count);
count++;
}
return *this;
}
template<typename Type>
ostream& operator<<(ostream& out, Vector<Type>& p) {
for(int i = 0; i < p.GetLength(); i++)
out << p(i) << " ";
out << endl;
return out;
}
template<typename Type>
void Vector<Type>::Write(char* fname) {
ofstream myfile;
myfile.open (fname,ios::app);
for(int i = 0; i < length; i++)
myfile << vec[i] << endl;
myfile.close();
}
template<typename Type>
Vector<Type> pow(Vector<Type>& p, double n) {
Vector<Type> v(p.GetLength());
for(int i = 0; i < p.GetLength(); i++)
v(i) = pow(p(i),n);
return v;
}
<file_sep>#include "Common.h"
#include "Matrix.h"
#include "Vector.h"
#include "DataStruct.h"
#include "Sparse.h"
double t(0.0), dt0 = 0.0001, PERIOD;
const double tmax = 1.0, tmin = tmax, dc = 0.05;
typedef Matrix<double> matrix;
typedef Vector<double> vector;
typedef Sparse<double> sparse;
typedef Vector<Matrix<double> > tensor;
vector ConstructBDF(int, const vector&);
sparse AssembleIsotropicDiffusion(const DataStructure&);
sparse BuildLaplacian(const DataStructure&);
sparse BuildAdvection(const DataStructure&, double velocity);
void LoadIC(matrix& c, double c0, double c1, DataStructure& Data,char* TYPE);
void ReLoadIC(tensor& x);
sparse AssembleAdvection(DataStructure& Data, double velocity, char*);
void FixRHS(vector& RHS);
double GlobRate(const DataStructure&, const vector&);
vector ConstructTheta(double cr, vector& c) {
vector theta(c.GetLength(),.0);
for(int i = 0; i < c.GetLength(); i++)
if(c(i) >= cr)
theta(i) = 1.0;
return theta;
}
double FixedPointStep(const DataStructure& Mesh, const sparse& Diff, const sparse& Adv1, const sparse& Adv2, const matrix& RHS,
vector& x1, vector& x2, vector& x3, vector& x4, vector& x5, double coef,char* BCType, int Npts)
{
vector theta1 = ConstructTheta(c1,x3),
theta2 = ConstructTheta(c2,x3),
theta3 = ConstructTheta(c3,x3),
RHS1 = RHS[0],
RHS2 = RHS[1],
RHS3 = RHS[2] + kr * x1 * x2 + alfa * c3 * theta3 + delta * c1 * theta1 * x5 + beta * (1.0 - theta2) * c2 * x4,
RHS4 = RHS[3] + (x3 - c3) * alfa * theta3,
RHS5 = RHS[4] + gama * (x3 - c2) * theta2 * x4;
if(!strcmp(BCType,"Dirichlet")) {
FixRHS(RHS1);
FixRHS(RHS2);
}
sparse Op1 = - (Diff * Da) + (Adv1 * velocity1), Op2 = - (Diff * Db) + (Adv2 * velocity2), Op3 = - Diff * Dc;
vector v1 = coef + kr * x2,
v2 = coef + kr * x1,
v3 = coef + alfa * theta3 + delta * theta1 * x5 + beta * (1.0 - theta2) * x4;
Op1.Diag(v1);
Op2.Diag(v2);
Op3.Diag(v3);
vector sol1 = Op1 / RHS1, //Op1.PCCG(RHS1,x1),
sol2 = Op2 / RHS2, //Op2.PCCG(RHS2,x2),
sol3 = Op3 / RHS3, //Op3.PCCG(RHS3,x3),
sol4(Npts,.0),
sol5(Npts,.0),
Op4 = coef + gama * (x3 - c2) * theta2 + beta * (1.0 - theta2) * (c2 - x3),
Op5 = coef - delta * (x3 - c1) * theta1;
sol4 = RHS4 / Op4;
sol5 = RHS5 / Op5;
double error = max((sol1 - x1).Amax(),max((sol2 - x2).Amax(),max((sol3 - x3).Amax(),max((sol4 - x4).Amax(),(sol5 - x5).Amax()))));
x1 = sol1; x2 = sol2; x3 = sol3; x4 = sol4; x5 = sol5;
return error;
}
double FPI_RD(const DataStructure& Mesh, sparse& Diff, matrix RHS, vector& x1, vector& x2, double coef, double dt)
{
int Npts = Mesh.GetNverts();
vector RHS1 = RHS[0],
RHS2 = RHS[1];
sparse Op1 = Diff * (Da * dt), Op2 = Diff * (Db * dt);
vector v1 = coef + (dt * kr) * x2,
v2 = coef + (dt * kr) * x1;
Op1.Diag(v1);
Op2.Diag(v2);
vector sol1 = Op1.PCCG(RHS1,x1),
sol2 = Op2.PCCG(RHS2,x2);
double error = max((sol1 - x1).Amax(),(sol2 - x2).Amax());
x1 = sol1; x2 = sol2;
return error;
}
double NTR_NU(const DataStructure& Mesh, sparse& Diff, matrix RHS, vector& x1, vector& x2, vector& x3, vector& x4,
vector& x5, double coef, double dt)
{
int Npts = Mesh.GetNverts();
sparse Opc = Diff * (Dc * dt);
vector theta1 = ConstructTheta(c1,x3),
theta2 = ConstructTheta(c2,x3),
theta3 = ConstructTheta(c3,x3),
z(Npts,.0),
RHS3 = RHS[2] - coef * x3 - Opc * x3 + dt * (kr * x1 * x2 - alfa * theta3 * (x3 - c3)
- delta * theta1 * (x3 - c1) * x5 + beta * (1.0 - theta2) * (c2 - x3) * x4),
RHS4 = RHS[3] - coef * x4 + dt * ((x3 - c3) * alfa * theta3 - beta * (1.0 - theta2) * (x3 - c2) * x4
- gama * theta2 * (x3 - c2) * x4),
RHS5 = RHS[4] - coef * x5 + dt * (gama * (x3 - c2) * theta2 * x4 + delta * (x3 - c1) * theta1 * x5);
vector J11 = coef + dt * (alfa * theta3 + delta * theta1 * x5 + beta * (1.0 - theta2) * x4),
J12 = dt * (- beta * (c2 - x3) * (1.0 - theta2)),
J13 = dt * (delta * (x3 - c1) * theta1),
J21 = dt * (- alfa * theta3 + beta * (1.0 - theta2) * x4 + gama * theta2 * x4),
J22 = coef + dt * (beta * (c2 - x3) * (1.0 - theta2) + gama * theta2 * (x3 - c2)),
J31 = dt * (- gama * theta2 * x4 - delta * theta1 * x5),
J32 = dt *(- gama * (x3 - c2) * theta2),
J33 = coef - dt * (delta * (x3 - c1) * theta1),
V = J11 - J12 * J21 / J22 - J13 * J31 / J33 + J13 * J32 * J21 / (J22 * J33);
//cout << (Diff.Diag()).max() << " " << (Diff.Diag()).min() << endl;
Opc.Diag(V);
//Opc = PC * Opc;
vector RHSc = (RHS3 + (J12 / J22 - J13 * J32 / (J22*J33)) * RHS4 + J13 * RHS5 / J33),
dc = Opc.PCCG(RHSc,z),
dn = - (- RHS4 + J21 * dc) / J22,
dp = - (- RHS5 + J31 * dc + J32 * dn) / J33;
double error = max(dc.Amax(),max(dn.Amax(),dp.Amax()));
//cout << x3.Norm() << " " << x4.Norm() << " " << x5.Norm() << endl;
x3 += dc; x4 += dn; x5 += dp;
//cout << "Cond num = " << (Opc.Diag()).max() / (Opc.Diag()).min() << endl;
return error;
}
bool NewtonSolver(const DataStructure& Mesh, const sparse& Diff, const sparse& Adv1, const sparse& Adv2, tensor& x, vector& dt, int Order,
char* BCType, int Npts)
{
int theta, GOrder, max_iters = 20;
if(t >= (Order-1) * dt0)
GOrder = Order;
else {
theta = (t + dt0)/dt0;
GOrder = theta;
}
vector BDF1 = ConstructBDF(GOrder,dt), BDF2(GOrder,.0);
matrix RHS1(Nc,Npts), RHS2(Nc,Npts);
for(int j = 0; j < Nc; j++)
for(int i = 1; i < GOrder + 1; i++)
RHS1[j] -= BDF1(i) * x(j)[i];
if(GOrder > 1) {
BDF2 = ConstructBDF(GOrder-1,dt);
for(int j = 0; j < Nc; j++)
for(int i = 1; i < GOrder; i++)
RHS2[j] -= BDF2(i) * x(j)[i];
}
vector x1 = x(0)[0], x2 = x(1)[0], x3 = x(2)[0], x4 = x(3)[0], x5 = x(4)[0];
double error = 1.0, tol = pow(10.0,-5.0), est = .0, abs_error = 0.001, rel_error = 0.001;
int iters = 0;
while(error > tol) {
iters++;
error = FixedPointStep(Mesh,Diff,Adv1,Adv2,RHS1,x1,x2,x3,x4,x5,BDF1(0),BCType,Npts);
if(iters > max_iters)
break;
}
x(0)[Order+2] = x1; x(1)[Order+2] = x2; x(2)[Order+2] = x3; x(3)[Order+2] = x4;
x(4)[Order+2] = x5;
if(GOrder > 1 && iters <= max_iters) {
vector err(Nc*Npts,.0);
matrix deriv1 = RHS1, deriv2 = RHS2;
for(int i = 0; i < Nc; i++) {
deriv1[i] -= BDF1(0) * x(i)[Order+2];
deriv2[i] -= BDF2(0) * x(i)[Order+2];
}
for(int i = 0; i < Nc; i++)
for(int j = 0; j < Npts; j++)
if(fabs(deriv1[i](j)) > pow(10.0,-8.0))
err(i*Npts+j) = (fabs(deriv1[i](j)) - fabs(deriv2[i](j))); // / fabs(deriv1[i](j));
est = err.Norm(); double deno = .0;
for(int i = 0; i < Nc; i++)
deno += deriv1[i].Norm(); est = est / deno;
}
if(iters > max_iters) {
cout << "Failure to converge with attempted timestep = " << dt(0) << endl;
est = rel_error * 2.0; }
if( est < rel_error) {
for(int i = 0; i < Nc; i++)
x(i)[0] = x(i)[Order+2];
for(int i = 0; i < Nc; i++)
for(int j = Order; j > 0; j--)
x(i)[j] = x(i)[j-1];
t += dt(0);
vector rate = x(0)[0]*x(1)[0];
vector time(1,t+dt(0)), rg(1,GlobRate(Mesh,rate)), cm(1,(rate.Imax()-(Ny-1)/2)*hy);
time.Write("adaptive.dat");
cm.Write("cmax.dat");
rg.Write("GlobRate.dat");
for(int i = Order - 1; i > 0; i--)
dt(i) = dt(i-1);
cout << "Newton Adaptive BDF Solver Converged with c_max = " << cm << " at time " << t << endl;
}
if(GOrder > 1)
dt(0) = min(tmax,0.8 * dt(0) * pow(rel_error/est,1.0/(GOrder)));
return 0;
}
int main(int argc, char* argv[]) {
if(argc < 4) {
cout << "====================================================================" << endl;
cout << "====================================================================" << endl;
cout << "PDE solver for Lisegang systems, written by <NAME>" << endl;
cout << "The code was supposed to specifically simulate revert spacing, on " << endl;
cout << "any type of geometrical domain, but it is not yet fnished." << endl;
cout << "------------------------------------------------------------------" << endl;
cout << "Program in Computational Science, American University of Beirut" << endl;
cout << "====================================================================" << endl;
cout << "====================================================================" << endl;
cout << "Usage: ./PDES InitialCond Period InitialDist [OutputFname] [Mesh] [Order]" << endl << endl;
cout << "Required Args:" << endl << endl;
cout << "InitialCond = a string which initializes the simulation if" << endl
<< " 'Initialize' is selected, otherwise the simulation" << endl
<< " is resumed based on an input file input.dat" << endl;
cout << "Period = a floating point number that specifies the time at" << endl
<< " which the simulation ends." << endl;
cout << "InitialDist = a string that specifies how each components" << endl
<< " is initially distributed." << endl << endl;
cout << "Optional Args:" << endl << endl;
cout << "Order = an integer specifying the maximum BDF order." << endl;
cout << "OutputFname = a string that specifies the output filename," << endl
<< " by defaul it is output.dat" << endl;
cout << "Mesh = a string that specifies the mesh data structure" << endl
<< " file (for FEM/CVFEM only)" << endl;
exit(1);
}
else
{
char* InitCond = argv[1];
double PERIOD = atof(argv[2]);
char* InitialDist = argv[3];
int BDFOrder = 4;
if(argc >= 5)
BDFOrder = atoi(argv[4]);
char* OutputFname = "output.dat";
if(argc >= 6)
OutputFname = argv[5];
DataStructure Mesh(Nx,Ny);
int Npts = Mesh.GetNpts(); //Mesh.GetNverts();
char* BCType = "Neumann";
/*sparse Diff = AssembleIsotropicDiffusion(Mesh), Adv1 = AssembleAdvection(Mesh,velocity1,BCType),
Adv2 = AssembleAdvection(Mesh,velocity2,BCType);*/
sparse Diff = BuildLaplacian(Mesh), Adv1 = BuildAdvection(Mesh,velocity1),
Adv2 = BuildAdvection(Mesh,velocity2);
cout << "BDF order : " << BDFOrder << endl << "Simulation time : " << PERIOD << endl;
if(!strcmp(InitCond,"Initialize"))
cout << "Initializing simulation ..." << endl;
else
cout << "Resuming simulation ..." << endl;
vector dt(BDFOrder,dt0);
matrix m(BDFOrder+3,Npts,.0);
tensor x(Nc,m);
if(strcmp(InitCond,"Initialize"))
ReLoadIC(x);
else {
LoadIC(x(0),a0,.0,Mesh,InitialDist);
LoadIC(x(1),.0,b0,Mesh,InitialDist);
}
while(t <= PERIOD)
NewtonSolver(Mesh,Diff,Adv1,Adv2,x,dt,BDFOrder,BCType,Npts);
for(int i = 0; i < Nc; i++)
x(i)[0].Write(OutputFname);
}
return 0;
}
<file_sep>all:
g++ -fpermissive -w -O3 *.cpp ../Lib/libcsparse.a -o PDES
<file_sep>#include "Main.h"
#include "cs.h"
#include "Vector.h"
#include "assert.h"
#ifndef SPARSE_H
#define SPARSE_H
#endif
template<typename T> class Sparse {
int* rows;
int* cols;
double* vals;
int nnz, nnz_red, n_rows, n_cols;
cs* Operator;
public:
Sparse(int N, int M, int NNZ) : nnz(NNZ), n_rows(N), n_cols(M),
rows(new int[NNZ]), cols(new int[NNZ]), vals(new double[NNZ]) {}
Sparse(int N, int NNZR) : nnz(NNZR), n_rows(N), n_cols(N),
rows(new int[NNZR]), cols(new int[N]), vals(new double[NNZR]) {}
Sparse(int, double);
Sparse(const Sparse<T>& S);
Sparse(Vector<T>& v);
Sparse(Vector<int> rows, Vector<int> cols, Vector<T> vals, int, int);
~Sparse() { delete[] rows; delete[] cols; delete[] vals; cs_spfree(Operator); }
int& NNZ() { return nnz; }
int& NNZ_R() { return nnz_red; }
int& ROWS() { return n_rows; }
int& COLS() { return n_cols; }
T& Val(const int i) { return vals[i]; }
int& Row(const int i) { return rows[i]; }
int& Col(const int i) { return cols[i]; }
void CreateSparse();
void CreateJacobian();
Sparse<T> transpose();
cs* ReturnOp() const { return Operator; }
Sparse<T> operator+(const T);
Sparse<T> operator-(const T);
Sparse<T> operator*(const T);
Sparse<T> operator/(const T);
T& operator()(const int i, const int j);
Sparse<T>& operator&&(Vector<T>& v);
Sparse<T> operator+();
Sparse<T> operator-();
Sparse<T>& Diag(T &);
Sparse<T>& Diag(Vector<T> &);
Vector<T> Diag();
template<typename Type>
friend Sparse<Type> operator+(Sparse<Type>, Sparse<Type>);
template<typename Type>
friend Sparse<Type> operator-(Sparse<Type>, Sparse<Type>);
template<typename Type>
friend Sparse<Type> operator*(Sparse<Type>, Sparse<Type>);
Vector<T> operator*(Vector<T>);
Vector<T> operator/(Vector<T>);
Vector<T> operator()(Vector<T>, Vector<T>);
template<typename Type>
friend ostream& operator<<(ostream&, Sparse<T>&);
Sparse<T>& operator=(Sparse<T>);
Vector<T> LoadJacobi();
Sparse<T> LoadICChol();
Vector<T> BiCG(Vector<T>& RHS);
};
template<typename T>
Sparse<T>::Sparse(int N = 0, double num = 0.0) : nnz(N), n_rows(N), n_cols(N),
rows(new int[N]), cols(new int[N]), vals(new double[N]) {
Operator = cs_spalloc(N,N,N,1,1);
for(int i = 0; i < N; i++)
cs_entry(Operator,i,i,num);
Operator = cs_compress(Operator);
nnz_red = Operator->nzmax;
}
template<typename T>
Sparse<T>::Sparse(Vector<int> rows, Vector<int> cols, Vector<T> vals, int N, int M) : nnz(N*M), n_rows(N), n_cols(M),
rows(new int[rows.GetLength()]), cols(new int[cols.GetLength()]), vals(new double[vals.GetLength()]) {
assert(vals.GetLength() == rows.GetLength());
assert(cols.GetLength() == vals.GetLength());
Operator = cs_spalloc(N,M,N*M,1,1);
for(int i = 0; i < N*M; i++)
cs_entry(Operator,rows(i),cols(i),vals(i));
Operator = cs_compress(Operator);
nnz_red = Operator->nzmax;
}
template<typename T>
Sparse<T>::Sparse(const Sparse<T>& S) : nnz(S.NNZ_R()), n_rows(S.ROWS()), n_cols(S.COLS()),
rows(new int[S.NNZ_R()]), cols(new int[S.NNZ_R()]), vals(new T[S.NNZ_R()]) {
int count = 0;
for(int e = 0; e < n_rows; e++) {
int entries = S.ReturnOp()->p[e+1];
while(count < entries) {
rows[count] = S.ReturnOp()->i[count];
cols[count] = e;
vals[count] = S.ReturnOp()->x[count];
count++;
}
}
CreateSparse();
}
template<typename T>
Sparse<T>::Sparse(Vector<T>& v) : nnz(v.GetLength()), n_rows(v.GetLength()), n_cols(v.GetLength()),
rows(new int[v.GetLength()]), cols(new int[v.GetLength()]), vals(new T[v.GetLength()]) {
int count = 0;
for(int e = 0; e < n_rows; e++) {
rows[e] = e;
cols[e] = e;
vals[e] = v(e);
}
CreateSparse();
}
template<typename T>
void Sparse<T>::CreateSparse() {
Operator = cs_spalloc(n_cols,n_rows,nnz,0,1);
free(Operator->i); free(Operator->p); free(Operator->x);
Operator->i = rows;
Operator->p = cols;
Operator->x = vals;
Operator->nz = nnz;
Operator = cs_compress(Operator);
cs_dupl(Operator);
nnz_red = Operator->nzmax;
}
template<typename T>
void Sparse<T>::CreateJacobian() {
Operator = cs_spalloc(n_cols,n_rows,nnz,1,1);
free(Operator->i); free(Operator->p); free(Operator->x);
Operator->i = rows;
Operator->p = cols;
Operator->x = vals;
Operator->nz = nnz;
nnz_red = Operator->nzmax;
}
template<typename T>
Sparse<T>& Sparse<T>::operator=(Sparse<T> S) {
//Sparse::~Sparse();
delete[] rows; delete[] cols; delete[] vals; cs_spfree(this->ReturnOp());
nnz = S.NNZ();
n_rows = S.ROWS();
n_cols = S.COLS();
rows = new int[nnz];
cols = new int[nnz];
vals = new T[nnz];
int count = 0;
for(int e = 0; e < n_rows; e++) {
int entries = S.ReturnOp()->p[e+1];
while(count < entries) {
rows[count] = S.ReturnOp()->i[count];
cols[count] = e;
vals[count] = S.ReturnOp()->x[count];
count++;
}
}
CreateSparse();
return *this;
}
template<typename T>
Sparse<T> Sparse<T>::operator+(const T a) {
Sparse<T> C = *this;
for(int i = 0; i < Operator->nzmax; i++)
C.ReturnOp()->x[i] = Operator->x[i] + a;
return C;
}
template<typename T>
Sparse<T> Sparse<T>::operator-(const T a) {
Sparse<T> C = *this;
for(int i = 0; i < Operator->nzmax; i++)
C.ReturnOp()->x[i] = Operator->x[i] - a;
return C;
}
template<typename T>
Sparse<T> Sparse<T>::operator*(const T a) {
Sparse<T> C = *this;
for(int i = 0; i < Operator->nzmax; i++)
C.ReturnOp()->x[i] = Operator->x[i] * a;
return C;
}
template<typename T>
Sparse<T> Sparse<T>::operator/(const T a) {
Sparse<T> C = *this;
for(int i = 0; i < Operator->nzmax; i++)
C.ReturnOp()->x[i] = Operator->x[i] / a;
return C;
}
template<typename T>
Sparse<T> operator+(Sparse<T> M, Sparse<T> N) {
Sparse<T> C(M.n_rows,M.n_cols,M.nnz);
C.Operator = cs_add(M.ReturnOp(),N.ReturnOp(),1.0,1.0);
C.NNZ_R() = C.ReturnOp()->nzmax;
return C;
}
template<typename T>
Sparse<T> operator-(Sparse<T> M, Sparse<T> N) {
Sparse<T> C(M.n_rows,M.n_cols,M.nnz);
C.Operator = cs_add(M.ReturnOp(),N.ReturnOp(),1.0,-1.0);
C.NNZ_R() = C.ReturnOp()->nzmax;
return C;
}
template<typename T>
Sparse<T> operator*(Sparse<T> M, Sparse<T> N) {
assert(M.n_cols == N.n_rows);
cs* Operator = cs_multiply(M.ReturnOp(),N.ReturnOp());
Sparse<T> C(M.ROWS(),N.COLS(),Operator->nzmax);
C.Operator = Operator;
C.NNZ_R() = Operator->nzmax;
return C;
}
template<typename T>
ostream& operator<<(ostream& out, Sparse<T>& S) {
cs_print(S.Operator,0);
return out;
}
template<typename T>
Vector<T> Sparse<T>::operator*(Vector<T> v) {
Vector<T> p(v.GetLength());
cs_gaxpy(Operator,v.GetAddress(),p.GetAddress());
return p;
}
template<typename T>
Vector<T> Sparse<T>::operator/(Vector<T> v) {
//cs_lusol(1,Operator,v.GetAddress(),0);
cs_cholsol(1,Operator,v.GetAddress());
Vector<double> p(v);
return p;
}
template<typename T>
Sparse<T> Sparse<T>::transpose() {
Sparse<T> trans(n_cols,n_rows,Operator->nzmax);
trans.Operator = cs_transpose(Operator,1);
trans.NNZ_R() = Operator->nzmax;
return trans;
}
template<typename T>
Vector<T> Sparse<T>::operator()(Vector<T> b, Vector<T> x0) {
Vector<T> r0 = b - (*this) * x0;
if(r0.Norm() == .0) {
Vector<T> z(x0.GetLength(),pow(10.0,-7.0));
r0 = b - (*this) * z;
cout << "Initial residual in CG iz zero!" << endl;
}
//Vector<T> PC = LoadJacobi();
Vector<T> z0 = r0; // PC * r0
Vector<T> p0 = z0;
T error = 1.0, tol = pow(10.0,-6.0);
int iters = 0;
while( error > tol ) {
Vector<T> Ap0 = (*this) * p0;
T alfa = (r0 && z0) / (p0 && Ap0 );
x0 += alfa * p0;
T rtr = (z0 && r0);
r0 -= alfa * Ap0;
z0 = r0; // PC * r0
error = sqrt(r0 && r0);
T beta = (z0 && r0) / rtr;
p0 = beta * p0 + z0;
iters++;
}
cout << "CG converged in " << iters << endl;
return x0;
}
template<typename T>
Sparse<T> Sparse<T>::LoadICChol() {
css *order = cs_schol(1,Operator);
csn* Chol = cs_chol(Operator,order);
cs* IChol = cs_multiply(Chol->L,Chol->U);
cout << IChol->nzmax << endl;
Sparse<T> C(n_rows,n_cols,IChol->nzmax);
C.Operator = IChol;
C.NNZ_R() = IChol->nzmax;
return C;
}
template<typename T>
Vector<T> Sparse<T>::LoadJacobi() {
int index1 = 0, index2 = 0;
Vector<T> PC(n_cols);
for(int k = 0; k < n_cols ; k++) {
index2 = Operator->p[k+1];
for(int j = index1; j < index2; j++)
if( Operator->i[j] == k )
PC(k) = 1.0 / Operator->x[j];
index1 = index2;
}
return PC;
}
template<typename T>
Sparse<T> Sparse<T>::operator+() {
return *this;
}
template<typename T>
Sparse<T> Sparse<T>::operator-() {
Sparse<T> S = *this;
for(int i = 0; i < Operator->nzmax; i++)
S.ReturnOp()->x[i] = - Operator->x[i];
return S;
}
template<typename T>
Vector<T> Sparse<T>::BiCG(Vector<T>& RHS)
{
int NVERTS = RHS.GetLength();
Vector<T> r0(NVERTS), r(NVERTS), p(NVERTS), v(NVERTS), t(NVERTS), s(NVERTS), x(NVERTS);
Vector<T> PC = LoadJacobi();
r0 = RHS;
r = r0;
int iters = 0;
double rho0 = 1.0, rho1, w0 = 1.0, alfa = 1.0, beta, Norm_r = 1.0, tol = pow(10.0,-10);
while( Norm_r > tol ) {
iters++;
rho1 = r0 && r;
beta = (rho1 / rho0) * (alfa / w0);
p = r + beta * (p - w0 * v);
Vector<T> y = PC * p;
v = (*this) * y;
alfa = rho1 / (r0 && v);
s = r - alfa * v;
Vector<T> z = PC * s;
t = (*this) * z;
Vector<T> temp = PC * t;
w0 = (temp && (PC * s)) / (temp && temp);
x += alfa * y + w0 * z;
r = s - w0 * t;
rho0 = rho1;
Norm_r = r.Norm();
}
return x;
}
template<typename T>
Sparse<T>& Sparse<T>::Diag(T& s) {
int index1 = 0, index2 = 0;
for(int k = 0; k < n_cols; k++) {
index2 = Operator->p[k+1];
for(int j = index1; j < index2; j++)
if(Operator->i[j] == k)
Operator->x[j] += s;
index1 = index2;
}
return *this;
}
template<typename T>
Sparse<T>& Sparse<T>::Diag(Vector<T>& s) {
int index1 = 0, index2 = 0;
for(int k = 0; k < n_cols; k++) {
index2 = Operator->p[k+1];
for(int j = index1; j < index2; j++)
if(Operator->i[j] == k)
Operator->x[j] += s(k);
index1 = index2;
}
return *this;
}
template<typename T>
Vector<T> Sparse<T>::Diag() {
int index1 = 0, index2 = 0;
assert(n_rows == n_cols);
Vector<T> V(n_rows,.0);
for(int k = 0; k < n_cols; k++) {
index2 = Operator->p[k+1];
for(int j = index1; j < index2; j++)
if(Operator->i[j] == k)
V(k) += Operator->x[j];
index1 = index2;
}
return V;
}
template<typename T>
T& Sparse<T>::operator()(const int row, const int col) {
int entries = Operator->p[col+1] - Operator->p[col];
T a;
for(int j = 0; j < entries; j++) {
int index = Operator->p[col]+j;
if(Operator->i[index] == row)
return Operator->x[row]; }
return a;
}
template<typename T>
Sparse<T>& Sparse<T>::operator&&(Vector<T>& v) {
int index1 = 0, index2;
for(int j = 0; j < v.GetLength(); j++) {
index2 = Operator->p[j+1];
for(int k = index1; k < index2; k++)
Operator->x[k] *= v(j);
index1 = index2;
}
return *this;
}
<file_sep>#include "Common.h"
#include "Matrix.h"
#include "DataStruct.h"
typedef Matrix<double> matrix;
typedef Vector<Matrix<double> > tensor;
void ReLoadIC(tensor& x) {
ifstream fp("input.dat");
if(fp.is_open()) {
for(int i = 0; i < Nc; i++) {
for(int j = 0; j < x(i).GetCols(); j++)
fp >> x(i)[0](j);
x(i)[1] = x(i)[0];
}
fp.close();
}
}
void LoadIC(matrix& c, double c0, double c1, DataStructure& Data, char* TYPE) {
if(!strcmp(TYPE,"Circle"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
x0 = 0.0, y0 = 0.0, r0 = sqrt(50.0);
if(pow(x-x0,2.0) + pow(y-y0,2.0) <= pow(r0,2.0))
c[0](i) = c0;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Separate"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
l0 = 25.0;
if(x <= 60 && x >= 40)
c[0](i) = c0;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Grid"))
for(int i = 1; i < Ny - 1; i++)
for(int j = 1; j < Nx - 1; j++)
if(i <= (Ny-1)/2)
c[0](Data(i,j)) = c0;
else
c[0](Data(i,j)) = c1;
if(!strcmp(TYPE,"Two-Circles"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
x0 = 3.0, y0 = 2.0, r0 = sqrt(1.0);
if(pow(x-x0,2.0) + pow(y+y0,2.0) <= pow(r0,2.0) ||
pow(x+x0,2.0) + pow(y-y0,2.0) <= pow(r0,2.0))
c[0](i) = c0;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Multiple-Circles")) {
int NumCirclesX = 4, NumCirclesY = 4;
double x0 = -15.0, y0 = 15.0, r0 = sqrt(0.5),
SpacingX = (2.0 * fabs(x0) - 2.0 * NumCirclesX * r0) / (NumCirclesX + 1.0),
SpacingY = (2.0 * fabs(y0) - 2.0 * NumCirclesY * r0) / (NumCirclesY + 1.0);
for(int i = 0; i < c.GetCols(); i++) {
bool IsInterior = false;
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1);
for(int j = 0; j < NumCirclesY; j++)
for(int k = 0; k < NumCirclesX; k++)
if( (pow(x - k*(SpacingX+2.0*r0) + 1.5*(2.0*r0 + SpacingX),2.0)+pow(y - j*(SpacingY+2.0*r0) + 1.5*(2.0*r0 + SpacingY),2.0)) <= pow(r0,2.0) ) {
IsInterior = true; }
if(IsInterior)
c[0](i) = c0;
else
c[0](i) = c1;
}
}
if(!strcmp(TYPE,"Multiple-Triangles")) {
int NumTrisX = 3, NumTrisY = 3;
double L = 50.0, l = sqrt(20.0),
SpacingX = (L - NumTrisX * l) / (NumTrisX + 1.f),
SpacingY = (L - NumTrisY * sqrt(3.f) * l / 2.f) / (NumTrisY + 1.f);
cout << SpacingX << " " << SpacingY << endl;
for(int i = 0; i < c.GetCols(); i++) {
bool IsInterior = false;
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1), dx;
for(int j = 0; j < NumTrisY; j++)
for(int k = 0; k < NumTrisX; k++)
if(x >= (SpacingX*(k+1) + k*l) && x <= (SpacingX*(k+1) + (k+1)*l)) {
if(x >= (SpacingX*(k+1) + k*l))
dx = ((SpacingX*(k+1) + (k+1)*l) - x);
else
dx = x - (SpacingX*(k+1) + k*l);
if(y >= (SpacingY*(j+1) + j*l*sqrt(3.f)/2.f) && y <= (tan(pi/4.f) * dx
+ SpacingY*(j+1) + j*l*sqrt(3.f)/2.f))
IsInterior = true;
}
if(IsInterior)
c[0](i) = c0;
else
c[0](i) = c1;
}
}
if(!strcmp(TYPE,"Triangle"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
x0 = 1.50, y0 = x0 * cos(pi/6.0), trans = 0.0;
if( (x >= -x0 && x <= x0) && ( y >= (-y0 - trans) && y <= (y0 - trans)) )
if( (y + y0 + trans) <= (x0 - fabs(x)) * tan(pi/3.0))
c[0](i) = c0;
else
c[0](i) = c1;
else
c[0](i) = c1;
}
c[1] = c[0];
}
<file_sep>#ifndef DATASTRUCT_H
#define DATASTRUCT_H
#include <fstream>
#include <iomanip>
#include <limits>
#include "Common.h"
class DataStructure {
int ** tris, ** neigh, Ntris, Nverts;
int GRIDPTS_X, GRIDPTS_Y, GRIDPTS, *is, *js, **id;
double ** verts, * area;
public:
// Structureless data structure
DataStructure(char* fname);
int GetNtris() const { return Ntris; }
int GetNverts() const { return Nverts; }
double GetVerts(const int i, const int j) const { return verts[i][j]; }
int GetTris(const int i, const int j) const { return tris[i][j]; }
int GetNeigh(const int i, const int j) const { return neigh[i][j]; }
double GetArea(const int i) const { return area[i]; }
// Structured (grid) data structure
DataStructure(int Npts1, int Npts2);
int GetNpts() const { return GRIDPTS; }
int GetXNpts() const { return GRIDPTS_X; }
int GetYNpts() const { return GRIDPTS_Y; }
int operator()(int i, int j) const { return id[i][j]; }
int operator[](int i) const { return is[i]; }
int operator()(int j) const { return js[j]; }
// Missing destructor
};
#endif
<file_sep>#include "Vector.h"
#ifndef MATRIX_H
#define MATRIX_H
#pragma once
template<typename T>
class Matrix: public Vector<Vector<T> >
{
protected:
int rows, cols;
public:
/*** Constructors ***/
Matrix(int dim1, int dim2, const T);
Matrix(Matrix<T>&);
Matrix() {;}
/*** Access operators ***/
Vector<T> operator()(const int);
Vector<T>& operator[](const int) const;
T& operator()(const int i, const int j) const {
return Vector<Vector<T> >::vec[i](j); }
template<typename Type>
friend ostream& operator<<(ostream&, Matrix<Type>&);
int GetRows() const { return rows; }
int GetCols() const { return cols; }
int GetLength() const { return Vector<T>::length; }
Matrix<T>& operator=(T);
Matrix<T>& operator=(Matrix<T>&);
/*** Matrix-Matrix Operators ***/
Matrix<T> operator+(Matrix<T>&);
Matrix<T> operator-(Matrix<T>&);
Matrix<T> operator*(Matrix<T>&);
Matrix<T> operator/(Matrix<T>&);
/*** Matrix-Vector Operators ***/
Vector<T> operator*(Vector<T>&);
template<typename Type>
friend Vector<Type> operator*(Vector<Type>& p, Matrix<Type> &m);
/*** Matrix self-operators ***/
template<typename Type>
Matrix<Type> trans(Matrix<Type>&);
~Matrix() {;}
};
#endif
/*** Constructors ***/
template<typename T>
Matrix<T>::Matrix(int dim1, int dim2, const T a = 0.0) : rows(dim1), cols(dim2) {
Vector<Vector<T> >::length = dim1;
Vector<Vector<T> >::vec = rows ? new Vector<T>[rows] : 0;
for(int i = 0; i < dim1; i++)
Vector<Vector<T> >::vec[i].Allocate(dim2,a);
}
template<typename T>
Matrix<T>::Matrix(Matrix<T>& m) {
Vector<Vector<T> >::vec = m.GetRows() ? new Vector<T>[m.GetRows()] : 0;
Vector<Vector<T> >::length = m.GetRows();
m.length = Vector<Vector<T> >::length;
rows = Vector<Vector<T> >::length;
cols = m.GetCols();
for(int i = 0; i < rows; i++)
Vector<Vector<T> >::vec[i].Allocate(cols,0.0);
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
Vector<Vector<T> >::vec[i](j) = m(i,j);
}
/*** Access operators ***/
template<typename T>
Vector<T> Matrix<T>::operator()(const int i) {
assert(i >= 0 && i < cols);
Vector<T> temp(rows,.0);
for(int j = 0; j < rows; j++) temp(j) = Vector<Vector<T> >::vec[j](i);
return temp;
}
template<typename T>
Vector<T>& Matrix<T>::operator[](const int i) const {
assert(i >= 0 && i <= rows);
return Vector<Vector<T> >::vec[i];
}
template<typename T>
ostream& operator<<(ostream& out, Matrix<T>& m) {
for(int i = 0; i < m.GetRows(); i++) {
for(int j = 0; j < m.GetCols(); j++)
out << m(i,j) << " ";
out << endl;
}
return out;
}
/*** Self-Matrix operators ***/
template<typename T>
Matrix<T> trans(Matrix<T>& m) {
Matrix<T> mt(m.GetCols(),m.GetRows(),.0);
for(int i = 0; i < m.GetRows(); i++)
for(int j = 0; j < m.GetCols(); j++)
mt(j,i) = m(i,j);
return mt;
}
/*** Matrix-Matrix operators ***/
template<typename T>
Matrix<T> Matrix<T>::operator+(Matrix<T>& m) {
Matrix<T> temp(rows,cols);
for(int i = 0; i < cols; i++)
temp(i) = m(i) + Vector<Vector<T> >::vec[i];
return temp;
}
template<typename T>
Matrix<T> Matrix<T>::operator-(Matrix<T>& m) {
Matrix<T> temp(rows,cols);
for(int i = 0; i < cols; i++)
temp(i) = Vector<Vector<T> >::vec[i] - m(i);
return temp;
}
/*** Matrix-vector operation(s) ***/
template<typename T>
Vector<T> Matrix<T>::operator*(Vector<T>& p) {
Vector<T> temp(rows);
for(int i = 0; i < cols; i++)
temp += Vector<Vector<T> >::vec[i] * p(i);
return temp;
}
template<typename T>
Vector<T> operator*(Vector<T>& p, Matrix<T> &m) {
Vector<T> temp(m.GetCols());
for(int i = 0; i < m.GetRows(); i++)
temp += m(i) * p(i);
return temp;
}
template<typename T>
Matrix<T>& Matrix<T>::operator=(T s) {
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
Vector<Vector<T> >::vec[i](j) = s;
return *this;
}
template<typename T>
Matrix<T>& Matrix<T>::operator=(Matrix<T>& m) {
Vector<Vector<T> >::vec = m.GetRows() ? new Vector<T>[m.GetRows()] : 0;
Vector<Vector<T> >::length = m.GetRows();
m.length = Vector<Vector<T> >::length;
rows = Vector<Vector<T> >::length;
cols = m.GetCols();
for(int i = 0; i < rows; i++)
Vector<Vector<T> >::vec[i].Allocate(cols,0.0);
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
Vector<Vector<T> >::vec[i](j) = m(i,j);
return *this;
}<file_sep>#include "Sparse.h"
#include "DataStruct.h"
#include "Vector.h"
extern double t, dt;
typedef Sparse<double> sparse;
typedef Vector<int> vector;
typedef Vector<double> vec;
template <typename T>
int find(Vector<T>& v, int c) {
for(int i = 0; i < v.GetLength(); i++)
if(v(i) == c)
return i;
return -1;
}
bool CheckBC(int index, const Vector<int>& BoundPoints) {
bool IsBC = false;
for(int i = 0; i < BoundPoints.GetLength(); i++)
if(index == BoundPoints(i)) {
IsBC = true;
break;
}
return IsBC;
}
sparse AssembleAdvection(DataStructure& Data, double velocity, char* BCType) {
/* Dirichlet BC is implemented inefficiently here */
int Nverts = Data.GetNverts(), nnz = 0, NNZMAX = 0, nBC = 0, uBC;
bool DirichletIsTrue = false;
if(!strcmp(BCType,"Dirichlet"))
DirichletIsTrue = true;
for(int i = 0; i < Data.GetNverts(); i++)
NNZMAX += Data.GetNeigh(i,0);
sparse Advection(Nverts,Nverts,2*NNZMAX);
ifstream file;
if(DirichletIsTrue) {
file.open("Dirichlet.dat");
file >> nBC >> uBC;
}
vector BoundPts(nBC);
if(DirichletIsTrue)
for(int i = 0; i < nBC; i++)
file >> BoundPts(i);
file.close();
for(int i = 0; i < Nverts; i++) {
int n = Data.GetNeigh(i,0);
double Area_C = .0;
for(int k = 1; k <= n; k++)
Area_C += Data.GetArea(Data.GetNeigh(i,k));
Area_C *= 1.0/3.0;
for(int j = 1; j <= n; j++) {
double x[3], y[3]; vector nodes(3);
for(int k = 0; k < 3; k++)
nodes(k) = Data.GetTris(Data.GetNeigh(i,j),k);
int index1 = find(nodes,i), index2 = 1, index3 = 2;
if(index1 == 1) {
index2 = 2;
index3 = 0;
}
if(index1 == 2) {
index2 = 0;
index3 = 1;
}
x[0] = Data.GetVerts(nodes(index1),0);
y[0] = Data.GetVerts(nodes(index1),1);
x[1] = Data.GetVerts(nodes(index2),0);
y[1] = Data.GetVerts(nodes(index2),1);
x[2] = Data.GetVerts(nodes(index3),0);
y[2] = Data.GetVerts(nodes(index3),1);
bool IsBoundary1 = CheckBC(nodes(index1),BoundPts),
IsBoundary2 = CheckBC(nodes(index2),BoundPts),
IsBoundary3 = CheckBC(nodes(index3),BoundPts);
double delta_x1 = x[2]/3.0 - x[1]/6.0 - x[0]/6.0,
delta_y1 = y[2]/3.0 - y[1]/6.0 - y[0]/6.0,
delta_x2 = x[2]/6.0 - x[1]/3.0 + x[0]/6.0,
delta_y2 = y[2]/6.0 - y[1]/3.0 + y[0]/6.0;
double qf1 = velocity * (delta_y1 - delta_x1),
qf2 = velocity * (delta_y2 - delta_x2);
if(qf1 > 0) {
Advection.Row(nnz) = i;
Advection.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index1);
if(IsBoundary1)
Advection.Val(nnz) = .0;
else
Advection.Val(nnz) = - qf1 / Area_C;
nnz++;
}
else {
Advection.Row(nnz) = i;
Advection.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index2);
if(IsBoundary2)
Advection.Val(nnz) = .0;
else
Advection.Val(nnz) = - qf1 / Area_C;
nnz++;
}
if(qf2 > 0) {
Advection.Row(nnz) = i;
Advection.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index1);
if(IsBoundary1)
Advection.Val(nnz) = .0;
else
Advection.Val(nnz) = - qf2 / Area_C;
nnz++;
}
else {
Advection.Row(nnz) = i;
Advection.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index3);
if(IsBoundary3)
Advection.Val(nnz) = .0;
else
Advection.Val(nnz) = - qf2 / Area_C;
nnz++;
}
}
}
Advection.CreateSparse();
return Advection;
}
sparse BuildAdvection(const DataStructure& Domain, double velocity) {
int Npts = Domain.GetNpts();
sparse Advection(Npts,Npts,3*Npts);
int nnz = 0;
if(velocity > .0)
for(int i = 0; i < Npts; i++) {
Advection.Val(nnz) = - 1.0 / hx - 1.0 / hy;
Advection.Row(nnz) = i;
Advection.Col(nnz) = i;
nnz++;
if(Domain(Domain[i],Domain(i)+1) != -4) {
Advection.Val(nnz) = 1.0 / hx;
Advection.Row(nnz) = i;
Advection.Col(nnz) = Domain(Domain[i],Domain(i)+1);
nnz++;
}
else {
Advection.Val(nnz) = 1.0 / hx;
Advection.Row(nnz) = i;
Advection.Col(nnz) = i;
nnz++;
}
if(Domain(Domain[i] + 1,Domain(i)) != -3) {
Advection.Val(nnz) = 1.0/hy;
Advection.Row(nnz) = i;
Advection.Col(nnz) = Domain(Domain[i]+1,Domain(i));
nnz++;
}
else {
Advection.Val(nnz) = 1.0/hy;
Advection.Row(nnz) = i;
Advection.Col(nnz) = i;
nnz++;
}
}
else
for(int i = 0; i < Npts; i++) {
Advection.Val(nnz) = 1.0 / hx + 1.0 / hy;
Advection.Row(nnz) = i;
Advection.Col(nnz) = i;
nnz++;
if(Domain(Domain[i],Domain(i) - 1) != -2) {
Advection.Val(nnz) = - 1.0 / hx;
Advection.Row(nnz) = i;
Advection.Col(nnz) = Domain(Domain[i],Domain(i)-1);
nnz++;
}
else {
Advection.Val(nnz) = - 1.0 / hx;
Advection.Row(nnz) = i;
Advection.Col(nnz) = i;
nnz++;
}
if(Domain(Domain[i]-1,Domain(i)) != -1) {
Advection.Val(nnz) = - 1.0/hy;
Advection.Row(nnz) = i;
Advection.Col(nnz) = Domain(Domain[i]-1,Domain(i));
nnz++;
}
else {
Advection.Val(nnz) = - 1.0/hy;
Advection.Row(nnz) = i;
Advection.Col(nnz) = i;
nnz++;
}
}
Advection.CreateSparse();
return Advection;
}
<file_sep>#include "Common.h"
#include "Matrix.h"
#include "Sparse.h"
typedef Vector<double> vector;
typedef Matrix<double> matrix;
typedef Sparse<double> sparse;
/*vector ConstructEqs(const vector& x, const matrix& RHS, const sparse& L);
sparse ConstructJacobian(const vector& x, const matrix& RHS, const sparse& Diff)
{
unsigned N = x.GetLength(), nnz = 0, NNZMAX = 3*N*Nc;
int *rows = new int[NNZMAX],
*cols = new int[NNZMAX];
vector Derivative(N);
double h = pow(10.0,-6.0), *vals = new double[NNZMAX];
for(int i = 0; i < N; i++) {
vector Eqs = ConstructEqs(x,RHS,Diff);
x(i) += h;
vector NewEqs = ConstructEqs(x,RHS,Diff);
x(i) -= h;
Derivative = (NewEqs - Eqs);
for(int k = 0; k < N; k++)
if(Derivative(k) != .0) {
rows[nnz] = k;
cols[nnz] = i;
vals[nnz] = Derivative(k) / h;
nnz++;
}
}
assert(nnz <= NNZMAX);
sparse Jacobian(N,N,nnz);
for(int k = 0; k < nnz; k++) {
Jacobian.Row(k) = rows[k];
Jacobian.Col(k) = cols[k];
Jacobian.Val(k) = vals[k];
}
Jacobian.CreateSparse();
delete[] rows; delete[] cols; delete[] vals;
return Jacobian;
}
*/
vector ComputeRecursiveDerivative(int order, int Gorder, int n, const vector& dt, const vector& x, vector& der) {
double coef = dt(0), sum = dt(0);
for(int i = 1; i < Gorder; i++)
sum += dt(i);
coef /= sum;
if(order == 1)
der = coef * (x(n-1) - x(n)) / (dt(n-1));
else
der = (ComputeRecursiveDerivative(order-1,Gorder,n-1,dt,x,der) - ComputeRecursiveDerivative(order-1,Gorder,n,dt,x,der));
//cout << "der : " << order << " - " << der << endl;
return der;
}
matrix ConstructSequence(const vector& dt, const vector& x) {
int Order = dt.GetLength();
matrix Sequence(Order,1);
for(int i = Order; i > 0; i--)
Sequence[i-1] = ComputeRecursiveDerivative(i,i,i,dt,x,Sequence[i-1]);
return Sequence;
}
vector ConstructBDF(int Order, const vector& dt) {
vector coef(Order+1,.0);
Vector<int> occ1(Order,1), occ2(Order,0);
coef(0) = 1.0; coef(1) = -1.0;
for(int i = 0; i < 2; i++) {
int num = (i%2) ? -1 : 1;
for(int j = 1; j < Order; j++) {
double factor = .0;
for(int k = 0; k <= j; k++)
factor += dt(k);
factor = dt(0) * dt(0) / factor;
// The 'i' is optional ... could use an if statement too //
occ2(j) = occ1(j-1) + i * occ2(j-1);
if( i > 0)
coef(i) += num * (occ1(j-1) / dt(i-1) + occ2(j-1) / dt(i)) * factor;
else
coef(i) += num * (occ1(j-1) / dt(i)) * factor;
}
occ2(0) = 1;
}
occ1 = occ2;
for(int i = 2; i <= Order; i++) {
int num = (i%2) ? -1 : 1;
occ2(i-2) = 0;
for(int j = i - 1; j < Order; j++) {
double factor = .0;
for(int k = 0; k <= j; k++)
factor += dt(k);
factor = dt(0) * dt(0) / factor;
occ2(j) = occ1(j-1) + occ2(j-1);
if(i == Order)
coef(i) += num * (occ1(j-1) / dt(i-1)) * factor;
else
coef(i) += num * (occ1(j-1) / dt(i-1) + occ2(j-1) / dt(i)) * factor;
}
occ1 = occ2;
}
return coef/dt(0);
}
vector ConstructBDFConst(int length) {
vector coef(length+1,.0);
Vector<int> occ1(length,1), occ2(length,0);
coef(0) = 1.0; coef(1) = -1.0;
for(int i = 0; i < 2; i++) {
int num = (i%2) ? -1 : 1;
for(int j = 1; j < length; j++) {
occ2(j) = occ1(j-1) + i * occ2(j-1);
coef(i) += num * occ2(j) / (j+1.0);
}
occ2(0) = 1;
}
occ1 = occ2;
for(int i = 2; i <= length; i++) {
int num = (i%2) ? -1 : 1;
occ2(i-2) = 0;
for(int j = i - 1; j < length; j++) {
occ2(j) = occ1(j-1) + occ2(j-1);
coef(i) += num * occ2(j) / (j+1.0);
}
occ1 = occ2;
}
return coef;
}
<file_sep>AUB
===
My vertex-based FVM code for simulating Liesegang patterns in 2D
<file_sep>#include <fstream>
#include<iomanip>
#include <limits>
#include "Main.h"
#ifndef DATASTRUCT_H
#define DATASTRUCT_H
class DataStructure {
private:
int ** tris, ** neigh, Ntris, Nverts;
double ** verts, * area;
public:
DataStructure(char* fname);
int GetNtris() const { return Ntris; }
int GetNverts() const { return Nverts; }
double GetVerts(const int i, const int j) const { return verts[i][j]; }
int GetTris(const int i, const int j) const { return tris[i][j]; }
int GetNeigh(const int i, const int j) const { return neigh[i][j]; }
double GetArea(const int i) const { return area[i]; }
};
#endif
<file_sep>#include "Common.h"
#include "Vector.h"
#include "DataStruct.h"
double GlobRate(const DataStructure& Domain, const Vector<double>& R) {
double GR = .0;
for(int i = 1; i < Domain.GetYNpts() - 2; i++)
GR += (R(Domain(i,1)) + R(Domain(i+1,1)));
return 0.5*hy*GR;
}
<file_sep>#include <iostream>
#include <cmath>
#include "assert.h"
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib> // for GCC 4.3 and above
#include <cstring> // for GCC 4.3 and above
#pragma once
#define pi 3.141592653589793
using namespace std;
const double Da = 0.1, Db = 0.1, Dc = 0.0001, a0 = 100.0,
b0 = 5.0, kr = pow(10.0,-6.0), c1 = 0.1, c2 = 0.25, c3 = 0.4,
alfa = 10.0, beta = 10.0, gama = 10.0, delta = 10.0,
velocity1 = 0.01, velocity2 = -velocity1, Nx = 3,
Ny = 3001, hx = 0.1, hy = 0.1;
const int Nc = 5;
<file_sep>#include "Matrix.h"
#include "Vector.h"
#include "DataStruct.h"
#include "Sparse.h"
double t(0.0), dt0 = pow(10.0,-6.0), PERIOD;
const double tmax = 100.0, tmin = tmax, dc = 0.05;
typedef Matrix<double> matrix;
typedef Vector<double> vector;
typedef Sparse<double> sparse;
typedef Vector<Matrix<double> > tensor;
vector Construct_BDF(int, const vector&);
sparse AssembleIsotropicDiffusion(DataStructure&);
void LoadIC(matrix& c, double c0, double c1, DataStructure& Data,char* TYPE);
void LoadIC(tensor& x);
void FixRHS(vector& RHS);
vector ConstructTheta(double cr, vector& c) {
vector theta(c.GetLength(),.0);
for(int i = 0; i < c.GetLength(); i++)
if(c(i) >= cr)
theta(i) = 1.0;
return theta;
}
double FixedPointStep(const DataStructure& Mesh, const sparse& Diff, const matrix& RHS, vector& x1, vector& x2, vector& x3,
vector& x4, vector& x5, double coef)
{
int Npts = Mesh.GetNverts();
vector theta1 = ConstructTheta(c1,x3),
theta2 = ConstructTheta(c2,x3),
theta3 = ConstructTheta(c3,x3),
RHS1 = RHS[0],
RHS2 = RHS[1],
RHS3 = RHS[2] + kr * x1 * x2 + alfa * c3 * theta3 + delta * c1 * theta1 * x5 + beta * (1.0 - theta2) * c2 * x4,
RHS4 = RHS[3] + (x3 - c3) * alfa * theta3,
RHS5 = RHS[4] + gama * (x3 - c2) * theta2 * x4;
sparse Op1 = Diff * Da, Op2 = Diff * Db, Op3 = Diff * Dc;
vector v1 = coef + kr * x2,
v2 = coef + kr * x1,
v3 = coef + alfa * theta3 + delta * theta1 * x5 + beta * (1.0 - theta2) * x4;
Op1.Diag(v1);
Op2.Diag(v2);
Op3.Diag(v3);
vector sol1 = Op1(RHS1,x1),
sol2 = Op2(RHS2,x2),
sol3 = Op3(RHS3,x3),
sol4(Npts,.0),
sol5(Npts,.0),
Op4 = coef + gama * (x3 - c2) * theta2 + beta * (1.0 - theta2) * (c2 - x3),
Op5 = coef - delta * (x3 - c1) * theta1;
sol4 = RHS4 / Op4;
sol5 = RHS5 / Op5;
double error = max((sol1 - x1).Amax(),max((sol2 - x2).Amax(),max((sol3 - x3).Amax(),max((sol4 - x4).Amax(),(sol5 - x5).Amax()))));
x1 = sol1; x2 = sol2; x3 = sol3; x4 = sol4; x5 = sol5;
return error;
}
double FPI_RD(const DataStructure& Mesh, sparse& Diff, matrix RHS, vector& x1, vector& x2, double coef, double dt)
{
int Npts = Mesh.GetNverts();
vector RHS1 = RHS[0],
RHS2 = RHS[1];
sparse Op1 = Diff * (Da * dt), Op2 = Diff * (Db * dt);
vector v1 = coef + (dt * kr) * x2,
v2 = coef + (dt * kr) * x1;
Op1.Diag(v1);
Op2.Diag(v2);
vector sol1 = Op1(RHS1,x1),
sol2 = Op2(RHS2,x2);
double error = max((sol1 - x1).Amax(),(sol2 - x2).Amax());
x1 = sol1; x2 = sol2;
return error;
}
double NTR_NU(const DataStructure& Mesh, sparse& Diff, matrix RHS, vector& x1, vector& x2, vector& x3, vector& x4,
vector& x5, double coef, double dt)
{
int Npts = Mesh.GetNverts();
sparse Opc = Diff * (Dc * dt);
vector theta1 = ConstructTheta(c1,x3),
theta2 = ConstructTheta(c2,x3),
theta3 = ConstructTheta(c3,x3),
z(Npts,.0),
RHS3 = RHS[2] - coef * x3 - Opc * x3 + dt * (kr * x1 * x2 - alfa * theta3 * (x3 - c3)
- delta * theta1 * (x3 - c1) * x5 + beta * (1.0 - theta2) * (c2 - x3) * x4),
RHS4 = RHS[3] - coef * x4 + dt * ((x3 - c3) * alfa * theta3 - beta * (1.0 - theta2) * (x3 - c2) * x4
- gama * theta2 * (x3 - c2) * x4),
RHS5 = RHS[4] - coef * x5 + dt * (gama * (x3 - c2) * theta2 * x4 + delta * (x3 - c1) * theta1 * x5);
vector J11 = coef + dt * (alfa * theta3 + delta * theta1 * x5 + beta * (1.0 - theta2) * x4),
J12 = dt * (- beta * (c2 - x3) * (1.0 - theta2)),
J13 = dt * (delta * (x3 - c1) * theta1),
J21 = dt * (- alfa * theta3 + beta * (1.0 - theta2) * x4 + gama * theta2 * x4),
J22 = coef + dt * (beta * (c2 - x3) * (1.0 - theta2) + gama * theta2 * (x3 - c2)),
J31 = dt * (- gama * theta2 * x4 - delta * theta1 * x5),
J32 = dt *(- gama * (x3 - c2) * theta2),
J33 = coef - dt * (delta * (x3 - c1) * theta1),
V = J11 - J12 * J21 / J22 - J13 * J31 / J33 + J13 * J32 * J21 / (J22 * J33);
//cout << (Diff.Diag()).max() << " " << (Diff.Diag()).min() << endl;
Opc.Diag(V);
//Opc = PC * Opc;
vector RHSc = (RHS3 + (J12 / J22 - J13 * J32 / (J22*J33)) * RHS4 + J13 * RHS5 / J33),
dc = Opc(RHSc,z),
dn = - (- RHS4 + J21 * dc) / J22,
dp = - (- RHS5 + J31 * dc + J32 * dn) / J33;
double error = max(dc.Amax(),max(dn.Amax(),dp.Amax()));
//cout << x3.Norm() << " " << x4.Norm() << " " << x5.Norm() << endl;
x3 += dc; x4 += dn; x5 += dp;
//cout << "Cond num = " << (Opc.Diag()).max() / (Opc.Diag()).min() << endl;
return error;
}
bool NewtonSolver(const DataStructure& Mesh, const sparse& Diff, tensor& x, vector& dt, int Order)
{
int theta, GOrder, Npts = Mesh.GetNverts(), max_iters = 20;
vector cm(1,.0);
if(t >= (Order-1) * dt0)
GOrder = Order;
else {
theta = (t + dt0)/dt0;
GOrder = theta;
}
vector BDF1 = Construct_BDF(GOrder,dt), BDF2(GOrder,.0);
matrix RHS1(Nc,Npts), RHS2(Nc,Npts);
for(int j = 0; j < Nc; j++)
for(int i = 1; i < GOrder + 1; i++)
RHS1[j] -= BDF1(i) * x(j)[i];
if(GOrder > 1) {
BDF2 = Construct_BDF(GOrder-1,dt);
for(int j = 0; j < Nc; j++)
for(int i = 1; i < GOrder; i++)
RHS2[j] -= BDF2(i) * x(j)[i];
}
vector x1 = x(0)[0], x2 = x(1)[0], x3 = x(2)[0], x4 = x(3)[0], x5 = x(4)[0];
double error = 1.0, tol = pow(10.0,-6.0), est = .0, abs_error = 0.0001, rel_error = abs_error;
int iters = 0;
while(error > tol) {
iters++;
error = FixedPointStep(Mesh,Diff,RHS1,x1,x2,x3,x4,x5,BDF1(0));
if(iters > max_iters)
break;
}
cout << "FPI iters = " << iters << endl;
x(0)[Order+2] = x1; x(1)[Order+2] = x2; x(2)[Order+2] = x3; x(3)[Order+2] = x4;
x(4)[Order+2] = x5;
if(GOrder > 1 && iters <= max_iters) {
vector err(Nc*Npts,.0);
matrix deriv1 = RHS1, deriv2 = RHS2;
for(int i = 0; i < Nc; i++) {
deriv1[i] -= BDF1(0) * x(i)[Order+2];
deriv2[i] -= BDF2(0) * x(i)[Order+2];
}
for(int i = 0; i < Nc; i++)
for(int j = 0; j < Npts; j++)
if(fabs(deriv1[i](j)) > pow(10.0,-8.0))
err(i*Npts+j) = (fabs(deriv1[i](j)) - fabs(deriv2[i](j))); // / fabs(deriv1[i](j));
est = err.Norm(); double deno = .0;
for(int i = 0; i < Nc; i++)
deno += deriv1[i].Norm(); est = est / deno;
}
if(iters > max_iters) {
cout << "Failure to converge with attempted timestep = " << dt(0) << endl;
est = rel_error * 2.0; }
if( est < rel_error) {
for(int i = 0; i < Nc; i++)
x(i)[0] = x(i)[Order+2];
for(int i = 0; i < Nc; i++)
for(int j = Order; j > 0; j--)
x(i)[j] = x(i)[j-1];
t += dt(0);
vector time(1,dt(0));
cm(0) = x(2)[0].Amax();
time.Write("adaptive.dat");
cm.Write("cmax.dat");
for(int i = Order - 1; i > 0; i--)
dt(i) = dt(i-1);
cout << "Newton Adaptive BDF Solver Converged with c_max = " << cm << " at time " << t << endl;
}
if(GOrder > 1 && cm(0) < (c3 - dc))
dt(0) = min(tmax,0.8 * dt(0) * pow(rel_error/est,1.0/(GOrder)));
else
if(cm(0) >= (c3 - dc))
dt(0) = min(tmin,0.8 * dt(0) * pow(rel_error/est,1.0/GOrder));
return 0;
}
int main(int argc, char* argv[]) {
DataStructure Mesh(argv[6]);
int Npts = Mesh.GetNverts();
sparse Diff = AssembleIsotropicDiffusion(Mesh);
if(!strcmp(argv[1],"help")) {
cout << "==================================================================" << endl;
cout << "==================================================================" << endl;
cout << "CVFEM PDE solver for Lisegang systems, written by <NAME>" << endl;
cout << "------------------------------------------------------------------" << endl;
cout << "Program in Computational Science, American University of Beirut" << endl;
cout << "==================================================================" << endl;
cout << "==================================================================" << endl;
cout << "Usage: ./PDES [Order Cond Period Type OutputFname] [Mesh]" << endl << endl;
cout << "Order = an integer specifying the BDF order." << endl << endl;
cout << "Cond = a string which initializes the simulation if 'Initialize' is selected, otherwise the simulation is resumed "
<< "based on an input file input.dat" << endl << endl;
cout << "Period = a floating point number that specifies the time at which the simulation ends." << endl << endl;
exit(1);
}
else
if(argc == 7)
{
int Order = atoi(argv[2]);
char* IC_COND = argv[1];
double PERIOD = atof(argv[3]);
char* Type = argv[4];
char* Output = argv[5];
//dt0 = atof(argv[7]);
cout << "BDF order : " << Order << endl << "Simulation time : " << PERIOD << endl;
if(!strcmp(IC_COND,"Initialize"))
cout << "Initializing simulation ..." << endl;
else
cout << "Resuming simulation ..." << endl;
vector dt(Order,dt0);
matrix m(Order+3,Npts,.0);
tensor x(Nc,m);
if(strcmp(IC_COND,"Initialize"))
LoadIC(x);
else {
LoadIC(x(0),a0,.0,Mesh,Type);
LoadIC(x(1),0.0,b0,Mesh,Type);
}
while(t <= PERIOD)
NewtonSolver(Mesh,Diff,x,dt,Order);
for(int i = 0; i < Nc; i++)
x(i)[0].Write(Output);
}
else {
cout << "Error in syntax." << endl;
cout << "Type ./PDES help for instructions on how to run the program." << endl;
exit(1);
}
return 0;
}
<file_sep>#include "Main.h"
#include "Vector.h"
typedef Vector<double> vector;
vector Construct_BDF(int Order, const vector& dt) {
vector coef(Order+1,.0);
Vector<int> occ1(Order,1), occ2(Order,0);
coef(0) = 1.0; coef(1) = -1.0;
for(int i = 0; i < 2; i++) {
int num = (i%2) ? -1 : 1;
for(int j = 1; j < Order; j++) {
double factor = .0;
for(int k = 0; k <= j; k++)
factor += dt(k);
factor = dt(0) * dt(0) / factor;
// The 'i' is optional ... could use an if statement too //
occ2(j) = occ1(j-1) + i * occ2(j-1);
if( i > 0)
coef(i) += num * (occ1(j-1) / dt(i-1) + occ2(j-1) / dt(i)) * factor;
else
coef(i) += num * (occ1(j-1) / dt(i)) * factor;
}
occ2(0) = 1;
}
occ1 = occ2;
for(int i = 2; i <= Order; i++) {
int num = (i%2) ? -1 : 1;
occ2(i-2) = 0;
for(int j = i - 1; j < Order; j++) {
double factor = .0;
for(int k = 0; k <= j; k++)
factor += dt(k);
factor = dt(0) * dt(0) / factor;
occ2(j) = occ1(j-1) + occ2(j-1);
if(i == Order)
coef(i) += num * (occ1(j-1) / dt(i-1)) * factor;
else
coef(i) += num * (occ1(j-1) / dt(i-1) + occ2(j-1) / dt(i)) * factor;
}
occ1 = occ2;
}
return coef/dt(0);
}
vector Construct_BDF_const(int length) {
vector coef(length+1,.0);
Vector<int> occ1(length,1), occ2(length,0);
coef(0) = 1.0; coef(1) = -1.0;
for(int i = 0; i < 2; i++) {
int num = (i%2) ? -1 : 1;
for(int j = 1; j < length; j++) {
occ2(j) = occ1(j-1) + i * occ2(j-1);
coef(i) += num * occ2(j) / (j+1.0);
}
occ2(0) = 1;
}
occ1 = occ2;
for(int i = 2; i <= length; i++) {
int num = (i%2) ? -1 : 1;
occ2(i-2) = 0;
for(int j = i - 1; j < length; j++) {
occ2(j) = occ1(j-1) + occ2(j-1);
coef(i) += num * occ2(j) / (j+1.0);
}
occ1 = occ2;
}
return coef;
}
<file_sep>#include "Sparse.h"
#include "DataStruct.h"
#include "Vector.h"
extern double t, dt;
typedef Sparse<double> sparse;
typedef Vector<int> vector;
typedef Vector<double> vec;
template <typename T>
int find(Vector<T>& v, int c) {
for(int i = 0; i < v.GetLength(); i++)
if(v(i) == c)
return i;
return -1;
}
sparse AssembleIsotropicDiffusion(const DataStructure& Data) {
int Nverts = Data.GetNverts(), nnz = 0, NNZMAX = 0;
for(int i = 0; i < Data.GetNverts(); i++)
NNZMAX += Data.GetNeigh(i,0);
sparse Diffusion(Nverts,Nverts,3*NNZMAX);
for(int i = 0; i < Nverts; i++) {
int n = Data.GetNeigh(i,0);
double Area_C = .0;
for(int k = 1; k <= n; k++)
Area_C += Data.GetArea(Data.GetNeigh(i,k));
Area_C *= 1.0/3.0;
for(int j = 1; j <= n; j++) {
double x[3], y[3]; vector nodes(3);
for(int k = 0; k < 3; k++)
nodes(k) = Data.GetTris(Data.GetNeigh(i,j),k);
// Tris(:,:) contains nodes in an anti-clockwise geomtric pattern
int index1 = find(nodes,i), index2 = 1, index3 = 2;
if(index1 == 1) {
index2 = 2;
index3 = 0;
}
if(index1 == 2) {
index2 = 0;
index3 = 1;
}
x[0] = Data.GetVerts(nodes(index1),0);
y[0] = Data.GetVerts(nodes(index1),1);
x[1] = Data.GetVerts(nodes(index2),0);
y[1] = Data.GetVerts(nodes(index2),1);
x[2] = Data.GetVerts(nodes(index3),0);
y[2] = Data.GetVerts(nodes(index3),1);
double delta_x1 = x[2]/3.0 - x[1]/6.0 - x[0]/6.0,
delta_y1 = y[2]/3.0 - y[1]/6.0 - y[0]/6.0,
delta_x2 = x[2]/6.0 - x[1]/3.0 + x[0]/6.0,
delta_y2 = y[2]/6.0 - y[1]/3.0 + y[0]/6.0,
Area = Data.GetArea(Data.GetNeigh(i,j)),
div_x[3] = {(y[1] - y[2]) / (2.0*Area),
(y[2] - y[0]) / (2.0*Area),
(y[0] - y[1]) / (2.0*Area)},
div_y[3] = {(x[2] - x[1]) / (2.0*Area),
(x[0] - x[2]) / (2.0*Area),
(x[1] - x[0]) / (2.0*Area)},
a1 = div_x[0] * (delta_y1 + delta_y2) - div_y[0] * (delta_x1 + delta_x2),
a2 = div_x[1] * (delta_y1 + delta_y2) - div_y[1] * (delta_x1 + delta_x2),
a3 = div_x[2] * (delta_y1 + delta_y2) - div_y[2] * (delta_x1 + delta_x2);
Diffusion.Row(nnz) = i;
Diffusion.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index1);
Diffusion.Val(nnz) = - a1 / Area_C;
nnz++;
Diffusion.Row(nnz) = i;
Diffusion.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index2);
Diffusion.Val(nnz) = - a2 / Area_C;
nnz++;
Diffusion.Row(nnz) = i;
Diffusion.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index3);
Diffusion.Val(nnz) = - a3 / Area_C;
nnz++;
}
}
Diffusion.CreateSparse();
return Diffusion;
}
sparse BuildLaplacian(const DataStructure& Domain) {
int Npts = Domain.GetNpts();
sparse Laplace(Npts,Npts,5*Npts);
int nnz = 0;
for(int i = 0; i < Npts; i++) {
Laplace.Val(nnz) = - 2.0 / (hx*hx) - 2.0 / (hy*hy);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = i;
nnz++;
if(Domain(Domain[i],Domain(i)+1) != -4) {
Laplace.Val(nnz) = 1.0 / (hx*hx);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = Domain(Domain[i],Domain(i)+1);
nnz++;
}
else {
Laplace.Val(nnz) = 1.0 / (hx*hx);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = i;
nnz++;
}
if(Domain(Domain[i],Domain(i) - 1) != -2) {
Laplace.Val(nnz) = 1.0 / (hx*hx);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = Domain(Domain[i],Domain(i)-1);
nnz++;
}
else {
Laplace.Val(nnz) = 1.0 / (hx*hx);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = i;
nnz++;
}
if(Domain(Domain[i] + 1,Domain(i)) != -3) {
Laplace.Val(nnz) = 1.0/(hy*hy);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = Domain(Domain[i]+1,Domain(i));
nnz++;
}
else {
Laplace.Val(nnz) = 1.0/(hy*hy);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = i;
nnz++;
}
if(Domain(Domain[i]-1,Domain(i)) != -1) {
Laplace.Val(nnz) = 1.0/(hy*hy);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = Domain(Domain[i]-1,Domain(i));
nnz++;
}
else {
Laplace.Val(nnz) = 1.0/(hy*hy);
Laplace.Row(nnz) = i;
Laplace.Col(nnz) = i;
nnz++;
}
}
Laplace.CreateSparse();
return Laplace;
}
<file_sep>#include "Main.h"
#include "Sparse.h"
#include "DataStruct.h"
#include "Vector.h"
extern double t, dt;
typedef Sparse<double> sparse;
typedef Vector<int> vector;
typedef Vector<double> vec;
template <typename T>
int find(Vector<T>& v, int c) {
for(int i = 0; i < v.GetLength(); i++)
if(v(i) == c)
return i;
return -1;
}
void AssembleTransient(sparse &Op, double Coef) {
int index1 = 0, index2 = 0;
for(int k = 0; k < Op.COLS() ; k++) {
index2 = Op.ReturnOp()->p[k+1];
for(int j = index1; j < index2; j++)
if(Op.ReturnOp()->i[j] == k)
Op.ReturnOp()->x[j] += Coef;
index1 = index2;
}
}
sparse AssembleSource(sparse &Op, Vector<double>& v) {
int index1 = 0, index2 = 0;
sparse Oper = Op;
for(int k = 0; k < Op.COLS() ; k++) {
index2 = Op.ReturnOp()->p[k+1];
for(int j = index1; j < index2; j++)
if(Op.ReturnOp()->i[j] == k)
Oper.ReturnOp()->x[j] += kr * v(k);
index1 = index2;
}
return Oper;
}
sparse AssembleNucleation(sparse &Op, vec& n, vec& p, vec& c, double Coef) {
int index1 = 0, index2 = 0;
sparse Oper = Op;
for(int k = 0; k < Op.COLS(); k++) {
bool theta1 = c(k) >= c1, theta2 = c(k) >= c2, theta3 = c(k) >= c3;
double D1 = Coef + beta * c2 - beta * c(k) + (c(k) - c2) * theta2 * beta
+ gama * theta2 * (c(k) - c2),
D2 = beta * n(k) * (theta2 - 1.0) + gama * theta2 * n(k) - alfa * theta3,
D3 = gama * theta2 * (c2 - c(k)),
D4 = Coef + delta * theta1 * (c1 - c(k)),
D5 = - delta * theta1 * p(k) - gama * theta2 * n(k),
D6 = beta * c(k) * (1.0 - theta2) + beta * c2 * (theta2 - 1.0),
D7 = delta * theta1 * (c(k) - c1),
L = alfa * theta3 + delta * theta1 * p(k) + beta * n(k) * (1.0 - theta2),
V = - D6 * D2/D1 - D5 * D7/D4 + D2*D3*D7 / (D1*D4) + L;
index2 = Op.ReturnOp()->p[k+1];
for(int j = index1; j < index2; j++)
if(Op.ReturnOp()->i[j] == k)
Oper.ReturnOp()->x[j] += V;
index1 = index2;
}
return Oper;
}
sparse AssembleNucleation_Picard(sparse &Op, vec& n, vec& p, vec& c) {
int index1 = 0, index2 = 0;
sparse Oper = Op;
for(int k = 0; k < Op.COLS(); k++) {
bool theta1 = c(k) >= c1, theta2 = c(k) >= c2, theta3 = c(k) >= c3;
double V = alfa * theta3 + delta * theta1 * p(k) + beta * n(k) * (1.0 - theta2);
index2 = Op.ReturnOp()->p[k+1];
for(int j = index1; j < index2; j++)
if(Op.ReturnOp()->i[j] == k)
Oper.ReturnOp()->x[j] += V;
index1 = index2;
}
return Oper;
}
sparse AssembleIsotropicDiffusion(DataStructure& Data) {
int Nverts = Data.GetNverts(), nnz = 0, NNZMAX = 0;
for(int i = 0; i < Data.GetNverts(); i++)
NNZMAX += Data.GetNeigh(i,0);
sparse Diffusion(Nverts,Nverts,3*NNZMAX);
for(int i = 0; i < Nverts; i++) {
int n = Data.GetNeigh(i,0);
double Area_C = .0;
for(int k = 1; k <= n; k++)
Area_C += Data.GetArea(Data.GetNeigh(i,k));
Area_C *= 1.0/3.0;
for(int j = 1; j <= n; j++) {
double x[3], y[3]; vector nodes(3);
for(int k = 0; k < 3; k++)
nodes(k) = Data.GetTris(Data.GetNeigh(i,j),k);
int index1 = find(nodes,i), index2 = 1, index3 = 2;
if(index1 == 1) {
index2 = 2;
index3 = 0;
}
if(index1 == 2) {
index2 = 0;
index3 = 1;
}
x[0] = Data.GetVerts(nodes(index1),0);
y[0] = Data.GetVerts(nodes(index1),1);
x[1] = Data.GetVerts(nodes(index2),0);
y[1] = Data.GetVerts(nodes(index2),1);
x[2] = Data.GetVerts(nodes(index3),0);
y[2] = Data.GetVerts(nodes(index3),1);
double delta_x1 = x[2]/3.0 - x[1]/6.0 - x[0]/6.0,
delta_y1 = y[2]/3.0 - y[1]/6.0 - y[0]/6.0,
delta_x2 = x[2]/6.0 - x[1]/3.0 + x[0]/6.0,
delta_y2 = y[2]/6.0 - y[1]/3.0 + y[0]/6.0,
Area = Data.GetArea(Data.GetNeigh(i,j)),
div_x[3] = {(y[1] - y[2]) / (2.0*Area),
(y[2] - y[0]) / (2.0*Area),
(y[0] - y[1]) / (2.0*Area)},
div_y[3] = {(x[2] - x[1]) / (2.0*Area),
(x[0] - x[2]) / (2.0*Area),
(x[1] - x[0]) / (2.0*Area)},
a1 = div_x[0] * (delta_y1 + delta_y2) - div_y[0] * (delta_x1 + delta_x2),
a2 = div_x[1] * (delta_y1 + delta_y2) - div_y[1] * (delta_x1 + delta_x2),
a3 = div_x[2] * (delta_y1 + delta_y2) - div_y[2] * (delta_x1 + delta_x2);
Diffusion.Row(nnz) = i;
Diffusion.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index1);
Diffusion.Val(nnz) = - a1 / Area_C;
nnz++;
Diffusion.Row(nnz) = i;
Diffusion.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index2);
Diffusion.Val(nnz) = - a2 / Area_C;
nnz++;
Diffusion.Row(nnz) = i;
Diffusion.Col(nnz) = Data.GetTris(Data.GetNeigh(i,j),index3);
Diffusion.Val(nnz) = - a3 / Area_C;
nnz++;
}
}
Diffusion.CreateSparse();
return Diffusion;
}
<file_sep>#include "Main.h"
#include "Matrix.h"
#include "DataStruct.h"
typedef Matrix<double> matrix;
typedef Vector<Matrix<double> > tensor;
void LoadIC(tensor& x) {
ifstream fp("input.dat");
if(fp.is_open()) {
for(int i = 0; i < Nc; i++) {
for(int j = 0; j < x(i).GetCols(); j++)
fp >> x(i)[0](j);
x(i)[1] = x(i)[0];
}
fp.close();
}
}
void LoadIC(matrix& c, double c0, double c1, DataStructure& Data, char* TYPE) {
if(!strcmp(TYPE,"Circle"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
x0 = 0.0, y0 = 0.0, r0 = sqrt(200.0);
if(pow(x-x0,2.0) + pow(y-y0,2.0) <= pow(r0,2.0))
c[0](i) = c0;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Square"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
l0 = sqrt(pi * 200.0);
if(fabs(x) <= l0/2.f && fabs(y) <= l0/2.f)
c[0](i) = c0;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Two-Circles"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
x0 = 3.0, y0 = 2.0, r0 = sqrt(1.0);
if(pow(x-x0,2.0) + pow(y+y0,2.0) <= pow(r0,2.0) ||
pow(x+x0,2.0) + pow(y-y0,2.0) <= pow(r0,2.0))
c[0](i) = c0;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Multiple-Circles")) {
int NumCirclesX = 2, NumCirclesY = 2;
double fact = 1.0;
double r0 = sqrt(150.0), x0 = - 100.0 * fact, y0 = x0,
SpacingX = (2.0 * fabs(x0) - 2.0 * NumCirclesX * r0) / (NumCirclesX + 1.0),
SpacingY = (2.0 * fabs(y0) - 2.0 * NumCirclesY * r0) / (NumCirclesY + 1.0);
for(int i = 0; i < c.GetCols(); i++) {
bool IsInterior = false;
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1);
for(int j = 0; j < NumCirclesY; j++)
for(int k = 0; k < NumCirclesX; k++)
if( (pow(x -(x0 + SpacingX+r0+k*(2*r0+SpacingX)),2.0)
+pow(y -(y0 + SpacingY+r0+j*(2*r0+SpacingY)),2.0)) <= pow(r0,2.0) )
IsInterior = true;
if(IsInterior)
c[0](i) = c0;
else
c[0](i) = c1;
}
}
if(!strcmp(TYPE,"Triangle"))
for(int i = 0; i < c.GetCols(); i++) {
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1),
x0 = sqrt(pi*100.0), y0 = x0 * cos(pi/6.0), trans = 0.0;
if( (x >= -x0 && x <= x0) && ( y >= (-y0 - trans) && y <= (y0 - trans)) )
if( (y + y0 + trans) <= (x0 - fabs(x)) * tan(pi/3.0))
c[0](i) = c0;
else
c[0](i) = c1;
else
c[0](i) = c1;
}
if(!strcmp(TYPE,"Multiple-Triangles")) {
int NumTrisX = 1, NumTrisY = 1;
double L = 50.0, l = sqrt(20.0),
SpacingX = (L - NumTrisX * l) / (NumTrisX + 1.f),
SpacingY = (L - NumTrisY * sqrt(3.f) * l / 2.f) / (NumTrisY + 1.f);
for(int i = 0; i < c.GetCols(); i++) {
bool IsInterior = false;
double x = Data.GetVerts(i,0), y = Data.GetVerts(i,1), dx;
for(int j = 0; j < NumTrisY; j++)
for(int k = 0; k < NumTrisX; k++)
if(x >= (SpacingX*(k+1) + k*l) && x <= (SpacingX*(k+1) + (k+1)*l)) {
if(x >= (SpacingX*(k+1) + k*l))
dx = ((SpacingX*(k+1) + (k+1)*l) - x);
else
dx = x - (SpacingX*(k+1) + k*l);
if(y >= (SpacingY*(j+1) + j*l*sqrt(3.f)/2.f) && y <= (tan(pi/4.f) * dx
+ SpacingY*(j+1) + j*l*sqrt(3.f)/2.f))
IsInterior = true;
}
if(IsInterior)
c[0](i) = c0;
else
c[0](i) = c1;
}
}
c[1] = c[0];
}
<file_sep>#ifndef COMMON_H
#define COMMON_H
using namespace std;
#include <iostream>
#include <cmath>
#include "assert.h"
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib> // for GCC 4.3 and above
#include <cstring> // for GCC 4.3 and above
#include "Revert.h"
#endif
<file_sep>#include <iostream>
#include <cmath>
#include "assert.h"
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib> // for GCC 4.3 and above
#include <cstring> // for GCC 4.3 and above
#pragma once
#define pi 3.141592653589793
using namespace std;
/*const double Da = pow(10.0,-4.0), Db = Da, Dc = 1.1 * pow(10.0,-4.0),
a0 = 1000.0,
b0 = 3.0, kr = pow(10.0,-5.0), c1 = 1.1, c2 = 2.0, c3 = 2.0,
alfa = 0.01, beta = 0.01, gama = 0.01, delta = 0.003;
Params above lead to thick rings.
*/
/* Multi-circles params */
/*
const double Da = pow(10.0,-4.0), Db = Da, Dc = 5.0 * pow(10.0,-5.0),
a0 = 500.0, b0 = 3.0, kr = pow(10.0,-5.0),
c1 = 1.1, c2 = 2.0, c3 = 2.0,
alfa = 0.01, beta = 0.01, gama = 0.01, delta = 0.003;
*/
/* Fast systems */
const double Da = 1.0, Db = Da, Dc = 1.0, a0 = 500.0,b0 = 3.0, kr =
0.001, c1 = 1.0, c2 = 1.25, c3 = 1.5, alfa = 2.0, beta = 1.0, gama = 1.0,
delta = 0.5;
/* Triangle
const double Da = pow(10.0,-3.0), Db = Da, Dc = 1.1 * Da, a0 = 1500,
b0 = 3.0, kr = 5.0 * pow(10.0,-5.0), c1 = 1.7, c2 = 2.0,
c3 = 2.0, alfa = 0.1, beta = 0.1, gama = 0.1, delta = 0.1;
*/
const int Nc = 5;
<file_sep>#include "DataStruct.h"
DataStructure::DataStructure(char* fname) {
ifstream ReadFile;
ReadFile.open(fname);
ReadFile >> Nverts >> Ntris;
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
tris = new int*[Ntris];
neigh = new int*[Nverts];
verts = new double*[Nverts];
area = new double[Ntris];
for(int i = 0; i < Nverts; i++)
verts[i] = new double[3];
for(int i = 0; i < Ntris; i++)
tris[i] = new int[3];
for(int i = 0; i < Nverts; i++) {
for(int j = 0; j < 3; j++)
ReadFile >> verts[i][j];
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < Ntris; i++) {
for(int j = 0; j < 3; j++)
ReadFile >> tris[i][j];
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < Nverts; i++) {
int length;
ReadFile >> length;
neigh[i] = new int[length+1];
neigh[i][0] = length;
for(int j = 1; j <= neigh[i][0]; j++)
ReadFile >> neigh[i][j];
ReadFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < Ntris; i++) {
double x1 = verts[tris[i][0]][0],
x2 = verts[tris[i][1]][0],
x3 = verts[tris[i][2]][0],
y1 = verts[tris[i][0]][1],
y2 = verts[tris[i][1]][1],
y3 = verts[tris[i][2]][1];
area[i] = 0.5 * fabs( x1*y2 - x2*y1 - x1*y3 + x3*y1 + x2*y3 - x3*y2 );
}
}
DataStructure::DataStructure(int Npts1, int Npts2) : GRIDPTS_X(Npts1), GRIDPTS_Y(Npts2) {
GRIDPTS = (GRIDPTS_X - 2) * (GRIDPTS_Y - 2);
is = new int[GRIDPTS];
js = new int[GRIDPTS];
id = new int*[GRIDPTS_Y];
for(int i = 0; i < GRIDPTS_Y; i++)
id[i] = new int[GRIDPTS_X];
int count = 0;
for(int i = 0; i < GRIDPTS_Y; i++)
for(int j = 0; j < GRIDPTS_X; j++)
if(i == 0)
id[i][j] = -1;
else
if(j == 0)
id[i][j] = -2;
else
if(i == (GRIDPTS_Y - 1))
id[i][j] = -3;
else
if(j == (GRIDPTS_X - 1))
id[i][j] = -4;
else {
is[count] = i;
js[count] = j;
id[i][j] = count++;
}
}
<file_sep>#include "Common.h"
#include "Matrix.h"
typedef Vector<double> vector;
typedef Matrix<double> matrix;
typedef Vector<Matrix<double> > tensor;
void FixRHS(vector& RHS) {
int nBC; double uBC;
ifstream file;
file.open("Dirichlet.dat");
file >> nBC >> uBC;
Vector<int> BoundPts(nBC);
for(int i = 0; i < nBC; i++)
file >> BoundPts(i);
for(int i = 0; i < nBC; i++)
RHS(BoundPts(i)) = uBC;
}
<file_sep>#include <iostream>
#include <cmath>
#include "assert.h"
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib> // for GCC 4.3 and above
#include <cstring> // for GCC 4.3 and above
#pragma once
#define pi 3.141592653589793
using namespace std;
/*const double Da = pow(10.0,-4.0), Db = Da, Dc = 1.1 * pow(10.0,-4.0),
a0 = 1000.0,
b0 = 3.0, kr = pow(10.0,-5.0), c1 = 1.1, c2 = 2.0, c3 = 2.0,
alfa = 0.01, beta = 0.01, gama = 0.01, delta = 0.003;
Params above lead to thick rings.
*/
const double Da = pow(10.0,-6.0), Db = Da, Dc = 11.0 * Da, a0 = 1500.0, b0
= 3.0,
kr = Da, c1 = 1.6, c2 = 2.0, c3 = 2.0, alfa = 0.01,
beta = 0.01,
gama = 0.01, delta = 0.003;
const int Nc = 5;
<file_sep>#ifndef VECTOR_H
#define VECTOR_H
#include "Common.h"
template <typename Type>
class Vector
{
protected:
Type *vec;
int length;
public:
Type* GetAddress() { return vec; }
void Allocate(int, Type);
/*** Constructors ***/
Vector(int, Type a = 0.0);
Vector(const Vector &);
Vector(int, Type*);
Vector() {}
/*** Access Ops ***/
int GetLength() const { return length; }
Type& operator()(int i) const;
template<typename T>
friend ostream& operator<<(ostream& out, const Vector<T>& p);
Vector<Type>& operator()(const Vector<Type>& p ,const int i, const int j);
Vector<Type> operator()(const int i, const int j,const Vector<Type>& p);
Vector<Type> operator()(const int i, const int j);
void Write(char* fname);
void Read(char* fname);
/*** Scalar Ops ***/
Vector<Type>& operator*=(Type scalar);
Vector<Type>& operator+=(Type scalar);
Vector<Type>& operator-=(Type scalar);
Vector<Type>& operator/=(Type scalar);
Vector<Type> operator-();
Vector<Type> operator+();
Vector<Type> test();
template<typename T>
friend Vector<T> pow(const Vector<T>& p, double n);
Type operator&&(const Vector<Type>&);
Type Trapezoidal(const Vector<Type>&);
Type Amax();
Type Amin();
Type Amean();
Type max();
Type min();
Type Norm();
int Imax() ;
Type Sum();
template<typename T>
friend Vector<T> operator*(T, const Vector<T>&);
template<typename T>
friend Vector<T> operator+(T, const Vector<T>&);
template<typename T>
friend Vector<T> operator-(T, const Vector<T>&);
template<typename T>
friend Vector<T> operator/(T, const Vector<T>&);
template<typename T>
friend Vector<T> operator+(const Vector<T>&,T);
template<typename T>
friend Vector<T> operator-(const Vector<T>&, T);
template<typename T>
friend Vector<T> operator*(const Vector<T>&, T);
template<typename T>
friend Vector<T> operator/(const Vector<T>&, T);
/*** Vector Ops ***/
template<typename T>
friend Vector<T> operator+(const Vector<T>&, const Vector<T>&);
template<typename T>
friend Vector<T> operator-(const Vector<T>&, const Vector<T>&);
template<typename T>
friend Vector<T> operator*(const Vector<T>&, const Vector<T>&);
template<typename T>
friend Vector<T> operator/(const Vector<T>&, const Vector<T>&);
Vector<Type> diff();
Vector<Type>& operator+=(const Vector<Type>&);
Vector<Type>& operator-=(const Vector<Type>&);
Vector<Type>& operator*=(const Vector<Type>&);
Vector<Type>& operator/=(const Vector<Type>&);
Vector<Type>& operator=(const Vector<Type>&);
Vector<Type>& operator=(Type);
~Vector() { delete[] vec; }
};
/*template<typename T>
Vector<T> Vector<T>::NewtonKrylov(const Vector<T>& b, Vector<T> x0, Vector<T> (*Jdv)(const Vector<T>&, const Vector<T>&)) {
Vector<T> r0 = b - Jdv(x0,x0);
if(r0.Norm() == .0) {
Vector<T> z(x0.GetLength(),pow(10.0,-7.0));
r0 = b - (*this) * z;
cout << "Initial residual in CG iz zero!" << endl;
}
Vector<T> PC = LoadJacobi();
Vector<T> z0 = PC * r0;
Vector<T> p0 = z0;
T error = 1.0, tol = pow(10.0,-6.0);
int iters = 0;
while( error > tol ) {
Vector<T> Ap0 = Jdv(x0,p0);
T alfa = (r0 && z0) / (p0 && Ap0 );
x0 += alfa * p0;
T rtr = (z0 && r0);
r0 -= alfa * Ap0;
z0 = PC * r0;
error = sqrt(r0 && r0);
T beta = (z0 && r0) / rtr;
p0 = beta * p0 + z0;
iters++;
}
return x0;
} */
template<typename Type>
void Vector<Type>::Allocate(int n, Type a) {
vec = new Type[n];
length = n;
(*this) = a;
}
template<typename Type>
Vector<Type> Vector<Type>::operator-() {
Vector<Type> v = *this;
for(int i = 0; i < length; i++)
v(i) = - vec[i];
return v;
}
template<typename Type>
Vector<Type> Vector<Type>::operator+() {
Vector<Type> v = *this;
return v;
}
/*** Scalar Ops ***/
template<typename Type>
Vector<Type>& Vector<Type>::operator+=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] += scalar;
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator/=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] /= scalar;
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator-=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] -= scalar;
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator*=(Type scalar) {
for(int i = 0; i < length; i++)
vec[i] *= scalar;
return *this;
}
template<typename Type>
Type Vector<Type>::Amax() {
Type max = vec[0];
for(int i = 1; i < length; i++)
max = max < fabs(vec[i]) ? fabs(vec[i]) : max;
return max;
}
template<typename Type>
Type Vector<Type>::Sum() {
Type sum = vec[0];
for(int i = 1; i < length; i++)
sum += vec[i];
return sum;
}
template<typename Type>
Type Vector<Type>::max() {
Type max = vec[0];
for(int i = 1; i < length; i++)
max = max < vec[i] ? vec[i] : max;
return max;
}
template<typename Type>
Type Vector<Type>::min() {
Type min = vec[0];
for(int i = 1; i < length; i++)
min = min > vec[i] ? vec[i] : min;
return min;
}
template<typename Type>
Type Vector<Type>::Amin() {
Type min = vec[0];
for(int i = 1; i < length; i++)
min = min > fabs(vec[i]) ? fabs(vec[i]) : min;
return min;
}
template<typename Type>
Type Vector<Type>::Amean() {
Type mean = fabs(vec[0]);
for(int i = 1; i < length; i++)
mean += fabs(vec[i]);
return mean/length;
}
template<typename Type>
int Vector<Type>::Imax() {
Type max = vec[0];
int j = 0;
for(int i = 1; i < length; i++) {
j = max < fabs(vec[i]) ? i : j;
max = max < fabs(vec[i]) ? fabs(vec[i]) : max;
}
return j;
}
template<typename Type>
Type Vector<Type>::Norm() {
Type norm = pow(vec[0],2.0);
for(int i = 1; i < length; i++)
norm += pow(vec[i],2.0);
return sqrt(norm);
}
/// Friend Operators ///
template<typename T>
Vector<T> operator+(T scalar, const Vector<T>& p) {
T* temp = new T[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) + scalar;
return Vector<T>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator+(const Vector<Type>& p, Type scalar) {
Type *temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) + scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator/(Type scalar, const Vector<Type>& p) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = scalar / p(i);
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator/(const Vector<Type>& p, Type scalar) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) / scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator-(Type scalar, const Vector<Type>& p) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = - p(i) + scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator-(const Vector<Type>& p, Type scalar) {
Type *temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) - scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator*(Type scalar, const Vector<Type>& p) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) * scalar;
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator*(const Vector<Type>& p, Type scalar) {
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) * scalar;
return Vector<Type>(p.GetLength(),temp);
}
/// Dot Product ///
template<typename Type>
Type Vector<Type>::operator&&(const Vector<Type>& p) {
assert(p.GetLength() == length);
Type output = 0;
for(int i = 0; i < length; i++)
output += p(i) * vec[i];
return output;
}
/// Integration Int ///
template<typename Type>
Type Vector<Type>::Trapezoidal(const Vector<Type> &p) {
assert(p.GetLength() == length);
Type output = 0;
for(int i = 0; i < length - 1; i++)
output += (p(i) + p(i+1)) * vec[i];
return 0.5 * output;
}
/*** Vectors Ops ***/
template<typename Type>
Vector<Type> operator+(const Vector<Type>& p, const Vector<Type>& u) {
assert(p.GetLength() == u.GetLength());
Type* temp = new Type[p.GetLength()];
for(int i = 0; i < p.GetLength(); i++)
temp[i] = p(i) + u(i);
return Vector<Type>(p.GetLength(),temp);
}
template<typename Type>
Vector<Type> operator-(const Vector<Type>& p, const Vector<Type>& u) {
assert(p.GetLength() == u.GetLength());
Type* temp = new Type[p.length];
for(int i = 0; i < p.length; i++)
temp[i] = p(i) - u(i);
return Vector<Type>(p.length,temp);
}
template<typename Type>
Vector<Type> operator*(const Vector<Type>& p, const Vector<Type>& u) {
int size = p.GetLength();
assert(size == u.GetLength());
Type* temp = new Type[size];
for(int i = 0; i < size; i++)
temp[i] = p(i) * u(i);
return Vector<Type>(size,temp);
}
template<typename Type>
Vector<Type> operator/(const Vector<Type>& p, const Vector<Type>& u) {
int size = p.GetLength();
assert(size == u.GetLength());
Type* temp = new Type[size];
for(int i = 0; i < size; i++)
temp[i] = p(i) / u(i);
return Vector<Type>(size,temp);
}
template<typename Type>
Vector<Type>& Vector<Type>::operator+=(const Vector<Type>& p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] += p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator-=(const Vector<Type>& p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] -= p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator*=(const Vector<Type>& p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] *= p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator/=(const Vector<Type>& p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] /= p(i);
return *this;
}
template<typename Type>
Vector<Type> Vector<Type>::diff() {
Vector<Type> p(length - 1,.0);
for(int i = 0; i < length - 1; i++)
p(i) = vec[i+1] - vec[i];
return p;
}
/*** Constructors ***/
template<typename Type>
Vector<Type>::Vector(int dim, Type a) : length(dim), vec(dim ? new Type[dim] : 0) {
for(int i = 0; i < length; i++)
vec[i] = a;
}
template<typename Type>
Vector<Type>::Vector(const Vector<Type>& p) : length(p.GetLength()),
vec(p.GetLength() ? new Type[p.GetLength()] : 0) {
for(int i = 0; i < p.GetLength(); i++)
vec[i] = p(i);
}
template<typename Type>
Vector<Type>::Vector(int dim, Type* p) : length(dim) {
vec = p;
}
/*** ***/
template<typename Type>
Vector<Type>& Vector<Type>::operator=(const Vector<Type>& p) {
assert(p.GetLength() == length);
for(int i = 0; i < length; i++)
vec[i] = p(i);
return *this;
}
template<typename Type>
Vector<Type>& Vector<Type>::operator=(Type a) {
for(int i = 0; i < length; i++)
vec[i] = a;
return *this;
}
/*** Access operator ***/
template<typename Type>
Type& Vector<Type>::operator()(int i) const{
assert(i >=0 && i <length);
return vec[i];
}
template<typename Type>
Vector<Type>& Vector<Type>::operator()(const Vector<Type>& p ,const int i, const int j) {
assert(i >=0 && j < length);
for(int k = i; k <= j; k++)
vec[k] = p(k-i);
return *this;
}
template<typename Type>
Vector<Type> Vector<Type>::operator()(const int i, const int j) {
assert(i >= 0 && j < length);
Vector<Type> temp(j-i+1);
for(int k = i; k <= j; k++)
temp(k-i) = (*this)(k);
return temp;
}
template<typename Type>
Vector<Type> Vector<Type>::operator()(const int i, const int j, const Vector<Type>& p) {
assert(i >= 0 && j < p.GetLength());
Vector<Type> temp(j-i+1);
for(int k = i; k <= j; k++)
temp(k-i) = p(k);
return temp;
}
template<typename Type>
ostream& operator<<(ostream& out, const Vector<Type>& p) {
for(int i = 0; i < p.GetLength(); i++)
out << p(i) << " ";
out << endl;
return out;
}
template<typename Type>
void Vector<Type>::Write(char* fname) {
ofstream myfile;
myfile.open (fname,ios::app);
for(int i = 0; i < length; i++)
myfile << vec[i] << endl;
myfile.close();
}
template<typename Type>
void Vector<Type>::Read(char* fname) {
ifstream myfile;
myfile.open (fname,ios::app);
for(int i = 0; i < length; i++)
myfile >> vec[i] >> endl;
myfile.close();
}
template<typename Type>
Vector<Type> pow(const Vector<Type>& p, double n) {
Vector<Type> v(p.GetLength());
for(int i = 0; i < p.GetLength(); i++)
v(i) = pow(p(i),n);
return v;
}
#endif
<file_sep>VERSION = 3.0.2
C:
( cd Lib ; $(MAKE) )
( cd cv ; $(MAKE) )
all: C cov
library:
( cd Lib ; $(MAKE) )
( cd cv; $(MAKE) )
clean:
( cd Lib ; $(MAKE) clean )
purge:
( cd Lib ; $(MAKE) purge )
distclean: purge
# do not install CSparse; use CXSparse instead
install:
# uninstall CSparse: do nothing
uninstall:
| 7bcc861a707dcc01e23e1f99a0d5dde069075339 | [
"Markdown",
"Makefile",
"C++"
] | 27 | Makefile | anabiman/Finite-Volume | 66628c5371fc3e8293a35b4c3630d106b2505daa | 2b5fc3d878664732d4867588af549b47cc444534 |
refs/heads/master | <file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Runtime.CompilerServices;
namespace libsupcs
{
unsafe class exceptions
{
[ThreadStatic]
static void** start, end, cur;
const int stack_length = 1024;
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("push_ehdr")]
static extern void PushEhdr(void* eh, void* fp);
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("pop_ehdr")]
static extern void* PopEhdr();
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("peek_ehdr")]
static extern void* PeekEhdr();
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("pop_fp")]
static extern void* PopFramePointer();
// Default versions of push/pop ehdr, not thread safe
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("push_ehdr")]
static void push_ehdr(void *eh, void *fp)
{
if(start == null)
{
void** new_start = (void**)MemoryOperations.GcMalloc(stack_length * sizeof(void*));
fixed(void ***start_addr = &start)
{
if(OtherOperations.CompareExchange((void**)start_addr, (void*)new_start) == null)
{
end = start + stack_length;
cur = start;
System.Diagnostics.Debugger.Log(0, "libsupcs", "new ehdr stack at " + ((ulong)start).ToString("X") + "-" + ((ulong)end).ToString("X"));
}
}
}
if ((cur + 1) >= end)
{
System.Diagnostics.Debugger.Break();
throw new OutOfMemoryException("exception header stack overflowed");
}
//if(System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
// System.Diagnostics.Debugger.Log(0, "libsupcs", "exceptions: push_ehdr: " + ((ulong)eh).ToString("X"));
// the following should be atomic for the current stack only, so disabling interrupts is
// sufficient
var state = OtherOperations.EnterUninterruptibleSection();
*cur++ = eh;
*cur++ = fp;
OtherOperations.ExitUninterruptibleSection(state);
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("pop_ehdr")]
static void* pop_ehdr()
{
if (start == null || (void**)cur <= (void**)start)
{
System.Diagnostics.Debugger.Break();
throw new OutOfMemoryException("exception header stack underflowed");
}
var state = OtherOperations.EnterUninterruptibleSection();
var ret = *--cur;
OtherOperations.ExitUninterruptibleSection(state);
return ret;
//if (System.Threading.Thread.CurrentThread.ManagedThreadId != 1)
// System.Diagnostics.Debugger.Log(0, "libsupcs", "exceptions: pop_ehdr: " + ((ulong)*cur).ToString("X"));
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("peek_ehdr")]
static void* peek_ehdr()
{
if (start == null || (void**)cur <= (void**)start)
{
return null;
}
var state = OtherOperations.EnterUninterruptibleSection();
var ret = *(cur - 2);
OtherOperations.ExitUninterruptibleSection(state);
return ret;
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("pop_fp")]
static void* pop_fp()
{
if (start == null || cur <= start)
{
System.Diagnostics.Debugger.Break();
throw new OutOfMemoryException("exception header stack underflowed");
}
var state = OtherOperations.EnterUninterruptibleSection();
var ret = *--cur;
OtherOperations.ExitUninterruptibleSection(state);
return ret;
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("enter_try")]
internal static void enter_try(void *eh, void *fp)
{
if (eh == PeekEhdr())
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "enter_try: recursive try block found from calling_pc: " +
((ulong)OtherOperations.GetUnwinder().UnwindOne().GetInstructionPointer()).ToString("X"));
}
PushEhdr(eh, fp);
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("enter_catch")]
internal static void enter_catch(void* eh, void *fp)
{
PushEhdr(eh, fp);
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("leave_try")]
internal static void leave_try(void* eh)
{
void* fp = PopFramePointer();
void* popped = PopEhdr();
if (eh != popped)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "leave_try: popping incorrect exception header");
System.Diagnostics.Debugger.Log(0, "libsupcs", "expected: " + ((ulong)eh).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "got: " + ((ulong)popped).ToString("X") + ", fp: " + ((ulong)fp).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "start: " + ((ulong)start).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "end: " + ((ulong)end).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "cur: " + ((ulong)cur).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "calling_pc: " + ((ulong)OtherOperations.GetUnwinder().UnwindOne().GetInstructionPointer()).ToString("X"));
while (true) ;
}
void** ehdr = (void**)eh;
int eh_type = *(int*)ehdr;
if (eh_type == 2)
{
// handle finally clause
void* handler = *(ehdr + 1);
OtherOperations.CallI(fp, handler);
PopFramePointer();
PopEhdr();
}
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("leave_handler")]
internal static void leave_handler(void* eh)
{
while (true) ;
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("rethrow")]
internal static void rethrow(void* eh)
{
while (true) ;
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using metadata;
namespace libtysila5
{
public class Code
{
public TysilaState s;
public metadata.MethodSpec ms;
public List<cil.CilNode> cil;
public List<cil.CilNode.IRNode> ir;
public List<target.MCInst> mc;
public int lvar_sig_tok;
public List<cil.CilNode> starts;
public target.Target.Reg[] lv_locs;
public target.Target.Reg[] la_locs;
public int[] lv_sizes;
public int[] la_sizes;
public int lv_total_size;
public int stack_total_size = 0;
public metadata.TypeSpec[] lv_types;
public metadata.TypeSpec[] la_types;
public target.Target.Reg[] incoming_args;
public bool[] la_needs_assign;
internal int cctor_ret_tag = -1;
public bool is_cctor = false;
public util.Set<TypeSpec> static_types_referenced = new util.Set<TypeSpec>();
public metadata.TypeSpec ret_ts = null;
public ulong regs_used = 0;
public List<target.Target.Reg> regs_saved = new List<target.Target.Reg>();
public int next_mclabel = -1;
public target.Target t;
public List<int> offset_order = new List<int>();
public Dictionary<int, cil.CilNode> offset_map =
new Dictionary<int, cil.CilNode>(new libtysila5.GenericEqualityComparer<int>());
static ir.SpecialMethods _special = null;
internal List<ExceptionHeader> ehdrs;
public ir.SpecialMethods special_meths
{
get
{
if (_special == null)
_special = new libtysila5.ir.SpecialMethods(ms.m);
return _special;
}
}
public List<Label> extra_labels = new List<Label>();
public class Label
{
public int Offset;
public string Name;
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace TableMap
{
class Program
{
static internal StreamWriter sw;
static void Main(string[] args)
{
var this_file = System.Reflection.Assembly.GetEntryAssembly().Location;
var this_fi = new FileInfo(this_file);
foreach (var file in args)
{
MakeState s = new MakeState();
s.search_paths.Add(this_fi.DirectoryName);
new PrintFunction { args = new List<FunctionStatement.FunctionArg> { new FunctionStatement.FunctionArg { name = "val", argtype = Expression.EvalResult.ResultType.Int } } }.Execute(s);
new PrintFunction { args = new List<FunctionStatement.FunctionArg> { new FunctionStatement.FunctionArg { name = "val", argtype = Expression.EvalResult.ResultType.String } } }.Execute(s);
new PrintFunction { args = new List<FunctionStatement.FunctionArg> { new FunctionStatement.FunctionArg { name = "val", argtype = Expression.EvalResult.ResultType.Object } } }.Execute(s);
new PrintFunction { args = new List<FunctionStatement.FunctionArg> { new FunctionStatement.FunctionArg { name = "val", argtype = Expression.EvalResult.ResultType.Array } } }.Execute(s);
new VarGenFunction(Expression.EvalResult.ResultType.Int).Execute(s);
new VarGenFunction(Expression.EvalResult.ResultType.Array).Execute(s);
new VarGenFunction(Expression.EvalResult.ResultType.String).Execute(s);
new VarGenFunction(Expression.EvalResult.ResultType.Object).Execute(s);
new VarGetFunction().Execute(s);
new DefineBlobFunction().Execute(s);
new ToIntFunction().Execute(s);
new DumpBlobFunction().Execute(s);
new ToByteArrayFunction(4).Execute(s);
new ToByteArrayFunction(2).Execute(s);
new ToByteArrayFunction(1).Execute(s);
new ToByteArrayFunction(8).Execute(s);
new ThrowFunction().Execute(s);
FileInfo fi = new FileInfo(file);
string output = fi.FullName;
output = output.Substring(0, output.Length - fi.Extension.Length) + ".cs";
FileStream fs = new FileStream(output, FileMode.Create,
FileAccess.Write);
sw = new StreamWriter(fs);
// Boilerplate
BoilerPlate(sw, output, file);
ExecuteFile(file, s);
sw.Close();
}
}
private static void BoilerPlate(StreamWriter sw, string output, string file)
{
sw.Write("/* " + output + "\n");
sw.Write(" * This is an auto-generated file\n");
sw.Write(" * DO NOT EDIT\n");
sw.Write(" * It was generated at " + DateTime.Now.ToLongTimeString() +
" on " + DateTime.Now.ToLongDateString() + "\n");
sw.Write(" * from " + file + "\n");
sw.Write(" * by TableMap (part of tysos: http://www.tysos.org)\n");
sw.Write(" * Please edit the source file, rather than this file, to make any changes\n");
sw.Write(" */\n");
sw.Write("\n");
}
internal static Expression.EvalResult ExecuteFile(string name, MakeState s)
{
// find the file by using search paths
FileInfo fi = null;
foreach(var sp in s.search_paths)
{
var test = sp + "/" + name;
var test2 = sp + name;
try
{
fi = new FileInfo(test);
if (fi.Exists)
break;
}
catch (Exception) { }
try
{
fi = new FileInfo(test2);
if (fi.Exists)
break;
}
catch (Exception) { }
}
if (fi == null || fi.Exists == false)
throw new Exception("included file: " + name + " not found");
// add included files location to search paths
s.search_paths.Insert(0, fi.DirectoryName);
FileStream f = fi.OpenRead();
Parser p = new Parser(new Scanner(f, fi.FullName));
bool res = p.Parse();
if (res == false)
throw new Exception("Parse error");
var ret = p.output.Execute(s);
f.Close();
return ret;
}
}
class VarGenFunction : FunctionStatement
{
internal static Dictionary<string, Expression.EvalResult> all_defs =
new Dictionary<string, Expression.EvalResult>();
public VarGenFunction(Expression.EvalResult.ResultType arg_type)
{
name = "vargen";
args = new List<FunctionArg>() {
new FunctionArg { argtype = Expression.EvalResult.ResultType.String },
new FunctionArg { argtype = arg_type }
};
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
var n = passed_args[0].strval;
s.SetDefine(n, passed_args[1], true);
all_defs[n] = passed_args[1];
return passed_args[1];
}
}
class ToIntFunction : FunctionStatement
{
public ToIntFunction()
{
name = "toint";
args = new List<FunctionArg>() { new FunctionArg { argtype = Expression.EvalResult.ResultType.String } };
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
return new Expression.EvalResult(int.Parse(passed_args[0].strval));
}
}
class ThrowFunction : FunctionStatement
{
public ThrowFunction()
{
name = "throw";
args = new List<FunctionArg> { new FunctionArg { argtype = Expression.EvalResult.ResultType.String }, new FunctionArg { argtype = Expression.EvalResult.ResultType.String } };
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
var obj_type = passed_args[0].strval;
var msg = passed_args[1].strval;
var obj_ts = Type.GetType(obj_type);
var obj_ctor = obj_ts.GetConstructor(new Type[] { typeof(string) });
var obj = obj_ctor.Invoke(new object[] { msg });
throw obj as Exception;
}
}
class ToByteArrayFunction : FunctionStatement
{
int bc = 0;
public ToByteArrayFunction(int byte_count)
{
name = "tobytearray" + byte_count.ToString();
args = new List<FunctionArg> { new FunctionArg { argtype = Expression.EvalResult.ResultType.Any } };
bc = byte_count;
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
IList<byte> ret = GetBytes(passed_args[0]);
if (ret == null)
throw new Exception("Cannot call " + name + " with " + passed_args[0].ToString());
List<Expression.EvalResult> r = new List<Expression.EvalResult>();
for(int i = 0; i < bc; i++)
{
if (i < ret.Count)
r.Add(new Expression.EvalResult(ret[i]));
else
r.Add(new Expression.EvalResult(0));
}
return new Expression.EvalResult(r);
}
private IList<byte> GetBytes(Expression.EvalResult e)
{
switch (e.Type)
{
case Expression.EvalResult.ResultType.Int:
return BitConverter.GetBytes(e.intval);
case Expression.EvalResult.ResultType.String:
return Encoding.UTF8.GetBytes(e.strval);
case Expression.EvalResult.ResultType.Array:
var ret = new List<byte>();
foreach (var aentry in e.arrval)
ret.AddRange(GetBytes(aentry));
return ret;
default:
return null;
}
}
}
class VarGetFunction : FunctionStatement
{
public VarGetFunction()
{
name = "varget";
args = new List<FunctionArg>()
{
new FunctionArg { argtype = Expression.EvalResult.ResultType.String }
};
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
return VarGenFunction.all_defs[passed_args[0].strval];
}
}
class DefineBlobFunction : FunctionStatement
{
/* Used to generate a hash table
Arguments are:
name
key
value
Hash table contains three parts:
bucket list
chain list
data list
- concatenations of:
1 byte: length of key
key
value
*/
public static Dictionary<string, HTable> tables = new Dictionary<string, HTable>();
public class HTable
{
public List<byte> data = new List<byte>();
public List<KeyIndex> keys = new List<KeyIndex>();
public class KeyIndex
{
public List<byte> key = new List<byte>();
public int idx;
public uint hc;
}
}
public DefineBlobFunction()
{
name = "defblob";
args = new List<FunctionArg>()
{
new FunctionArg { argtype = Expression.EvalResult.ResultType.String },
new FunctionArg { argtype = Expression.EvalResult.ResultType.Array },
new FunctionArg { argtype = Expression.EvalResult.ResultType.Array }
};
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
var name = passed_args[0].strval;
var key = passed_args[1].arrval;
var value = passed_args[2].arrval;
/* Coerce key and value to byte arrays */
var key_b = ToByteArray(key);
var value_b = ToByteArray(value);
/* Get hash code */
var hc = Hash(key_b);
/* Get hash table */
HTable ht;
if(tables.TryGetValue(name, out ht) == false)
{
ht = new HTable();
tables[name] = ht;
}
/* Build table entry */
HTable.KeyIndex k = new HTable.KeyIndex();
k.hc = hc;
k.idx = ht.data.Count;
k.key = key_b;
ht.keys.Add(k);
/* Add data entry */
if (key_b.Count > 255)
throw new Exception("key too large");
ht.data.Add((byte)key_b.Count);
ht.data.AddRange(key_b);
ht.data.AddRange(value_b);
return new Expression.EvalResult();
}
public static uint Hash(IEnumerable<byte> v)
{
uint h = 0;
uint g = 0;
foreach(var b in v)
{
h = (h << 4) + b;
g = h & 0xf0000000U;
if (g != 0)
h ^= g >> 24;
h &= ~g;
}
return h;
}
private List<byte> ToByteArray(List<Expression.EvalResult> v)
{
List<byte> ret = new List<byte>();
foreach(var b in v)
{
ToByteArray(b, ret);
}
return ret;
}
public List<byte> ToByteArray(Expression.EvalResult v)
{
List<byte> ret = new List<byte>();
ToByteArray(v, ret);
return ret;
}
public void CompressInt(int val, List<byte> ret)
{
var u = BitConverter.ToUInt32(BitConverter.GetBytes(val), 0);
CompressUInt(u, ret);
}
public void CompressUInt(uint u, List<byte> ret)
{
var b1 = u & 0xff;
var b2 = (u >> 8) & 0xff;
var b3 = (u >> 16) & 0xff;
var b4 = (u >> 24) & 0xff;
if (u <= 0x7fU)
{
ret.Add((byte)b1);
return;
}
else if (u <= 0x3fffU)
{
ret.Add((byte)(b2 | 0x80U));
ret.Add((byte)b1);
}
else if (u <= 0x1FFFFFFFU)
{
ret.Add((byte)(b4 | 0xc0U));
ret.Add((byte)b3);
ret.Add((byte)b2);
ret.Add((byte)b1);
}
else
throw new Exception("integer too large to compress");
}
public void ToByteArray(Expression.EvalResult v, List<byte> ret)
{
switch(v.Type)
{
case Expression.EvalResult.ResultType.Array:
foreach (var a in v.arrval)
ToByteArray(a, ret);
break;
case Expression.EvalResult.ResultType.Int:
CompressInt((int)v.intval, ret);
/*ret.Add((byte)(v.intval & 0xff));
ret.Add((byte)((v.intval >> 8) & 0xff));
ret.Add((byte)((v.intval >> 16) & 0xff));
ret.Add((byte)((v.intval >> 24) & 0xff));*/
break;
case Expression.EvalResult.ResultType.Object:
var vlist = new List<string>();
foreach (var kvp in v.objval)
vlist.Add(kvp.Key);
vlist.Sort();
foreach (var k in vlist)
ToByteArray(v.objval[k]);
break;
case Expression.EvalResult.ResultType.String:
ret.AddRange(Encoding.UTF8.GetBytes(v.strval));
break;
default:
throw new NotImplementedException();
}
}
}
class DumpBlobFunction : FunctionStatement
{
/* Dump the hash table defined with a DefBlob function */
public DumpBlobFunction()
{
name = "dumpblob";
args = new List<FunctionArg>()
{
new FunctionArg { argtype = Expression.EvalResult.ResultType.String },
new FunctionArg { argtype = Expression.EvalResult.ResultType.String }
};
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
var blob_name = passed_args[0].strval;
var hc_name = passed_args[1].strval;
var hc = DefineBlobFunction.tables[blob_name];
// Decide on a sensible value for nbuckets - sqroot(n)
// seems appropriate
var nbuckets = (int)Math.Sqrt(hc.keys.Count);
/* We need a map between key indices and data blob offsets
- this is stored in idx_map.
To find entries, we perform hc % nbuckets to get a
bucket number. Then index buckets[bucket_no] to get
index of first item. If it is not what we want, go to
next item chain[cur_index] and so on.
To create the hash table, therefore, we iterate through
each key. First, store its index to the idx_map. Next,
calculate bucket_no. chain[cur_idx] is set to whatever
is currently in buckets[bucket_no], and buckets[bucket_no]
is updated to the current index. This means the last item
added will actually be the first out, and the first item
will have its chain[] value set to -1 (the initial value
of buckets[])
*/
int[] buckets = new int[nbuckets];
for (int i = 0; i < nbuckets; i++)
buckets[i] = -1;
int[] chain = new int[hc.keys.Count];
int[] idx_map = new int[hc.keys.Count];
for (int i = 0; i < hc.keys.Count; i++)
{
var hte = hc.keys[i];
idx_map[i] = hte.idx;
var bucket_no = hte.hc % (uint)nbuckets;
var cur_bucket = buckets[bucket_no];
chain[i] = cur_bucket;
buckets[bucket_no] = i;
}
/* Now dump the hash table:
var hc_name = new HashTable {
nbucket = nbuckets,
nchain = hc.keys.Count,
bucket = new byte[] {
bucket_dump
},
chain = new byte[] {
chain_dump
},
idx_map = new byte[] {
idx_map_dump
},
data = new byte[] {
data_dump
}
};
*/
Program.sw.Write("\t\t\tvar " + hc_name + " = new HashTable {\n");
Program.sw.Write("\t\t\t\tnbucket = " + nbuckets.ToString() + ",\n");
Program.sw.Write("\t\t\t\tnchain = " + hc.keys.Count.ToString() + ",\n");
Program.sw.Write("\t\t\t\tbucket = new int[] {\n");
DumpArray<int>(buckets);
Program.sw.Write("\t\t\t\t},\n");
Program.sw.Write("\t\t\t\tchain = new int[] {\n");
DumpArray<int>(chain);
Program.sw.Write("\t\t\t\t},\n");
Program.sw.Write("\t\t\t\tidx_map = new int[] {\n");
DumpArray<int>(idx_map);
Program.sw.Write("\t\t\t\t},\n");
Program.sw.Write("\t\t\t\tdata = new byte[] {\n");
DumpArray<byte>(hc.data, "\t\t\t\t\t", 16);
Program.sw.Write("\t\t\t\t},\n");
Program.sw.Write("\t\t\t};\n");
Program.sw.Write("\n");
return new Expression.EvalResult();
}
void DumpArray<T>(IList<T> arr)
{
DumpArray(arr, "\t\t\t\t\t", 8);
}
void DumpArray<T>(IList<T> arr, string line_prefix, int per_line)
{
int cur_line = 0;
for(int i = 0; i < arr.Count; i++)
{
var b = arr[i];
if (cur_line == 0)
Program.sw.Write(line_prefix);
Program.sw.Write(b.ToString());
Program.sw.Write(", ");
cur_line++;
if(cur_line == per_line)
{
Program.sw.Write("\n");
cur_line = 0;
}
}
if (cur_line != 0)
Program.sw.Write("\n");
}
}
class PrintFunction : FunctionStatement
{
public PrintFunction()
{
name = "print";
}
public override Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> args)
{
Print(args[0], true);
return new Expression.EvalResult();
}
void Print(Expression.EvalResult e, bool toplevel)
{
switch (e.Type)
{
case Expression.EvalResult.ResultType.Int:
Program.sw.Write(e.intval);
break;
case Expression.EvalResult.ResultType.String:
if (!toplevel)
Program.sw.Write("\"");
Program.sw.Write(e.strval);
if (!toplevel)
Program.sw.Write("\"");
break;
case Expression.EvalResult.ResultType.Array:
Program.sw.Write("[ ");
for (int i = 0; i < e.arrval.Count; i++)
{
if (i != 0)
Program.sw.Write(", ");
Print(e.arrval[i], false);
}
Program.sw.Write(" ]");
break;
case Expression.EvalResult.ResultType.Object:
Program.sw.Write("[ ");
int j = 0;
foreach (KeyValuePair<string, Expression.EvalResult> kvp in e.objval)
{
if (j != 0)
Program.sw.Write(", ");
Program.sw.Write(kvp.Key);
Program.sw.Write(": ");
Print(kvp.Value, false);
j++;
}
Program.sw.Write(" ]");
break;
}
}
}
partial class Parser
{
internal Parser(Scanner s) : base(s) { }
internal void AddDefine(string t, string val)
{
throw new NotImplementedException();
}
internal void AddDefine(string t, int val)
{
throw new NotImplementedException();
}
internal int ResolveAsInt(string t)
{
throw new NotImplementedException();
}
}
partial class Scanner
{
string filename;
internal Scanner(Stream file, string fname) : this(file) { filename = fname; }
public override void yyerror(string format, params object[] args)
{
throw new ParseException(String.Format(format, args) + " at line " + yyline + ", col " + yycol + " in " + filename, yyline, yycol);
}
internal int sline { get { return yyline; } }
internal int scol { get { return yycol; } }
}
public class ParseException : Exception
{
int l, c;
public ParseException(string msg, int line, int col) : base(msg) { l = line; c = col; }
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Collections.Generic;
namespace libtysila5.target
{
public class Trie<T>
{
public int[] trie;
public int start;
public T[] vals;
public int MaxDepth
{
get
{
return trie_get_max_depth(start);
}
}
public T GetValue(int[] keys)
{
var max_depth = trie_get_max_depth(start);
if (keys.Length > max_depth)
return default(T);
return trie_get(start, vals, keys, 0);
}
public T GetValue(List<cil.CilNode.IRNode> nodes,
int start_key, int count)
{
var max_depth = trie_get_max_depth(start);
if (count > max_depth)
return default(T);
return trie_get(start, vals, nodes, start_key, count, 0);
}
private int trie_get_max_depth(int idx)
{
return trie[idx + 1];
}
private int trie_get_start(int idx)
{
return trie[idx + 2];
}
private int trie_get_length(int idx)
{
return trie[idx + 3];
}
private int trie_get_next_trie(int idx, int next_key)
{
var start = trie_get_start(idx);
var length = trie_get_length(idx);
var end = start + length;
if (next_key < start || next_key >= end)
return 0;
return trie[idx + 4 + next_key - start];
}
private T trie_get(int idx, T[] vals, int[] keys, int v)
{
if (v >= keys.Length)
{
return trie_get_val(idx, vals);
}
var next_key = keys[v];
var next_trie = trie_get_next_trie(idx, next_key);
if (next_trie == 0)
return default(T);
return trie_get(next_trie, vals, keys, v + 1);
}
private T trie_get(int idx, T[] vals,
List<cil.CilNode.IRNode> nodes,
int start_key, int count, int v)
{
if (v >= count)
{
return trie_get_val(idx, vals);
}
var next_key = nodes[start_key + v].opcode;
var next_trie = trie_get_next_trie(idx, next_key);
if (next_trie == 0)
return default(T);
return trie_get(next_trie, vals, nodes,
start_key, count, v + 1);
}
private T trie_get_val(int idx, T[] vals)
{
return vals[trie[idx]];
}
}
}
<file_sep>/* Copyright (C) 2018 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using metadata;
namespace tysila4
{
class Interactive
{
class InteractiveState
{
public InteractiveMetadataStream m = null;
public InteractiveTypeSpec ts = null;
public InteractiveMethodSpec ms = null;
}
class InteractiveFieldSpec
{
public string Name;
public int Offset;
public InteractiveTypeSpec Type;
public bool IsTls;
public override string ToString()
{
return (IsTls ? "TLS+" : " ") + Offset.ToString("X4") + ": " + Type.Name + " " + Name;
}
}
class InteractiveMethodSpec
{
public metadata.MethodSpec ms = null;
public string Name;
public static implicit operator InteractiveMethodSpec(metadata.MethodSpec _ms) { return new InteractiveMethodSpec(_ms); }
public static implicit operator MethodSpec(InteractiveMethodSpec ims) { return ims.ms; }
public InteractiveMethodSpec(metadata.MethodSpec _ms)
{
ms = _ms;
StringBuilder sb = new StringBuilder();
var meth_name = ms.m.GetStringEntry(metadata.MetadataStream.tid_MethodDef, ms.mdrow, 3);
var cur_sig = (int)ms.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef, ms.mdrow, 4);
sb.Append(meth_name);
if(ms.IsInstantiatedGenericMethod)
{
sb.Append("<");
for(int idx = 0; idx < ms.gmparams.Length; idx++)
{
if (idx > 0)
sb.Append(",");
sb.Append(((InteractiveTypeSpec)ms.gmparams[idx]).Name);
}
sb.Append(">");
}
sb.Append("(");
var need_this = ms.m.GetMethodDefSigHasNonExplicitThis(cur_sig);
var pcount = ms.m.GetMethodDefSigParamCount(cur_sig);
cur_sig = ms.m.GetMethodDefSigRetTypeIndex(cur_sig);
if(need_this)
{
sb.Append("this");
}
// skip ret type
ms.m.GetTypeSpec(ref cur_sig, ms.gtparams, ms.gmparams);
for(int idx = 0; idx < pcount; idx++)
{
if (idx > 0 || need_this)
sb.Append(",");
sb.Append(((InteractiveTypeSpec)ms.m.GetTypeSpec(ref cur_sig, ms.gtparams, ms.gmparams)).Name);
}
sb.Append(")");
Name = sb.ToString();
}
}
class InteractiveTypeSpec
{
public metadata.TypeSpec ts = null;
public string Name;
public InteractiveTypeSpec() { }
public InteractiveTypeSpec(metadata.TypeSpec _ts)
{
ts = _ts;
StringBuilder sb = new StringBuilder();
GetName(ts, sb);
Name = sb.ToString();
}
private void GetName(TypeSpec ts, StringBuilder sb)
{
switch (ts.stype)
{
case metadata.TypeSpec.SpecialType.None:
sb.Append(ts.Namespace + "." + ts.Name.Replace('+', '.'));
if (ts.IsInstantiatedGenericType)
{
sb.Append("<");
for (int idx = 0; idx < ts.gtparams.Length; idx++)
{
if (idx > 0)
sb.Append(",");
sb.Append(((InteractiveTypeSpec)ts.gtparams[idx]).Name);
}
sb.Append(">");
}
break;
case TypeSpec.SpecialType.SzArray:
GetName(ts.other, sb);
sb.Append("[]");
break;
case TypeSpec.SpecialType.Ptr:
if (ts.other == null)
sb.Append("void *");
else
{
GetName(ts.other, sb);
sb.Append("*");
}
break;
case TypeSpec.SpecialType.Var:
sb.Append("!");
sb.Append('T' + ts.idx);
break;
case TypeSpec.SpecialType.MVar:
sb.Append("!!");
sb.Append('t' + ts.idx);
break;
case TypeSpec.SpecialType.Boxed:
GetName(ts.other, sb);
break;
case TypeSpec.SpecialType.MPtr:
GetName(ts.other, sb);
sb.Append("&");
break;
default:
throw new NotImplementedException();
}
}
public static implicit operator InteractiveTypeSpec(metadata.TypeSpec _ts) { return new InteractiveTypeSpec(_ts); }
public static implicit operator metadata.TypeSpec(InteractiveTypeSpec its) { return its.ts; }
public int TypeSize
{
get
{
return libtysila5.layout.Layout.GetFieldOffset(ts, null, Program.t, out var is_tls, false);
}
}
internal Dictionary<string, InteractiveFieldSpec> all_fields = null;
public Dictionary<string, InteractiveFieldSpec> AllFields
{
get
{
if(all_fields == null)
{
List<string> fld_names = new List<string>();
List<TypeSpec> fld_types = new List<TypeSpec>();
List<int> fld_offsets = new List<int>();
libtysila5.layout.Layout.GetFieldOffset(ts, null, Program.t, out var is_tls,
false, fld_types, fld_names, fld_offsets);
all_fields = new Dictionary<string, InteractiveFieldSpec>();
for(int i = 0; i < fld_names.Count; i++)
{
var ifs = new InteractiveFieldSpec()
{
Name = fld_names[i],
Type = new InteractiveTypeSpec(fld_types[i]),
Offset = fld_offsets[i]
};
all_fields[fld_names[i]] = ifs;
}
}
return all_fields;
}
}
internal Dictionary<string, InteractiveMethodSpec> all_methods = null;
public Dictionary<string, InteractiveMethodSpec> AllMethods
{
get
{
if (all_methods == null)
{
all_methods = new Dictionary<string, InteractiveMethodSpec>();
var first_mdef = ts.m.GetIntEntry(metadata.MetadataStream.tid_TypeDef, ts.tdrow, 5);
var last_mdef = ts.m.GetLastMethodDef(ts.tdrow);
for (uint mdef_row = first_mdef; mdef_row < last_mdef; mdef_row++)
{
var cur_sig = (int)ts.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef, (int)mdef_row, 4);
var ms = new metadata.MethodSpec { m = ts.m, type = ts, mdrow = (int)mdef_row, msig = cur_sig };
var ims = new InteractiveMethodSpec(ms);
all_methods[ims.Name] = ims;
}
}
return all_methods;
}
}
}
class InteractiveMetadataStream
{
public metadata.MetadataStream m = null;
internal Dictionary<string, InteractiveTypeSpec> all_types = null;
public Dictionary<string, InteractiveTypeSpec> AllTypes
{
get
{
if(all_types == null)
{
all_types = new Dictionary<string, InteractiveTypeSpec>();
for (int i = 1; i <= m.table_rows[metadata.MetadataStream.tid_TypeDef]; i++)
{
var ts = new metadata.TypeSpec { m = m, tdrow = i };
var name = ts.Namespace + "." + ts.Name.Replace('+', '.');
all_types[name] = new InteractiveTypeSpec { Name = name, ts = ts };
}
}
/* Add in basic corlib types */
var mscorlib = m.al.GetAssembly("mscorlib");
all_types["string"] = mscorlib.GetTypeSpec("System", "String");
all_types["object"] = mscorlib.GetTypeSpec("System", "Object");
all_types["int"] = mscorlib.GetTypeSpec("System", "Int32");
all_types["uint"] = mscorlib.GetTypeSpec("System", "UInt32");
all_types["long"] = mscorlib.GetTypeSpec("System", "Int64");
all_types["ulong"] = mscorlib.GetTypeSpec("System", "UInt64");
all_types["short"] = mscorlib.GetTypeSpec("System", "Int16");
all_types["ushort"] = mscorlib.GetTypeSpec("System", "UInt16");
all_types["byte"] = mscorlib.GetTypeSpec("System", "Byte");
all_types["sbyte"] = mscorlib.GetTypeSpec("System", "SByte");
all_types["char"] = mscorlib.GetTypeSpec("System", "Char");
all_types["float"] = mscorlib.GetTypeSpec("System", "Single");
all_types["double"] = mscorlib.GetTypeSpec("System", "Double");
return all_types;
}
}
}
InteractiveState s = new InteractiveState();
libtysila5.target.Target t;
InteractiveMetadataStream corlib;
AutoCompleteHandler ach;
libtysila5.TysilaState tst = new libtysila5.TysilaState();
List<string> cmds = new List<string>
{
"select.type",
"select.method",
"select.module",
"quit",
"q",
"continue",
"c",
"assemble.method",
"list.interfaces",
"list.methods",
"implement.interface",
"list.vmethods",
"list.fields",
};
internal Interactive(metadata.MetadataStream metadata, libtysila5.target.Target target)
{
s.m = new InteractiveMetadataStream { m = metadata };
t = target;
corlib = new InteractiveMetadataStream { m = metadata.al.GetAssembly("mscorlib") };
}
internal bool DoInteractive()
{
ach = new AutoCompleteHandler(this);
ReadLine.AutoCompletionHandler = ach;
ReadLine.HistoryEnabled = true;
while(true)
{
dump_state();
string[] cmd;
while ((cmd = get_command()).Length == 0) ;
// handle the command
int idx = 0;
if (cmd[idx] == "select.type")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
s.ts = instantiate_type(s.ts);
}
else if (cmd[idx] == "select.method")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
s.ms = ParseMethod(cmd, ref idx);
}
else if(cmd[idx] == "select.module")
{
idx++;
s.m = ParseModule2(cmd, ref idx);
}
else if (cmd[idx] == "quit" || cmd[idx] == "q")
{
return false;
}
else if (cmd[idx] == "continue" || cmd[idx] == "c")
{
return true;
}
else if (cmd[idx] == "assemble.method")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
s.ms = ParseMethod(cmd, ref idx);
t.InitIntcalls();
tst.r = new libtysila5.CachingRequestor(s.m.m);
tst.st = new libtysila5.StringTable("Interactive", s.ms.ms.m.al, Program.t);
StringBuilder sb = new StringBuilder();
libtysila5.libtysila.AssembleMethod(s.ms.ms, new binary_library.binary.FlatBinaryFile(), t, tst, sb);
Console.WriteLine(sb.ToString());
}
else if (cmd[idx] == "list.methods")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
foreach (var meth in s.ts.AllMethods.Keys)
Console.WriteLine(meth);
}
else if(cmd[idx] == "list.fields")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
foreach (var fld in s.ts.AllFields.Keys)
Console.WriteLine(s.ts.AllFields[fld].ToString());
Console.WriteLine(" Total size: " + s.ts.TypeSize.ToString("X"));
}
else if (cmd[idx] == "list.vmethods")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
var vmeths = libtysila5.layout.Layout.GetVirtualMethodDeclarations(s.ts);
libtysila5.layout.Layout.ImplementVirtualMethods(s.ts, vmeths);
foreach (var vmeth in vmeths)
{
var impl_ms = vmeth.impl_meth;
string impl_target = (impl_ms == null) ? "__cxa_pure_virtual" : impl_ms.MethodReferenceAlias;
var ims = new InteractiveMethodSpec(vmeth.unimpl_meth);
Console.WriteLine(ims.Name + " -> " + impl_target);
}
}
else if (cmd[idx] == "list.interfaces")
{
idx++;
s.m = ParseModule(cmd, ref idx);
s.ts = ParseType(cmd, ref idx);
foreach (var ii in s.ts.ts.ImplementedInterfaces)
Console.WriteLine(((InteractiveTypeSpec)ii).Name);
}
else if (cmd[idx] == "implement.interface")
{
idx++;
InteractiveState istate = new InteractiveState();
istate.m = ParseModule(cmd, ref idx);
istate.ts = ParseType(cmd, ref idx, istate);
t.InitIntcalls();
tst.r = new libtysila5.CachingRequestor(s.m.m);
var iis = libtysila5.layout.Layout.ImplementInterface(s.ts, istate.ts, t, tst);
foreach (var ii in iis)
{
Console.WriteLine(((InteractiveMethodSpec)ii.InterfaceMethod).Name + " -> " + ii.TargetName);
}
}
else
{
Console.WriteLine("Unknown command: " + cmd[idx]);
}
}
throw new NotImplementedException();
return false;
}
private InteractiveTypeSpec instantiate_type(InteractiveTypeSpec ts)
{
if (ts.ts.IsGenericTemplate)
{
TypeSpec[] gtparams = new TypeSpec[ts.ts.GenericParamCount];
for(int i = 0; i < ts.ts.GenericParamCount; i++)
{
string[] cmd;
ach.JustType = true;
while ((cmd = get_command("GP" + i.ToString() + "> ")).Length == 0) ;
ach.JustType = false;
int idx = 0;
var type = ParseType(cmd, ref idx);
gtparams[i] = type;
}
ts.ts.gtparams = gtparams;
return ts;
}
else
return ts;
}
private InteractiveMethodSpec ParseMethod(string[] cmd, ref int idx)
{
if (idx >= (cmd.Length - 1) || cmd[idx] != ":")
return s.ms;
idx++;
var mname = cmd[idx++];
if (s.ts.AllMethods.ContainsKey(mname))
{
var new_ms = s.ts.AllMethods[mname];
return new_ms;
}
else
{
Console.WriteLine("Method: " + mname + " not found in [" + s.m.m.AssemblyName + "]" + s.ts.ts.Namespace + "." + s.ts.ts.Name.Replace('+', '.'));
return s.ms;
}
}
private InteractiveMetadataStream ParseModule(string[] cmd, ref int idx)
{
if (idx >= (cmd.Length - 2) || cmd[idx] != "[" || cmd[idx + 2] != "]")
return s.m;
var new_m = s.m.m.al.GetAssembly(cmd[idx + 1]);
idx += 3;
return new InteractiveMetadataStream { m = new_m };
}
private InteractiveMetadataStream ParseModule2(string[] cmd, ref int idx)
{
if (idx >= cmd.Length)
return s.m;
var new_m = s.m.m.al.GetAssembly(cmd[idx]);
idx++;
return new InteractiveMetadataStream { m = new_m };
}
private InteractiveTypeSpec ParseType(string[] cmd, ref int idx, InteractiveState state = null)
{
if (state == null)
state = s;
if (idx >= cmd.Length || cmd[idx] == ":")
return state.ts;
var tname = cmd[idx++];
InteractiveTypeSpec new_ts = null;
if(state.m.AllTypes.ContainsKey(tname))
new_ts = state.m.AllTypes[tname];
else if(corlib.AllTypes.ContainsKey(tname))
new_ts = corlib.AllTypes[tname];
if(new_ts == null)
{
Console.WriteLine("Type: " + tname + " not found in " + state.m.m.AssemblyName);
return state.ts;
}
if(idx < cmd.Length)
{
if(cmd[idx] == "<")
{
// handle generics
idx++;
var gtparams = new List<TypeSpec>();
while (cmd[idx] != ">")
{
gtparams.Add(ParseType(cmd, ref idx, state));
if (cmd[idx] == ",")
idx++;
}
idx++;
new_ts.ts.gtparams = gtparams.ToArray();
}
}
return new_ts;
}
private string[] get_command(string prompt = "> ")
{
var cmd = get_string(prompt);
return AutoCompleteHandler.Tokenize(cmd, AutoCompleteHandler.seps).ToArray();
}
class AutoCompleteHandler : IAutoCompleteHandler
{
internal static char[] seps = new char[] { ' ', '>', '<', '[', ']', ':' };
public char[] Separators { get; set; } = seps;
Interactive i;
internal bool JustType;
public AutoCompleteHandler(Interactive interactive) { i = interactive; }
public string[] GetSuggestions(string text, int index)
{
string match_text = text.Substring(index);
string context_text = text.Substring(0, index);
List<string> opts;
if (JustType)
{
var ctx = Tokenize(context_text, Separators);
int idx = 0;
opts = ParseTypeForOptions(ctx, ref idx, i.s);
}
else
opts = GetContext(context_text);
List<string> ret = new List<string>();
foreach(var test in opts)
{
if (test.StartsWith(match_text))
ret.Add(test);
}
if (ret.Count == 0)
return new string[] { };
if (ret.Count == 1)
return new string[] { ret[0] + " " }; // if only one entry can put space after
/* Find common starting characters */
int start_common = 0;
while(true)
{
char cur_c = ' '; // matching character at position start_common
bool is_first = true; // is this the first string in the foreach loop?
foreach(var str in ret)
{
if (start_common >= str.Length)
return new string[] { ret[0].Substring(0, start_common) };
if (is_first)
{
cur_c = str[start_common];
is_first = false;
}
else
{
if (str[start_common] != cur_c)
return new string[] { ret[0].Substring(0, start_common) };
}
}
start_common++;
}
}
private List<string> GetContext(string context_text)
{
context_text = context_text.Trim();
if (context_text == string.Empty)
return i.cmds;
var ctx = Tokenize(context_text, Separators);
int idx = 0;
var state = new InteractiveState { m = i.s.m, ms = i.s.ms, ts = i.s.ts };
return ParseCommandForOptions(ctx, ref idx, state);
throw new NotImplementedException();
}
private List<string> ParseCommandForOptions(List<string> ctx, ref int idx, InteractiveState state)
{
var cmd = ctx[idx++];
if (cmd == "select.type")
return ParseTypeForOptions(ctx, ref idx, state);
else if (cmd == "select.module")
return ParseModuleForOptions2(ctx, ref idx, state);
if (cmd == "implement.interface")
return ParseInterfaceForOptions(ctx, ref idx, state);
else if (cmd == "select.method")
return ParseMethodForOptions(ctx, ref idx, state);
else if (cmd == "assemble.method")
{
if (idx < ctx.Count || state.ms == null)
return ParseMethodForOptions(ctx, ref idx, state);
else
return new List<string>();
}
else if (cmd == "list.methods" || cmd == "list.interfaces" || cmd == "list.vmethods" || cmd == "list.fields")
{
if (idx < ctx.Count || state.ts == null)
return ParseTypeForOptions(ctx, ref idx, state);
else
return new List<string>();
}
return new List<string>();
throw new NotImplementedException();
}
private List<string> ParseInterfaceForOptions(List<string> ctx, ref int idx, InteractiveState state)
{
if (idx >= ctx.Count && state.ts != null)
{
var ret = new List<string>();
foreach (var ii in state.ts.ts.ImplementedInterfaces)
ret.Add(((InteractiveTypeSpec)ii).Name);
return ret;
}
return new List<string>();
}
private List<string> ParseMethodForOptions(List<string> ctx, ref int idx, InteractiveState state)
{
// methods may be described by name or type:name
var ret = ParseTypeForOptions(ctx, ref idx, state);
if (ret == null)
ret = new List<string>();
if (idx < ctx.Count && ctx[idx] == ":")
idx++;
if (idx >= ctx.Count && state.ts != null)
ret.AddRange(state.ts.AllMethods.Keys);
return ret;
}
private List<string> ParseTypeForOptions(List<string> ctx, ref int idx, InteractiveState state)
{
if(idx >= ctx.Count)
{
// no types listed, return all in the current module
return new List<string>(state.m.AllTypes.Keys);
}
if(ctx[idx] == "[")
{
idx++;
var ret = ParseModuleForOptions(ctx, ref idx, state);
if (ret != null)
return ret;
}
if (state.m.AllTypes.ContainsKey(ctx[idx]))
state.ts = state.m.AllTypes[ctx[idx++]];
return null;
}
private List<string> ParseModuleForOptions2(List<string> ctx, ref int idx, InteractiveState state)
{
return new List<string>(state.m.m.al.LoadedAssemblies);
}
private List<string> ParseModuleForOptions(List<string> ctx, ref int idx, InteractiveState state)
{
if(idx >= ctx.Count)
{
// end of the parse, return all loaded modules
return new List<string>(state.m.m.al.LoadedAssemblies);
}
// else, make the new module our current scope
var mod_list = new List<string>(state.m.m.al.LoadedAssemblies);
var new_mod = ctx[idx++];
if(mod_list.Contains(new_mod))
{
var new_m = new InteractiveMetadataStream { m = state.m.m.al.GetAssembly(new_mod) };
state.m = new_m;
}
if(idx++ >= ctx.Count)
{
// must terminate a module with closing bracket
return new List<string> { "]" };
}
return ParseTypeForOptions(ctx, ref idx, state);
}
internal static List<string> Tokenize(string text, char[] separators)
{
List<string> ret = new List<string>();
StringBuilder sb = new StringBuilder();
foreach(var c in text)
{
bool in_sep = false;
foreach(var sep in separators)
{
if(sep == c)
{
in_sep = true;
break;
}
}
if (in_sep)
{
var txt = sb.ToString().Trim();
if (txt.Length > 0)
ret.Add(txt);
sb = new StringBuilder();
if(c != ' ')
ret.Add(new string(new char[] { c }));
}
else
{
sb.Append(c);
}
}
var txt2 = sb.ToString().Trim();
if (txt2.Length > 0)
ret.Add(txt2);
return ret;
}
}
private string get_string(string prompt = "")
{
return ReadLine.Read(prompt);
}
private void dump_state()
{
Console.WriteLine();
Console.WriteLine("Module: " + s.m.m.FullName);
Console.WriteLine("Type: " + (s.ts == null ? "{null}" : s.ts.Name));
Console.WriteLine("Method: " + (s.ms == null ? "{null}" : s.ms.Name));
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libsupcs
{
class ConstructorInfo : System.Reflection.ConstructorInfo
{
TysosMethod _meth;
TysosType _type;
internal ConstructorInfo(TysosMethod meth, TysosType type) {
if (meth == null)
throw new Exception("libsupcs.ConstructorInfo constructor called with meth as null");
if (type == null)
throw new Exception("libsupcs.ConstructorInfo constructor called with type as null");
_meth = meth; _type = type;
}
public override object Invoke(System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture)
{
if (_meth == null)
throw new Exception("libsupcs.ConstructorInfo.Invoke: _meth is null");
if (_type == null)
throw new Exception("libsupcs.ConstructorInfo.Invoke: _type is null");
object obj = _type.Create();
_meth.Invoke(obj, invokeAttr, binder, parameters, culture);
return obj;
}
public override System.Reflection.MethodAttributes Attributes
{
get { return _meth.Attributes; }
}
public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags()
{
return _meth.GetMethodImplementationFlags();
}
public override System.Reflection.ParameterInfo[] GetParameters()
{
return _meth.GetParameters();
}
public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture)
{
_meth.Invoke(obj, invokeAttr, binder, parameters, culture);
return obj;
}
public override RuntimeMethodHandle MethodHandle
{
get { return _meth.MethodHandle; }
}
public override Type DeclaringType
{
get { return _meth.DeclaringType; }
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _meth.GetCustomAttributes(attributeType, inherit);
}
public override object[] GetCustomAttributes(bool inherit)
{
return _meth.GetCustomAttributes(inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return _meth.IsDefined(attributeType, inherit);
}
public override string Name
{
get { return _meth.Name; }
}
public override Type ReflectedType
{
get { return _meth.ReflectedType; }
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using binary_library;
using binary_library.elf;
using XGetoptCS;
namespace tysila4
{
public class Program
{
/* Boiler plate */
const string year = "2009 - 2018";
const string authors = "<NAME> <<EMAIL>>";
const string website = "http://www.tysos.org";
const string nl = "\n";
public static string bplate = "tysila " + libtysila5.libtysila.VersionString + " (" + website + ")" + nl +
"Copyright (C) " + year + " " + authors + nl +
"This is free software. Please see the source for copying conditions. There is no warranty, " +
"not even for merchantability or fitness for a particular purpose";
static string comment = nl + "tysila" + nl + "ver: " + libtysila5.libtysila.VersionString + nl;
public static List<string> search_dirs = new List<string> {
"",
".",
Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(Program)).Location),
DirectoryDelimiter
};
static List<string> new_search_dirs = new List<string>();
internal static libtysila5.target.Target t;
static bool func_sects = false;
static bool data_sects = false;
static bool class_sects = false;
static bool do_dwarf = false;
public static string DirectoryDelimiter
{
get
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
return "/";
else
return "\\";
}
}
static void Main(string[] args)
{
var argc = args.Length;
char c;
var go = new XGetoptCS.XGetopt();
var arg_str = "t:L:f:e:o:d:qDC:H:m:i";
string target = "x86";
string debug_file = null;
string output_file = null;
string epoint = null;
string cfile = null;
string hfile = null;
bool quiet = false;
bool require_metadata_version_match = true;
bool interactive = false;
string act_epoint = null;
Dictionary<string, object> opts = new Dictionary<string, object>();
while((c = go.Getopt(argc, args, arg_str)) != '\0')
{
switch(c)
{
case 't':
target = go.Optarg;
break;
case 'L':
new_search_dirs.Add(go.Optarg);
break;
case 'd':
debug_file = go.Optarg;
break;
case 'o':
output_file = go.Optarg;
break;
case 'e':
epoint = go.Optarg;
break;
case 'q':
quiet = true;
break;
case 'D':
require_metadata_version_match = false;
break;
case 'C':
cfile = go.Optarg;
break;
case 'H':
hfile = go.Optarg;
break;
case 'f':
parse_f_option(go);
break;
case 'i':
interactive = true;
break;
case 'g':
do_dwarf = true;
break;
case 'm':
{
var opt = go.Optarg;
object optval = true;
if(opt.Contains("="))
{
var optvals = opt.Substring(opt.IndexOf("=") + 1);
opt = opt.Substring(0, opt.IndexOf("="));
int intval;
if (optvals.ToLower() == "false" || optvals.ToLower() == "off" || optvals.ToLower() == "no")
optval = false;
else if (optvals.ToLower() == "true" || optvals.ToLower() == "on" || optvals.ToLower() == "yes")
optval = true;
else if (int.TryParse(optvals, out intval))
optval = intval;
else
optval = optvals;
}
else if(opt.StartsWith("no-"))
{
opt = opt.Substring(3);
optval = false;
}
opts[opt] = optval;
}
break;
}
}
var fname = go.Optarg;
if(fname == String.Empty)
{
Console.WriteLine("No input file specified");
return;
}
// Insert library directories specified on the command line before the defaults
search_dirs.InsertRange(0, new_search_dirs);
if(cfile != null && hfile == null)
{
Console.WriteLine("-H must be used if -C is used");
return;
}
libtysila5.libtysila.AssemblyLoader al = new libtysila5.libtysila.AssemblyLoader(
new FileSystemFileLoader());
/* Load up type forwarders */
foreach(var libdir in search_dirs)
{
try
{
var di = new DirectoryInfo(libdir);
if (di.Exists)
{
foreach (var tfw_file in di.GetFiles("*.tfw"))
{
var tfr = new StreamReader(tfw_file.OpenRead());
while (!tfr.EndOfStream)
{
var tfr_line = tfr.ReadLine();
var tfr_lsplit = tfr_line.Split('=');
al.TypeForwarders[tfr_lsplit[0]] = tfr_lsplit[1];
}
tfr.Close();
}
}
}
catch (Exception) { }
}
//search_dirs.Add(@"..\mono\corlib");
al.RequireVersionMatch = require_metadata_version_match;
// add containing directory of input to search dirs
var ifi = new FileInfo(fname);
search_dirs.Add(ifi.DirectoryName);
var m = al.GetAssembly(fname);
if(m == null)
{
Console.WriteLine("Input file " + fname + " not found");
throw new Exception(fname + " not found");
}
t = libtysila5.target.Target.targets[target];
// try and set target options
foreach(var kvp in opts)
{
if(!t.Options.TrySet(kvp.Key, kvp.Value))
{
Console.WriteLine("Unable to set target option " + kvp.Key + " to " + kvp.Value.ToString());
return;
}
}
if (interactive)
{
if (new Interactive(m, t).DoInteractive() == false)
return;
}
libtysila5.dwarf.DwarfCU dwarf = null;
if(do_dwarf)
{
dwarf = new libtysila5.dwarf.DwarfCU(t, m);
}
libtysila5.TysilaState s = new libtysila5.TysilaState();
if (output_file != null)
{
var bf = new binary_library.elf.ElfFile(binary_library.Bitness.Bits32);
s.bf = bf;
bf.Init();
bf.Architecture = target;
var st = new libtysila5.StringTable(
m.GetStringEntry(metadata.MetadataStream.tid_Module,
1, 1), al, t);
s.st = st;
s.r = new libtysila5.CachingRequestor(m);
t.InitIntcalls();
/* for now, just assemble all public and protected
non-generic methods in public types, plus the
entry point */
StringBuilder debug = new StringBuilder();
for (int i = 1; i <= m.table_rows[metadata.MetadataStream.tid_MethodDef]; i++)
{
metadata.MethodSpec ms = new metadata.MethodSpec
{
m = m,
mdrow = i,
msig = 0
};
ms.type = new metadata.TypeSpec
{
m = m,
tdrow = m.methoddef_owners[ms.mdrow]
};
var mflags = m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
i, 2);
var tflags = m.GetIntEntry(metadata.MetadataStream.tid_TypeDef,
ms.type.tdrow, 0);
mflags &= 0x7;
tflags &= 0x7;
ms.msig = (int)m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
i, 4);
/* See if this is the entry point */
int tid, row;
m.InterpretToken(m.entry_point_token, out tid, out row);
if (tid == metadata.MetadataStream.tid_MethodDef)
{
if (row == i)
{
if (epoint != null)
ms.aliases = new List<string> { epoint };
mflags = 6;
tflags = 1;
ms.AlwaysCompile = true;
act_epoint = ms.MangleMethod();
}
}
/* See if we have an always compile attribute */
if (ms.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs22AlwaysCompileAttribute_7#2Ector_Rv_P1u1t") ||
ms.type.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs22AlwaysCompileAttribute_7#2Ector_Rv_P1u1t"))
{
mflags = 6;
tflags = 1;
ms.AlwaysCompile = true;
}
if (ms.type.IsGenericTemplate == false &&
ms.IsGenericTemplate == false &&
(mflags == 0x4 || mflags == 0x5 || mflags == 0x6) &&
tflags != 0)
{
s.r.MethodRequestor.Request(ms);
}
}
/* Also assemble all public non-generic type infos */
for (int i = 1; i <= m.table_rows[metadata.MetadataStream.tid_TypeDef]; i++)
{
var flags = (int)m.GetIntEntry(metadata.MetadataStream.tid_TypeDef,
i, 0);
if (((flags & 0x7) != 0x1) &&
((flags & 0x7) != 0x2))
continue;
var ts = new metadata.TypeSpec { m = m, tdrow = i };
if (ts.IsGeneric)
continue;
s.r.StaticFieldRequestor.Request(ts);
s.r.VTableRequestor.Request(ts.Box);
}
/* If corlib, add in the default equality comparers so we don't have to jit these
* commonly used classes */
if(m.is_corlib)
{
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemByte }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt8 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt16 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemUInt16 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt32 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemUInt32 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt64 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemUInt64 }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemString }), ".ctor"));
s.r.MethodRequestor.Request(m.GetMethodSpec(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemObject }), ".ctor"));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemByte }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt8 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt16 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemUInt16 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt32 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemUInt32 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemInt64 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemUInt64 }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemString }));
s.r.VTableRequestor.Request(m.GetTypeSpec("System.Collections.Generic", "GenericEqualityComparer`1", new metadata.TypeSpec[] { m.SystemObject }));
}
/* Generate a thread-local data section. We may not use it. */
var tlsos = bf.CreateContentsSection();
tlsos.Name = ".tdata";
tlsos.IsAlloc = true;
tlsos.IsExecutable = false;
tlsos.IsWriteable = true;
tlsos.IsThreadLocal = true;
while (!s.r.Empty)
{
if (!s.r.MethodRequestor.Empty)
{
var ms = s.r.MethodRequestor.GetNext();
ISection tsect = null;
ISection datasect = null;
if (func_sects && !ms.ms.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetTextSection(), "." + ms.ms.MangleMethod());
datasect = get_decorated_section(bf, bf.GetDataSection(), "." + ms.ms.MangleMethod() + "_SignatureTable");
}
else if(class_sects && !ms.ms.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetTextSection(), "." + ms.ms.type.MangleType());
datasect = get_decorated_section(bf, bf.GetDataSection(), "." + ms.ms.type.MangleType() + "_SignatureTable");
}
libtysila5.libtysila.AssembleMethod(ms.ms,
bf, t, s, debug, m, ms.c, tsect, datasect, dwarf);
if (!quiet)
Console.WriteLine(ms.ms.m.MangleMethod(ms.ms));
}
else if (!s.r.StaticFieldRequestor.Empty)
{
var sf = s.r.StaticFieldRequestor.GetNext();
ISection tsect = null;
if (data_sects && !sf.AlwaysCompile)
tsect = get_decorated_section(bf, bf.GetDataSection(), "." + sf.MangleType() + "S");
else if (class_sects && !sf.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetDataSection(), "." + sf.MangleType() + "S");
}
libtysila5.layout.Layout.OutputStaticFields(sf,
t, bf, m, tsect, tlsos);
if (!quiet)
Console.WriteLine(sf.MangleType() + "S");
}
else if (!s.r.EHRequestor.Empty)
{
var eh = s.r.EHRequestor.GetNext();
ISection tsect = null;
if (func_sects && !eh.ms.AlwaysCompile)
tsect = get_decorated_section(bf, bf.GetRDataSection(), "." + eh.ms.MangleMethod() + "EH");
else if (class_sects && !eh.ms.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetRDataSection(), "." + eh.ms.type.MangleType() + "EH");
}
libtysila5.layout.Layout.OutputEHdr(eh,
t, bf, s, m, tsect);
if (!quiet)
Console.WriteLine(eh.ms.MangleMethod() + "EH");
}
else if (!s.r.VTableRequestor.Empty)
{
var vt = s.r.VTableRequestor.GetNext();
ISection tsect = null;
ISection data_sect = null;
if (data_sects && !vt.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetRDataSection(), "." + vt.MangleType());
data_sect = get_decorated_section(bf, bf.GetDataSection(), "." + vt.MangleType() + "_SignatureTable");
}
else if (class_sects && !vt.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetTextSection(), "." + vt.MangleType());
data_sect = get_decorated_section(bf, bf.GetDataSection(), "." + vt.MangleType() + "_SignatureTable");
}
libtysila5.layout.Layout.OutputVTable(vt,
t, bf, s, m, tsect, data_sect);
if (!quiet)
Console.WriteLine(vt.MangleType());
}
else if(!s.r.DelegateRequestor.Empty)
{
var d = s.r.DelegateRequestor.GetNext();
libtysila5.ir.ConvertToIR.CreateDelegate(d, t, s);
if (!quiet)
Console.WriteLine(d.MangleType() + "D");
}
else if(!s.r.BoxedMethodRequestor.Empty)
{
var bm = s.r.BoxedMethodRequestor.GetNext();
ISection tsect = null;
if (func_sects && !bm.ms.AlwaysCompile)
tsect = get_decorated_section(bf, bf.GetTextSection(), "." + bm.ms.MangleMethod());
else if (class_sects && !bm.ms.AlwaysCompile)
{
tsect = get_decorated_section(bf, bf.GetTextSection(), "." + bm.ms.type.MangleType());
}
libtysila5.libtysila.AssembleBoxedMethod(bm.ms,
bf, t, s, debug, tsect);
if (!quiet)
Console.WriteLine(bm.ms.MangleMethod());
}
}
if (debug_file != null)
{
string d = debug.ToString();
StreamWriter sw = new StreamWriter(debug_file);
sw.Write(d);
sw.Close();
}
if (tlsos.Length > 0)
bf.AddSection(tlsos);
/* String table */
st.WriteToOutput(bf, m, t);
/* Include original metadata */
var rdata = bf.GetRDataSection();
rdata.Align(t.GetPointerSize());
var mdsym = bf.CreateSymbol();
mdsym.Name = m.AssemblyName;
mdsym.ObjectType = binary_library.SymbolObjectType.Object;
mdsym.Offset = (ulong)rdata.Data.Count;
mdsym.Type = binary_library.SymbolType.Global;
var len = m.file.GetLength();
mdsym.Size = len;
rdata.AddSymbol(mdsym);
for (int i = 0; i < len; i++)
rdata.Data.Add(m.file.ReadByte(i));
var mdsymend = bf.CreateSymbol();
mdsymend.Name = m.AssemblyName + "_end";
mdsymend.ObjectType = binary_library.SymbolObjectType.Object;
mdsymend.Offset = (ulong)rdata.Data.Count;
mdsymend.Type = binary_library.SymbolType.Global;
mdsymend.Size = 0;
rdata.AddSymbol(mdsymend);
/* Add resource symbol if present */
if(m.GetPEFile().ResourcesSize != 0)
{
var rsym = bf.CreateSymbol();
rsym.Name = m.AssemblyName + "_resources";
rsym.ObjectType = SymbolObjectType.Object;
rsym.Offset = (ulong)m.GetPEFile().ResourcesOffset + mdsym.Offset;
rsym.Type = SymbolType.Global;
rsym.Size = m.GetPEFile().ResourcesSize;
rdata.AddSymbol(rsym);
}
/* Add comment */
var csect = bf.CreateContentsSection();
csect.IsAlloc = false;
csect.IsExecutable = false;
csect.IsWriteable = false;
csect.Name = ".comment";
var cbytes = Encoding.ASCII.GetBytes(comment);
foreach (var cbyte in cbytes)
csect.Data.Add(cbyte);
csect.Data.Add(0);
if(act_epoint != null)
{
var epbytes = Encoding.ASCII.GetBytes("entry: " +
act_epoint);
foreach (var epbyte in epbytes)
csect.Data.Add(epbyte);
csect.Data.Add(0);
}
bf.AddSection(csect);
/* Add debugger sections */
if(dwarf != null)
{
var dwarf_sects = new libtysila5.dwarf.DwarfSections(bf);
dwarf.WriteToOutput(dwarf_sects);
}
/* Write output file */
bf.Filename = output_file;
bf.Write();
}
if(hfile != null)
{
COutput.WriteHeader(m, t, hfile, cfile);
}
}
private static ISection get_decorated_section(ElfFile bf, ISection section, string add_to_name)
{
var decorated_name = section.Name + add_to_name;
var sect = bf.FindSection(decorated_name);
if(sect == null)
{
sect = bf.CopySectionType(section, decorated_name);
}
return sect;
}
private static void parse_f_option(XGetopt go)
{
if (go.Optarg == "function-sections")
func_sects = true;
else if (go.Optarg == "data-sections")
data_sects = true;
else if (go.Optarg == "class-sections")
class_sects = true;
else
throw new NotImplementedException();
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using libtysila5.ir;
namespace libtysila5.target
{
public partial class Target
{
public class TargetOption
{
object val;
Type t;
public void Set(object v)
{
if (t == null)
{
val = v;
t = v.GetType();
}
else if (v.GetType().Equals(t))
{
val = v;
}
else
throw new InvalidCastException();
}
public bool TrySet(object v)
{
if (t == null)
{
val = v;
t = v.GetType();
return true;
}
else if (v.GetType().Equals(t))
{
val = v;
return true;
}
else
return false;
}
public object Get()
{
return val;
}
internal TargetOption(object v)
{
Set(v);
}
}
public class TargetOptions : IDictionary<string, object>
{
Dictionary<string, TargetOption> d;
internal TargetOptions()
{
d = new Dictionary<string, TargetOption>(new metadata.GenericEqualityComparer<string>());
}
internal TargetOptions(IDictionary<string, object> v)
{
d = new Dictionary<string, TargetOption>(new metadata.GenericEqualityComparer<string>());
foreach (var kvp in v)
d[kvp.Key] = new TargetOption(kvp.Value);
}
internal void InternalAdd(string key, object v)
{
d[key] = new TargetOption(v);
}
public bool TrySet(string key, object v)
{
if (!d.ContainsKey(key))
return false;
return d[key].TrySet(v);
}
public object this[string key]
{
get
{
return d[key].Get();
}
set
{
d[key].Set(value);
}
}
object IDictionary<string, object>.this[string key]
{
get
{
return d[key].Get();
}
set
{
d[key].Set(value);
}
}
public int Count
{
get
{
return d.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public ICollection<string> Keys
{
get
{
return d.Keys;
}
}
public ICollection<object> Values
{
get
{
List<object> ret = new List<object>();
foreach (var v in d.Values)
ret.Add(v.Get());
return ret;
}
}
int ICollection<KeyValuePair<string, object>>.Count
{
get
{
return d.Count;
}
}
bool ICollection<KeyValuePair<string, object>>.IsReadOnly
{
get
{
return false;
}
}
ICollection<string> IDictionary<string, object>.Keys
{
get
{
return d.Keys;
}
}
ICollection<object> IDictionary<string, object>.Values
{
get
{
List<object> ret = new List<object>();
foreach (var v in d.Values)
ret.Add(v.Get());
return ret;
}
}
public void Add(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
public void Add(string key, object value)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
public bool ContainsKey(string key)
{
return d.ContainsKey(key);
}
public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
foreach(var kvp in d)
{
yield return new KeyValuePair<string, object>(kvp.Key, kvp.Value.Get());
}
}
public bool Remove(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
public bool Remove(string key)
{
throw new NotSupportedException();
}
public bool TryGetValue(string key, out object value)
{
if(d.ContainsKey(key))
{
value = d[key].Get();
return true;
}
value = null;
return false;
}
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
void IDictionary<string, object>.Add(string key, object value)
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<string, object>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
bool IDictionary<string, object>.ContainsKey(string key)
{
return d.ContainsKey(key);
}
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
throw new NotSupportedException();
}
IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
{
foreach (var kvp in d)
{
yield return new KeyValuePair<string, object>(kvp.Key, kvp.Value.Get());
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var kvp in d)
{
yield return new KeyValuePair<string, object>(kvp.Key, kvp.Value.Get());
}
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
throw new NotSupportedException();
}
bool IDictionary<string, object>.Remove(string key)
{
throw new NotSupportedException();
}
bool IDictionary<string, object>.TryGetValue(string key, out object value)
{
if (d.ContainsKey(key))
{
value = d[key].Get();
return true;
}
value = null;
return false;
}
}
}
}
<file_sep>// This code was generated by the Gardens Point Parser Generator
// Copyright (c) <NAME>, <NAME>, QUT 2005-2014
// (see accompanying GPPGcopyright.rtf)
// GPPG version 1.5.2
// Machine: DESKTOP-JOHN
// DateTime: 25/03/2017 17:57:54
// UserName: jncro
// Input file <tablemap.y - 25/03/2017 17:57:25>
// options: conflicts lines gplex conflicts
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Text;
using QUT.Gppg;
namespace TableMap
{
internal enum Tokens {error=2,EOF=3,EQUALS=4,COLON=5,MUL=6,
LPAREN=7,RPAREN=8,AMP=9,PLUS=10,MINUS=11,DOLLARS=12,
COMMA=13,NEWLINE=14,FUNC=15,ASSIGN=16,NOT=17,NOTEQUAL=18,
LEQUAL=19,GEQUAL=20,LBRACE=21,RBRACE=22,LBRACK=23,RBRACK=24,
DOT=25,LT=26,GT=27,LSHIFT=28,RSHIFT=29,SEMICOLON=30,
LOR=31,LAND=32,OR=33,AND=34,APPEND=35,ASSIGNIF=36,
IF=37,ELSE=38,INCLUDE=39,RULEFOR=40,INPUTS=41,DEPENDS=42,
ALWAYS=43,SHELLCMD=44,TYPROJECT=45,SOURCES=46,MKDIR=47,FUNCTION=48,
RETURN=49,EXPORT=50,ISDIR=51,ISFILE=52,DEFINED=53,BUILD=54,
INTEGER=55,STRING=56,VOID=57,ARRAY=58,OBJECT=59,FUNCREF=60,
ANY=61,NULL=62,FOR=63,FOREACH=64,IN=65,WHILE=66,
DO=67,INT=68,LABEL=69};
internal partial struct ValueType
#line 16 "tablemap.y"
{
public int intval;
public string strval;
public Statement stmtval;
public Expression exprval;
public List<Expression> exprlist;
public TableMap.Tokens tokval;
public Expression.EvalResult.ResultType typeval;
public FunctionStatement.FunctionArg argval;
public List<FunctionStatement.FunctionArg> arglistval;
public List<Expression.EvalResult.ResultType> typelistval;
public List<ObjDef> objdeflist;
public ObjDef objdefval;
public bool bval;
}
#line default
// Abstract base class for GPLEX scanners
[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")]
internal abstract class ScanBase : AbstractScanner<ValueType,LexLocation> {
private LexLocation __yylloc = new LexLocation();
public override LexLocation yylloc { get { return __yylloc; } set { __yylloc = value; } }
protected virtual bool yywrap() { return true; }
}
// Utility class for encapsulating token information
[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")]
internal class ScanObj {
public int token;
public ValueType yylval;
public LexLocation yylloc;
public ScanObj( int t, ValueType val, LexLocation loc ) {
this.token = t; this.yylval = val; this.yylloc = loc;
}
}
[GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")]
internal partial class Parser: ShiftReduceParser<ValueType, LexLocation>
{
#pragma warning disable 649
private static Dictionary<int, string> aliases;
#pragma warning restore 649
private static Rule[] rules = new Rule[107];
private static State[] states = new State[186];
private static string[] nonTerms = new string[] {
"file", "export", "expr", "expr2", "expr3", "expr4", "expr5", "expr6",
"expr7", "expr7a", "expr8", "expr9", "expr10", "expr11", "strlabelexpr",
"funccall", "labelexpr", "labelexpr2", "funcrefexpr", "stmtblock", "stmtlist",
"stmt", "stmt2", "define", "ifblock", "cmd", "include", "funcdef", "forblock",
"foreachblock", "whileblock", "doblock", "exprlist", "arrayexpr", "assignop",
"arg", "argtype", "arglist", "typelist", "objmember", "objlist", "objexpr",
"$accept", };
static Parser() {
states[0] = new State(new int[]{21,4,69,52,56,58,37,122,63,129,64,140,66,148,67,154,50,173,49,177,39,181,3,-2,48,-20},new int[]{-1,1,-20,3,-21,185,-22,184,-23,8,-24,9,-17,11,-18,60,-16,117,-15,118,-25,121,-29,128,-30,139,-31,147,-32,153,-2,160,-26,175,-27,179});
states[1] = new State(new int[]{3,2});
states[2] = new State(-1);
states[3] = new State(-3);
states[4] = new State(new int[]{22,183,69,52,56,58,37,122,63,129,64,140,66,148,67,154,50,173,49,177,39,181,48,-20},new int[]{-21,5,-22,184,-23,8,-24,9,-17,11,-18,60,-16,117,-15,118,-25,121,-29,128,-30,139,-31,147,-32,153,-2,160,-26,175,-27,179});
states[5] = new State(new int[]{22,6,69,52,56,58,37,122,63,129,64,140,66,148,67,154,50,173,49,177,39,181,48,-20},new int[]{-22,7,-23,8,-24,9,-17,11,-18,60,-16,117,-15,118,-25,121,-29,128,-30,139,-31,147,-32,153,-2,160,-26,175,-27,179});
states[6] = new State(-14);
states[7] = new State(-17);
states[8] = new State(-18);
states[9] = new State(new int[]{30,10});
states[10] = new State(-21);
states[11] = new State(new int[]{16,114,36,115,35,116,25,-6,23,-6},new int[]{-35,12});
states[12] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,13,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[13] = new State(-35);
states[14] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-4,15,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[15] = new State(new int[]{8,16});
states[16] = new State(-50);
states[17] = new State(new int[]{31,18,30,-53,8,-53,13,-53,24,-53,21,-53});
states[18] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-4,19,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[19] = new State(-52);
states[20] = new State(new int[]{32,21,31,-55,30,-55,8,-55,13,-55,24,-55,21,-55});
states[21] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-5,22,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[22] = new State(-54);
states[23] = new State(new int[]{33,24,32,-57,31,-57,30,-57,8,-57,13,-57,24,-57,21,-57});
states[24] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-6,25,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[25] = new State(-56);
states[26] = new State(new int[]{34,27,33,-59,32,-59,31,-59,30,-59,8,-59,13,-59,24,-59,21,-59});
states[27] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-7,28,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[28] = new State(-58);
states[29] = new State(new int[]{4,30,18,112,34,-62,33,-62,32,-62,31,-62,30,-62,8,-62,13,-62,24,-62,21,-62});
states[30] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-8,31,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[31] = new State(-60);
states[32] = new State(new int[]{26,33,27,106,19,108,20,110,4,-67,18,-67,34,-67,33,-67,32,-67,31,-67,30,-67,8,-67,13,-67,24,-67,21,-67});
states[33] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-9,34,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[34] = new State(-63);
states[35] = new State(new int[]{28,36,29,104,26,-70,27,-70,19,-70,20,-70,4,-70,18,-70,34,-70,33,-70,32,-70,31,-70,30,-70,8,-70,13,-70,24,-70,21,-70});
states[36] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-10,37,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[37] = new State(-68);
states[38] = new State(new int[]{10,39,11,102,28,-73,29,-73,26,-73,27,-73,19,-73,20,-73,4,-73,18,-73,34,-73,33,-73,32,-73,31,-73,30,-73,8,-73,13,-73,24,-73,21,-73});
states[39] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-11,40,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[40] = new State(-71);
states[41] = new State(new int[]{6,42,10,-75,11,-75,28,-75,29,-75,26,-75,27,-75,19,-75,20,-75,4,-75,18,-75,34,-75,33,-75,32,-75,31,-75,30,-75,8,-75,13,-75,24,-75,21,-75});
states[42] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-12,43,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[43] = new State(-74);
states[44] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-13,45,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[45] = new State(-76);
states[46] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-13,47,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[47] = new State(-77);
states[48] = new State(-78);
states[49] = new State(new int[]{25,50,23,99,6,-79,10,-79,11,-79,28,-79,29,-79,26,-79,27,-79,19,-79,20,-79,4,-79,18,-79,34,-79,33,-79,32,-79,31,-79,30,-79,8,-79,13,-79,24,-79,21,-79});
states[50] = new State(new int[]{69,52},new int[]{-18,51,-16,61});
states[51] = new State(-8);
states[52] = new State(new int[]{7,53,16,-10,36,-10,35,-10,25,-10,23,-10,6,-10,10,-10,11,-10,28,-10,29,-10,26,-10,27,-10,19,-10,20,-10,4,-10,18,-10,34,-10,33,-10,32,-10,31,-10,30,-10,8,-10,13,-10,24,-10,21,-10});
states[53] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86,8,-48,13,-48},new int[]{-33,54,-4,96,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[54] = new State(new int[]{8,55,13,56});
states[55] = new State(-12);
states[56] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-4,57,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[57] = new State(-46);
states[58] = new State(-5);
states[59] = new State(-6);
states[60] = new State(-7);
states[61] = new State(-11);
states[62] = new State(-80);
states[63] = new State(-81);
states[64] = new State(new int[]{17,44,11,46,56,58,69,97,68,62,23,64,60,71,62,86,24,-48,13,-48},new int[]{-33,65,-41,87,-4,96,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70,-40,98});
states[65] = new State(new int[]{24,66,13,67});
states[66] = new State(-89);
states[67] = new State(new int[]{24,68,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-4,57,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[68] = new State(-90);
states[69] = new State(-82);
states[70] = new State(-83);
states[71] = new State(new int[]{69,72});
states[72] = new State(new int[]{7,73});
states[73] = new State(new int[]{55,78,56,79,58,80,59,81,57,82,48,83,61,84,8,-88,13,-88},new int[]{-39,74,-37,85});
states[74] = new State(new int[]{8,75,13,76});
states[75] = new State(-85);
states[76] = new State(new int[]{55,78,56,79,58,80,59,81,57,82,48,83,61,84},new int[]{-37,77});
states[77] = new State(-86);
states[78] = new State(-99);
states[79] = new State(-100);
states[80] = new State(-101);
states[81] = new State(-102);
states[82] = new State(-103);
states[83] = new State(-104);
states[84] = new State(-105);
states[85] = new State(-87);
states[86] = new State(-84);
states[87] = new State(new int[]{24,88,13,89});
states[88] = new State(-94);
states[89] = new State(new int[]{24,90,69,92},new int[]{-40,91});
states[90] = new State(-95);
states[91] = new State(-97);
states[92] = new State(new int[]{16,93});
states[93] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,94,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[94] = new State(-98);
states[95] = new State(-51);
states[96] = new State(-47);
states[97] = new State(new int[]{7,53,16,93,25,-10,23,-10,6,-10,10,-10,11,-10,28,-10,29,-10,26,-10,27,-10,19,-10,20,-10,4,-10,18,-10,34,-10,33,-10,32,-10,31,-10,24,-10,13,-10});
states[98] = new State(-96);
states[99] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,100,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[100] = new State(new int[]{24,101});
states[101] = new State(-9);
states[102] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-11,103,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[103] = new State(-72);
states[104] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-10,105,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[105] = new State(-69);
states[106] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-9,107,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[107] = new State(-64);
states[108] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-9,109,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[109] = new State(-65);
states[110] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-9,111,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[111] = new State(-66);
states[112] = new State(new int[]{17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-8,113,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[113] = new State(-61);
states[114] = new State(-36);
states[115] = new State(-37);
states[116] = new State(-38);
states[117] = new State(new int[]{16,-11,36,-11,35,-11,25,-11,23,-11,30,-33});
states[118] = new State(new int[]{25,119,23,99});
states[119] = new State(new int[]{69,52},new int[]{-18,51,-16,120});
states[120] = new State(new int[]{30,-34,16,-11,36,-11,35,-11,25,-11,23,-11});
states[121] = new State(-22);
states[122] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,123,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[123] = new State(new int[]{21,4},new int[]{-20,124});
states[124] = new State(new int[]{38,125,69,-39,56,-39,37,-39,63,-39,64,-39,66,-39,67,-39,50,-39,49,-39,39,-39,48,-39,3,-39,22,-39});
states[125] = new State(new int[]{21,4,37,122},new int[]{-20,126,-25,127});
states[126] = new State(-40);
states[127] = new State(-41);
states[128] = new State(-23);
states[129] = new State(new int[]{7,130});
states[130] = new State(new int[]{69,52,56,58},new int[]{-24,131,-17,11,-18,60,-16,61,-15,138});
states[131] = new State(new int[]{30,132});
states[132] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,133,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[133] = new State(new int[]{30,134});
states[134] = new State(new int[]{69,52,56,58},new int[]{-24,135,-17,11,-18,60,-16,61,-15,138});
states[135] = new State(new int[]{8,136});
states[136] = new State(new int[]{21,4},new int[]{-20,137});
states[137] = new State(-42);
states[138] = new State(new int[]{25,50,23,99});
states[139] = new State(-24);
states[140] = new State(new int[]{7,141});
states[141] = new State(new int[]{69,142});
states[142] = new State(new int[]{65,143});
states[143] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,144,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[144] = new State(new int[]{8,145});
states[145] = new State(new int[]{21,4},new int[]{-20,146});
states[146] = new State(-43);
states[147] = new State(-25);
states[148] = new State(new int[]{7,149});
states[149] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,150,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[150] = new State(new int[]{8,151});
states[151] = new State(new int[]{21,4},new int[]{-20,152});
states[152] = new State(-44);
states[153] = new State(-26);
states[154] = new State(new int[]{21,4},new int[]{-20,155});
states[155] = new State(new int[]{66,156});
states[156] = new State(new int[]{7,157});
states[157] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,158,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[158] = new State(new int[]{8,159});
states[159] = new State(-45);
states[160] = new State(new int[]{48,162},new int[]{-28,161});
states[161] = new State(-27);
states[162] = new State(new int[]{69,163});
states[163] = new State(new int[]{7,164});
states[164] = new State(new int[]{55,78,56,79,58,80,59,81,57,82,48,83,61,84,8,-93,13,-93},new int[]{-38,165,-36,172,-37,170});
states[165] = new State(new int[]{8,166,13,168});
states[166] = new State(new int[]{21,4},new int[]{-20,167});
states[167] = new State(-13);
states[168] = new State(new int[]{55,78,56,79,58,80,59,81,57,82,48,83,61,84},new int[]{-36,169,-37,170});
states[169] = new State(-91);
states[170] = new State(new int[]{69,171});
states[171] = new State(-106);
states[172] = new State(-92);
states[173] = new State(new int[]{69,174,48,-19});
states[174] = new State(-30);
states[175] = new State(new int[]{30,176});
states[176] = new State(-28);
states[177] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86,30,-32},new int[]{-3,178,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[178] = new State(-31);
states[179] = new State(new int[]{30,180});
states[180] = new State(-29);
states[181] = new State(new int[]{7,14,17,44,11,46,56,58,69,52,68,62,23,64,60,71,62,86},new int[]{-3,182,-4,95,-5,17,-6,20,-7,23,-8,26,-9,29,-10,32,-11,35,-12,38,-13,41,-14,48,-15,49,-17,59,-18,60,-16,61,-34,63,-42,69,-19,70});
states[182] = new State(-49);
states[183] = new State(-15);
states[184] = new State(-16);
states[185] = new State(new int[]{69,52,56,58,37,122,63,129,64,140,66,148,67,154,50,173,49,177,39,181,3,-4,48,-20},new int[]{-22,7,-23,8,-24,9,-17,11,-18,60,-16,117,-15,118,-25,121,-29,128,-30,139,-31,147,-32,153,-2,160,-26,175,-27,179});
for (int sNo = 0; sNo < states.Length; sNo++) states[sNo].number = sNo;
rules[1] = new Rule(-43, new int[]{-1,3});
rules[2] = new Rule(-1, new int[]{});
rules[3] = new Rule(-1, new int[]{-20});
rules[4] = new Rule(-1, new int[]{-21});
rules[5] = new Rule(-15, new int[]{56});
rules[6] = new Rule(-15, new int[]{-17});
rules[7] = new Rule(-17, new int[]{-18});
rules[8] = new Rule(-17, new int[]{-15,25,-18});
rules[9] = new Rule(-17, new int[]{-15,23,-3,24});
rules[10] = new Rule(-18, new int[]{69});
rules[11] = new Rule(-18, new int[]{-16});
rules[12] = new Rule(-16, new int[]{69,7,-33,8});
rules[13] = new Rule(-28, new int[]{48,69,7,-38,8,-20});
rules[14] = new Rule(-20, new int[]{21,-21,22});
rules[15] = new Rule(-20, new int[]{21,22});
rules[16] = new Rule(-21, new int[]{-22});
rules[17] = new Rule(-21, new int[]{-21,-22});
rules[18] = new Rule(-22, new int[]{-23});
rules[19] = new Rule(-2, new int[]{50});
rules[20] = new Rule(-2, new int[]{});
rules[21] = new Rule(-23, new int[]{-24,30});
rules[22] = new Rule(-23, new int[]{-25});
rules[23] = new Rule(-23, new int[]{-29});
rules[24] = new Rule(-23, new int[]{-30});
rules[25] = new Rule(-23, new int[]{-31});
rules[26] = new Rule(-23, new int[]{-32});
rules[27] = new Rule(-23, new int[]{-2,-28});
rules[28] = new Rule(-23, new int[]{-26,30});
rules[29] = new Rule(-23, new int[]{-27,30});
rules[30] = new Rule(-26, new int[]{50,69});
rules[31] = new Rule(-26, new int[]{49,-3});
rules[32] = new Rule(-26, new int[]{49});
rules[33] = new Rule(-26, new int[]{-16});
rules[34] = new Rule(-26, new int[]{-15,25,-16});
rules[35] = new Rule(-24, new int[]{-17,-35,-3});
rules[36] = new Rule(-35, new int[]{16});
rules[37] = new Rule(-35, new int[]{36});
rules[38] = new Rule(-35, new int[]{35});
rules[39] = new Rule(-25, new int[]{37,-3,-20});
rules[40] = new Rule(-25, new int[]{37,-3,-20,38,-20});
rules[41] = new Rule(-25, new int[]{37,-3,-20,38,-25});
rules[42] = new Rule(-29, new int[]{63,7,-24,30,-3,30,-24,8,-20});
rules[43] = new Rule(-30, new int[]{64,7,69,65,-3,8,-20});
rules[44] = new Rule(-31, new int[]{66,7,-3,8,-20});
rules[45] = new Rule(-32, new int[]{67,-20,66,7,-3,8});
rules[46] = new Rule(-33, new int[]{-33,13,-4});
rules[47] = new Rule(-33, new int[]{-4});
rules[48] = new Rule(-33, new int[]{});
rules[49] = new Rule(-27, new int[]{39,-3});
rules[50] = new Rule(-3, new int[]{7,-4,8});
rules[51] = new Rule(-3, new int[]{-4});
rules[52] = new Rule(-4, new int[]{-5,31,-4});
rules[53] = new Rule(-4, new int[]{-5});
rules[54] = new Rule(-5, new int[]{-6,32,-5});
rules[55] = new Rule(-5, new int[]{-6});
rules[56] = new Rule(-6, new int[]{-7,33,-6});
rules[57] = new Rule(-6, new int[]{-7});
rules[58] = new Rule(-7, new int[]{-8,34,-7});
rules[59] = new Rule(-7, new int[]{-8});
rules[60] = new Rule(-8, new int[]{-9,4,-8});
rules[61] = new Rule(-8, new int[]{-9,18,-8});
rules[62] = new Rule(-8, new int[]{-9});
rules[63] = new Rule(-9, new int[]{-10,26,-9});
rules[64] = new Rule(-9, new int[]{-10,27,-9});
rules[65] = new Rule(-9, new int[]{-10,19,-9});
rules[66] = new Rule(-9, new int[]{-10,20,-9});
rules[67] = new Rule(-9, new int[]{-10});
rules[68] = new Rule(-10, new int[]{-11,28,-10});
rules[69] = new Rule(-10, new int[]{-11,29,-10});
rules[70] = new Rule(-10, new int[]{-11});
rules[71] = new Rule(-11, new int[]{-12,10,-11});
rules[72] = new Rule(-11, new int[]{-12,11,-11});
rules[73] = new Rule(-11, new int[]{-12});
rules[74] = new Rule(-12, new int[]{-13,6,-12});
rules[75] = new Rule(-12, new int[]{-13});
rules[76] = new Rule(-13, new int[]{17,-13});
rules[77] = new Rule(-13, new int[]{11,-13});
rules[78] = new Rule(-13, new int[]{-14});
rules[79] = new Rule(-14, new int[]{-15});
rules[80] = new Rule(-14, new int[]{68});
rules[81] = new Rule(-14, new int[]{-34});
rules[82] = new Rule(-14, new int[]{-42});
rules[83] = new Rule(-14, new int[]{-19});
rules[84] = new Rule(-14, new int[]{62});
rules[85] = new Rule(-19, new int[]{60,69,7,-39,8});
rules[86] = new Rule(-39, new int[]{-39,13,-37});
rules[87] = new Rule(-39, new int[]{-37});
rules[88] = new Rule(-39, new int[]{});
rules[89] = new Rule(-34, new int[]{23,-33,24});
rules[90] = new Rule(-34, new int[]{23,-33,13,24});
rules[91] = new Rule(-38, new int[]{-38,13,-36});
rules[92] = new Rule(-38, new int[]{-36});
rules[93] = new Rule(-38, new int[]{});
rules[94] = new Rule(-42, new int[]{23,-41,24});
rules[95] = new Rule(-42, new int[]{23,-41,13,24});
rules[96] = new Rule(-41, new int[]{-40});
rules[97] = new Rule(-41, new int[]{-41,13,-40});
rules[98] = new Rule(-40, new int[]{69,16,-3});
rules[99] = new Rule(-37, new int[]{55});
rules[100] = new Rule(-37, new int[]{56});
rules[101] = new Rule(-37, new int[]{58});
rules[102] = new Rule(-37, new int[]{59});
rules[103] = new Rule(-37, new int[]{57});
rules[104] = new Rule(-37, new int[]{48});
rules[105] = new Rule(-37, new int[]{61});
rules[106] = new Rule(-36, new int[]{-37,69});
}
protected override void Initialize() {
this.InitSpecialTokens((int)Tokens.error, (int)Tokens.EOF);
this.InitStates(states);
this.InitRules(rules);
this.InitNonTerminals(nonTerms);
}
protected override void DoAction(int action)
{
#pragma warning disable 162, 1522
switch (action)
{
case 2: // file -> /* empty */
#line 49 "tablemap.y"
{ output = new StatementList(); }
#line default
break;
case 3: // file -> stmtblock
#line 50 "tablemap.y"
{ output = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 4: // file -> stmtlist
#line 51 "tablemap.y"
{ output = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 5: // strlabelexpr -> STRING
#line 54 "tablemap.y"
{ CurrentSemanticValue.exprval = new StringExpression { val = ValueStack[ValueStack.Depth-1].strval }; }
#line default
break;
case 6: // strlabelexpr -> labelexpr
#line 55 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 7: // labelexpr -> labelexpr2
#line 58 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 8: // labelexpr -> strlabelexpr, DOT, labelexpr2
#line 59 "tablemap.y"
{ CurrentSemanticValue.exprval = new LabelMemberExpression { label = ValueStack[ValueStack.Depth-3].exprval, member = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 9: // labelexpr -> strlabelexpr, LBRACK, expr, RBRACK
#line 60 "tablemap.y"
{ CurrentSemanticValue.exprval = new LabelIndexedExpression { label = ValueStack[ValueStack.Depth-4].exprval, index = ValueStack[ValueStack.Depth-2].exprval }; }
#line default
break;
case 10: // labelexpr2 -> LABEL
#line 63 "tablemap.y"
{ CurrentSemanticValue.exprval = new LabelExpression { val = ValueStack[ValueStack.Depth-1].strval }; }
#line default
break;
case 11: // labelexpr2 -> funccall
#line 64 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 12: // funccall -> LABEL, LPAREN, exprlist, RPAREN
#line 67 "tablemap.y"
{ CurrentSemanticValue.exprval = new FuncCall { target = ValueStack[ValueStack.Depth-4].strval, args = ValueStack[ValueStack.Depth-2].exprlist }; }
#line default
break;
case 13: // funcdef -> FUNCTION, LABEL, LPAREN, arglist, RPAREN, stmtblock
#line 70 "tablemap.y"
{ CurrentSemanticValue.stmtval = new FunctionStatement { name = ValueStack[ValueStack.Depth-5].strval, args = ValueStack[ValueStack.Depth-3].arglistval, code = ValueStack[ValueStack.Depth-1].stmtval }; }
#line default
break;
case 14: // stmtblock -> LBRACE, stmtlist, RBRACE
#line 73 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 15: // stmtblock -> LBRACE, RBRACE
#line 74 "tablemap.y"
{ CurrentSemanticValue.stmtval = new StatementList(); ((StatementList)CurrentSemanticValue.stmtval).list = new List<Statement>(); }
#line default
break;
case 16: // stmtlist -> stmt
#line 77 "tablemap.y"
{ StatementList sl = new StatementList(); sl.list = new List<Statement>(); sl.list.Add(ValueStack[ValueStack.Depth-1].stmtval); CurrentSemanticValue.stmtval = sl; }
#line default
break;
case 17: // stmtlist -> stmtlist, stmt
#line 78 "tablemap.y"
{ ((StatementList)ValueStack[ValueStack.Depth-2].stmtval).list.Add(ValueStack[ValueStack.Depth-1].stmtval); CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 18: // stmt -> stmt2
#line 81 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 19: // export -> EXPORT
#line 84 "tablemap.y"
{ CurrentSemanticValue.bval = true; }
#line default
break;
case 20: // export -> /* empty */
#line 85 "tablemap.y"
{ CurrentSemanticValue.bval = false; }
#line default
break;
case 21: // stmt2 -> define, SEMICOLON
#line 89 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 22: // stmt2 -> ifblock
#line 90 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 23: // stmt2 -> forblock
#line 91 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 24: // stmt2 -> foreachblock
#line 92 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 25: // stmt2 -> whileblock
#line 93 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 26: // stmt2 -> doblock
#line 94 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; }
#line default
break;
case 27: // stmt2 -> export, funcdef
#line 95 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-1].stmtval; ValueStack[ValueStack.Depth-1].stmtval.export = ValueStack[ValueStack.Depth-2].bval; }
#line default
break;
case 28: // stmt2 -> cmd, SEMICOLON
#line 96 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 29: // stmt2 -> include, SEMICOLON
#line 97 "tablemap.y"
{ CurrentSemanticValue.stmtval = ValueStack[ValueStack.Depth-2].stmtval; }
#line default
break;
case 30: // cmd -> EXPORT, LABEL
#line 100 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ExportStatement { v = ValueStack[ValueStack.Depth-1].strval }; }
#line default
break;
case 31: // cmd -> RETURN, expr
#line 101 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ReturnStatement { v = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 32: // cmd -> RETURN
#line 102 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ReturnStatement { v = new ResultExpression { e = new Expression.EvalResult() } }; }
#line default
break;
case 33: // cmd -> funccall
#line 103 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ExpressionStatement { expr = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 34: // cmd -> strlabelexpr, DOT, funccall
#line 104 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ExpressionStatement { expr = new LabelMemberExpression { label = ValueStack[ValueStack.Depth-3].exprval, member = ValueStack[ValueStack.Depth-1].exprval } }; }
#line default
break;
case 35: // define -> labelexpr, assignop, expr
#line 107 "tablemap.y"
{ CurrentSemanticValue.stmtval = new DefineExprStatement { tok_name = ValueStack[ValueStack.Depth-3].exprval, assignop = ValueStack[ValueStack.Depth-2].tokval, val = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 36: // assignop -> ASSIGN
#line 110 "tablemap.y"
{ CurrentSemanticValue.tokval = Tokens.ASSIGN; }
#line default
break;
case 37: // assignop -> ASSIGNIF
#line 111 "tablemap.y"
{ CurrentSemanticValue.tokval = Tokens.ASSIGNIF; }
#line default
break;
case 38: // assignop -> APPEND
#line 112 "tablemap.y"
{ CurrentSemanticValue.tokval = Tokens.APPEND; }
#line default
break;
case 39: // ifblock -> IF, expr, stmtblock
#line 115 "tablemap.y"
{ CurrentSemanticValue.stmtval = new IfBlockStatement { test = ValueStack[ValueStack.Depth-2].exprval, if_block = ValueStack[ValueStack.Depth-1].stmtval, else_block = null }; }
#line default
break;
case 40: // ifblock -> IF, expr, stmtblock, ELSE, stmtblock
#line 116 "tablemap.y"
{ CurrentSemanticValue.stmtval = new IfBlockStatement { test = ValueStack[ValueStack.Depth-4].exprval, if_block = ValueStack[ValueStack.Depth-3].stmtval, else_block = ValueStack[ValueStack.Depth-1].stmtval }; }
#line default
break;
case 41: // ifblock -> IF, expr, stmtblock, ELSE, ifblock
#line 117 "tablemap.y"
{ CurrentSemanticValue.stmtval = new IfBlockStatement { test = ValueStack[ValueStack.Depth-4].exprval, if_block = ValueStack[ValueStack.Depth-3].stmtval, else_block = ValueStack[ValueStack.Depth-1].stmtval }; }
#line default
break;
case 42: // forblock -> FOR, LPAREN, define, SEMICOLON, expr, SEMICOLON, define, RPAREN,
// stmtblock
#line 120 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ForBlockStatement { init = ValueStack[ValueStack.Depth-7].stmtval, test = ValueStack[ValueStack.Depth-5].exprval, incr = ValueStack[ValueStack.Depth-3].stmtval, code = ValueStack[ValueStack.Depth-1].stmtval }; }
#line default
break;
case 43: // foreachblock -> FOREACH, LPAREN, LABEL, IN, expr, RPAREN, stmtblock
#line 123 "tablemap.y"
{ CurrentSemanticValue.stmtval = new ForEachBlock { val = ValueStack[ValueStack.Depth-5].strval, enumeration = ValueStack[ValueStack.Depth-3].exprval, code = ValueStack[ValueStack.Depth-1].stmtval }; }
#line default
break;
case 44: // whileblock -> WHILE, LPAREN, expr, RPAREN, stmtblock
#line 126 "tablemap.y"
{ CurrentSemanticValue.stmtval = new WhileBlock { test = ValueStack[ValueStack.Depth-3].exprval, code = ValueStack[ValueStack.Depth-1].stmtval }; }
#line default
break;
case 45: // doblock -> DO, stmtblock, WHILE, LPAREN, expr, RPAREN
#line 129 "tablemap.y"
{ CurrentSemanticValue.stmtval = new DoBlock { test = ValueStack[ValueStack.Depth-2].exprval, code = ValueStack[ValueStack.Depth-5].stmtval }; }
#line default
break;
case 46: // exprlist -> exprlist, COMMA, expr2
#line 132 "tablemap.y"
{ CurrentSemanticValue.exprlist = new List<Expression>(ValueStack[ValueStack.Depth-3].exprlist); CurrentSemanticValue.exprlist.Add(ValueStack[ValueStack.Depth-1].exprval); }
#line default
break;
case 47: // exprlist -> expr2
#line 133 "tablemap.y"
{ CurrentSemanticValue.exprlist = new List<Expression> { ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 48: // exprlist -> /* empty */
#line 134 "tablemap.y"
{ CurrentSemanticValue.exprlist = new List<Expression>(); }
#line default
break;
case 49: // include -> INCLUDE, expr
#line 137 "tablemap.y"
{ CurrentSemanticValue.stmtval = new IncludeStatement { include_file = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 50: // expr -> LPAREN, expr2, RPAREN
#line 140 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-2].exprval; }
#line default
break;
case 51: // expr -> expr2
#line 141 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 52: // expr2 -> expr3, LOR, expr2
#line 144 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LOR }; }
#line default
break;
case 53: // expr2 -> expr3
#line 145 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 54: // expr3 -> expr4, LAND, expr3
#line 148 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LAND }; }
#line default
break;
case 55: // expr3 -> expr4
#line 149 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 56: // expr4 -> expr5, OR, expr4
#line 152 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.OR }; }
#line default
break;
case 57: // expr4 -> expr5
#line 153 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 58: // expr5 -> expr6, AND, expr5
#line 156 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.AND }; }
#line default
break;
case 59: // expr5 -> expr6
#line 157 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 60: // expr6 -> expr7, EQUALS, expr6
#line 160 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.EQUALS }; }
#line default
break;
case 61: // expr6 -> expr7, NOTEQUAL, expr6
#line 161 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.NOTEQUAL }; }
#line default
break;
case 62: // expr6 -> expr7
#line 162 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 63: // expr7 -> expr7a, LT, expr7
#line 165 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LT }; }
#line default
break;
case 64: // expr7 -> expr7a, GT, expr7
#line 166 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.GT }; }
#line default
break;
case 65: // expr7 -> expr7a, LEQUAL, expr7
#line 167 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LEQUAL }; }
#line default
break;
case 66: // expr7 -> expr7a, GEQUAL, expr7
#line 168 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.GEQUAL }; }
#line default
break;
case 67: // expr7 -> expr7a
#line 169 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 68: // expr7a -> expr8, LSHIFT, expr7a
#line 172 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.LSHIFT }; }
#line default
break;
case 69: // expr7a -> expr8, RSHIFT, expr7a
#line 173 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.RSHIFT }; }
#line default
break;
case 70: // expr7a -> expr8
#line 174 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 71: // expr8 -> expr9, PLUS, expr8
#line 177 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.PLUS }; }
#line default
break;
case 72: // expr8 -> expr9, MINUS, expr8
#line 178 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.MINUS }; }
#line default
break;
case 73: // expr8 -> expr9
#line 179 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 74: // expr9 -> expr10, MUL, expr9
#line 182 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-3].exprval, b = ValueStack[ValueStack.Depth-1].exprval, op = Tokens.MUL }; }
#line default
break;
case 75: // expr9 -> expr10
#line 183 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 76: // expr10 -> NOT, expr10
#line 186 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-1].exprval, b = null, op = Tokens.NOT }; }
#line default
break;
case 77: // expr10 -> MINUS, expr10
#line 187 "tablemap.y"
{ CurrentSemanticValue.exprval = new Expression { a = ValueStack[ValueStack.Depth-1].exprval, b = null, op = Tokens.MINUS }; }
#line default
break;
case 78: // expr10 -> expr11
#line 188 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 79: // expr11 -> strlabelexpr
#line 191 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 80: // expr11 -> INT
#line 192 "tablemap.y"
{ CurrentSemanticValue.exprval = new IntExpression { val = ValueStack[ValueStack.Depth-1].intval }; }
#line default
break;
case 81: // expr11 -> arrayexpr
#line 193 "tablemap.y"
{ CurrentSemanticValue.exprval = new ArrayExpression { val = ValueStack[ValueStack.Depth-1].exprlist }; }
#line default
break;
case 82: // expr11 -> objexpr
#line 194 "tablemap.y"
{ CurrentSemanticValue.exprval = new ObjExpression { val = ValueStack[ValueStack.Depth-1].objdeflist }; }
#line default
break;
case 83: // expr11 -> funcrefexpr
#line 195 "tablemap.y"
{ CurrentSemanticValue.exprval = ValueStack[ValueStack.Depth-1].exprval; }
#line default
break;
case 84: // expr11 -> NULL
#line 196 "tablemap.y"
{ CurrentSemanticValue.exprval = new NullExpression(); }
#line default
break;
case 85: // funcrefexpr -> FUNCREF, LABEL, LPAREN, typelist, RPAREN
#line 199 "tablemap.y"
{ CurrentSemanticValue.exprval = new FunctionRefExpression { name = ValueStack[ValueStack.Depth-4].strval, args = ValueStack[ValueStack.Depth-2].typelistval }; }
#line default
break;
case 86: // typelist -> typelist, COMMA, argtype
#line 202 "tablemap.y"
{ CurrentSemanticValue.typelistval = new List<Expression.EvalResult.ResultType>(ValueStack[ValueStack.Depth-3].typelistval); CurrentSemanticValue.typelistval.Add(ValueStack[ValueStack.Depth-1].typeval); }
#line default
break;
case 87: // typelist -> argtype
#line 203 "tablemap.y"
{ CurrentSemanticValue.typelistval = new List<Expression.EvalResult.ResultType>(); CurrentSemanticValue.typelistval.Add(ValueStack[ValueStack.Depth-1].typeval); }
#line default
break;
case 88: // typelist -> /* empty */
#line 204 "tablemap.y"
{ CurrentSemanticValue.typelistval = new List<Expression.EvalResult.ResultType>(); }
#line default
break;
case 89: // arrayexpr -> LBRACK, exprlist, RBRACK
#line 207 "tablemap.y"
{ CurrentSemanticValue.exprlist = ValueStack[ValueStack.Depth-2].exprlist; }
#line default
break;
case 90: // arrayexpr -> LBRACK, exprlist, COMMA, RBRACK
#line 208 "tablemap.y"
{ CurrentSemanticValue.exprlist = ValueStack[ValueStack.Depth-3].exprlist; }
#line default
break;
case 91: // arglist -> arglist, COMMA, arg
#line 211 "tablemap.y"
{ CurrentSemanticValue.arglistval = new List<FunctionStatement.FunctionArg>(ValueStack[ValueStack.Depth-3].arglistval); CurrentSemanticValue.arglistval.Add(ValueStack[ValueStack.Depth-1].argval); }
#line default
break;
case 92: // arglist -> arg
#line 212 "tablemap.y"
{ CurrentSemanticValue.arglistval = new List<FunctionStatement.FunctionArg>(); CurrentSemanticValue.arglistval.Add(ValueStack[ValueStack.Depth-1].argval); }
#line default
break;
case 93: // arglist -> /* empty */
#line 213 "tablemap.y"
{ CurrentSemanticValue.arglistval = new List<FunctionStatement.FunctionArg>(); }
#line default
break;
case 94: // objexpr -> LBRACK, objlist, RBRACK
#line 216 "tablemap.y"
{ CurrentSemanticValue.objdeflist = ValueStack[ValueStack.Depth-2].objdeflist; }
#line default
break;
case 95: // objexpr -> LBRACK, objlist, COMMA, RBRACK
#line 217 "tablemap.y"
{ CurrentSemanticValue.objdeflist = ValueStack[ValueStack.Depth-3].objdeflist; }
#line default
break;
case 96: // objlist -> objmember
#line 220 "tablemap.y"
{ CurrentSemanticValue.objdeflist = new List<ObjDef> { ValueStack[ValueStack.Depth-1].objdefval }; }
#line default
break;
case 97: // objlist -> objlist, COMMA, objmember
#line 221 "tablemap.y"
{ ValueStack[ValueStack.Depth-3].objdeflist.Add(ValueStack[ValueStack.Depth-1].objdefval); CurrentSemanticValue.objdeflist = ValueStack[ValueStack.Depth-3].objdeflist; }
#line default
break;
case 98: // objmember -> LABEL, ASSIGN, expr
#line 224 "tablemap.y"
{ CurrentSemanticValue.objdefval = new ObjDef { name = ValueStack[ValueStack.Depth-3].strval, val = ValueStack[ValueStack.Depth-1].exprval }; }
#line default
break;
case 99: // argtype -> INTEGER
#line 228 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.Int; }
#line default
break;
case 100: // argtype -> STRING
#line 229 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.String; }
#line default
break;
case 101: // argtype -> ARRAY
#line 230 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.Array; }
#line default
break;
case 102: // argtype -> OBJECT
#line 231 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.Object; }
#line default
break;
case 103: // argtype -> VOID
#line 232 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.Void; }
#line default
break;
case 104: // argtype -> FUNCTION
#line 233 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.Function; }
#line default
break;
case 105: // argtype -> ANY
#line 234 "tablemap.y"
{ CurrentSemanticValue.typeval = Expression.EvalResult.ResultType.Any; }
#line default
break;
case 106: // arg -> argtype, LABEL
#line 237 "tablemap.y"
{ CurrentSemanticValue.argval = new FunctionStatement.FunctionArg { name = ValueStack[ValueStack.Depth-1].strval, argtype = ValueStack[ValueStack.Depth-2].typeval }; }
#line default
break;
}
#pragma warning restore 162, 1522
}
protected override string TerminalToString(int terminal)
{
if (aliases != null && aliases.ContainsKey(terminal))
return aliases[terminal];
else if (((Tokens)terminal).ToString() != terminal.ToString(CultureInfo.InvariantCulture))
return ((Tokens)terminal).ToString();
else
return CharToString((char)terminal);
}
#line 241 "tablemap.y"
internal Statement output;
#line default
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.cil
{
public class CilNode
{
public CilNode(metadata.MethodSpec ms, int cil_offset)
{
m = ms.m;
il_offset = cil_offset;
_ms = ms;
}
public class IRNode
{
public CilNode parent;
public List<target.MCInst> mc;
public bool ignore_for_mcoffset = false;
public int opcode;
public int ct = ir.Opcode.ct_unknown;
public int ct2 = ir.Opcode.ct_unknown;
int _ctret = ir.Opcode.ct_unknown;
bool has_ctret = false;
public int ctret { get { if (has_ctret) return _ctret; else return ct; } set { _ctret = value; has_ctret = true; } }
public int vt_size;
public util.Stack<ir.StackItem> stack_before;
public util.Stack<ir.StackItem> stack_after;
public int arg_a = 0;
public int arg_b = 1;
public int arg_c = 2;
public int arg_d = 3;
public List<int> arg_list = null;
public int res_a = 0;
public long imm_l;
public ulong imm_ul;
public byte[] imm_val;
public string imm_lab;
public metadata.MethodSpec imm_ms;
public metadata.TypeSpec imm_ts;
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(ir.Opcode.oc_names[opcode]);
if(ct != ir.Opcode.ct_unknown)
{
sb.Append(".");
sb.Append(ir.Opcode.ct_names[ct]);
}
if (ct2 != ir.Opcode.ct_unknown)
{
sb.Append(".");
sb.Append(ir.Opcode.ct_names[ct2]);
}
if(vt_size != 0)
{
sb.Append(".");
sb.Append(vt_size.ToString());
}
return sb.ToString();
}
}
public List<IRNode> irnodes = new List<IRNode>();
metadata.MetadataStream m;
metadata.MethodSpec _ms;
public int il_offset;
public int mc_offset = -1;
public bool is_block_start = false;
public bool is_meth_start = false;
public bool is_eh_start = false;
public bool is_filter_start = false;
public bool is_in_excpt_handler = false;
public bool visited = false;
public util.Stack<ir.StackItem> stack_after;
public List<metadata.ExceptionHeader> try_starts = new List<metadata.ExceptionHeader>();
public List<metadata.ExceptionHeader> handler_starts = new List<metadata.ExceptionHeader>();
public Opcode opcode;
public int inline_int;
public uint inline_uint;
public long inline_long;
public byte[] inline_val;
public double inline_double;
public float inline_float;
public List<int> inline_array;
public List<int> il_offsets_after = new List<int>();
public int il_offset_after;
public List<CilNode> prev = new List<CilNode>();
// prefixes
public bool constrained;
public uint constrained_tok;
public bool no_typecheck;
public bool no_rangecheck;
public bool no_nullcheck;
public bool read_only;
public bool tail;
public bool unaligned;
public int unaligned_alignment;
public bool volatile_;
public override string ToString()
{
return opcode == null ? "" : opcode.ToString();
}
public bool HasConstant
{ get { return opcode.sop == Opcode.SimpleOpcode.ldc; } }
public bool HasLocalVarLoc
{
get
{
if (opcode.sop != Opcode.SimpleOpcode.ldloc &&
opcode.sop != Opcode.SimpleOpcode.stloc)
return false;
return true;
}
}
public bool HasLocalArgLoc
{
get
{
if (opcode.sop != Opcode.SimpleOpcode.ldarg &&
opcode.sop != Opcode.SimpleOpcode.starg)
return false;
return true;
}
}
public int GetConstantType()
{
if (opcode.sop != Opcode.SimpleOpcode.ldc)
throw new Exception("Not a constant node");
switch (opcode.opcode1)
{
case Opcode.SingleOpcodes.ldc_i4_0:
case Opcode.SingleOpcodes.ldc_i4_1:
case Opcode.SingleOpcodes.ldc_i4_2:
case Opcode.SingleOpcodes.ldc_i4_3:
case Opcode.SingleOpcodes.ldc_i4_4:
case Opcode.SingleOpcodes.ldc_i4_5:
case Opcode.SingleOpcodes.ldc_i4_6:
case Opcode.SingleOpcodes.ldc_i4_7:
case Opcode.SingleOpcodes.ldc_i4_8:
case Opcode.SingleOpcodes.ldc_i4_m1:
case Opcode.SingleOpcodes.ldc_i4:
case Opcode.SingleOpcodes.ldc_i4_s:
return ir.Opcode.ct_int32;
case Opcode.SingleOpcodes.ldc_i8:
return ir.Opcode.ct_int64;
case Opcode.SingleOpcodes.ldc_r4:
case Opcode.SingleOpcodes.ldc_r8:
return ir.Opcode.ct_float;
case Opcode.SingleOpcodes.ldnull:
return ir.Opcode.ct_object;
}
throw new NotSupportedException();
}
public long GetConstant()
{
if (opcode.sop != Opcode.SimpleOpcode.ldc)
throw new Exception("Not a constant node");
switch(opcode.opcode1)
{
case Opcode.SingleOpcodes.ldc_i4_0:
case Opcode.SingleOpcodes.ldnull:
return 0;
case Opcode.SingleOpcodes.ldc_i4_1:
return 1;
case Opcode.SingleOpcodes.ldc_i4_2:
return 2;
case Opcode.SingleOpcodes.ldc_i4_3:
return 3;
case Opcode.SingleOpcodes.ldc_i4_4:
return 4;
case Opcode.SingleOpcodes.ldc_i4_5:
return 5;
case Opcode.SingleOpcodes.ldc_i4_6:
return 6;
case Opcode.SingleOpcodes.ldc_i4_7:
return 7;
case Opcode.SingleOpcodes.ldc_i4_8:
return 8;
case Opcode.SingleOpcodes.ldc_i4_m1:
return -1;
case Opcode.SingleOpcodes.ldc_i4:
case Opcode.SingleOpcodes.ldc_i4_s:
case Opcode.SingleOpcodes.ldc_i8:
return inline_long;
case Opcode.SingleOpcodes.ldc_r4:
case Opcode.SingleOpcodes.ldc_r8:
throw new NotImplementedException();
}
throw new NotSupportedException();
}
public int GetCondCode()
{
int ret;
if (opcode.opcode1 == Opcode.SingleOpcodes.double_)
{
if (ir.Opcode.cc_double_map.TryGetValue(opcode.opcode2, out ret))
return ret;
else
return ir.Opcode.cc_always;
}
else if (ir.Opcode.cc_single_map.TryGetValue(opcode.opcode1, out ret))
return ret;
else
return ir.Opcode.cc_always;
}
public int GetLocalArgLoc()
{
if (opcode.sop != Opcode.SimpleOpcode.ldarg &&
opcode.sop != Opcode.SimpleOpcode.starg)
throw new Exception("Not a local arg node");
switch (opcode.opcode1)
{
case Opcode.SingleOpcodes.ldarg_s:
case Opcode.SingleOpcodes.ldarga_s:
case Opcode.SingleOpcodes.starg_s:
return inline_int;
case Opcode.SingleOpcodes.ldarg_0:
return 0;
case Opcode.SingleOpcodes.ldarg_1:
return 1;
case Opcode.SingleOpcodes.ldarg_2:
return 2;
case Opcode.SingleOpcodes.ldarg_3:
return 3;
default:
throw new NotSupportedException();
}
}
public int GetLocalVarLoc()
{
switch(opcode.opcode1)
{
case Opcode.SingleOpcodes.ldloc_0:
case Opcode.SingleOpcodes.stloc_0:
return 0;
case Opcode.SingleOpcodes.ldloc_1:
case Opcode.SingleOpcodes.stloc_1:
return 1;
case Opcode.SingleOpcodes.ldloc_2:
case Opcode.SingleOpcodes.stloc_2:
return 2;
case Opcode.SingleOpcodes.ldloc_3:
case Opcode.SingleOpcodes.stloc_3:
return 3;
case Opcode.SingleOpcodes.ldloc_s:
case Opcode.SingleOpcodes.stloc_s:
case Opcode.SingleOpcodes.ldloca_s:
return inline_int;
case Opcode.SingleOpcodes.double_:
switch(opcode.opcode2)
{
case Opcode.DoubleOpcodes.ldloc:
case Opcode.DoubleOpcodes.ldloca:
case Opcode.DoubleOpcodes.stloc:
return inline_int;
}
break;
}
throw new Exception("Not a local var node");
}
public void GetToken(out metadata.MetadataStream metadata,
out uint token)
{
metadata = m;
token = inline_uint;
}
public metadata.TypeSpec GetTokenAsTypeSpec(Code c)
{
int table_id, row;
m.InterpretToken(inline_uint, out table_id, out row);
return m.GetTypeSpec(table_id, row, c.ms.gtparams, c.ms.gmparams);
}
public metadata.MethodSpec GetTokenAsMethodSpec(Code c)
{
return m.GetMethodSpec(inline_uint, c.ms.gtparams, c.ms.gmparams);
}
}
}
<file_sep>/* ===-- fixunsdfsi.c - Implement __fixunsdfsi -----------------------------===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
* ===----------------------------------------------------------------------===
*/
#define DOUBLE_PRECISION
#include "fp_lib.h"
typedef su_int fixuint_t;
#include "fp_fixuint_impl.inc"
ARM_EABI_FNALIAS(d2uiz, fixunsdfsi)
COMPILER_RT_ABI su_int
__fixunsdfsi(fp_t a) {
return __fixuint(a);
}
<file_sep>/* Copyright (C) 2012 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs.x86_64
{
[ArchDependent("x86_64")]
public class Cpu
{
[Bits64Only]
public unsafe static void Lidt(ulong addr, ushort limit)
{
/* Build a idt_pointer:
*
* least significant 16 bits = limit
* next 64 bits = address
*/
ulong *idt_ptr = stackalloc ulong[2];
idt_ptr[1] = (addr >> 48) & 0xffffUL;
idt_ptr[0] = (addr << 16) | ((ulong)limit & 0xffffUL);
Lidt(idt_ptr);
}
[Bits32Only]
public unsafe static void Lidt(uint addr, ushort limit)
{
/* Build a idt_pointer:
*
* least significant 16 bits = limit
* next 32 bits = address
*/
uint *idt_ptr = stackalloc uint[2];
idt_ptr[1] = (addr >> 16) & 0xffffU;
idt_ptr[0] = (addr << 16) | ((uint)limit & 0xffffU);
Lidt(idt_ptr);
}
[Bits64Only]
public unsafe static void Sgdt(out void *addr, out ushort limit)
{
byte* ptr = stackalloc byte[10];
Sgdt(ptr);
addr = *(void**)(ptr + 2);
limit = *(ushort*)ptr;
}
[InterruptRegisterStructure]
public struct InterruptRegisters64
{
public ulong xmm15;
public ulong xmm14;
public ulong xmm13;
public ulong xmm12;
public ulong xmm11;
public ulong xmm10;
public ulong xmm9;
public ulong xmm8;
public ulong r15;
public ulong r14;
public ulong r13;
public ulong r12;
public ulong r11;
public ulong r10;
public ulong r9;
public ulong r8;
public ulong xmm7;
public ulong xmm6;
public ulong xmm5;
public ulong xmm4;
public ulong xmm3;
public ulong xmm2;
public ulong xmm1;
public ulong xmm0;
public ulong rsi;
public ulong rdi;
public ulong rdx;
public ulong rcx;
public ulong rbx;
public ulong rax;
}
[InterruptRegisterStructure]
public struct InterruptRegisters32
{
public uint xmm7;
public uint xmm6;
public uint xmm5;
public uint xmm4;
public uint xmm3;
public uint xmm2;
public uint xmm1;
public uint xmm0;
public uint rsi;
public uint rdi;
public uint rdx;
public uint rcx;
public uint rbx;
public uint rax;
}
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern void Sgdt(void* ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void Lidt(void* ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Ltr(ulong selector);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Invlpg(ulong vaddr);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Break();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Int(byte int_no);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern ulong RdMsr(uint reg_no);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void WrMsr(uint reg_no, ulong val);
[MethodImpl(MethodImplOptions.InternalCall)]
private static unsafe extern void _Cpuid(uint req_no, uint* buf);
public static uint[] Cpuid(uint req_no)
{
uint[] buf = new uint[4];
unsafe
{
_Cpuid(req_no, (uint*)MemoryOperations.GetInternalArray(buf));
}
return buf;
}
public extern static ulong RBP
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern static ulong RSP
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern static uint Mxcsr
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern static ulong Tsc
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
public extern static ulong Cr0
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern static ulong Cr2
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern static ulong Cr3
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
public extern static ulong Cr4
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
[MethodImpl(MethodImplOptions.InternalCall)]
set;
}
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void Sti();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void Cli();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe static void* ReadFSData(int offset);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe static void* ReadGSData(int offset);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe static void WriteFSData(int offset, void* data);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe static void WriteGSData(int offset, void* data);
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libsupcs
{
public abstract class Unwinder
{
public abstract UIntPtr GetInstructionPointer();
public abstract UIntPtr GetFramePointer();
public abstract Unwinder UnwindOne();
public abstract Unwinder UnwindOne(libsupcs.TysosMethod cur_method);
public abstract libsupcs.TysosMethod GetMethodInfo();
public abstract Unwinder Init();
public abstract bool CanContinue();
public virtual object[] DoUnwind(UIntPtr exit_address, bool get_symbols = true) { return DoUnwind(this, exit_address, get_symbols); }
public class UnwinderEntry
{
public UIntPtr ProgramCounter;
public string Symbol;
public UIntPtr Offset;
}
internal static unsafe object[] DoUnwind(Unwinder u, UIntPtr exit_address, bool get_symbols = true)
{
System.Collections.ArrayList ret = new System.Collections.ArrayList();
UIntPtr pc;
while (u.CanContinue() && ((pc = u.GetInstructionPointer()) != exit_address))
{
void* offset;
string sym;
if (get_symbols)
{
sym = JitOperations.GetNameOfAddress((void*)pc, out offset);
}
else
{
offset = (void*)pc;
sym = "offset_0";
}
ret.Add(new UnwinderEntry { ProgramCounter = pc, Symbol = sym, Offset = (UIntPtr)offset });
u.UnwindOne();
}
return ret.ToArray();
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_ZW20System#2EDiagnostics10StackTrace_22GetStackFramesInternal_Rv_P4V16StackFrameHelperibU6System9Exception")]
internal static unsafe void StackTrace_GetStackFramesInternal(void *sfh, int iSkip, bool fNeedFileInfo, Exception e)
{
/* We set the 'reentrant' member of the stack frame helper here to prevent InitializeSourceInfo running further and set
* iFrameCount to zero to prevent stack traces occuring via CoreCLR */
*(int*)((byte*)OtherOperations.GetStaticObjectAddress("_ZW20System#2EDiagnostics16StackFrameHelperS")
+ ClassOperations.GetStaticFieldOffset("_ZW20System#2EDiagnostics16StackFrameHelper", "t_reentrancy")) = 1;
*(int*)((byte*)sfh + ClassOperations.GetFieldOffset("_ZW20System#2EDiagnostics16StackFrameHelper", "iFrameCount")) = 0;
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_ZW20System#2EDiagnostics6Assert_23ShowDefaultAssertDialog_Ri_P4u1Su1Su1Su1S")]
internal static int Assert_ShowDefaultAssertDialog(string conditionString, string message, string stackTrace, string windowTitle)
{
OtherOperations.EnterUninterruptibleSection();
System.Diagnostics.Debugger.Log(0, "Assert", windowTitle);
System.Diagnostics.Debugger.Log(0, "Assert", conditionString);
System.Diagnostics.Debugger.Log(0, "Assert", message);
System.Diagnostics.Debugger.Log(0, "Assert", stackTrace);
while (true) ;
}
}
}
<file_sep>/* Copyright (C) 2018 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Runtime.CompilerServices;
namespace libsupcs
{
public class Monitor
{
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void ReliableEnter(object o, ref bool success);
public static void Enter(object o)
{
bool s = false;
ReliableEnter(o, ref s);
}
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Exit(object o);
[libsupcs.AlwaysCompile]
[libsupcs.WeakLinkage]
[libsupcs.MethodAlias("_ZW18System#2EThreading7Monitor_13ReliableEnter_Rv_P2u1ORb")]
[MethodAlias("_ZN14libsupcs#2Edll8libsupcs7Monitor_13ReliableEnter_Rv_P2u1ORb")]
static unsafe void ReliableEnter(byte *obj, ref bool success)
{
var tid = System.Threading.Thread.CurrentThread.ManagedThreadId;
var mla = obj + ClassOperations.GetMutexLockOffset();
while (try_acquire(mla, tid) != 1) ;
success = true;
}
[libsupcs.AlwaysCompile]
[libsupcs.MethodAlias("_ZW18System#2EThreading7Monitor_4Exit_Rv_P1u1O")]
[MethodAlias("_ZN14libsupcs#2Edll8libsupcs7Monitor_4Exit_Rv_P1u1O")]
static unsafe void Monitor_exit(byte *obj)
{
var tid = System.Threading.Thread.CurrentThread.ManagedThreadId;
var mla = obj + ClassOperations.GetMutexLockOffset();
release(mla, tid);
}
[libsupcs.AlwaysCompile]
[libsupcs.MethodAlias("__try_acquire")]
static unsafe int try_acquire(byte* mutex_lock_address, int cur_thread_id)
{
// Low byte of mutex is used as a spinlock
// 2nd and 3rd bytes (as a ushort) are nesting level
// 4th-7th bytes (as int) are thread id
int ret = 0;
libsupcs.OtherOperations.Spinlock(mutex_lock_address);
unsafe
{
int* thread_id = (int*)(mutex_lock_address + 4);
ushort* nest = (ushort*)(mutex_lock_address + 2);
if ((*thread_id == 0) || (*thread_id == cur_thread_id))
{
*thread_id = cur_thread_id;
ushort cur_nest = *nest;
cur_nest++;
*nest = cur_nest;
ret = 1;
}
}
libsupcs.OtherOperations.Spinunlock(mutex_lock_address);
return ret;
}
[libsupcs.AlwaysCompile]
[libsupcs.MethodAlias("__release")]
unsafe static void release(byte* mutex_lock_address, int cur_thread_id)
{
libsupcs.OtherOperations.Spinlock(mutex_lock_address);
unsafe
{
int* thread_id = (int*)(mutex_lock_address + 4);
ushort* nest = (ushort*)(mutex_lock_address + 2);
if (*thread_id == cur_thread_id)
{
ushort cur_nest = *nest;
cur_nest--;
*nest = cur_nest;
if (cur_nest == 0)
*thread_id = 0;
}
else
{
System.Diagnostics.Debugger.Break();
libsupcs.OtherOperations.Spinunlock(mutex_lock_address);
throw new System.Threading.SynchronizationLockException("Attempt to release lock not owned by thread");
}
}
libsupcs.OtherOperations.Spinunlock(mutex_lock_address);
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using binary_library;
using metadata;
namespace libtysila5.layout
{
public partial class Layout
{
public static int GetTypeAlignment(metadata.TypeSpec ts,
target.Target t, bool is_static)
{
if(ts.m.classlayouts[ts.tdrow] != 0 && ts.IsGeneric == false && ts.IsGenericTemplate == false)
{
// see if there is a packing specified
var pack = ts.m.GetIntEntry(metadata.MetadataStream.tid_ClassLayout,
ts.m.classlayouts[ts.tdrow],
0);
if (pack != 0)
return (int)pack;
}
if (ts.stype != TypeSpec.SpecialType.None)
return t.psize;
// types always align on their most strictly aligned type
int cur_align = 1;
if (ts.SimpleType != 0)
{
// simple types larger than a pointer (e.g. object/string)
// still aling to pointer size;
var ret = GetTypeSize(ts, t, is_static);
if (ret < t.psize)
return ret;
return t.psize;
}
// reference types will always have a pointer and int64 in them
if (is_static == false && !ts.IsValueType)
{
cur_align = t.psize;
cur_align = util.util.align(cur_align, t.GetCTSize(ir.Opcode.ct_int64));
}
// and static will always have an 'is_initialized'
else if (is_static)
cur_align = t.psize;
/* Iterate through methods looking for requested
one */
var first_fdef = ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
ts.tdrow, 4);
var last_fdef = ts.m.GetLastFieldDef(ts.tdrow);
for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
// Ensure field is static if requested
var flags = ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 0);
if (((flags & 0x10) == 0x10 && is_static == true) ||
((flags & 0x10) == 0 && is_static == false))
{
// Get alignment of underlying type
var fsig = (int)ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 2);
var ft = ts.m.GetFieldType(ref fsig, ts.gtparams, null);
int ft_align;
if (ft.IsValueType)
ft_align = GetTypeAlignment(ft, t, false);
else
ft_align = t.psize;
if (ft_align > cur_align)
cur_align = ft_align;
}
}
return cur_align;
}
public static int GetFieldOffset(metadata.TypeSpec ts,
metadata.MethodSpec fs, target.Target t, out bool is_tls, bool is_static = false)
{
int align = 1;
is_tls = false;
if(ts.SimpleType == 0 || ts.SimpleType == 0xe) // class or string
align = GetTypeAlignment(ts, t, is_static);
/* Iterate through methods looking for requested
one */
var first_fdef = ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
ts.tdrow, 4);
var last_fdef = ts.m.GetLastFieldDef(ts.tdrow);
uint search_field_name = 0;
if (fs != null)
{
search_field_name = fs.m.GetIntEntry(MetadataStream.tid_Field,
fs.mdrow, 1);
}
int cur_offset = 0;
int cur_tl_offset = 0;
if (is_static == false && !ts.IsValueType)
{
if (ts.GetExtends() == null)
{
// Add a vtable entry
cur_offset += t.GetCTSize(ir.Opcode.ct_object);
cur_offset = util.util.align(cur_offset, align);
// Add a mutex lock entry
cur_offset += t.GetCTSize(ir.Opcode.ct_int64);
cur_offset = util.util.align(cur_offset, align);
}
else
{
cur_offset = GetFieldOffset(ts.GetExtends(), (string)null, t, out is_tls);
cur_offset = util.util.align(cur_offset, align);
}
}
else if(is_static)
{
// Add an is_initalized field
cur_offset += t.GetCTSize(ir.Opcode.ct_intptr);
cur_offset = util.util.align(cur_offset, align);
}
for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
// Ensure field is static if requested
var flags = ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 0);
if (((flags & 0x10) == 0x10 && is_static == true) ||
((flags & 0x10) == 0 && is_static == false))
{
// Check on name if we are looking for a particular field
bool f_is_tls = ts.m.thread_local_fields[fdef_row];
if (search_field_name != 0)
{
var fname = ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 1);
if (MetadataStream.CompareString(ts.m, fname,
fs.m, search_field_name))
{
if (f_is_tls)
{
is_tls = true;
return cur_tl_offset;
}
else
{
is_tls = false;
return cur_offset;
}
}
}
// Increment by type size
var fsig = (int)ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 2);
var ft = ts.m.GetFieldType(ref fsig, ts.gtparams, null);
var ft_size = t.GetSize(ft);
if (f_is_tls)
{
cur_tl_offset += ft_size;
cur_tl_offset = util.util.align(cur_tl_offset, align);
}
else
{
cur_offset += ft_size;
cur_offset = util.util.align(cur_offset, align);
}
}
}
// Shouldn't get here if looking for a specific field
if(search_field_name != 0)
throw new MissingFieldException();
// Else return size of complete type
return cur_offset;
}
public static int GetFieldOffset(metadata.TypeSpec ts,
string fname, target.Target t, out bool is_tls, bool is_static = false,
List<TypeSpec> field_types = null, List<string> field_names = null,
List<int> field_offsets = null)
{
int align = 1;
is_tls = false;
if (ts.SimpleType == 0) // class
align = GetTypeAlignment(ts, t, is_static);
if (ts.SimpleType == 0xe && !is_static) // string
align = t.GetPointerSize();
if(ts.Equals(ts.m.SystemString) && !is_static)
{
/* System.String has a special layout in dotnet clr because the fields
* length and firstchar are reversed */
if(field_names != null)
{
field_names.Add("__vtbl");
field_names.Add("__mutex_lock");
field_names.Add("m_stringLength");
field_names.Add("m_firstChar");
}
if(field_types != null)
{
field_types.Add(ts.m.SystemIntPtr);
field_types.Add(ts.m.SystemInt64);
field_types.Add(ts.m.SystemInt32);
field_types.Add(ts.m.SystemChar);
}
if(field_offsets != null)
{
field_offsets.Add(0);
field_offsets.Add(GetArrayFieldOffset(ArrayField.MutexLock, t));
field_offsets.Add(GetTypeSize(ts.m.SystemObject, t));
field_offsets.Add(GetTypeSize(ts.m.SystemObject, t) + t.GetPointerSize());
}
if(fname == null)
{
// size = sizeof(Object) + sizeof(int length), aligned to pointer size
return GetTypeSize(ts.m.SystemObject, t) + t.GetPointerSize();
}
else
{
if (fname == "length" || fname == "m_stringLength")
{
return GetTypeSize(ts.m.SystemObject, t);
}
else if (fname == "start_char" || fname == "m_firstChar")
{
return GetTypeSize(ts.m.SystemObject, t) + t.GetPointerSize();
}
else
throw new NotSupportedException();
}
}
/* Iterate through methods looking for requested
one */
var first_fdef = ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
ts.tdrow, 4);
var last_fdef = ts.m.GetLastFieldDef(ts.tdrow);
int cur_offset = 0;
int cur_tl_offset = 0;
if (is_static == false && !ts.IsValueType)
{
if (ts.GetExtends() == null)
{
// Add a vtable entry
if (field_offsets != null)
field_offsets.Add(cur_offset);
cur_offset += t.GetCTSize(ir.Opcode.ct_object);
cur_offset = util.util.align(cur_offset, align);
if (field_types != null)
field_types.Add(ts.m.SystemIntPtr);
if (field_names != null)
field_names.Add("__vtbl");
// Add a mutex lock entry
if (field_offsets != null)
field_offsets.Add(cur_offset);
cur_offset += t.GetCTSize(ir.Opcode.ct_int64);
cur_offset = util.util.align(cur_offset, align);
if (field_types != null)
field_types.Add(ts.m.SystemInt64);
if (field_names != null)
field_names.Add("__mutex_lock");
}
else
{
cur_offset = GetFieldOffset(ts.GetExtends(), (string)null, t,
out is_tls,
is_static, field_types, field_names, field_offsets);
cur_offset = util.util.align(cur_offset, align);
}
}
else if (is_static)
{
// Add an is_initalized field
cur_offset += t.GetCTSize(ir.Opcode.ct_intptr);
cur_offset = util.util.align(cur_offset, align);
}
for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
// Ensure field is static if requested
var flags = ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 0);
if (((flags & 0x10) == 0x10 && is_static == true) ||
((flags & 0x10) == 0 && is_static == false))
{
// Check on name if we are looking for a particular field
bool f_is_tls = ts.m.thread_local_fields[fdef_row];
if (fname != null)
{
var ffname = ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 1);
if (MetadataStream.CompareString(ts.m, ffname, fname))
{
if (f_is_tls)
{
is_tls = true;
return cur_tl_offset;
}
else
{
is_tls = false;
return cur_offset;
}
}
}
// Increment by type size
var fsig = (int)ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 2);
var ft = ts.m.GetFieldType(ref fsig, ts.gtparams, null);
var ft_size = t.GetSize(ft);
if (field_types != null)
field_types.Add(ft);
if(field_names != null)
{
var cur_fname = ts.m.GetStringEntry(MetadataStream.tid_Field,
(int)fdef_row, 1);
field_names.Add(cur_fname);
}
if (field_offsets != null)
{
if (f_is_tls)
field_offsets.Add(cur_tl_offset);
else
field_offsets.Add(cur_offset);
}
if (f_is_tls)
{
cur_tl_offset += ft_size;
cur_tl_offset = util.util.align(cur_tl_offset, align);
}
else
{
cur_offset += ft_size;
cur_offset = util.util.align(cur_offset, align);
}
}
}
// Shouldn't get here if looking for a specific field
if (fname != null)
throw new MissingFieldException();
// Else return size of complete type
return cur_offset;
}
public static int GetTypeSize(metadata.TypeSpec ts,
target.Target t, bool is_static = false)
{
switch(ts.stype)
{
case TypeSpec.SpecialType.None:
if(ts.Equals(ts.m.SystemRuntimeTypeHandle) ||
ts.Equals(ts.m.SystemRuntimeMethodHandle) ||
ts.Equals(ts.m.SystemRuntimeFieldHandle))
{
return is_static ? 0 : (t.GetPointerSize());
}
if (ts.m.classlayouts[ts.tdrow] != 0 && ts.IsGeneric == false && ts.IsGenericTemplate == false)
{
var size = ts.m.GetIntEntry(metadata.MetadataStream.tid_ClassLayout,
ts.m.classlayouts[ts.tdrow],
1);
if(size != 0)
return (int)size;
}
return GetFieldOffset(ts, (string)null, t, out var is_tls, is_static);
case TypeSpec.SpecialType.SzArray:
case TypeSpec.SpecialType.Array:
if (is_static)
return 0;
return GetArrayObjectSize(t);
case TypeSpec.SpecialType.Boxed:
if (is_static)
return 0;
return GetTypeSize(ts.m.SystemObject, t) +
GetTypeSize(ts.Unbox, t);
default:
throw new NotImplementedException();
}
}
public static void OutputStaticFields(metadata.TypeSpec ts,
target.Target t, binary_library.IBinaryFile of,
MetadataStream base_m = null,
binary_library.ISection os = null,
binary_library.ISection tlsos = null)
{
// Don't compile if not for this architecture
if (!t.IsTypeValid(ts))
return;
int align = 1;
if (ts.SimpleType == 0)
align = GetTypeAlignment(ts, t, true);
if(os == null)
os = of.GetDataSection();
os.Align(t.GetPointerSize());
os.Align(align);
ulong offset = (ulong)os.Data.Count;
ulong tl_offset = 0;
if(tlsos != null)
{
tl_offset = (ulong)tlsos.Data.Count;
}
int cur_offset = 0;
int cur_tloffset = 0;
/* is_initialized */
for (int i = 0; i < t.psize; i++)
os.Data.Add(0);
cur_offset += t.psize;
/* Iterate through methods looking for requested
one */
var first_fdef = ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
ts.tdrow, 4);
var last_fdef = ts.m.GetLastFieldDef(ts.tdrow);
for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
// Ensure field is static or not as required
var flags = ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 0);
if ((flags & 0x10) == 0x10)
{
// Increment by type size
var fsig = (int)ts.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 2);
var ft = ts.m.GetFieldType(ref fsig, ts.gtparams, null);
var ft_size = t.GetSize(ft);
ft_size = util.util.align(ft_size, align);
bool is_tls = ts.m.thread_local_fields[(int)fdef_row];
ISection cur_os = os;
if(is_tls)
{
if (tlsos == null)
throw new NotSupportedException("No thread-local section provided");
cur_os = tlsos;
}
/* See if there is any data defined as an rva */
var rva = ts.m.fieldrvas[(int)fdef_row];
if (rva != 0)
{
var rrva = (int)ts.m.ResolveRVA(rva);
for (int i = 0; i < ft_size; i++)
cur_os.Data.Add(ts.m.file.ReadByte(rrva++));
}
else
{
for (int i = 0; i < ft_size; i++)
cur_os.Data.Add(0);
}
/* Output any additional defined symbols */
foreach(var alias in ts.m.GetFieldAliases((int)fdef_row))
{
var asym = of.CreateSymbol();
asym.Name = alias;
asym.Offset = offset + (ulong)cur_offset;
asym.Type = binary_library.SymbolType.Global;
asym.ObjectType = binary_library.SymbolObjectType.Object;
cur_os.AddSymbol(asym);
asym.Size = ft_size;
if (base_m != null && ts.m != base_m)
asym.Type = binary_library.SymbolType.Weak;
}
if (is_tls)
cur_tloffset += ft_size;
else
cur_offset += ft_size;
}
}
if (cur_offset > 0)
{
/* Add symbol */
var sym = of.CreateSymbol();
sym.Name = ts.m.MangleType(ts) + "S";
sym.Offset = offset;
sym.Type = binary_library.SymbolType.Global;
sym.ObjectType = binary_library.SymbolObjectType.Object;
os.AddSymbol(sym);
sym.Size = os.Data.Count - (int)offset;
if (base_m != null && ts.m != base_m)
sym.Type = binary_library.SymbolType.Weak;
}
if(cur_tloffset > 0)
{
/* Add thread local symbol */
var sym = of.CreateSymbol();
sym.Name = ts.m.MangleType(ts) + "ST";
sym.Offset = tl_offset;
sym.Type = binary_library.SymbolType.Global;
sym.ObjectType = binary_library.SymbolObjectType.Object;
tlsos.AddSymbol(sym);
sym.Size = tlsos.Data.Count - (int)tl_offset;
if (base_m != null && ts.m != base_m)
sym.Type = binary_library.SymbolType.Weak;
}
}
}
}
<file_sep>using System;
namespace ConsoleUtils
{
public class KeyPressResult
{
public KeyPressResult(ConsoleKeyInfo consoleKeyInfo, LineState lineBeforeKeyPress, LineState lineAfterKeyPress)
{
ConsoleKeyInfo = consoleKeyInfo;
LineBeforeKeyPress = lineBeforeKeyPress;
LineAfterKeyPress = lineAfterKeyPress;
}
public ConsoleKeyInfo ConsoleKeyInfo { get; private set; }
public ConsoleKey Key { get { return ConsoleKeyInfo.Key; } }
public char KeyChar { get { return ConsoleKeyInfo.KeyChar; } }
public ConsoleModifiers Modifiers { get { return ConsoleKeyInfo.Modifiers; } }
public LineState LineBeforeKeyPress { get; private set; }
public LineState LineAfterKeyPress { get; private set; }
}
}
<file_sep>/* Copyright (C) 2014 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* Standard C library functions */
namespace libsupcs
{
class clib
{
[libsupcs.MethodAlias("__mbstrlen")]
[libsupcs.MethodAlias("mbstrlen")]
[libsupcs.MethodAlias("strlen")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static int MbStrLen(sbyte* value)
{
/* For ASCII strings only! This doesn't properly handle UTF-8 yet */
int length = 0;
while (*value != 0x00)
{
length++;
value++;
}
return length;
}
[libsupcs.MethodAlias("wmemset")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static char* wmemset(char* wcs, char wc, int n)
{
char* dest = wcs;
for (int i = 0; i < n; i++)
*dest++ = wc;
return wcs;
}
[libsupcs.MethodAlias("wcslen")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static int wcslen(char* s)
{
int length = 0;
while (*s != 0x00)
{
length++;
s++;
}
return length;
}
[libsupcs.MethodAlias("memset")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static byte* memset(byte* s, int c, int n)
{
byte* dest = s;
for (int i = 0; i < n; i++)
*dest++ = (byte)c;
return s;
}
[libsupcs.MethodAlias("memcmp")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static int memcmp(byte *s1, byte *s2, int n)
{
for(int i = 0; i < n; i++)
{
int v = s1[i] - s2[i];
if (v != 0)
return v;
}
return 0;
}
[libsupcs.MethodAlias("memcpy")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static byte* memcpy(byte* dest, byte* src, int n)
{
byte* d = dest;
while (n-- > 0)
*dest++ = *src++;
return d;
}
[libsupcs.MethodAlias("memmove")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe internal static byte* memmove(byte* dest, byte* src, int n)
{
byte* d = dest;
byte* s = src;
if (d > s)
{
/* Perform a backwards copy */
d += n;
s += n;
while (n-- > 0)
{
*--d = *--s;
}
}
else
{
/* Normal memcpy-like copy */
while (n-- > 0)
*d++ = *s++;
}
return dest;
}
[libsupcs.MethodAlias("mbstowcs")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
unsafe static void MbsToWcs(char* dest, sbyte* src, int length)
{
for (int i = 0; i < length; i++)
{
/* For ASCII strings only! This doesn't properly handle UTF-8 yet */
*dest = (char)*src;
dest++;
src++;
}
}
[libsupcs.MethodAlias("abort")]
[libsupcs.WeakLinkage]
[libsupcs.AlwaysCompile]
static void Abort()
{
while (true) ;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.dwarf
{
/** <summary>Base class for a Dwarf DIE</summary> */
public abstract class DwarfDIE
{
public int Offset { get; set; }
public target.Target t { get; set; }
public DwarfCU dcu { get; set; }
public abstract void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent);
/** <summary>Write string offset to output</summary> */
protected void w(IList<byte> d, string s, StringMap smap)
{
uint offset = smap.GetStringAddress(s);
var bytes = BitConverter.GetBytes(offset);
if (t.psize == 8)
{
for (int i = 0; i < 4; i++)
d.Add(0);
}
for (int i = 0; i < 4; i++)
d.Add(bytes[i]);
}
/** <summary>Writes 0 at the pointer length</summary> */
protected void wp(IList<byte> d)
{
for (int i = 0; i < t.psize; i++)
d.Add(0);
}
/** <summary>Writes v at the pointer length</summary> */
protected void wp(IList<byte> d, long v)
{
var b = BitConverter.GetBytes(v);
for (int i = 0; i < t.psize; i++)
d.Add(b[i]);
}
/** <summary>LEB128 encode data to output file</summary> */
protected void w(binary_library.ISection s, uint[] data)
{
foreach (var d in data)
w(s.Data, d);
}
/** <summary>LEB128 encode data to output file</summary> */
protected void w(IList<byte> s, uint[] data)
{
foreach (var d in data)
w(s, d);
}
/** <summary>LEB128 encode data to output file</summary> */
protected void w(binary_library.ISection s, uint data)
{
w(s.Data, data);
}
/** <summary>LEB128 encode data to output file</summary> */
public static void w(IList<byte> s, uint data)
{
do
{
uint _byte = data & 0x7fU;
data >>= 7;
if (data != 0)
_byte |= 0x80U;
s.Add((byte)_byte);
} while (data != 0);
}
/** <summary>LEB128 encode data to output file</summary> */
public static void w(IList<byte> s, int data)
{
bool more = true;
bool negative = data < 0;
var size = 32;
while(more)
{
var b = data & 0x7f;
data >>= 7;
if(negative)
{
data |= -(1 << (size - 7));
}
if((data == 0 && (b & 0x40) == 0) ||
(data == -1 && (b & 0x40) == 0x40))
{
more = false;
}
else
{
b |= 0x80;
}
s.Add((byte)b);
}
}
}
public class StringMap
{
Dictionary<string, uint> smap = new Dictionary<string, uint>();
List<byte> d = new List<byte>();
public uint GetStringAddress(string v)
{
uint addr;
if (smap.TryGetValue(v, out addr))
{
return addr;
}
smap[v] = (uint)d.Count;
foreach (char c in v)
{
d.Add((byte)c);
}
d.Add(0);
return smap[v];
}
public void Write(binary_library.ISection str)
{
foreach (var c in d)
str.Data.Add(c);
}
}
/** <summary>A DIE with children</summary> */
public class DwarfParentDIE : DwarfDIE
{
public List<DwarfDIE> Children { get; } = new List<DwarfDIE>();
public override void WriteToOutput(DwarfSections ds, IList<byte> dinfo, DwarfDIE parent)
{
foreach (var c in Children)
{
c.Offset = dinfo.Count;
c.WriteToOutput(ds, dinfo, this);
}
dinfo.Add(0); // null-terminate
}
}
/** <summary>Encapsulates a compilation unit</summary> */
public class DwarfCU : DwarfParentDIE
{
/** <summary>The original metadata stream we load from</summary> */
public metadata.MetadataStream m { get; set; }
public DwarfCU(target.Target target, metadata.MetadataStream mdata)
{
dcu = this;
t = target;
m = mdata;
AddBaseTypes();
}
private void AddBaseTypes()
{
int[] btypes = new int[]
{
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x1c, 0x0e
};
/* Force there to be a base type in the empty namespace,
* with C# style names.
*
* Link to these using typedefs from System namespace (GDB
* doesn't seem to like base types in namespaces) */
foreach (var btype in btypes)
{
DwarfDIE btdie;
switch(btype)
{
case 0x0e:
// string
btdie = GetTypeDie(m.SystemString, false);
((DwarfTypeDIE)btdie).NameOverride = "string";
type_dies.Remove(m.SystemString);
break;
case 0x1c:
// object
btdie = GetTypeDie(m.SystemObject, false);
((DwarfTypeDIE)btdie).NameOverride = "object";
type_dies.Remove(m.SystemObject);
break;
default:
btdie = new DwarfBaseTypeDIE() { dcu = this, t = t, stype = btype };
break;
}
basetype_dies[btype] = btdie;
Children.Add(btdie);
}
}
/** <summary>Use when ref4s are not yet calculable.
* key is Offset where relocation is written
* value is target offset to place at Offset</summary> */
public Dictionary<int, DwarfDIE> fmap = new Dictionary<int, DwarfDIE>();
/** <summary>Line number program and its relocations, excluding header</summary> */
public List<byte> lnp = new List<byte>();
public Dictionary<int, binary_library.ISymbol> lnp_relocs = new Dictionary<int, binary_library.ISymbol>();
public Dictionary<string, uint> lnp_files = new Dictionary<string, uint>();
public List<string> lnp_fnames = new List<string>();
/** <summary>First and last symbol in CU</summary> */
public binary_library.ISymbol first_sym, last_sym;
public void WriteToOutput(DwarfSections odbgsect)
{
WriteAbbrev(odbgsect.abbrev);
WriteInfo(odbgsect);
odbgsect.smap.Write(odbgsect.str);
WriteLines(odbgsect);
WritePubTypes(odbgsect);
WritePubNames(odbgsect);
}
private void WritePubTypes(DwarfSections odbgsect)
{
/* Write lines header */
List<byte> d = new List<byte>();
// Reserve space for unit_length
if (t.psize == 4)
{
for (int i = 0; i < 4; i++)
d.Add(0);
}
else
{
for (int i = 0; i < 12; i++)
d.Add(0);
}
// version
d.Add(2);
d.Add(0);
// debug_info_offset
for (int i = 0; i < t.psize; i++)
d.Add(0);
// debug_info_length
var length = odbgsect.info.Data.Count;
var bytes = (t.psize == 4) ? BitConverter.GetBytes((int)length) :
BitConverter.GetBytes((long)length);
foreach (var b in bytes)
d.Add(b);
foreach(var kvp in type_dies)
{
// offset
bytes = (t.psize == 4) ? BitConverter.GetBytes((int)kvp.Value.Offset) :
BitConverter.GetBytes((long)kvp.Value.Offset);
foreach (var b in bytes)
d.Add(b);
// name
foreach (var c in kvp.Key.Name)
d.Add((byte)c);
d.Add(0);
}
// Finally, patch the length back in
if (t.psize == 4)
{
uint len = (uint)d.Count - 4;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = bytes[i];
}
else
{
ulong len = (ulong)d.Count - 12;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = 0xff;
for (int i = 0; i < 8; i++)
d[i + 4] = bytes[i];
}
// Store to section
for (int i = 0; i < d.Count; i++)
odbgsect.pubtypes.Data.Add(d[i]);
}
private void WritePubNames(DwarfSections odbgsect)
{
/* Write lines header */
List<byte> d = new List<byte>();
// Reserve space for unit_length
if (t.psize == 4)
{
for (int i = 0; i < 4; i++)
d.Add(0);
}
else
{
for (int i = 0; i < 12; i++)
d.Add(0);
}
// version
d.Add(2);
d.Add(0);
// debug_info_offset
for (int i = 0; i < t.psize; i++)
d.Add(0);
// debug_info_length
var length = odbgsect.info.Data.Count;
var bytes = (t.psize == 4) ? BitConverter.GetBytes((int)length) :
BitConverter.GetBytes((long)length);
foreach (var b in bytes)
d.Add(b);
foreach (var kvp in method_dies)
{
// offset
bytes = (t.psize == 4) ? BitConverter.GetBytes((int)kvp.Value.Offset) :
BitConverter.GetBytes((long)kvp.Value.Offset);
foreach (var b in bytes)
d.Add(b);
// name
foreach (var c in kvp.Key.MangleMethod())
d.Add((byte)c);
d.Add(0);
}
// Finally, patch the length back in
if (t.psize == 4)
{
uint len = (uint)d.Count - 4;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = bytes[i];
}
else
{
ulong len = (ulong)d.Count - 12;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = 0xff;
for (int i = 0; i < 8; i++)
d[i + 4] = bytes[i];
}
// Store to section
for (int i = 0; i < d.Count; i++)
odbgsect.pubnames.Data.Add(d[i]);
}
public int opcode_base = 13;
public int line_base = -3;
public int line_range = 6;
public int mc_advance_max { get { return (255 - opcode_base) / line_range; } }
private void WriteLines(DwarfSections odbgsect)
{
/* Write lines header */
List<byte> d = new List<byte>();
// Reserve space for unit_length
if (t.psize == 4)
{
for (int i = 0; i < 4; i++)
d.Add(0);
}
else
{
for (int i = 0; i < 12; i++)
d.Add(0);
}
// version
d.Add(4);
d.Add(0);
// header_length
var header_length_offset = d.Count;
for (int i = 0; i < t.psize; i++)
d.Add(0);
// minimum_instruction_length
d.Add(1);
// maximum_operations_per_instruction
d.Add(1);
// default_is_stmt
d.Add(1);
// line_base
if (line_base < 0)
d.Add((byte)(0x100 + line_base));
else
d.Add((byte)line_base);
// line_range
d.Add((byte)line_range);
// opcode_base
d.Add((byte)opcode_base);
// standard_opcode_lengths
d.AddRange(new byte[] { 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 });
// include_directories
d.Add(0);
// file_names
foreach(var fname in lnp_fnames)
{
foreach (var c in fname)
d.Add((byte)c);
d.Add(0);
// dir index
d.Add(0);
// last_mod
d.Add(0);
// length
d.Add(0);
}
d.Add(0);
// point header_length here
var doffset = d.Count;
var header_length = doffset - header_length_offset - t.psize;
byte[] bytes = (t.psize == 4) ? BitConverter.GetBytes((int)header_length) :
BitConverter.GetBytes((long)header_length);
for (int i = 0; i < t.psize; i++)
d[header_length_offset + i] = bytes[i];
// add the actual data
d.AddRange(lnp);
// add relocs
foreach(var reloc in lnp_relocs)
{
var r = odbgsect.bf.CreateRelocation();
r.Type = t.GetDataToDataReloc();
r.Offset = (ulong)(doffset + reloc.Key);
r.References = reloc.Value;
r.DefinedIn = odbgsect.line;
odbgsect.bf.AddRelocation(r);
}
// Finally, patch the length back in
if (t.psize == 4)
{
uint len = (uint)d.Count - 4;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = bytes[i];
}
else
{
ulong len = (ulong)d.Count - 12;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = 0xff;
for (int i = 0; i < 8; i++)
d[i + 4] = bytes[i];
}
// Store to section
for (int i = 0; i < d.Count; i++)
odbgsect.line.Data.Add(d[i]);
}
private void WriteInfo(DwarfSections ds)
{
var info = ds.info;
var string_map = ds.smap;
List<byte> d = new List<byte>();
// Output header
// Reserve space for unit_length
if(t.psize == 4)
{
for (int i = 0; i < 4; i++)
d.Add(0);
}
else
{
for (int i = 0; i < 12; i++)
d.Add(0);
}
// version
d.Add(4);
d.Add(0);
// debug_abbrev_offset
for (int i = 0; i < t.psize; i++)
d.Add(0);
// address_size
d.Add((byte)t.psize);
// Store offset of root entry
this.Offset = d.Count;
// Write the root DIE
w(d, 1);
w(d, "tysila", string_map);
w(d, 0x4); // pretend to be C++
var fname = m.file.Name;
if(fname == null || fname.Equals(string.Empty))
{
w(d, m.AssemblyName, string_map);
w(d, "", string_map);
}
else
{
var finfo = new System.IO.FileInfo(fname);
w(d, finfo.Name, string_map);
w(d, finfo.DirectoryName, string_map);
}
// store low/high pc offsets for patching later
var low_pc_offset = d.Count;
for (int i = 0; i < t.psize; i++)
d.Add(0);
var high_pc_offset = d.Count;
for (int i = 0; i < t.psize; i++)
d.Add(0);
var stmt_list_offset = d.Count;
for (int i = 0; i < t.psize; i++)
d.Add(0);
/* Children:
* Items in the empty namespace are placed as direct children
* Others are placed as children of the namespace
*/
foreach(var kvp in ns_dies)
{
if(kvp.Key == "")
{
foreach (var dc in kvp.Value.Children)
Children.Add(dc);
}
else
{
Children.Add(kvp.Value);
}
}
/* Add defintions for all the methods in the main namespace */
foreach(var methkvp in method_dies)
{
var methdef = new DwarfMethodDefDIE();
methdef.dcu = this;
methdef.t = t;
methdef.decl = methkvp.Value;
Children.Add(methdef);
}
// Write children
base.WriteToOutput(ds, d, null);
// Patch relocs
byte[] bytes;
foreach(var kvp in fmap)
{
uint dest = (uint)kvp.Value.Offset;
int addr = kvp.Key;
bytes = BitConverter.GetBytes(dest);
for (int i = 0; i < 4; i++)
d[addr + i] = bytes[i];
}
// Patch low/high_pc
var low_r = ds.bf.CreateRelocation();
low_r.Type = t.GetDataToDataReloc();
low_r.Offset = (ulong)low_pc_offset;
low_r.References = first_sym;
low_r.DefinedIn = ds.info;
ds.bf.AddRelocation(low_r);
var pc_size = last_sym.Offset - first_sym.Offset + (ulong)last_sym.Size;
bytes = (t.psize == 4) ? BitConverter.GetBytes((int)pc_size) :
BitConverter.GetBytes((long)pc_size);
for (int i = 0; i < t.psize; i++)
d[high_pc_offset + i] = bytes[i];
// Finally, patch the length back in
if (t.psize == 4)
{
uint len = (uint)d.Count - 4;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = bytes[i];
}
else
{
ulong len = (ulong)d.Count - 12;
bytes = BitConverter.GetBytes(len);
for (int i = 0; i < 4; i++)
d[i] = 0xff;
for (int i = 0; i < 8; i++)
d[i + 4] = bytes[i];
}
// Store to section
for (int i = 0; i < d.Count; i++)
info.Data.Add(d[i]);
}
/** Write standard abbreviations
* 1 - compile_unit
* 2 - base_type
* 3 - pointer type (generic)
* 4 - pointer type (with base type)
* 5 - subprogram, returns void, static, non-virt
* 6 - subprogram, returns object, static, non-virt
* 7 - subprogram, returns void, instance, non-virt
* 8 - subprogram, returns object, instance, non-virt
* 9 - subprogram, returns void, instance, virtual
* 10 - subprogram, returns object, instance, virtual
* 11 - formal_parameter
* 12 - namespace
* 13 - class
* 14 - structure
* 15 - base_type
* 16 - pointer
* 17 - reference
* 18 - member
* 19 - formal_parameter with no name and artificial flag set
* 20 - typedef
* 21 - variable
* 22 - method definition
* 23 - class with decl_file/line/column
* 24 - structure with decl_file/line/column
*/
private void WriteAbbrev(binary_library.ISection abbrev)
{
uint dtype = t.psize == 4 ? 0x06U : 0x07U; // data4/data 8 depending on target
w(abbrev, new uint[]
{
1, 0x11, 0x01, // compile_unit, has children
0x25, 0x0e, // producer, strp
0x13, 0x0b, // language, data1
0x03, 0x0e, // name, strp
0x1b, 0x0e, // comp_dir, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x10, 0x17, // stmt_list, sec_offset
0x00, 0x00 // terminate
});
w(abbrev, new uint[]
{
2, 0x24, 0x00, // base_type, no children
0x0b, 0x0b, // byte_size, data1
0x3e, 0x0b, // encoding, data1
0x03, 0x0e, // name, strp
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
3, 0x0f, 0x00, // pointer_type, no children
0x0b, 0x0b, // byte_size, data1
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
4, 0x0f, 0x00, // pointer_type, no children
0x0b, 0x0b, // byte_size, data1
0x49, 0x15, // type, LEB128 from start of CU in bytes
0x00, 0x00,
});
w(abbrev, new uint[]
{
5, 0x2e, 0x01, // subprogram, has children
0x03, 0x0e, // name, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x32, 0x0b, // accessibility, data1
0x6e, 0x0e, // linkage_name, strp
0x3c, 0x19, // declaration, present
0x27, 0x19, // prototyped, present
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
6, 0x2e, 0x01, // subprogram, has children
0x03, 0x0e, // name, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x32, 0x0b, // accessibility, data1
0x6e, 0x0e, // linkage_name, strp
0x49, 0x13, // type, ref4
0x3c, 0x19, // declaration, present
0x27, 0x19, // prototyped, present
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
7, 0x2e, 0x01, // subprogram, has children
0x03, 0x0e, // name, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x32, 0x0b, // accessibility, data1
0x6e, 0x0e, // linkage_name, strp
0x64, 0x13, // object_pointer, ref4
0x3c, 0x19, // declaration, present
0x27, 0x19, // prototyped, present
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
8, 0x2e, 0x01, // subprogram, has children
0x03, 0x0e, // name, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x32, 0x0b, // accessibility, data1
0x6e, 0x0e, // linkage_name, strp
0x49, 0x13, // type, ref4
0x64, 0x13, // object_pointer, ref4
0x3c, 0x19, // declaration, present
0x27, 0x19, // prototyped, present
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
9, 0x2e, 0x01, // subprogram, has children
0x03, 0x0e, // name, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x32, 0x0b, // accessibility, data1
0x6e, 0x0e, // linkage_name, strp
0x64, 0x13, // object_pointer, ref4
0x4c, 0x0b, // virtuality, data1
0x3c, 0x19, // declaration, present
0x27, 0x19, // prototyped, present
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
10, 0x2e, 0x01, // subprogram, has children
0x03, 0x0e, // name, strp
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
0x32, 0x0b, // accessibility, data1
0x6e, 0x0e, // linkage_name, strp
0x49, 0x13, // type, ref4
0x64, 0x13, // object_pointer, ref4
0x4c, 0x0b, // virtuality, data1
0x3c, 0x19, // declaration, present
0x27, 0x19, // prototyped, present
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
11, 0x05, 0x00, // formal_parameter, no children
0x03, 0x0e, // name, strp
0x49, 0x13, // type, ref4
0x02, 0x18, // location, exprloc
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
12, 0x39, 0x01, // namespace, has children
0x03, 0x0e, // name, strp
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
13, 0x02, 0x01, // class, has children
0x03, 0x0e, // name, strp
0x0b, 0x0f, // byte_size, udata (LEB128)
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
14, 0x13, 0x01, // structure, has children
0x03, 0x0e, // name, strp
0x0b, 0x0f, // byte_size, udata (LEB128)
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
15, 0x24, 0x00, // base_type, no children
0x03, 0x0e, // name, strp
0x0b, 0x0b, // byte_size, data1
0x3e, 0x0b, // encoding, data1
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
16, 0x0f, 0x00, // pointer_type, no children
0x0b, 0x0b, // byte_size, data1
0x49, 0x13, // type, ref4
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
17, 0x0f, 0x00, // reference_type, no children
0x0b, 0x0b, // byte_size, data1
0x49, 0x13, // type, ref4
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
18, 0x0d, 0x00, // member, no children
0x03, 0x0e, // name, strp
0x49, 0x13, // type, ref4
0x38, 0x0f, // data_member_location, udata (LEB128)
0x00, 0x00,
});
w(abbrev, new uint[]
{
19, 0x05, 0x00, // formal_parameter, no children
0x49, 0x13, // type, ref4
0x34, 0x19, // artificial, flag_present
0x02, 0x18, // location, exprloc
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
20, 0x16, 0x00, // typedef, no children
0x03, 0x0e, // name, strp
0x49, 0x13, // type, ref4
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
21, 0x34, 0x00, // variable, no children
0x03, 0x0e, // name, strp
0x49, 0x13, // type, ref4
0x02, 0x18, // location, exprloc
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
22, 0x2e, 0x01, // subprogram, has children
0x47, 0x13, // specification, ref4
0x11, 0x01, // low_pc, addr
0x12, dtype, // high_pc, data (i.e. length)
//0x64, 0x13, // object_pointer, ref4
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
23, 0x02, 0x01, // class, has children
0x03, 0x0e, // name, strp
0x0b, 0x0f, // byte_size, udata (LEB128)
0x3a, 0x0b, // decl_file, data1
0x3b, 0x0b, // decl_line, data1
0x39, 0x0b, // decl_column, data1
0x00, 0x00, // terminate
});
w(abbrev, new uint[]
{
24, 0x13, 0x01, // structure, has children
0x03, 0x0e, // name, strp
0x0b, 0x0f, // byte_size, udata (LEB128)
0x3a, 0x0b, // decl_file, data1
0x3b, 0x0b, // decl_line, data1
0x39, 0x0b, // decl_column, data1
0x00, 0x00, // terminate
});
// last unit should have type 0
w(abbrev, new uint[]
{
0x00, 0x00
});
}
/* Here, we store all the allocated and non-allocated types etc that we
* later need to access.
* Calling the 'Get' function will create a blank DIE if necessary but ensure
* that DIE's are unique for each spec type */
Dictionary<string, DwarfNSDIE> ns_dies = new Dictionary<string, DwarfNSDIE>();
Dictionary<metadata.TypeSpec, DwarfTypeDIE> type_dies = new Dictionary<metadata.TypeSpec, DwarfTypeDIE>();
Dictionary<metadata.MethodSpec, DwarfMethodDIE> method_dies = new Dictionary<metadata.MethodSpec, DwarfMethodDIE>();
public Dictionary<int, DwarfDIE> basetype_dies = new Dictionary<int, DwarfDIE>();
public DwarfNSDIE GetNSDie(string ns)
{
DwarfNSDIE ret;
if (ns_dies.TryGetValue(ns, out ret))
return ret;
ret = new DwarfNSDIE();
ret.ns = ns;
ret.t = t;
ret.dcu = this;
ns_dies[ns] = ret;
return ret;
}
public DwarfDIE GetTypeDie(metadata.TypeSpec ts, bool add_ns = true)
{
DwarfTypeDIE ret;
if (type_dies.TryGetValue(ts, out ret))
return ret;
if(ts.SimpleType != 0)
{
DwarfDIE dret;
if (basetype_dies.TryGetValue(ts.SimpleType, out dret))
return dret;
}
ret = new DwarfTypeDIE();
ret.ts = ts;
ret.t = t;
ret.dcu = this;
type_dies[ts] = ret;
if (add_ns)
{
// Generate namespace too
var ns = GetNSDie(ts.Namespace);
ns.Children.Add(ret);
}
// Ensure base classes etc are referenced
if (ts.GetExtends() != null)
GetTypeDie(ts.GetExtends());
switch(ts.stype)
{
case metadata.TypeSpec.SpecialType.Array:
case metadata.TypeSpec.SpecialType.SzArray:
case metadata.TypeSpec.SpecialType.MPtr:
case metadata.TypeSpec.SpecialType.Ptr:
if(ts.other != null)
GetTypeDie(ts.other);
break;
}
// Ensure field types are referenced
if(ts.SimpleType == 0x1c || // Object
ts.SimpleType == 0x0e || // String
(ts.SimpleType == 0 &&
ts.stype == metadata.TypeSpec.SpecialType.None &&
ts.m == m)) // Class/struct in current module
{
bool is_tls;
List<metadata.TypeSpec> fld_types = new List<metadata.TypeSpec>();
List<string> fnames = new List<string>();
List<int> foffsets = new List<int>();
layout.Layout.GetFieldOffset(ts, null, t, out is_tls,
false, fld_types, fnames, foffsets);
for(int i = 0; i < fld_types.Count; i++)
{
var ft = fld_types[i];
var fdie = new DwarfMemberDIE();
fdie.dcu = dcu;
fdie.Name = fnames[i];
fdie.FieldOffset = foffsets[i];
fdie.FieldType = GetTypeDie(ft);
fdie.t = t;
ret.Children.Add(fdie);
}
layout.Layout.GetFieldOffset(ts, null, t, out is_tls,
true, fld_types);
foreach (var ft in fld_types)
GetTypeDie(ft);
}
return ret;
}
public DwarfMethodDIE GetMethodDie(metadata.MethodSpec ms)
{
DwarfMethodDIE ret;
if (method_dies.TryGetValue(ms, out ret))
return ret;
ret = new DwarfMethodDIE();
ret.ms = ms;
ret.t = t;
ret.dcu = this;
method_dies[ms] = ret;
return ret;
}
}
/** <summary>All the various .debug sections for the current compilation</summary> */
public class DwarfSections
{
public binary_library.ISection abbrev, aranges, frame, info, line, loc, macinfo, pubnames, pubtypes,
ranges, str, types;
public binary_library.IBinaryFile bf;
public StringMap smap = new StringMap();
binary_library.ISection CreateDwarfSection(string name)
{
name = ".debug_" + name;
var ret = bf.FindSection(name);
if (ret != null)
return ret;
ret = bf.CreateContentsSection();
ret.IsAlloc = false;
ret.IsExecutable = false;
ret.IsWriteable = false;
ret.Name = name;
bf.AddSection(ret);
return ret;
}
public DwarfSections(binary_library.IBinaryFile _bf)
{
bf = _bf;
abbrev = CreateDwarfSection("abbrev");
//aranges = CreateDwarfSection("aranges");
frame = CreateDwarfSection("frame");
info = CreateDwarfSection("info");
line = CreateDwarfSection("line");
//loc = CreateDwarfSection("loc");
//macinfo = CreateDwarfSection("macinfo");
pubnames = CreateDwarfSection("pubnames");
pubtypes = CreateDwarfSection("pubtypes");
//ranges = CreateDwarfSection("ranges");
str = CreateDwarfSection("str");
//types = CreateDwarfSection("types");
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.layout;
using libtysila5.util;
using metadata;
/* Implements a generic requestor to use for vtables and methods, and a
default implementation that cache requests */
namespace libtysila5
{
public abstract class Requestor
{
public abstract IndividualRequestor<TypeSpec> VTableRequestor { get; }
public abstract IndividualRequestor<layout.Layout.MethodSpecWithEhdr> MethodRequestor { get; }
public abstract IndividualRequestor<layout.Layout.MethodSpecWithEhdr> EHRequestor { get; }
public abstract IndividualRequestor<layout.Layout.MethodSpecWithEhdr> BoxedMethodRequestor { get; }
public abstract IndividualRequestor<TypeSpec> StaticFieldRequestor { get; }
public abstract IndividualRequestor<TypeSpec> DelegateRequestor { get; }
public virtual bool Empty
{
get
{
if (!VTableRequestor.Empty)
return false;
if (!MethodRequestor.Empty)
return false;
if (!EHRequestor.Empty)
return false;
if (!StaticFieldRequestor.Empty)
return false;
if (!DelegateRequestor.Empty)
return false;
if (!BoxedMethodRequestor.Empty)
return false;
return true;
}
}
}
public class CachingRequestor : Requestor
{
CachingIndividualRequestor<layout.Layout.MethodSpecWithEhdr> m;
CachingIndividualRequestor<layout.Layout.MethodSpecWithEhdr> eh;
CachingIndividualRequestor<layout.Layout.MethodSpecWithEhdr> bm;
CachingIndividualRequestor<TypeSpec> vt;
CachingIndividualRequestor<TypeSpec> sf;
CachingIndividualRequestor<TypeSpec> d;
#if DEBUG
void CheckInstatiated(TypeSpec t)
{
if (t.IsGenericTemplate)
throw new Exception();
}
#endif
#if DEBUG
void CheckGMInstantiated(Layout.MethodSpecWithEhdr t)
{
if (t.ms.IsGeneric && t.ms.IsGenericTemplate)
throw new Exception();
}
#endif
public CachingRequestor(MetadataStream mstream = null)
{
m = new CachingIndividualRequestor<layout.Layout.MethodSpecWithEhdr>(mstream);
eh = new CachingIndividualRequestor<layout.Layout.MethodSpecWithEhdr>(mstream);
bm = new CachingIndividualRequestor<layout.Layout.MethodSpecWithEhdr>(mstream);
vt = new CachingIndividualRequestor<TypeSpec>(mstream);
sf = new CachingIndividualRequestor<TypeSpec>(mstream);
d = new CachingIndividualRequestor<TypeSpec>(mstream);
#if DEBUG
d.DebugCheck = CheckInstatiated;
m.DebugCheck = CheckGMInstantiated;
#endif
}
public override IndividualRequestor<layout.Layout.MethodSpecWithEhdr> MethodRequestor
{
get
{
return m;
}
}
public override IndividualRequestor<layout.Layout.MethodSpecWithEhdr> EHRequestor
{
get
{
return eh;
}
}
public override IndividualRequestor<TypeSpec> VTableRequestor
{
get
{
return vt;
}
}
public override IndividualRequestor<TypeSpec> StaticFieldRequestor
{
get
{
return sf;
}
}
public override IndividualRequestor<TypeSpec> DelegateRequestor
{
get
{
return d;
}
}
public override IndividualRequestor<Layout.MethodSpecWithEhdr> BoxedMethodRequestor
{
get
{
return bm;
}
}
}
public abstract class IndividualRequestor<T> where T : IEquatable<T>
{
public abstract T GetNext();
public abstract bool Empty { get; }
public abstract void Request(T v);
public abstract void Remove(T v);
}
public class CachingIndividualRequestor<T> : IndividualRequestor<T> where T : Spec, IEquatable<T>
{
Set<T> done_and_pending = new Set<T>();
util.Stack<T> pending = new util.Stack<T>();
MetadataStream m;
#if DEBUG
public delegate void DebugChecker(T val);
public DebugChecker DebugCheck { get; internal set; }
#endif
public CachingIndividualRequestor(MetadataStream mstream = null)
{
m = mstream;
}
public override bool Empty
{
get
{
return pending.Count == 0;
}
}
public override T GetNext()
{
return pending.Pop();
}
public override void Request(T v)
{
#if DEBUG
if(DebugCheck != null)
DebugCheck(v);
#endif
if (m != null && m != v.Metadata)
{
if(!v.IsInstantiatedGenericType &&
!v.IsInstantiatedGenericMethod &&
!v.IsArray)
return;
}
if(!done_and_pending.Contains(v))
{
done_and_pending.Add(v);
pending.Push(v);
}
}
public override void Remove(T v)
{
if (done_and_pending.Contains(v))
done_and_pending.Remove(v);
}
}
}
<file_sep>namespace BareBones
{
unsafe struct Console
{
byte *fb;
int pos;
public Console(byte *framebuffer)
{
fb = framebuffer;
pos = 0;
}
public void Clear()
{
for(int i = 0; i < 80 * 25 * 2; i++)
*(fb + i) = 0;
}
public void Print(string s)
{
foreach(char c in s)
Print(c);
}
public void Print(char c)
{
*(byte *)(fb + pos) = (byte)c;
*(byte *)(fb + pos + 1) = 0x0f;
pos += 2;
}
}
unsafe class Program
{
static Console c = new Console((byte *)0xb8000);
static void Main()
{
c.Clear();
c.Print("Hello World!");
while(true);
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs.x86_64
{
[ArchDependent("x86_64")]
public class Unwinder : libsupcs.Unwinder
{
ulong cur_rbp;
ulong cur_rip;
[MethodAlias("__get_unwinder")]
[AlwaysCompile]
static libsupcs.Unwinder GetUnwinder()
{
return new Unwinder().UnwindOne();
}
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
private static extern libsupcs.TysosMethod ReinterpretAsMethodInfo(ulong addr);
public Unwinder()
{
cur_rbp = libsupcs.x86_64.Cpu.RBP;
UnwindOne();
}
public override libsupcs.Unwinder UnwindOne(TysosMethod cur_method)
{
if ((cur_method.TysosFlags & libsupcs.TysosMethod.TF_X86_ISREC) == libsupcs.TysosMethod.TF_X86_ISREC)
return UnwindOneWithErrorCode();
else
return UnwindOne();
}
public override libsupcs.Unwinder Init()
{
cur_rbp = libsupcs.x86_64.Cpu.RBP;
UnwindOne();
return this;
}
public override UIntPtr GetInstructionPointer()
{
unsafe
{
return (UIntPtr)cur_rip;
}
}
public override UIntPtr GetFramePointer()
{
return (UIntPtr)cur_rbp;
}
public override libsupcs.Unwinder UnwindOne()
{
unsafe
{
cur_rip = *(ulong*)(cur_rbp + 8);
cur_rbp = *(ulong*)cur_rbp;
}
return this;
}
public libsupcs.Unwinder UnwindOneWithErrorCode()
{
unsafe
{
cur_rip = *(ulong*)(cur_rbp + 16);
cur_rbp = *(ulong*)cur_rbp;
}
return this;
}
public override libsupcs.TysosMethod GetMethodInfo()
{
unsafe
{
// assume a dodgy pointer if below image
ulong meth_ptr = *(ulong*)(cur_rbp - 8);
if ((meth_ptr < 0x40000000) || !IsValidPtr(meth_ptr))
return null;
object o = libsupcs.CastOperations.ReinterpretAsObject(meth_ptr);
return o as libsupcs.TysosMethod;
}
}
[WeakLinkage]
private static bool IsValidPtr(ulong ptr)
{
return true;
}
public ulong GetRBP() { return cur_rbp; }
public override bool CanContinue()
{
return IsValidPtr(cur_rbp);
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// Interface with the metadata module to interpret metadata embedded in modules
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using metadata;
namespace libsupcs
{
public unsafe class Metadata
{
static metadata.MetadataStream mscorlib = null;
static BinaryAssemblyLoader bal = null;
public static BinaryAssemblyLoader BAL
{
get
{
if (bal == null)
bal = new BinaryAssemblyLoader();
return bal;
}
}
public static metadata.MetadataStream MSCorlib
{
get
{
if (mscorlib == null)
load_mscorlib();
return mscorlib;
}
}
public static metadata.AssemblyLoader AssemblyLoader
{
get
{
return BAL;
}
}
private static void load_mscorlib()
{
var str = AssemblyLoader.LoadAssembly("mscorlib");
metadata.PEFile pef = new metadata.PEFile();
var m = pef.Parse(str, AssemblyLoader);
AssemblyLoader.AddToCache(m, "mscorlib");
mscorlib = m;
BinaryAssemblyLoader.ptr_cache[(ulong)OtherOperations.GetStaticObjectAddress("mscorlib")] = m;
}
internal static unsafe metadata.TypeSpec GetTypeSpec(TysosType t)
{
void** impl_ptr = t.GetImplOffset();
return GetTypeSpec(*impl_ptr);
}
internal static unsafe metadata.TypeSpec GetTypeSpec(RuntimeTypeHandle rth)
{
void* ptr = CastOperations.ReinterpretAsPointer(rth.Value);
return GetTypeSpec(ptr);
}
internal static unsafe metadata.TypeSpec GetTypeSpec(void* ptr)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.GetTypeSpec: called with vtbl " + ((ulong)ptr).ToString("X16"));
// Ensure ptr is valid
if (ptr == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.GetTypeSpec: called with null pointer");
throw new Exception("Invalid type handle");
}
// dereference vtbl pointer to get ti ptr
ptr = *((void**)ptr);
if (ptr == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.GetTypeSpec: called with null pointer");
throw new Exception("Invalid type handle");
}
if ((*((int*)ptr) & 0xf) != 0)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.GetTypeSpec: called with invalid runtimehandle: " +
(*((int*)ptr)).ToString() + " at " + ((ulong)ptr).ToString("X16"));
System.Diagnostics.Debugger.Break();
throw new Exception("Invalid type handle");
}
// Get number of metadata references and pointers to each
var ti_ptr = (void**)ptr;
// skip over type, enum underlying type field, tysos type pointer, cctor and flags
ti_ptr += 5;
var mdref_count = *(int*)(ti_ptr);
var mdref_arr = ti_ptr + 1;
var sig_ptr = (byte*)(mdref_arr + mdref_count);
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.GetTypeSpec: found " + mdref_count.ToString() + " metadata references");
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.GetTypeSpec: parsing signature at " + ((ulong)sig_ptr).ToString("X16"));
// Parse the actual signature
return ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, null, null);
}
private static TypeSpec ParseTypeSpecSignature(ref byte* sig_ptr, int mdref_count, void** mdref_arr,
TypeSpec[] gtparams, TypeSpec[] gmparams)
{
TypeSpec ts = new TypeSpec();
var b = *sig_ptr++;
bool is_generic = false;
// CMOD_REQD/OPT
while (b == 0x1f || b == 0x20)
b = *sig_ptr++;
if(b == 0x15)
{
is_generic = true;
b = *sig_ptr++;
}
switch (b)
{
case 0x01:
// VOID
return null;
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
case 0x08:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0d:
case 0x0e:
case 0x16:
case 0x18:
case 0x19:
case 0x1c:
ts.m = MSCorlib;
ts.tdrow = ts.m.simple_type_rev_idx[b];
break;
case 0x0f:
ts.m = AssemblyLoader.GetAssembly("mscorlib");
ts.stype = TypeSpec.SpecialType.Ptr;
ts.other = ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, gtparams, gmparams);
break;
case 0x10:
ts.m = AssemblyLoader.GetAssembly("mscorlib");
ts.stype = TypeSpec.SpecialType.MPtr;
ts.other = ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, gtparams, gmparams);
break;
case 0x31:
case 0x32:
// Encoded class/vtype
var mdidx = SigReadUSCompressed(ref sig_ptr);
ts.m = BAL.GetAssembly(*(mdref_arr + mdidx));
var tok = SigReadUSCompressed(ref sig_ptr);
int tid, trow;
ts.m.GetCodedIndexEntry(tok, ts.m.TypeDefOrRef,
out tid, out trow);
ts = ts.m.GetTypeSpec(tid, trow, gtparams, gmparams);
break;
case 0x13:
// VAR
var gtidx = SigReadUSCompressed(ref sig_ptr);
if (gtparams == null)
ts = new TypeSpec { stype = TypeSpec.SpecialType.Var, idx = (int)gtidx };
else
ts = gtparams[gtidx];
break;
case 0x1e:
// MVAR
var gmidx = SigReadUSCompressed(ref sig_ptr);
if (gmparams == null)
ts = new TypeSpec { stype = TypeSpec.SpecialType.MVar, idx = (int)gmidx };
else
ts = gmparams[gmidx];
break;
case 0x1d:
ts.m = BAL.GetAssembly("mscorlib");
ts.stype = TypeSpec.SpecialType.SzArray;
ts.other = ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, gtparams, gmparams);
break;
case 0x14:
ts.m = BAL.GetAssembly("mscorlib");
ts.stype = TypeSpec.SpecialType.Array;
ts.other = ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, gtparams, gmparams);
ts.arr_rank = (int)SigReadUSCompressed(ref sig_ptr);
int boundsCount = (int)SigReadUSCompressed(ref sig_ptr);
ts.arr_sizes = new int[boundsCount];
for (int i = 0; i < boundsCount; i++)
ts.arr_sizes[i] = (int)SigReadUSCompressed(ref sig_ptr);
int loCount = (int)SigReadUSCompressed(ref sig_ptr);
ts.arr_lobounds = new int[loCount];
for (int i = 0; i < loCount; i++)
ts.arr_lobounds[i] = (int)SigReadUSCompressed(ref sig_ptr);
break;
case 0x45:
ts = ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, gtparams, gmparams);
ts.Pinned = true;
break;
default:
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.ParseTypeSpecSignature: invalid signature byte: " + b.ToString());
throw new NotImplementedException();
}
if (is_generic)
{
var gen_count = SigReadUSCompressed(ref sig_ptr);
ts.gtparams = new TypeSpec[gen_count];
for (uint i = 0; i < gen_count; i++)
{
ts.gtparams[i] = ParseTypeSpecSignature(ref sig_ptr, mdref_count, mdref_arr, gtparams, gmparams);
}
}
return ts;
}
private static uint SigReadUSCompressed(ref byte* sig_ptr)
{
byte b1 = *sig_ptr++;
if ((b1 & 0x80) == 0)
return b1;
byte b2 = *sig_ptr++;
if ((b1 & 0xc0) == 0x80)
return (b1 & 0x3fU) << 8 | b2;
byte b3 = *sig_ptr++;
byte b4 = *sig_ptr++;
return (b1 & 0x1fU) << 24 | ((uint)b2 << 16) |
((uint)b3 << 8) | b4;
}
public class BinaryAssemblyLoader : metadata.AssemblyLoader
{
internal static Dictionary<ulong, metadata.MetadataStream> ptr_cache =
new Dictionary<ulong, metadata.MetadataStream>(
new GenericEqualityComparer<ulong>());
public override DataInterface LoadAssembly(string name)
{
void* ptr;
System.Diagnostics.Debugger.Log(0, "metadata", "Metadata.BinaryAssemblyLoader.LoadAssembly: request to load " + name);
if(name == "mscorlib" || name == "mscorlib.dll")
{
ptr = OtherOperations.GetStaticObjectAddress("mscorlib");
}
else if(name == "libsupcs" || name == "libsupcs.dll")
{
ptr = OtherOperations.GetStaticObjectAddress("libsupcs");
}
else if (name == "metadata" || name == "metadata.dll")
{
ptr = OtherOperations.GetStaticObjectAddress("metadata");
}
else
{
ptr = JitOperations.GetAddressOfObject(name);
}
return new BinaryInterface(ptr);
}
public unsafe virtual MetadataStream GetAssembly(void *ptr)
{
MetadataStream m;
if (ptr_cache.TryGetValue((ulong)ptr, out m))
return m;
System.Diagnostics.Debugger.Log(0, "libsupcs", "Metadata.BinaryAssemblyLoader: loading assembly at: " + ((ulong)ptr).ToString());
var bi = new BinaryInterface(ptr);
PEFile p = new PEFile();
m = p.Parse(bi, this);
ptr_cache[(ulong)ptr] = m;
cache[m.AssemblyName] = m;
return m;
}
}
unsafe internal class BinaryInterface : metadata.DataInterface
{
internal byte* b;
public BinaryInterface(void *ptr)
{
b = (byte*)ptr;
}
public override byte ReadByte(int offset)
{
var ret = *(b + offset);
//System.Diagnostics.Debugger.Break();
return ret;
}
public override DataInterface Clone(int offset)
{
return new BinaryInterface(b + offset);
}
}
class BinaryStream : System.IO.Stream
{
byte* d;
bool canwrite;
long pos;
long len;
public BinaryStream(byte *data, long length)
{
System.Diagnostics.Debugger.Break();
d = data;
len = length;
canwrite = true;
pos = 0;
}
public override int ReadByte()
{
var ret = *(d + pos++);
System.Diagnostics.Debugger.Break();
return ret;
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanSeek
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return canwrite;
}
}
public override long Length
{
get
{
return len;
}
}
public override long Position
{
get
{
return pos;
}
set
{
pos = value;
}
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
for(int i = 0; i < count; i++)
{
buffer[offset + i] = *(d + pos++);
}
System.Diagnostics.Debugger.Break();
return count;
}
public override long Seek(long offset, SeekOrigin origin)
{
switch(origin)
{
case SeekOrigin.Begin:
pos = offset;
break;
case SeekOrigin.Current:
pos += offset;
break;
case SeekOrigin.End:
pos = len - offset;
break;
}
return pos;
}
public override void SetLength(long value)
{
}
public override void Write(byte[] buffer, int offset, int count)
{
for(int i = 0; i < count; i++)
{
*(d + pos++) = buffer[offset + i];
}
}
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.util
{
public class Set<T> : ICollection<T> where T : class, System.IEquatable<T>
{
Dictionary<T, int> d = new Dictionary<T, int>(
new GenericEqualityComparer<T>());
public int Count
{
get
{
return d.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void Add(T item)
{
d[item] = 0;
}
public void Clear()
{
d.Clear();
}
public bool Contains(T item)
{
return d.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
foreach (var kvp in d)
array[arrayIndex++] = kvp.Key;
}
public IEnumerator<T> GetEnumerator()
{
return d.Keys.GetEnumerator();
}
public bool Remove(T item)
{
return d.Remove(item);
}
IEnumerator IEnumerable.GetEnumerator()
{
return d.Keys.GetEnumerator();
}
public T GetAny()
{
if (d.Count == 0)
return null;
var e = d.Keys.GetEnumerator();
e.MoveNext();
return e.Current;
}
internal Set<T> Clone()
{
var other = new Set<T>();
foreach (var key in d.Keys)
other.d[key] = 0;
return other;
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using binary_library;
using libtysila5.target;
using metadata;
namespace libtysila5.layout
{
public partial class Layout
{
/* Vtable:
TIPtr (just to a glorified TypeSpec)
IFacePtr (to list of implemented interfaces)
Extends (to base classes for quick castclassex)
TypeSize (to allow MemberwiseClone to work without full Reflection)
Any target-specific data
Method 0
...
IFaceList TODO
*/
public static void OutputVTable(TypeSpec ts,
target.Target t, binary_library.IBinaryFile of,
TysilaState s,
MetadataStream base_m = null,
ISection os = null,
ISection data_sect = null)
{
// Don't compile if not for this architecture
if (!t.IsTypeValid(ts))
return;
/* New signature table */
s.sigt = new SignatureTable(ts.MangleType());
// If its a delegate type we also need to output its methods
if (ts.IsDelegate && !ts.IsGenericTemplate)
s.r.DelegateRequestor.Request(ts);
if(os == null)
os = of.GetRDataSection();
var d = os.Data;
var ptr_size = t.GetCTSize(ir.Opcode.ct_object);
os.Align(ptr_size);
ulong offset = (ulong)os.Data.Count;
/* Symbol */
var sym = of.CreateSymbol();
sym.Name = ts.MangleType();
sym.ObjectType = binary_library.SymbolObjectType.Object;
sym.Offset = offset;
sym.Type = binary_library.SymbolType.Global;
os.AddSymbol(sym);
if (base_m != null && ts.m != base_m)
sym.Type = SymbolType.Weak;
/* TIPtr */
var tiptr_offset = s.sigt.GetSignatureAddress(ts.Signature, t, s);
var ti_reloc = of.CreateRelocation();
ti_reloc.Addend = tiptr_offset;
ti_reloc.DefinedIn = os;
ti_reloc.Offset = offset;
ti_reloc.Type = t.GetDataToDataReloc();
ti_reloc.References = of.CreateSymbol();
ti_reloc.References.Name = s.sigt.GetStringTableName();
of.AddRelocation(ti_reloc);
for (int i = 0; i < ptr_size; i++, offset++)
d.Add(0);
/* IFacePtr */
IRelocation if_reloc = null;
if (!ts.IsGenericTemplate && !ts.IsInterface && ts.stype != TypeSpec.SpecialType.Ptr && ts.stype != TypeSpec.SpecialType.MPtr)
{
if_reloc = of.CreateRelocation();
if_reloc.DefinedIn = os;
if_reloc.Offset = offset;
if_reloc.Type = t.GetDataToDataReloc();
if_reloc.References = sym;
of.AddRelocation(if_reloc);
}
for (int i = 0; i < ptr_size; i++, offset++)
d.Add(0);
/* Extends */
var ts_extends = ts.GetExtends();
if(ts_extends != null)
{
var ext_reloc = of.CreateRelocation();
ext_reloc.Addend = 0;
ext_reloc.DefinedIn = os;
ext_reloc.Offset = offset;
ext_reloc.Type = t.GetDataToDataReloc();
var ext_sym = of.CreateSymbol();
ext_sym.Name = ts_extends.MangleType();
ext_reloc.References = ext_sym;
of.AddRelocation(ext_reloc);
s.r.VTableRequestor.Request(ts_extends);
}
for (int i = 0; i < ptr_size; i++, offset++)
d.Add(0);
if (ts.IsInterface || ts.IsGenericTemplate || ts.stype == TypeSpec.SpecialType.MPtr || ts.stype == TypeSpec.SpecialType.Ptr)
{
/* Type size is zero for somethinh we cannot
* instantiate */
for (int i = 0; i < ptr_size; i++, offset++)
d.Add(0);
/* Flags */
AddFlags(d, ts, ref offset, t);
/* BaseType */
AddBaseType(d, ts, of, os, ref offset, t, s);
// Target-specific information
t.AddExtraVTableFields(ts, d, ref offset);
}
else
{
/* Type size */
var tsize = t.IntPtrArray(BitConverter.GetBytes(GetTypeSize(ts, t)));
foreach (var b in tsize)
{
d.Add(b);
offset++;
}
/* Flags */
AddFlags(d, ts, ref offset, t);
/* BaseType */
AddBaseType(d, ts, of, os, ref offset, t, s);
// Target specific information
t.AddExtraVTableFields(ts, d, ref offset);
/* Virtual methods */
OutputVirtualMethods(ts, of, os,
d, ref offset, t, s);
/* Interface implementations */
// build list of implemented interfaces
var ii = ts.ImplementedInterfaces;
// first, add all interface implementations
List<ulong> ii_offsets = new List<ulong>();
for (int i = 0; i < ii.Count; i++)
{
ii_offsets.Add(offset - sym.Offset);
OutputInterface(ts, ii[i],
of, os, d, ref offset, t, s);
s.r.VTableRequestor.Request(ii[i]);
}
// point iface ptr here
if_reloc.Addend = (long)offset - (long)sym.Offset;
for (int i = 0; i < ii.Count; i++)
{
// list is pointer to interface declaration, then implementation
var id_ptr_sym = of.CreateSymbol();
id_ptr_sym.Name = ii[i].MangleType();
var id_ptr_reloc = of.CreateRelocation();
id_ptr_reloc.Addend = 0;
id_ptr_reloc.DefinedIn = os;
id_ptr_reloc.Offset = offset;
id_ptr_reloc.References = id_ptr_sym;
id_ptr_reloc.Type = t.GetDataToDataReloc();
of.AddRelocation(id_ptr_reloc);
for (int j = 0; j < ptr_size; j++, offset++)
d.Add(0);
// implementation
var ii_ptr_reloc = of.CreateRelocation();
ii_ptr_reloc.Addend = (long)ii_offsets[i];
ii_ptr_reloc.DefinedIn = os;
ii_ptr_reloc.Offset = offset;
ii_ptr_reloc.References = sym;
ii_ptr_reloc.Type = t.GetDataToDataReloc();
of.AddRelocation(ii_ptr_reloc);
for (int j = 0; j < ptr_size; j++, offset++)
d.Add(0);
}
// null terminate the list
for (int j = 0; j < ptr_size; j++, offset++)
d.Add(0);
}
sym.Size = (long)(offset - sym.Offset);
/* Output signature table if any */
if (data_sect == null)
data_sect = of.GetDataSection();
s.sigt.WriteToOutput(of, base_m, t, data_sect);
}
private static void AddBaseType(IList<byte> d, TypeSpec ts, IBinaryFile of, ISection os, ref ulong offset, Target t,
TysilaState s)
{
if(ts.other != null && ts.stype != TypeSpec.SpecialType.Boxed)
{
var bt = ts.other.Box;
var ext_reloc = of.CreateRelocation();
ext_reloc.Addend = 0;
ext_reloc.DefinedIn = os;
ext_reloc.Offset = offset;
ext_reloc.Type = t.GetDataToDataReloc();
var ext_sym = of.CreateSymbol();
ext_sym.Name = bt.MangleType();
ext_reloc.References = ext_sym;
of.AddRelocation(ext_reloc);
s.r.VTableRequestor.Request(bt);
}
for (int i = 0; i < t.GetPointerSize(); i++, offset++)
d.Add(0);
}
private static void AddFlags(IList<byte> d, TypeSpec ts, ref ulong offset, Target t)
{
/* VTbl flags - minimum necessary to get CanCast working without need
* for reflection */
uint flags = 0;
switch(ts.stype)
{
case TypeSpec.SpecialType.SzArray:
flags |= 1;
break;
case TypeSpec.SpecialType.Array:
flags |= 2;
// rank in next 8 bits
if (ts.arr_rank >= 256)
throw new Exception("Array rank too large");
flags |= (uint)ts.arr_rank << 8;
break;
case TypeSpec.SpecialType.MPtr:
flags |= 3;
break;
case TypeSpec.SpecialType.Ptr:
flags |= 4;
break;
}
for(int i = 0; i < t.GetPointerSize(); i++, offset++)
{
if (i < 4)
d.Add((byte)((flags >> (i * 8)) & 0xff));
else
d.Add(0);
}
}
public class InterfaceMethodImplementation
{
public MethodSpec InterfaceMethod;
public MethodSpec ImplementationMethod;
public string TargetName
{
get
{
if (ImplementationMethod == null)
return "__cxa_pure_virtual";
else
return ImplementationMethod.MangleMethod();
}
}
}
public static List<InterfaceMethodImplementation> ImplementInterface(
TypeSpec impl_ts, TypeSpec iface_ts, Target t, TysilaState s)
{
var ret = new List<InterfaceMethodImplementation>();
bool is_boxed = false;
if (impl_ts.IsBoxed)
{
impl_ts = impl_ts.Unbox;
is_boxed = true;
/* 'boxed' versions of each method should unbox the
* first parameter to a managed pointer then call
* the acutal method
*/
}
/* Iterate through methods */
var first_mdef = iface_ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
iface_ts.tdrow, 5);
var last_mdef = iface_ts.m.GetLastMethodDef(iface_ts.tdrow);
for (uint mdef_row = first_mdef; mdef_row < last_mdef; mdef_row++)
{
MethodSpec iface_ms;
MethodSpec impl_ms = null;
iface_ts.m.GetMethodDefRow(MetadataStream.tid_MethodDef,
(int)mdef_row, out iface_ms, iface_ts.gtparams, null);
iface_ms.type = iface_ts;
// First determine if there is a relevant MethodImpl entry
for (int i = 1; i <= impl_ts.m.table_rows[MetadataStream.tid_MethodImpl]; i++)
{
var Class = impl_ts.m.GetIntEntry(MetadataStream.tid_MethodImpl, i, 0);
if (Class == impl_ts.tdrow)
{
int mdecl_id, mdecl_row, mbody_id, mbody_row;
impl_ts.m.GetCodedIndexEntry(MetadataStream.tid_MethodImpl, i, 2,
impl_ts.m.MethodDefOrRef, out mdecl_id, out mdecl_row);
MethodSpec mdecl_ms;
impl_ts.m.GetMethodDefRow(mdecl_id, mdecl_row, out mdecl_ms, impl_ts.gtparams);
/*if (MetadataStream.CompareString(mdecl_ms.m,
mdecl_ms.m.GetIntEntry(MetadataStream.tid_MethodDef, mdecl_ms.mdrow, 3),
iface_ms.m,
iface_ms.m.GetIntEntry(MetadataStream.tid_MethodDef, iface_ms.mdrow, 3)) &&
MetadataStream.CompareSignature(mdecl_ms, iface_ms))*/
if(mdecl_ms.Equals(iface_ms))
{
impl_ts.m.GetCodedIndexEntry(MetadataStream.tid_MethodImpl, i, 1,
impl_ts.m.MethodDefOrRef, out mbody_id, out mbody_row);
impl_ts.m.GetMethodDefRow(mbody_id, mbody_row, out impl_ms, impl_ts.gtparams);
impl_ms.type = impl_ts;
break;
}
}
}
// Then iterate through all base classes looking for an implementation
if (impl_ms == null)
impl_ms = GetVirtualMethod(impl_ts, iface_ms, t, true);
// Vectors implement methods which we need to provide
if (impl_ms == null && impl_ts.stype == TypeSpec.SpecialType.SzArray)
{
// Build a new method that is based in the vector class
impl_ms = iface_ms;
impl_ms.type = new TypeSpec
{
m = impl_ts.m,
tdrow = impl_ts.tdrow,
stype = impl_ts.stype,
other = impl_ts.other,
gtparams = iface_ms.type.gtparams
};
}
if (impl_ms != null)
{
if (impl_ms.ReturnType != null && impl_ms.ReturnType.IsValueType && t.NeedsBoxRetType(impl_ms) && (iface_ms.ReturnType == null || (iface_ms.ReturnType != null && !iface_ms.ReturnType.IsValueType)))
{
impl_ms = impl_ms.Clone();
impl_ms.ret_type_needs_boxing = true;
s.r.BoxedMethodRequestor.Request(impl_ms);
}
if (is_boxed)
{
impl_ms.is_boxed = true;
s.r.BoxedMethodRequestor.Request(impl_ms);
}
else
s.r.MethodRequestor.Request(impl_ms);
}
ret.Add(new InterfaceMethodImplementation { InterfaceMethod = iface_ms, ImplementationMethod = impl_ms });
}
return ret;
}
// TODO: Use ImplementInterface
private static void OutputInterface(TypeSpec impl_ts,
TypeSpec iface_ts, IBinaryFile of, ISection os,
IList<byte> d, ref ulong offset, Target t,
TysilaState s)
{
bool is_boxed = false;
if(impl_ts.IsBoxed)
{
impl_ts = impl_ts.Unbox;
is_boxed = true;
/* 'boxed' versions of each method should unbox the
* first parameter to a managed pointer then call
* the acutal method
*/
}
/* Iterate through methods */
var first_mdef = iface_ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
iface_ts.tdrow, 5);
var last_mdef = iface_ts.m.GetLastMethodDef(iface_ts.tdrow);
for (uint mdef_row = first_mdef; mdef_row < last_mdef; mdef_row++)
{
MethodSpec iface_ms;
MethodSpec impl_ms = null;
iface_ts.m.GetMethodDefRow(MetadataStream.tid_MethodDef,
(int)mdef_row, out iface_ms, iface_ts.gtparams, null);
iface_ms.type = iface_ts;
// First determine if there is a relevant MethodImpl entry
for (int i = 1; i <= impl_ts.m.table_rows[MetadataStream.tid_MethodImpl]; i++)
{
var Class = impl_ts.m.GetIntEntry(MetadataStream.tid_MethodImpl, i, 0);
if (Class == impl_ts.tdrow)
{
int mdecl_id, mdecl_row, mbody_id, mbody_row;
impl_ts.m.GetCodedIndexEntry(MetadataStream.tid_MethodImpl, i, 2,
impl_ts.m.MethodDefOrRef, out mdecl_id, out mdecl_row);
MethodSpec mdecl_ms;
impl_ts.m.GetMethodDefRow(mdecl_id, mdecl_row, out mdecl_ms, impl_ts.gtparams);
if (mdecl_ms.Equals(iface_ms))
{
impl_ts.m.GetCodedIndexEntry(MetadataStream.tid_MethodImpl, i, 1,
impl_ts.m.MethodDefOrRef, out mbody_id, out mbody_row);
impl_ts.m.GetMethodDefRow(mbody_id, mbody_row, out impl_ms, impl_ts.gtparams);
impl_ms.type = impl_ts;
break;
}
}
}
// Then iterate through all base classes looking for an implementation
if (impl_ms == null)
impl_ms = GetVirtualMethod(impl_ts, iface_ms, t, true);
if (iface_ms.MangleMethod().StartsWith("_ZW30System#2ECollections#2EGeneric13IEnumerable`1_G1") && impl_ts.stype == TypeSpec.SpecialType.SzArray)
{
// Special case this so we get the generic IEnumerator<T> rather than the standard IEnumator from System.Array.GetEnumerator
// coreclr does something similar for _all_ T[] methods (see https://github.com/dotnet/coreclr/blob/release/2.0.0/src/mscorlib/src/System/Array.cs#L2577)
var szarrayhelper = iface_ms.m.GetTypeSpec("System", "SZArrayHelper");
var genum_ms = iface_ms.m.GetMethodSpec(szarrayhelper, "GetEnumerator");
genum_ms.gmparams = new TypeSpec[] { impl_ts.other };
s.r.MethodRequestor.Request(genum_ms);
impl_ms = genum_ms;
}
// Vectors implement methods which we need to provide
if (impl_ms == null && impl_ts.stype == TypeSpec.SpecialType.SzArray)
{
// Build a new method that is based in the vector class
impl_ms = iface_ms;
impl_ms.type = new TypeSpec
{
m = impl_ts.m,
tdrow = impl_ts.tdrow,
stype = impl_ts.stype,
other = impl_ts.other,
gtparams = iface_ms.type.gtparams
};
}
if(impl_ms != null)
{
if (impl_ms.ReturnType != null && impl_ms.ReturnType.IsValueType && t.NeedsBoxRetType(impl_ms) && (iface_ms.ReturnType == null || (iface_ms.ReturnType != null && !iface_ms.ReturnType.IsValueType)))
{
impl_ms = impl_ms.Clone();
impl_ms.ret_type_needs_boxing = true;
s.r.BoxedMethodRequestor.Request(impl_ms);
}
else if (is_boxed)
{
impl_ms.is_boxed = true;
s.r.BoxedMethodRequestor.Request(impl_ms);
}
else
s.r.MethodRequestor.Request(impl_ms);
}
// Output reference
string impl_target = (impl_ms == null) ? "__cxa_pure_virtual" : impl_ms.MangleMethod();
//if(impl_ms == null)
//{
// System.Diagnostics.Debugger.Break();
// var test = GetVirtualMethod(impl_ts, iface_ms, t, true);
//}
var impl_sym = of.CreateSymbol();
impl_sym.Name = impl_target;
impl_sym.ObjectType = SymbolObjectType.Function;
var impl_reloc = of.CreateRelocation();
impl_reloc.Addend = 0;
impl_reloc.DefinedIn = os;
impl_reloc.Offset = offset;
impl_reloc.References = impl_sym;
impl_reloc.Type = t.GetDataToCodeReloc();
of.AddRelocation(impl_reloc);
for (int i = 0; i < t.GetPointerSize(); i++, offset++)
d.Add(0);
}
}
private static void OutputVirtualMethods(TypeSpec decl_ts,
IBinaryFile of, ISection os,
IList<byte> d, ref ulong offset, target.Target t,
TysilaState s)
{
var vmeths = GetVirtualMethodDeclarations(decl_ts);
ImplementVirtualMethods(decl_ts, vmeths);
foreach(var vmeth in vmeths)
{
var impl_ms = vmeth.impl_meth;
string impl_target = (impl_ms == null) ? "__cxa_pure_virtual" : impl_ms.MethodReferenceAlias;
var impl_sym = of.CreateSymbol();
impl_sym.Name = impl_target;
impl_sym.ObjectType = SymbolObjectType.Function;
var impl_reloc = of.CreateRelocation();
impl_reloc.Addend = 0;
impl_reloc.DefinedIn = os;
impl_reloc.Offset = offset;
impl_reloc.References = impl_sym;
impl_reloc.Type = t.GetDataToCodeReloc();
of.AddRelocation(impl_reloc);
for (int i = 0; i < t.GetPointerSize(); i++, offset++)
d.Add(0);
if (impl_ms != null)
s.r.MethodRequestor.Request(impl_ms);
}
}
public class VTableItem
{
public MethodSpec unimpl_meth; // the declaration site of the method
internal TypeSpec max_implementor; // the most derived class the method can possibly be implemented in
public MethodSpec impl_meth; // the implementation of the method
public override string ToString()
{
if (unimpl_meth == null)
return "{null}";
else if (impl_meth == null)
return unimpl_meth.ToString();
else
return unimpl_meth.ToString() + " (" + impl_meth.ToString() + ")";
}
internal VTableItem Clone()
{
return new VTableItem
{
unimpl_meth = unimpl_meth,
max_implementor = max_implementor,
impl_meth = impl_meth
};
}
}
static Dictionary<TypeSpec, List<VTableItem>> vmeth_list_cache =
new Dictionary<TypeSpec, List<VTableItem>>(
new GenericEqualityComparer<TypeSpec>());
public static List<VTableItem> GetVirtualMethodDeclarations(TypeSpec ts)
{
List<VTableItem> ret;
if (vmeth_list_cache.TryGetValue(ts, out ret))
return ret;
var extends = ts.GetExtends();
ret = new List<VTableItem>();
if (extends != null)
{
var base_list = GetVirtualMethodDeclarations(extends);
foreach(var base_item in base_list)
{
ret.Add(base_item.Clone());
}
}
/* Iterate through methods looking for virtual ones */
var first_mdef = ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
ts.tdrow, 5);
var last_mdef = ts.m.GetLastMethodDef(ts.tdrow);
for (uint mdef_row = first_mdef; mdef_row < last_mdef; mdef_row++)
{
var flags = ts.m.GetIntEntry(MetadataStream.tid_MethodDef,
(int)mdef_row, 2);
if((flags & 0x40) == 0x40)
{
// This is a virtual method
MethodSpec decl_ms;
ts.m.GetMethodDefRow(MetadataStream.tid_MethodDef,
(int)mdef_row, out decl_ms, ts.gtparams, null);
decl_ms.type = ts;
int cur_tab_idx = GetVTableIndex(decl_ms, ret);
if(cur_tab_idx == -1)
{
// This is not overriding anything, so give it a new slot (newslot is ignored)
ret.Add(new VTableItem { unimpl_meth = decl_ms, max_implementor = null });
}
else
{
// This is overriding something. We only assign a new slot if newslot is set
if((flags & 0x100) == 0x100)
{
// If newslot, then the old item is left untouched, and particularly it is
// only implemented by a method up to that point in the inheritance chain
ret.Add(new VTableItem { unimpl_meth = decl_ms, max_implementor = null });
ret[cur_tab_idx].max_implementor = extends;
}
else
{
// if not, then override the original slot
ret[cur_tab_idx].unimpl_meth = decl_ms;
}
}
}
}
vmeth_list_cache[ts] = ret;
return ret;
}
public static void ImplementVirtualMethods(TypeSpec ts, List<VTableItem> list)
{
// We implement those methods in the most derived class first and work back
foreach (var i in list)
{
// skip if already done
if (i.impl_meth != null)
continue;
// if we've gone back far enough to the max_implementor class
// we can start looking for implementations from here
if (i.max_implementor != null && i.max_implementor.Equals(ts))
i.max_implementor = null;
// if we haven't, skip this method for this class (it will be
// implemented in a base class)
if (i.max_implementor != null)
continue;
// Now, search for a matching method in this particular class
/* Iterate through methods looking for virtual ones */
var first_mdef = ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
ts.tdrow, 5);
var last_mdef = ts.m.GetLastMethodDef(ts.tdrow);
var search_meth_name = i.unimpl_meth.m.GetIntEntry(MetadataStream.tid_MethodDef,
i.unimpl_meth.mdrow, 3);
for (uint mdef_row = first_mdef; mdef_row < last_mdef; mdef_row++)
{
var flags = ts.m.GetIntEntry(MetadataStream.tid_MethodDef,
(int)mdef_row, 2);
if ((flags & 0x40) == 0x40)
{
// its a virtual method
MethodSpec impl_ms;
ts.m.GetMethodDefRow(MetadataStream.tid_MethodDef,
(int)mdef_row, out impl_ms, ts.gtparams, null);
impl_ms.type = ts;
// compare on name
if (MetadataStream.CompareString(i.unimpl_meth.m, search_meth_name,
ts.m, ts.m.GetIntEntry(MetadataStream.tid_MethodDef, (int)mdef_row, 3)))
{
// and on signature
if (MetadataStream.CompareSignature(i.unimpl_meth, impl_ms))
{
// If its marked abstract, we dont implement it
if ((flags & 0x400) == 0x400)
{
i.impl_meth = null;
}
else
{
// we have found a valid implementing method
i.impl_meth = impl_ms;
}
}
}
}
}
}
// now implement on base classes
var extends = ts.GetExtends();
if (extends != null)
ImplementVirtualMethods(extends, list);
}
private static int GetVTableIndex(MethodSpec ms, List<VTableItem> list)
{
for(int idx = 0; idx < list.Count; idx++)
{
var i = list[idx];
if (MetadataStream.CompareString(ms.m, ms.m.GetIntEntry(MetadataStream.tid_MethodDef, ms.mdrow, 3),
i.unimpl_meth.m, i.unimpl_meth.m.GetIntEntry(MetadataStream.tid_MethodDef, i.unimpl_meth.mdrow, 3)))
{
if(MetadataStream.CompareSignature(ms, i.unimpl_meth))
{
return idx;
}
}
}
return -1;
}
private static MethodSpec GetVirtualMethod(TypeSpec impl_ts, MethodSpec decl_ms,
target.Target t, bool allow_non_virtual = false)
{
/* Iterate through methods looking for virtual ones */
var first_mdef = impl_ts.m.GetIntEntry(MetadataStream.tid_TypeDef,
impl_ts.tdrow, 5);
var last_mdef = impl_ts.m.GetLastMethodDef(impl_ts.tdrow);
for (uint mdef_row = first_mdef; mdef_row < last_mdef; mdef_row++)
{
var flags = impl_ts.m.GetIntEntry(MetadataStream.tid_MethodDef,
(int)mdef_row, 2);
if (allow_non_virtual || (flags & 0x40) == 0x40)
{
MethodSpec impl_ms;
impl_ts.m.GetMethodDefRow(MetadataStream.tid_MethodDef,
(int)mdef_row, out impl_ms, impl_ts.gtparams, null);
impl_ms.type = impl_ts;
if ((flags & 0x400) != 0x400)
{
// Not marked abstract
if (MetadataStream.CompareString(impl_ms.m,
impl_ms.m.GetIntEntry(MetadataStream.tid_MethodDef, (int)mdef_row, 3),
decl_ms.m,
decl_ms.m.GetIntEntry(MetadataStream.tid_MethodDef, (int)decl_ms.mdrow, 3)))
{
if (MetadataStream.CompareSignature(impl_ms.m, impl_ms.msig,
impl_ts.gtparams, null,
decl_ms.m, decl_ms.msig, impl_ts.gtparams, null))
{
// this is the correct one
return impl_ms;
}
if (MetadataStream.CompareSignature(impl_ms.m, impl_ms.msig,
impl_ts.gtparams, null,
decl_ms.m, decl_ms.msig, decl_ms.gtparams, null))
{
// this is the correct one
return impl_ms;
}
}
}
}
}
// if not found, look to base classes
var bc = impl_ts.GetExtends();
if (bc != null)
return GetVirtualMethod(bc, decl_ms, t, allow_non_virtual);
else
return null;
}
public static int GetVTableOffset(metadata.MethodSpec ms, Target t)
{ return GetVTableOffset(ms.type, ms, t); }
public static int GetVTableOffset(metadata.TypeSpec ts,
metadata.MethodSpec ms, Target t)
{
var vtbl = GetVirtualMethodDeclarations(ts);
var search_meth_name = ms.m.GetIntEntry(MetadataStream.tid_MethodDef,
ms.mdrow, 3);
// find the requested method, match on name, signature and declaring type
for(int i = 0; i < vtbl.Count; i++)
{
var test = vtbl[i];
var mdecl = test.unimpl_meth;
if(mdecl.type.Equals(ts))
{
// Check on name
var mname = mdecl.m.GetIntEntry(MetadataStream.tid_MethodDef,
mdecl.mdrow, 3);
if (MetadataStream.CompareString(mdecl.m, mname,
ms.m, search_meth_name))
{
// Check on signature
if (MetadataStream.CompareSignature(mdecl.m, mdecl.msig,
mdecl.gtparams, mdecl.gmparams,
ms.m, ms.msig, ms.gtparams, ms.gmparams))
{
if (ts.IsInterface == false)
i += (6 + t.ExtraVTableFieldsPointerLength);
return i;
}
}
}
}
throw new Exception("Requested virtual method slot not found");
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class RemovePrecedingAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (console.CursorPosition > 0)
{
console.CurrentLine = console.CurrentLine.Remove(0, console.CursorPosition);
console.CursorPosition = 0;
}
}
}
}
<file_sep>
using System;
using System.Globalization;
namespace ConsoleUtils.ConsoleActions
{
public class AutoCompleteUsingPreviousLinesAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (!console.PreviousLineBuffer.HasLines)
return;
var pattern = console.CurrentLine.Substring(0, console.CursorPosition);
console.CurrentLine = pattern + AutoCompleteUsingPreviousLines(console, pattern);
}
private string AutoCompleteUsingPreviousLines(IConsole console, string pattern)
{
var previousLineBuffer = console.PreviousLineBuffer;
previousLineBuffer.CycleUpAndAround();
for (var i = previousLineBuffer.Index; i >= 0; i--)
{
var previousLine = previousLineBuffer.PreviousLines[i];
if (previousLine.StartsWith(pattern, false, CultureInfo.InvariantCulture))
{
previousLineBuffer.Index = i;
return previousLine.Remove(0, pattern.Length);
}
}
for (var i = previousLineBuffer.PreviousLines.Count - 1; i > previousLineBuffer.Index; i--)
{
var previousLine = previousLineBuffer.PreviousLines[i];
if (previousLine.StartsWith(pattern, false, CultureInfo.InvariantCulture))
{
previousLineBuffer.Index = i;
return previousLine.Remove(0, pattern.Length);
}
}
return string.Empty;
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Text;
using libtysila5.cil;
using metadata;
using libtysila5.util;
namespace libtysila5.ir
{
public class AllocRegs
{
public static void DoAllocation(Code c)
{
foreach(var n in c.ir)
{
DoAllocation(c, n.stack_before, c.t);
DoAllocation(c, n.stack_after, c.t);
}
}
internal static target.Target.Reg DoAllocation(Code c, int ct, target.Target t, ref long alloced, ref int cur_stack)
{
// rationalise thread-local addresses to use the same registers as normal ones
if (ct == Opcode.ct_tls_int32)
ct = Opcode.ct_int32;
else if (ct == Opcode.ct_tls_int64)
ct = Opcode.ct_int64;
else if (ct == Opcode.ct_tls_intptr)
ct = Opcode.ct_intptr;
long avail = t.ct_regs[ct] & ~alloced;
if (avail != 0)
{
// We have a valid allocation to use
int idx = 0;
while ((avail & 0x1) == 0)
{
idx++;
avail >>= 1;
}
var reg = t.regs[idx];
alloced |= (1L << idx);
return reg;
}
else
{
return t.AllocateStackLocation(c, t.GetCTSize(ct), ref cur_stack);
}
}
protected static target.Target.Reg DoAllocation(Code c, StackItem si, target.Target t, ref long alloced, ref int cur_stack)
{
si.reg = DoAllocation(c, si.ct, t, ref alloced, ref cur_stack);
return si.reg;
}
private static void DoAllocation(Code c, Stack<StackItem> stack, target.Target t)
{
long alloced = 0;
int stack_loc = 0;
foreach(var si in stack)
{
if (si.ct == Opcode.ct_vt)
{
si.reg = t.AllocateValueType(c, si.ts, ref alloced, ref stack_loc);
}
else if(si.has_address_taken)
{
int size = 0;
if (si.ts.IsValueType)
size = layout.Layout.GetTypeSize(si.ts, t, false);
else
size = t.GetPointerSize();
si.reg = t.AllocateStackLocation(c, size, ref stack_loc);
}
else
DoAllocation(c, si, t, ref alloced, ref stack_loc);
if (si.reg != null)
c.regs_used |= si.reg.mask;
}
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using binary_library;
using libtysila5.ir;
using libtysila5.util;
using metadata;
namespace libtysila5.target.x86
{
partial class x86_Assembler : Target
{
static x86_Assembler()
{
init_instrs();
}
bool has_cpu_feature(string name)
{
// get cpu family, model, stepping
int family = 0;
#if HAVE_SYSTEM
var lvls = Environment.GetEnvironmentVariable("PROCESSOR_LEVEL");
if(lvls != null)
{
int.TryParse(lvls, out family);
}
#endif
int model = 0;
int stepping = 0;
#if HAVE_SYSTEM
var rev = Environment.GetEnvironmentVariable("PROCESSOR_REVISION");
if(rev != null)
{
if(rev.Length == 4)
{
string mods = rev.Substring(0, 2);
string steps = rev.Substring(2, 2);
int.TryParse(mods, System.Globalization.NumberStyles.HexNumber, null, out model);
int.TryParse(steps, System.Globalization.NumberStyles.HexNumber, null, out stepping);
}
}
#endif
bool is_amd64 = false;
#if HAVE_SYSTEM
var parch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
if (parch != null && parch == "AMD64")
is_amd64 = true;
#endif
if(name == "sse2")
{
if (is_amd64)
return true;
if (family == 6 || family == 15)
return true;
return false;
}
if(name == "sse4_1")
{
if (family == 6 && model >= 6)
return true;
return false;
}
throw new NotImplementedException();
}
void init_cpu_feature_option(string s)
{
Options.InternalAdd(s, has_cpu_feature(s));
}
protected void init_options()
{
// cpu features
init_cpu_feature_option("sse4_1");
Options.InternalAdd("mcmodel", "small");
}
public override void InitIntcalls()
{
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs12IoOperations_7PortOut_Rv_P2th"] = portout_byte;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs12IoOperations_7PortOut_Rv_P2tt"] = portout_word;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs12IoOperations_7PortOut_Rv_P2tj"] = portout_dword;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs12IoOperations_7PortInb_Rh_P1t"] = portin_byte;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs12IoOperations_7PortInw_Rt_P1t"] = portin_word;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs12IoOperations_7PortInd_Rj_P1t"] = portin_dword;
ConvertToIR.intcalls["_ZW6System4Math_5Round_Rd_P1d"] = math_Round;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_27EnterUninterruptibleSection_Ru1I_P0"] = enter_cli;
ConvertToIR.intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_26ExitUninterruptibleSection_Rv_P1u1I"] = exit_cli;
}
private static util.Stack<StackItem> enter_cli(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Push(new StackItem { ts = c.ms.m.SystemIntPtr });
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_target_specific, imm_l = x86_enter_cli, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static util.Stack<StackItem> exit_cli(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_target_specific, imm_l = x86_exit_cli, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static util.Stack<StackItem> math_Round(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
var old = stack_after.Pop();
// propagate immediate value if there is one
double min_imm = Math.Round(BitConverter.ToDouble(BitConverter.GetBytes(old.min_ul), 0));
double max_imm = Math.Round(BitConverter.ToDouble(BitConverter.GetBytes(old.max_ul), 0));
stack_after.Push(new StackItem { ts = c.ms.m.GetSimpleTypeSpec(0xd), min_ul = BitConverter.ToUInt64(BitConverter.GetBytes(min_imm), 0), max_ul = BitConverter.ToUInt64(BitConverter.GetBytes(max_imm), 0) });
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_target_specific, imm_l = x86_roundsd_xmm_xmmm64_imm8, stack_before = stack_before, stack_after = stack_after, arg_a = 0, res_a = 0 });
return stack_after;
}
private static util.Stack<StackItem> portin_byte(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemByte, min_ul = 0, max_ul = 255 });
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_x86_portin, vt_size = 1, stack_before = stack_before, stack_after = stack_after, arg_a = 0, res_a = 0 });
return stack_after;
}
private static util.Stack<StackItem> portin_word(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemUInt16, min_ul = 0, max_ul = ushort.MaxValue });
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_x86_portin, vt_size = 2, stack_before = stack_before, stack_after = stack_after, arg_a = 0, res_a = 0 });
return stack_after;
}
private static util.Stack<StackItem> portin_dword(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemUInt32, min_ul = 0, max_ul = uint.MaxValue });
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_x86_portin, vt_size = 4, stack_before = stack_before, stack_after = stack_after, arg_a = 0, res_a = 0 });
return stack_after;
}
private static util.Stack<StackItem> portout_byte(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_x86_portout, vt_size = 1, stack_before = stack_before, stack_after = stack_after, arg_a = 1, arg_b = 0 });
return stack_after;
}
private static util.Stack<StackItem> portout_word(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_x86_portout, vt_size = 2, stack_before = stack_before, stack_after = stack_after, arg_a = 1, arg_b = 0 });
return stack_after;
}
private static util.Stack<StackItem> portout_dword(cil.CilNode n, Code c, util.Stack<StackItem> stack_before)
{
var stack_after = new util.Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_x86_portout, vt_size = 4, stack_before = stack_before, stack_after = stack_after, arg_a = 1, arg_b = 0 });
return stack_after;
}
protected internal override Reg GetMoveDest(MCInst i)
{
return i.p[1].mreg;
}
protected internal override Reg GetMoveSrc(MCInst i)
{
return i.p[2].mreg;
}
protected internal override int GetCondCode(MCInst i)
{
if (i.p == null || i.p.Length < 2 ||
i.p[1].t != Opcode.vl_cc)
return Opcode.cc_always;
return (int)i.p[1].v;
}
protected internal override bool IsBranch(MCInst i)
{
if (i.p != null && i.p.Length > 0 &&
i.p[0].t == Opcode.vl_str &&
(i.p[0].v == x86_jmp_rel32 ||
i.p[0].v == x86_jcc_rel32))
return true;
return false;
}
protected internal override bool IsCall(MCInst i)
{
if (i.p != null && i.p.Length > 0 &&
i.p[0].t == Opcode.vl_str &&
(i.p[0].v == x86_call_rel32))
return true;
return false;
}
protected internal override void SetBranchDest(MCInst i, int d)
{
if (!IsBranch(i))
throw new NotSupportedException();
if (i.p[0].v == x86_jcc_rel32)
i.p[2] = new Param { t = Opcode.vl_br_target, v = d };
else
i.p[1] = new Param { t = Opcode.vl_br_target, v = d };
}
protected internal override int GetBranchDest(MCInst i)
{
if (!IsBranch(i))
throw new NotSupportedException();
if (i.p[0].v == x86_jcc_rel32)
return (int)i.p[2].v;
else
return (int)i.p[1].v;
}
protected internal override MCInst SaveRegister(Reg r)
{
MCInst ret = new MCInst
{
p = new Param[]
{
new Param { t = Opcode.vl_str, str = "push", v = x86_push_r32 },
new Param { t = Opcode.vl_mreg, mreg = r }
}
};
return ret;
}
protected internal override MCInst RestoreRegister(Reg r)
{
MCInst ret = new MCInst
{
p = new Param[]
{
new Param { t = Opcode.vl_str, str = "pop", v = x86_pop_r32 },
new Param { t = Opcode.vl_mreg, mreg = r }
}
};
return ret;
}
/* Access to variables on the incoming stack is encoded as -address - 1 */
protected internal override Reg GetLVLocation(int lv_loc, int lv_size, Code c)
{
if (Opcode.GetCTFromType(c.ret_ts) == Opcode.ct_vt)
lv_loc += psize;
int disp = 0;
disp = -lv_size - lv_loc;
return new ContentsReg
{
basereg = r_ebp,
disp = disp,
size = lv_size
};
}
/* Access to variables on the incoming stack is encoded as -address - 1 */
protected internal override Reg GetLALocation(int la_loc, int la_size, Code c)
{
if (Opcode.GetCTFromType(c.ret_ts) == Opcode.ct_vt)
la_loc += psize;
return new ContentsReg
{
basereg = r_ebp,
disp = la_loc + 2 * psize,
size = la_size
};
}
protected internal override MCInst[] CreateMove(Reg src, Reg dest)
{
throw new NotImplementedException();
}
protected internal override MCInst[] SetupStack(int lv_size)
{
if (lv_size == 0)
return new MCInst[0];
else
return new MCInst[]
{
new MCInst { p = new Param[]
{
new Param { t = Opcode.vl_str, str = "sub", v = x86_sub_rm32_imm32 },
new Param { t = Opcode.vl_mreg, mreg = r_esp },
new Param { t = Opcode.vl_mreg, mreg = r_esp },
new Param { t = Opcode.vl_c, v = lv_size }
} }
};
}
protected internal override IRelocationType GetDataToDataReloc()
{
return new binary_library.elf.ElfFile.Rel_386_32();
}
protected internal override IRelocationType GetDataToCodeReloc()
{
return new binary_library.elf.ElfFile.Rel_386_32();
}
public override Reg AllocateStackLocation(Code c, int size, ref int cur_stack)
{
size = util.util.align(size, psize);
cur_stack -= size;
if (-cur_stack > c.stack_total_size)
c.stack_total_size = -cur_stack;
return new ContentsReg { basereg = r_ebp, disp = cur_stack - c.lv_total_size, size = size };
}
protected internal override int GetCTFromTypeForCC(TypeSpec t)
{
if (t.Equals(t.m.SystemRuntimeTypeHandle) || t.Equals(t.m.SystemRuntimeMethodHandle) ||
t.Equals(t.m.SystemRuntimeFieldHandle))
return ir.Opcode.ct_int32;
return base.GetCTFromTypeForCC(t);
}
protected internal override bool NeedsBoxRetType(MethodSpec ms)
{
if (Opcode.GetCTFromType(ms.ReturnType) == Opcode.ct_vt)
return true;
else
return false;
}
protected internal override Code AssembleBoxRetTypeMethod(MethodSpec ms, TysilaState s)
{
// Move all parameters up one - this will require knowledge of the param locs
// if the return type is an object (to get the 'from' locations) and
// knowledge of the param locs in the target method (the 'to' locations)
// Allocate space on heap (boxed return object)
var cc = cc_map[ms.CallingConvention];
var cc_class_map = cc_classmap[ms.CallingConvention];
int stack_loc = 0;
var from_locs = GetRegLocs(new ir.Param
{
m = ms.m,
ms = ms,
}, ref stack_loc, cc, cc_class_map,
ms.CallingConvention,
out var from_sizes, out var from_types,
null);
stack_loc = 0;
var to_locs = GetRegLocs(new ir.Param
{
m = ms.m,
ms = ms,
}, ref stack_loc, cc, cc_class_map,
ms.CallingConvention,
out var to_sizes, out var to_types,
ms.m.SystemIntPtr);
// Generate code
var c = new Code();
c.mc = new List<MCInst>();
c.s = s;
var n = new cil.CilNode(ms, 0);
var ir = new cil.CilNode.IRNode { parent = n, mc = c.mc };
ir.opcode = Opcode.oc_nop;
n.irnodes.Add(ir);
c.starts = new List<cil.CilNode>();
c.starts.Add(n);
c.ms = ms;
c.t = this;
// copy from[0:n] to to[1:n+1] in reverse order so
// we don't overwrite the previous registers
ulong defined = 0;
for(int i = from_locs.Length - 1; i >= 0 ; i--)
{
handle_move(to_locs[i + 1], from_locs[i], c.mc, ir, c, x86_64.x86_64_Assembler.r_rax, from_sizes[i]);
defined |= to_locs[i + 1].mask;
}
// call gcmalloc with the size of the boxed version of the return
// type
var ts = ms.ReturnType;
var tsize = GetSize(ts);
var sysobj_size = layout.Layout.GetTypeSize(c.ms.m.SystemObject, c.t);
var boxed_size = util.util.align(sysobj_size + tsize, psize);
// decide on the registers we need to save around gcmalloc
var caller_preserves = cc_caller_preserves_map[ms.CallingConvention];
var to_push = new util.Set();
to_push.Union(defined);
to_push.Intersect(caller_preserves);
List<Reg> push_list = new List<Reg>();
while (!to_push.Empty)
{
var first_set = to_push.get_first_set();
push_list.Add(c.t.regs[first_set]);
to_push.unset(first_set);
}
int push_length = 0;
foreach(var r in push_list)
{
handle_push(r, ref push_length, c.mc, ir, c);
}
c.mc.Add(inst(x86_call_rel32, new Param { t = Opcode.vl_call_target, str = "gcmalloc" },
new Param { t = Opcode.vl_c32, v = boxed_size }, ir));
for (int i = push_list.Count - 1; i >= 0; i--)
handle_pop(push_list[i], ref push_length, c.mc, ir, c);
// put vtable pointer into gcmalloc result
c.mc.Add(inst(x86_mov_rm32_lab, new ContentsReg { basereg = r_eax, size = 4 },
new Param { t = Opcode.vl_str, str = ts.MangleType() }, ir));
// put rax into to[0]
handle_move(to_locs[0], r_eax, c.mc, ir, c);
// unbox to[0] (i.e. increment pointer so it points to the inner data)
c.mc.Add(inst(psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, to_locs[0], sysobj_size, ir));
// call the actual function (see AssembleBoxedMethod below)
var unboxed = ms.Unbox;
var act_meth = unboxed.MangleMethod();
s.r.MethodRequestor.Request(unboxed);
// Save rax around the call and return it
// We do this because the actual method returns the address of a value type in rax
// and we want to return the address of the boxed object instead
c.mc.Add(inst(x86_push_r32, r_eax, ir));
c.mc.Add(inst(x86_call_rel32, new Param { t = Opcode.vl_str, str = act_meth }, ir));
c.mc.Add(inst(x86_pop_r32, r_eax, ir));
c.mc.Add(inst(x86_ret, ir));
return c;
}
protected internal override Code AssembleBoxedMethod(MethodSpec ms, TysilaState s)
{
/* To unbox, we simply add the size of system.object to
* first argument, then jmp to the actual method
*/
var c = new Code();
c.mc = new List<MCInst>();
c.s = s;
var this_reg = psize == 4 ? new ContentsReg { basereg = r_ebp, disp = 8, size = 4 } : x86_64.x86_64_Assembler.r_rdi;
var sysobjsize = layout.Layout.GetTypeSize(ms.m.SystemObject, this);
c.mc.Add(inst(psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, this_reg, sysobjsize, null));
var unboxed = ms.Unbox;
var act_meth = unboxed.MangleMethod();
c.s.r.MethodRequestor.Request(unboxed);
c.mc.Add(inst(x86_jmp_rel32, new Param { t = Opcode.vl_str, str = act_meth }, null));
return c;
}
public override bool AddDwarfLocation(Reg r, IList<byte> d)
{
if (r is ContentsReg)
{
var cr = r as ContentsReg;
if (cr.basereg.Equals(r_ebp))
{
if (psize == 4)
d.Add(0x75); // breg5
else
d.Add(0x76); // breg6
dwarf.DwarfDIE.w(d, (int)cr.disp);
return true;
}
}
return false;
}
}
}
namespace libtysila5.target.x86_64
{
partial class x86_64_Assembler : x86.x86_Assembler
{
protected internal override IRelocationType GetDataToCodeReloc()
{
return new binary_library.elf.ElfFile.Rel_x86_64_64();
}
protected internal override IRelocationType GetDataToDataReloc()
{
return new binary_library.elf.ElfFile.Rel_x86_64_64();
}
public override int GetCCClassFromCT(int ct, int size, TypeSpec ts, string cc)
{
if (cc == "sysv" | cc == "default")
{
switch (ct)
{
case Opcode.ct_vt:
// breaks spec - need to only use MEMORY for those more than 32 bytes
// but we don't wupport splitting arguments up yet
return sysvc_MEMORY;
}
}
else
{
throw new NotImplementedException();
}
return base.GetCCClassFromCT(ct, size, ts, cc);
}
/* runtime handles are void* pointers - we use the following to ensure they are passed in
* registers rather than on the stack */
protected internal override int GetCTFromTypeForCC(TypeSpec t)
{
if (t.Equals(t.m.SystemRuntimeTypeHandle) || t.Equals(t.m.SystemRuntimeMethodHandle) ||
t.Equals(t.m.SystemRuntimeFieldHandle))
return ir.Opcode.ct_int64;
return base.GetCTFromTypeForCC(t);
}
protected override Reg GetRegLoc(Param csite, ref int stack_loc, int cc_next, int ct, TypeSpec ts, string cc)
{
if(cc == "isr")
{
/* ISR with error codes have stack as:
*
* cur_rax - pushed at start of isr so we have a scratch reg [rbp-8]
* this is exchanged with the regs pointer as part of the init phase
* old_rbp - pushed at start as part of push ebp; mov ebp, esp sequence [rbp]
* ret_rip - [rbp + 8]
* ret_cs - [rbp + 16]
* rflags - [rbp + 24]
* ret_rsp - [rbp + 32]
* ret_ss - [rbp + 40]
*/
switch (cc_next)
{
case 0:
case 1:
case 2:
case 3:
case 4:
return new ContentsReg { basereg = r_ebp, disp = 8 + 8 * cc_next, size = 8 };
case 5:
return new ContentsReg { basereg = r_ebp, disp = -8, size = 8 };
}
}
else if(cc == "isrec")
{
/* ISR with error codes have stack as:
*
* cur_rax - pushed at start of isr so we have a scratch reg [rbp-8]
* this is exchanged with the regs pointer as part of the init phase
* old_rbp - pushed at start as part of push ebp; mov ebp, esp sequence [rbp]
* error_code - [rbp + 8]
* ret_rip - [rbp + 16]
* ret_cs - [rbp + 24]
* rflags - [rbp + 32]
* ret_rsp - [rbp + 40]
* ret_ss - [rbp + 48]
*/
switch(cc_next)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
return new ContentsReg { basereg = r_ebp, disp = 8 + 8 * cc_next, size = 8 };
case 6:
return new ContentsReg { basereg = r_ebp, disp = -8, size = 8 };
}
}
return base.GetRegLoc(csite, ref stack_loc, cc_next, ct, ts, cc);
}
internal override int GetCCStackReserve(string cc)
{
// isrs use stack space for the address of the regs array
if (cc == "isr" || cc == "isrec")
return psize;
else
return base.GetCCStackReserve(cc);
}
protected internal override void AddExtraVTableFields(TypeSpec ts, IList<byte> d, ref ulong offset)
{
// Unboxed versions here (all VTables refer to boxed types by definition as only these
// have a vtbl, however for Invoke et al we want to unbox members of the object[] array)
if (ts.IsBoxed)
ts = ts.Unbox;
// We add the SysV ABI calling convention class code here
int size;
if (ts.IsInterface || ts.IsGenericTemplate || ts.stype == TypeSpec.SpecialType.MPtr || ts.stype == TypeSpec.SpecialType.Ptr)
{
size = 0;
}
else
{
size = GetSize(ts);
}
var cmap = cc_classmap["sysv"];
var ct = GetCTFromTypeForCC(ts);
int class_code;
if (cmap.ContainsKey(ct))
class_code = cmap[ct];
else
class_code = GetCCClassFromCT(ct, size, ts, "sysv");
switch(class_code)
{
case sysvc_INTEGER:
d.Add(0);
break;
case sysvc_SSE:
d.Add(2);
break;
case sysvc_MEMORY:
d.Add(3);
break;
default:
throw new NotSupportedException();
}
// Now add the ct type encoded as class code (see libsupcs/x86_64_invoke.cs)
switch(ct)
{
case Opcode.ct_float:
d.Add(2);
break;
case Opcode.ct_int32:
d.Add(4);
break;
case Opcode.ct_int64:
case Opcode.ct_intptr:
d.Add(1);
break;
case Opcode.ct_object:
case Opcode.ct_ref:
d.Add(0);
break;
case Opcode.ct_vt:
d.Add(0);
break;
default:
throw new NotSupportedException();
}
// Now the simple type
d.Add((byte)ts.SimpleType);
// Pad with 5 zeros
for (int i = 0; i < 5; i++)
d.Add(0);
offset += 8;
}
protected internal override int ExtraVTableFieldsPointerLength => 1;
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs
{
public class Array
{
[MethodAlias("_ZW6System5Array_4Copy_Rv_P6V5ArrayiV5Arrayiib")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void Copy(void* srcArr, int srcIndex, void* dstArr, int dstIndex, int length,
bool reliable)
{
/* Ensure arrays are valid */
if (srcArr == null || dstArr == null)
throw new ArgumentNullException();
/* Ensure length is valid */
if (length < 0)
throw new ArgumentOutOfRangeException();
/* Ensure both arrays are of the same rank */
var srcRank = *(int*)((byte*)srcArr + ArrayOperations.GetRankOffset());
var dstRank = *(int*)((byte*)dstArr + ArrayOperations.GetRankOffset());
if (srcRank != dstRank)
throw new RankException();
/* Get source and dest element types */
var srcET = *(void**)((byte*)srcArr + ArrayOperations.GetElemTypeOffset());
var dstET = *(void**)((byte*)dstArr + ArrayOperations.GetElemTypeOffset());
/* See if we can do a quick copy */
bool can_quick_copy = false;
if (srcET == dstET)
can_quick_copy = true;
else if (TysosType.CanCast(srcET, dstET))
can_quick_copy = true;
else if (reliable)
throw new ArrayTypeMismatchException(); /* ConstrainedCopy requires types to be the same or derived */
else
can_quick_copy = false;
/* For now we don't handle arrays with lobounds != 0 */
var srcLobounds = *(int**)((byte*)srcArr + ArrayOperations.GetLoboundsOffset());
var dstLobounds = *(int**)((byte*)dstArr + ArrayOperations.GetLoboundsOffset());
for (int i = 0; i < srcRank; i++)
{
if (srcLobounds[i] != 0)
throw new NotImplementedException("srcLobounds != 0");
if (dstLobounds[i] != 0)
throw new NotImplementedException("dstLobounds != 0");
}
if (srcIndex < 0 || dstIndex < 0)
throw new ArgumentOutOfRangeException();
/* Ensure we don't overflow */
var src_len = GetLength(srcArr);
var dst_len = GetLength(dstArr);
if (srcIndex + length > src_len)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "Array.Copy srcIndex/length out of range");
System.Diagnostics.Debugger.Log(length, "libsupcs", "length");
System.Diagnostics.Debugger.Log(srcIndex, "libsupcs", "srcIndex");
System.Diagnostics.Debugger.Log(src_len, "libsupcs", "src_len");
throw new ArgumentOutOfRangeException();
}
if (dstIndex + length > dst_len)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "Array.Copy dstIndex/length out of range");
System.Diagnostics.Debugger.Log(length, "libsupcs", "length");
System.Diagnostics.Debugger.Log(dstIndex, "libsupcs", "dstIndex");
System.Diagnostics.Debugger.Log(dst_len, "libsupcs", "dst_len");
throw new ArgumentOutOfRangeException();
}
if (can_quick_copy)
{
/* Elem size of both arrays is guaranteed to be the same and we can do a shallow copy */
var e_size = *(int*)((byte*)srcArr + ArrayOperations.GetElemSizeOffset());
var src_ia = *(byte**)((byte*)srcArr + ArrayOperations.GetInnerArrayOffset());
var dst_ia = *(byte**)((byte*)dstArr + ArrayOperations.GetInnerArrayOffset());
MemoryOperations.MemMove(dst_ia + dstIndex * e_size, src_ia + srcIndex * e_size, length * e_size);
}
else
{
/* TODO: implement as per System.Array.Copy() semantics */
throw new NotImplementedException("Cannot quick copy " + ((ulong)srcET).ToString("X") +
" to " + ((ulong)dstET).ToString("X"));
}
}
[MethodAlias("_ZW6System5Array_8FastCopy_Rb_P5V5ArrayiV5Arrayii")]
[WeakLinkage]
[AlwaysCompile]
static unsafe bool FastCopy(void *srcArr, int srcIndex, void *dstArr, int dstIndex, int length)
{
/* This is often called with length == 0 when the
* first item is added to a List<T> as the default
* array within the list has length 0.
*/
if (length == 0)
return true;
// Ensure both arrays are of rank 1
int srcRank = *(int*)((byte*)srcArr + ArrayOperations.GetRankOffset());
int dstRank = *(int*)((byte*)dstArr + ArrayOperations.GetRankOffset());
if (srcRank != 1)
return false;
if (dstRank != 1)
return false;
// Ensure srcIndex is valid
int srcLobound = **(int**)((byte*)srcArr + ArrayOperations.GetLoboundsOffset());
int srcSize = **(int**)((byte*)srcArr + ArrayOperations.GetSizesOffset());
srcIndex -= srcLobound;
if (srcIndex + length > srcSize)
return false;
// Ensure destIndex is valid
int dstLobound = **(int**)((byte*)dstArr + ArrayOperations.GetLoboundsOffset());
int dstSize = **(int**)((byte*)dstArr + ArrayOperations.GetSizesOffset());
dstIndex -= dstLobound;
if (dstIndex + length > dstSize)
return false;
// Ensure both have same element type
void* srcET = *(void**)((byte*)srcArr + ArrayOperations.GetElemTypeOffset());
void* dstET = *(void**)((byte*)dstArr + ArrayOperations.GetElemTypeOffset());
if (srcET != dstET)
return false;
// Get element size
int elemSize = *(int*)((byte*)srcArr + ArrayOperations.GetElemSizeOffset());
srcIndex *= elemSize;
dstIndex *= elemSize;
byte* srcAddr = *(byte**)((byte*)srcArr + ArrayOperations.GetInnerArrayOffset()) + srcIndex;
byte* dstAddr = *(byte**)((byte*)dstArr + ArrayOperations.GetInnerArrayOffset()) + dstIndex;
length *= elemSize;
MemoryOperations.MemMove(dstAddr, srcAddr, length);
return true;
}
[MethodAlias("_ZW6System5Array_13GetLowerBound_Ri_P2u1ti")]
[WeakLinkage]
[AlwaysCompile]
static unsafe int GetLowerBound(void *arr, int rank)
{
int arrRank = *(int*)((byte*)arr + ArrayOperations.GetRankOffset());
if (rank < 0 || rank >= arrRank)
{
System.Diagnostics.Debugger.Break();
throw new IndexOutOfRangeException();
}
int* lbPtr = *(int**)((byte*)arr + ArrayOperations.GetLoboundsOffset());
return *(lbPtr + rank);
}
[MethodAlias("_ZW6System5Array_5Clear_Rv_P3V5Arrayii")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void Clear(void *arr, int index, int length)
{
/* Get a pointer to the source data */
var elem_size = *(int*)((byte*)arr + ArrayOperations.GetElemSizeOffset());
void* ia = *(void**)((byte*)arr + ArrayOperations.GetInnerArrayOffset());
void* sptr = (void*)((byte*)ia + index * elem_size);
var mem_size = length * elem_size;
MemoryOperations.MemSet(sptr, 0, mem_size);
}
[MethodAlias("_ZW6System5Array_10get_Length_Ri_P1u1t")]
[WeakLinkage]
[AlwaysCompile]
static unsafe int GetLength(void *arr)
{
int arrRank = *(int*)((byte*)arr + ArrayOperations.GetRankOffset());
int* szPtr = *(int**)((byte*)arr + ArrayOperations.GetSizesOffset());
int ret = 1;
for (int i = 0; i < arrRank; i++)
ret = ret * *(szPtr + i);
return ret;
}
[MethodAlias("_ZW6System5Array_9GetLength_Ri_P2u1ti")]
[WeakLinkage]
[AlwaysCompile]
static unsafe int GetLength(void *arr, int rank)
{
if(arr == null)
{
System.Diagnostics.Debugger.Break();
throw new ArgumentNullException();
}
int arrRank = *(int*)((byte*)arr + ArrayOperations.GetRankOffset());
if (rank < 0 || rank >= arrRank)
{
System.Diagnostics.Debugger.Break();
throw new IndexOutOfRangeException();
}
int* szPtr = *(int**)((byte*)arr + ArrayOperations.GetSizesOffset());
return *(szPtr + rank);
}
[MethodAlias("_ZW6System5Array_8get_Rank_Ri_P1u1t")]
[MethodAlias("_ZW6System5Array_7GetRank_Ri_P1u1t")]
[WeakLinkage]
[AlwaysCompile]
static unsafe int GetRank(void *arr)
{
return *(int*)((byte*)arr + ArrayOperations.GetRankOffset());
}
[MethodAlias("_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_15InitializeArray_Rv_P2U6System5ArrayV18RuntimeFieldHandle")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void InitializeArray(void *arr, void *fld_handle)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "InitializeArray: arr: " + ((ulong)arr).ToString("X16") + ", fld_handle: " + ((ulong)fld_handle).ToString("X16"));
void* dst = *(void**)((byte*)arr + ArrayOperations.GetInnerArrayOffset());
/* Get total number of elements, and hence data size */
int* sizes = *(int**)((byte*)arr + ArrayOperations.GetSizesOffset());
int rank = *(int*)((byte*)arr + ArrayOperations.GetRankOffset());
if (rank == 0)
return;
int size = sizes[0];
for (int i = 1; i < rank; i++)
size *= sizes[i];
int len = size * *(int*)((byte*)arr + ArrayOperations.GetElemSizeOffset());
/* Field Typeinfos hava a pointer to the stored data as their third element */
void* src = ((void**)fld_handle)[2];
System.Diagnostics.Debugger.Log(0, "libsupcs", "InitializeArray: src: " + ((ulong)src).ToString("X16") +
", dest: " + ((ulong)dst).ToString("X16") + ", len: " + len.ToString());
MemoryOperations.MemCpy(dst, src, len);
}
[WeakLinkage]
[MethodAlias("_ZW34System#2ERuntime#2EInteropServices7Marshal_13CopyToManaged_Rv_P4u1Iu1Oii")]
[AlwaysCompile]
static unsafe void CopyToManaged(void *src, void *dstArr, int startIndex, int length)
{
var esize = *(int*)((byte*)dstArr + ArrayOperations.GetElemSizeOffset());
int* lovals = *(int**)((byte*)dstArr + ArrayOperations.GetLoboundsOffset());
var dst = *(byte**)((byte*)dstArr + ArrayOperations.GetInnerArrayOffset()) + (startIndex - lovals[0]) * esize;
System.Diagnostics.Debugger.Log(0, null, "libsupcs: Array.CopyToManaged: src: " + ((ulong)src).ToString("X16") +
", dstArr: " + ((ulong)dstArr).ToString("X16") +
", startIndex: " + startIndex.ToString() +
", length: " + length.ToString() +
", esize: " + esize.ToString() +
", lovals[0]: " + lovals[0].ToString() +
", dst: " + ((ulong)dst).ToString("X16"));
MemoryOperations.MemCpy(dst, src, length * esize);
}
[WeakLinkage]
[MethodAlias("_ZW34System#2ERuntime#2EInteropServices7Marshal_12CopyToNative_Rv_P4u1Oiu1Ii")]
[AlwaysCompile]
static unsafe void CopyToNative(void *srcArr, int startIndex, void *dst, int length)
{
var esize = *(int*)((byte*)srcArr + ArrayOperations.GetElemSizeOffset());
int* lovals = *(int**)((byte*)srcArr + ArrayOperations.GetLoboundsOffset());
var src = *(byte**)((byte*)srcArr + ArrayOperations.GetInnerArrayOffset()) + (startIndex - lovals[0]) * esize;
MemoryOperations.MemCpy(dst, src, length * esize);
}
[WeakLinkage]
[MethodAlias("_ZW6System5Array_20InternalGetReference_Rv_P4u1tPviPi")]
[AlwaysCompile]
static unsafe void InternalGetReference(void *arr, System.TypedReference *typedref, int ranks, int *rank_indices)
{
// idx = rightmost-index + 2nd-right * rightmost-size + 3rd-right * 2nd-right-size * right-size + ...
// rank checking is done by System.Array members in coreclr
int* lovals = *(int**)((byte*)arr + ArrayOperations.GetLoboundsOffset());
int* sizes = *(int**)((byte*)arr + ArrayOperations.GetSizesOffset());
// first get index of first rank
if (rank_indices[0] > sizes[0])
throw new IndexOutOfRangeException();
int index = rank_indices[0] - lovals[0];
// now repeat mul rank size; add rank index; rank-1 times
for(int rank = 1; rank < ranks; rank++)
{
if (rank_indices[rank] > sizes[rank])
throw new IndexOutOfRangeException();
index *= sizes[rank];
index += rank_indices[rank];
}
// get pointer to actual data
int et_size = *(int*)((byte*)arr + ArrayOperations.GetElemSizeOffset());
void* ptr = *(byte**)((byte*)arr + ArrayOperations.GetInnerArrayOffset()) + index * et_size;
// store to the typed reference
*(void**)((byte*)typedref + ClassOperations.GetTypedReferenceValueOffset()) = ptr;
*(void**)((byte*)typedref + ClassOperations.GetTypedReferenceTypeOffset()) =
*(void**)((byte*)arr + ArrayOperations.GetElemTypeOffset());
}
[MethodAlias("_Zu1T_16InternalToObject_Ru1O_P1Pv")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void* InternalToObject(void *typedref)
{
// get the type from the typed reference to see if we need to box the object
// or simply return the address as a reference type
void* et = *(void**)((byte*)typedref + ClassOperations.GetTypedReferenceTypeOffset());
void* src = *(void**)((byte*)typedref + ClassOperations.GetTypedReferenceValueOffset());
void* etextends = *(void**)((byte*)et + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (etextends == OtherOperations.GetStaticObjectAddress("_Zu1L") ||
etextends == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
// this is a boxed value type. Get its size
var vt_size = TysosType.GetValueTypeSize(et);
// build a new boxed type
var ret = MemoryOperations.GcMalloc(*(int*)((byte*)et + ClassOperations.GetVtblTypeSizeOffset()));
// dst ptr
var dst = (byte*)ret + ClassOperations.GetBoxedTypeDataOffset();
CopyMem(dst, (byte*)src, vt_size);
return ret;
}
else
{
// simply copy the reference
return *(void**)src;
}
}
[MethodAlias("_ZW6System5Array_16InternalSetValue_Rv_P2Pvu1O")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void InternalSetValue(void* typedref, void* objval)
{
// get the type from the typed reference to see if we need to unbox the object
// or store as a reference type
void* et = *(void**)((byte*)typedref + ClassOperations.GetTypedReferenceTypeOffset());
void* ptr = *(void**)((byte*)typedref + ClassOperations.GetTypedReferenceValueOffset());
void* etextends = *(void**)((byte*)et + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (etextends == OtherOperations.GetStaticObjectAddress("_Zu1L") ||
etextends == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
// this is a boxed value type. Get its size
var vt_size = TysosType.GetValueTypeSize(et);
// src ptr
void* src = *(void**)((byte*)objval + ClassOperations.GetBoxedTypeDataOffset());
CopyMem((byte*)ptr, (byte*)src, vt_size);
}
else
{
// simply copy the reference
*(void**)ptr = objval;
}
}
private static unsafe void CopyMem(byte* dst, byte* src, int vt_size)
{
/* memcpy for non-aligned sizes and addresses - ensures we don't overwrite adjacent
* array indices. Does not return so breaks memcpy semantics */
// TODO ensure pointers are aligned
while(vt_size >+ 8)
{
*(ulong*)dst = *(ulong*)src;
dst += 8;
src += 8;
vt_size -= 8;
}
while (vt_size >+ 4)
{
*(uint*)dst = *(uint*)src;
dst += 4;
src += 4;
vt_size -= 4;
}
while (vt_size >+ 2)
{
*(ushort*)dst = *(ushort*)src;
dst += 2;
src += 2;
vt_size -= 2;
}
while(vt_size >= 1)
{
*dst = *src;
dst++;
src++;
vt_size--;
}
}
[MethodAlias("_ZW6System5Array_12GetValueImpl_Ru1O_P2u1ti")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void *GetValueImpl(void *arr, int pos)
{
/* Get the element type of the array */
void* et = *(void**)((byte*)arr + ArrayOperations.GetElemTypeOffset());
/* Get a pointer to the source data */
var elem_size = *(int*)((byte*)arr + ArrayOperations.GetElemSizeOffset());
void* ia = *(void**)((byte*)arr + ArrayOperations.GetInnerArrayOffset());
void* sptr = (void*)((byte*)ia + pos * elem_size);
/* Is this a value type? In which case we need to return a boxed value */
void* extends = *(void**)((byte*)et + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (extends == OtherOperations.GetStaticObjectAddress("_Zu1L") ||
extends == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
/* This is a value type. We need to read the size of the element,
* create a new object of the appropriate size and copy the data
* into it */
byte *ret = (byte*)MemoryOperations.GcMalloc(elem_size + ClassOperations.GetBoxedTypeDataOffset());
*(void**)(ret + ClassOperations.GetVtblFieldOffset()) = et;
*(ulong*)(ret + ClassOperations.GetMutexLockOffset()) = 0;
/* Avoid calls to memcpy if possible */
switch(elem_size)
{
case 1:
*(byte*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(byte*)sptr;
return ret;
case 2:
*(ushort*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(ushort*)sptr;
return ret;
case 4:
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(uint*)sptr;
return ret;
case 8:
if (OtherOperations.GetPointerSize() >= 8)
{
*(ulong*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(ulong*)sptr;
return ret;
}
else
{
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(uint*)sptr;
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset() + 4) = *(uint*)((byte*)sptr + 4);
return ret;
}
case 16:
if (OtherOperations.GetPointerSize() >= 8)
{
*(ulong*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(ulong*)sptr;
*(ulong*)(ret + ClassOperations.GetBoxedTypeDataOffset() + 8) = *(ulong*)((byte*)sptr + 8);
return ret;
}
else
{
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset()) = *(uint*)sptr;
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset() + 4) = *(uint*)((byte*)sptr + 4);
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset() + 8) = *(uint*)((byte*)sptr + 8);
*(uint*)(ret + ClassOperations.GetBoxedTypeDataOffset() + 12) = *(uint*)((byte*)sptr + 12);
return ret;
}
}
/* Do data copy via memcpy */
MemoryOperations.MemCpy(ret + ClassOperations.GetBoxedTypeDataOffset(),
sptr, elem_size);
return ret;
}
else
{
/* Its a reference type, so just return the pointer */
return *(void**)sptr;
}
}
/* Build an array of a particular type */
public static unsafe T[] CreateSZArray<T>(int nitems, void* data_addr)
{
TysosType arrtt = (TysosType)typeof(T[]);
TysosType elemtt = (TysosType)typeof(T);
int elemsize;
if (elemtt.IsValueType)
{
elemsize = elemtt.GetClassSize() - ClassOperations.GetBoxedTypeDataOffset();
}
else
{
elemsize = OtherOperations.GetPointerSize();
}
if (data_addr == null)
data_addr = MemoryOperations.GcMalloc(elemsize * nitems);
byte* ret = (byte*)MemoryOperations.GcMalloc(ArrayOperations.GetArrayClassSize() + 8); // extra space for lobounds and length array
void* vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(arrtt) + ClassOperations.GetSystemTypeImplOffset());
*(void**)(ret + ClassOperations.GetVtblFieldOffset()) = vtbl;
*(ulong*)(ret + ClassOperations.GetMutexLockOffset()) = 0;
*(void**)(ret + ArrayOperations.GetElemTypeOffset()) = *(void**)((byte*)CastOperations.ReinterpretAsPointer(elemtt) + ClassOperations.GetSystemTypeImplOffset());
*(int*)(ret + ArrayOperations.GetElemSizeOffset()) = elemsize;
*(void**)(ret + ArrayOperations.GetInnerArrayOffset()) = data_addr;
*(void**)(ret + ArrayOperations.GetLoboundsOffset()) = ret + ArrayOperations.GetArrayClassSize();
*(void**)(ret + ArrayOperations.GetSizesOffset()) = ret + ArrayOperations.GetArrayClassSize() + 4;
*(int*)(ret + ArrayOperations.GetRankOffset()) = 1;
*(int*)(ret + ArrayOperations.GetArrayClassSize()) = 0; // lobounds[0]
*(int*)(ret + ArrayOperations.GetArrayClassSize() + 4) = nitems; // sizes[0]
return (T[])CastOperations.ReinterpretAsObject(ret);
}
}
}
<file_sep>/* Copyright (C) 2019 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.util;
namespace libtysila5.target.arm
{
partial class arm_Assembler
{
private void InsertImm32(List<byte> c, int v, int offset)
{
c[offset] = (byte)(v & 0xff);
c[offset + 1] = (byte)((v >> 8) & 0xff);
c[offset + 2] = (byte)((v >> 16) & 0xff);
c[offset + 3] = (byte)((v >> 24) & 0xff);
}
private void AddImm64(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
c.Add((byte)((v >> 8) & 0xff));
c.Add((byte)((v >> 16) & 0xff));
c.Add((byte)((v >> 24) & 0xff));
c.Add((byte)((v >> 32) & 0xff));
c.Add((byte)((v >> 40) & 0xff));
c.Add((byte)((v >> 48) & 0xff));
c.Add((byte)((v >> 56) & 0xff));
}
private void AddImm32(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
c.Add((byte)((v >> 8) & 0xff));
c.Add((byte)((v >> 16) & 0xff));
c.Add((byte)((v >> 24) & 0xff));
}
private void AddImm16(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
c.Add((byte)((v >> 8) & 0xff));
}
private void AddImm8(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
}
/* Will the value 'v' fit into an immediate of length 'bits' ? */
bool FitsBits(long v, int bits, bool signed = false)
{
long mask = (~0L) << bits;
if (signed)
{
if ((v & mask) == 0)
return true;
if ((v & mask) == mask)
return true;
return false;
}
else
{
if ((v & mask) == 0)
return true;
return false;
}
}
protected internal override void AssemblePass(Code c)
{
var Code = c.s.text_section.Data as List<byte>;
var code_start = Code.Count;
Dictionary<int, int> il_starts = new Dictionary<int, int>(
new GenericEqualityComparer<int>());
/* Get maximum il offset of method */
int max_il = 0;
if (c.cil != null)
{
foreach (var cil in c.cil)
{
if (cil.il_offset > max_il)
max_il = cil.il_offset;
}
}
max_il++;
for (int i = 0; i < max_il; i++)
il_starts[i] = -1;
List<int> rel_srcs = new List<int>();
List<int> rel_dests = new List<int>();
foreach (var I in c.mc)
{
var mc_offset = Code.Count - code_start;
I.offset = mc_offset;
I.addr = Code.Count;
I.end_addr = Code.Count;
if (I.parent != null)
{
var cil = I.parent.parent;
if (il_starts[cil.il_offset] == -1)
{
var ir = I.parent;
/* We don't want the il offset for the first node to point
* to the enter/enter_handler opcode as this potentially breaks
* small methods like:
*
* IL_0000: br.s IL_0000
*
* where we want the jmp to be to the br irnode, rather than the enter irnode */
if (ir.opcode != libtysila5.ir.Opcode.oc_enter &&
ir.opcode != libtysila5.ir.Opcode.oc_enter_handler &&
ir.ignore_for_mcoffset == false)
{
il_starts[cil.il_offset] = mc_offset;
cil.mc_offset = mc_offset;
}
}
}
if (I.p.Length == 0)
continue;
int tls_flag = (int)I.p[0].v2;
switch (I.p[0].v)
{
case Generic.g_mclabel:
il_starts[(int)I.p[1].v] = mc_offset;
break;
case Generic.g_label:
c.extra_labels.Add(new Code.Label
{
Offset = mc_offset + code_start,
Name = I.p[1].str
});
break;
case arm_bl:
{
var target = I.p[3];
if (target.t == ir.Opcode.vl_call_target)
{
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_Arm_Thm_Call();
reloc.Addend = 0;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = target.str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Function;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0xf000);
AddImm32(Code, 0xd000);
}
else
{
throw new NotImplementedException();
}
}
break;
case arm_bx:
AddImm16(Code, (Rm(I) << 3) | 0x4700);
break;
case arm_ldm:
if(FitsBits(Rn(I), 3) &&
(FitsBits(Rlist(I), 8)) &&
(((W(I) == 1) && ((Rlist(I) & (1 << Rn(I))) == 0)) ||
((W(I) == 0) && ((Rlist(I) & (1 << Rn(I))) != 0))))
{
// encoding T1
throw new NotImplementedException();
}
else
{
// encoding T2
AddImm16(Code, Rn(I) | (W(I) << 5) | 0xe890);
AddImm16(Code, Rlist(I));
}
break;
case arm_ldr_imm:
if ((Rn(I) == 13) && FitsBits(Rt(I), 3) && FitsBits(Imm(I), 10) && ((Imm(I) & 0x3) == 0) && W(I) == 0)
{
// encoding T2
throw new NotImplementedException();
}
else if (FitsBits(Rn(I), 3) && FitsBits(Rt(I), 3) && FitsBits(Imm(I), 7) && ((Imm(I) & 0x3) == 0) && W(I) == 0)
{
// encoding T1
throw new NotImplementedException();
}
else if (FitsBits(Imm(I), 12) && W(I) == 0)
{
// encoding T3
throw new NotImplementedException();
}
else if ((Imm(I) < 256) && (Imm(I) > -256))
{
// encoding T4
if (W(I) == 1)
throw new NotImplementedException();
int index = 1;
int wback = 0;
int val = Imm(I);
int add = 1;
if (val < 0)
{
val = -val;
add = 0;
}
AddImm16(Code, Rn(I) | 0xf850);
AddImm16(Code, val | (wback << 8) | (add << 9) | (index << 10) | (1 << 11) | (Rt(I) << 12));
}
else
throw new NotImplementedException();
break;
case arm_mov_imm:
if(Str(I) != null)
{
// this has an embedded string target, need to generate relocs
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_Arm_Thm_Movw_Abs_Nc();
reloc.Addend = 0;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = Str(I);
reloc.References.ObjectType = binary_library.SymbolObjectType.Object;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
// encoding T3
AddImm16(Code, 0xf240);
AddImm16(Code, Rd(I) << 8);
}
else
{
// just an inline imm
if(FitsBits(Rd(I), 3) && FitsBits(Imm(I), 8))
{
// encoding T1
AddImm16(Code, (Rd(I) << 8) | Imm(I) | 0x2000);
}
else
{
// encoding T3
throw new NotImplementedException();
}
}
break;
case arm_mov_reg:
AddImm16(Code, (Rd(I) & 0x7) | ((Rm(I) & 0xf) << 3) | (((Rd(I) >> 3) & 0x1) << 7) | 0x4600);
break;
case arm_movt_imm:
if (Str(I) != null)
{
// this has an embedded string target, need to generate relocs
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_Arm_Thm_Movt_Abs();
reloc.Addend = 0;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = Str(I);
reloc.References.ObjectType = binary_library.SymbolObjectType.Object;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
// encoding T3
AddImm16(Code, 0xf2c0);
AddImm16(Code, Rd(I) << 8);
}
else
{
// just an inline imm
throw new NotImplementedException();
}
break;
case arm_push:
if(BitCount(Rlist(I)) == 0)
{
// NOP
}
if((Rlist(I) & 0xbf00) == 0)
{
// encoding T1
int m = (Rlist(I) >> 14) & 0x1;
AddImm16(Code, (Rlist(I) & 0xff) | (m << 8) | 0xb400);
}
else if(BitCount(Rlist(I)) > 1)
{
// encoding T2
throw new NotImplementedException();
}
else
{
// encoding T3
throw new NotImplementedException();
}
break;
case arm_pop:
if (BitCount(Rlist(I)) == 0)
{
// NOP
}
if ((Rlist(I) & 0x7f00) == 0)
{
// encoding T1
int p = (Rlist(I) >> 15) & 0x1;
AddImm16(Code, (Rlist(I) & 0xff) | (p << 8) | 0xbc00);
}
else if (BitCount(Rlist(I)) > 1)
{
// encoding T2
throw new NotImplementedException();
}
else
{
// encoding T3
throw new NotImplementedException();
}
break;
case arm_stmdb:
AddImm16(Code, Rn(I) | (W(I) << 5) | 0xe900);
AddImm16(Code, Rlist(I));
break;
case arm_str_imm:
if ((Rn(I) == 13) && FitsBits(Rt(I), 3) && FitsBits(Imm(I), 10) && ((Imm(I) & 0x3) == 0) && W(I) == 0)
{
// encoding T2
throw new NotImplementedException();
}
else if (FitsBits(Rn(I), 3) && FitsBits(Rt(I), 3) && FitsBits(Imm(I), 7) && ((Imm(I) & 0x3) == 0) && W(I) == 0)
{
// encoding T1
AddImm16(Code, Rt(I) | (Rn(I) << 3) | ((Imm(I) >> 2) << 6) | 0x6000);
}
else if (FitsBits(Imm(I), 12) && W(I) == 0)
{
// encoding T3
throw new NotImplementedException();
}
else if((Imm(I) < 256) && (Imm(I) > -256))
{
// encoding T4
if (W(I) == 1)
throw new NotImplementedException();
int index = 1;
int wback = 0;
int val = Imm(I);
int add = 1;
if(val < 0)
{
val = -val;
add = 0;
}
AddImm16(Code, Rn(I) | 0xf840);
AddImm16(Code, val | (wback << 8) | (add << 9) | (index << 10) | (1 << 11) | (Rt(I) << 12));
}
else
throw new NotImplementedException();
break;
case arm_sub_imm:
if (FitsBits(Rn(I), 3) && FitsBits(Rd(I), 3) && FitsBits(Imm(I), 3))
{
// encoding T1
throw new NotImplementedException();
}
else if ((Rn(I) == Rd(I)) && FitsBits(Rn(I), 3) && FitsBits(Imm(I), 8))
{
// encoding T2
throw new NotImplementedException();
}
else if (FitsBits(Imm(I), 12))
{
// encoding T4
AddImm16(Code, Rn(I) | (((Imm(I) >> 11) & 0x1) << 10) | 0xf2a0);
AddImm16(Code, (Imm(I) & 0xf) | (Rd(I) << 8) | (((Imm(I) >> 8) & 0x7) << 12));
}
else
throw new NotImplementedException();
break;
default:
throw new NotImplementedException(insts[(int)I.p[0].v]);
}
}
// Handle cil instructions which encode to nothing (e.g. nop) but may still be branch targets - point them to the next instruction
int cur_il_start = -1;
for (int i = 0; i < max_il; i++)
{
if (il_starts[i] == -1)
il_starts[i] = cur_il_start;
else
cur_il_start = il_starts[i];
}
// Patch up references
for (int i = 0; i < rel_srcs.Count; i++)
{
var src = rel_srcs[i];
var dest = rel_dests[i];
var dest_offset = il_starts[dest] + code_start;
var offset = dest_offset - src - 4;
throw new NotImplementedException();
//InsertImm32(Code, offset, src);
}
}
private int BitCount(int v)
{
int cnt = 0;
for(int i = 0; i < 32; i++)
{
cnt += (v & 0x1);
v >>= 1;
}
return cnt;
}
private int Rn(MCInst i)
{
return i.p[1].mreg.id;
}
private int Rd(MCInst i)
{
return i.p[2].mreg.id;
}
private int Rm(MCInst i)
{
return i.p[3].mreg.id;
}
private int Rt(MCInst i)
{
return i.p[4].mreg.id;
}
private int W(MCInst i)
{
return (int)i.p[6].v;
}
private int Imm(MCInst i)
{
return (int)i.p[5].v;
}
private int Rlist(MCInst i)
{
return (int)i.p[8].v;
}
private string Str(MCInst i)
{
return i.p[9]?.str;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TableMap
{
class MakeState
{
public MakeState parent = null;
public Expression.EvalResult returns = null;
public List<string> search_paths = new List<string> { ".", "" };
Dictionary<string, Expression.EvalResult> defs = new Dictionary<string, Expression.EvalResult>();
Dictionary<string, Expression.EvalResult> local_defs = new Dictionary<string, Expression.EvalResult>();
public Dictionary<string, FunctionStatement> funcs = new Dictionary<string, FunctionStatement>();
public bool IsDefined(string tag) {
if (local_defs.ContainsKey(tag) == true)
return true;
if (defs.ContainsKey(tag) == true)
return true;
return VarGenFunction.all_defs.ContainsKey(tag);
}
public void ClearLocalDefines()
{
local_defs = new Dictionary<string, Expression.EvalResult>();
}
public void SetDefine(string tag, Expression.EvalResult e) { defs[tag] = e; }
public void SetLocalDefine(string tag, Expression.EvalResult e) { local_defs[tag] = e; }
public void SetDefine(string tag, Expression.EvalResult e, bool export)
{
if (export == false)
SetLocalDefine(tag, e);
else
{
MakeState s = this;
while(s != null)
{
s.SetDefine(tag, e);
s = s.parent;
}
}
}
public Expression.EvalResult GetDefine(string tag) {
if (local_defs.ContainsKey(tag))
return local_defs[tag];
if (defs.ContainsKey(tag))
return defs[tag];
else return VarGenFunction.all_defs[tag];
}
public void SetDefine(string tag, Expression.EvalResult e, Tokens assignop)
{
switch (assignop)
{
case Tokens.ASSIGN:
local_defs[tag] = e;
break;
case Tokens.ASSIGNIF:
if (!defs.ContainsKey(tag) && !local_defs.ContainsKey(tag))
local_defs[tag] = e;
break;
case Tokens.APPEND:
if (local_defs.ContainsKey(tag))
{
Expression.EvalResult src = local_defs[tag];
Expression append = new Expression { a = src, b = e, op = Tokens.PLUS };
local_defs[tag] = append.Evaluate(this);
}
else if(defs.ContainsKey(tag))
{
Expression.EvalResult src = defs[tag];
Expression append = new Expression { a = src, b = e, op = Tokens.PLUS };
local_defs[tag] = append.Evaluate(this);
}
else
defs[tag] = e;
break;
}
}
public MakeState Clone()
{
MakeState other = new MakeState();
foreach (KeyValuePair<string, Expression.EvalResult> kvp in defs)
other.defs[kvp.Key] = kvp.Value;
foreach (KeyValuePair<string, Expression.EvalResult> kvp in local_defs)
other.local_defs[kvp.Key] = kvp.Value;
foreach (KeyValuePair<string, FunctionStatement> kvp in funcs)
other.funcs[kvp.Key] = kvp.Value;
other.parent = this;
other.search_paths = new List<string>(search_paths);
return other;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.target
{
partial class Target
{
public void AllocateLocalVarsArgs(Code c)
{
/* Generate list of locations of local vars */
var m = c.ms.m;
var ms = c.ms;
int idx = c.lvar_sig_tok;
int lv_count = m.GetLocalVarCount(ref idx);
int[] lv_locs = new int[lv_count];
c.lv_locs = new Reg[lv_count];
c.lv_sizes = new int[lv_count];
c.lv_types = new metadata.TypeSpec[lv_count];
int cur_loc = GetCCStackReserve(c.ms.CallingConvention);
for (int i = 0; i < lv_count; i++)
{
var type = m.GetTypeSpec(ref idx, c.ms.gtparams,
c.ms.gmparams);
int t_size = GetSize(type);
lv_locs[i] = cur_loc;
t_size = util.util.align(t_size, GetPointerSize());
c.lv_sizes[i] = t_size;
c.lv_types[i] = type;
c.lv_locs[i] = GetLVLocation(cur_loc, t_size, c);
cur_loc += t_size;
// align to pointer size
int diff = cur_loc % GetPointerSize();
if (diff != 0)
cur_loc = cur_loc - diff + GetPointerSize();
}
/* Do the same for local args */
int la_count = m.GetMethodDefSigParamCountIncludeThis(
c.ms.msig);
int[] la_locs = new int[la_count];
c.la_locs = new Reg[la_count];
c.la_needs_assign = new bool[la_count];
int la_count2 = m.GetMethodDefSigParamCount(
c.ms.msig);
int laidx = 0;
//cur_loc = 0;
var cc = cc_map[c.ms.CallingConvention];
var cc_class_map = cc_classmap[c.ms.CallingConvention];
bool has_hidden = ir.Opcode.GetCTFromType(c.ret_ts) == ir.Opcode.ct_vt;
int stack_loc = 0;
metadata.TypeSpec hidden_ts = null;
if (has_hidden)
hidden_ts = m.SystemIntPtr;
var la_phys_locs = GetRegLocs(new ir.Param
{
m = m,
ms = c.ms,
}, ref stack_loc, cc, cc_class_map,
c.ms.CallingConvention,
out c.la_sizes, out c.la_types,
hidden_ts);
if(has_hidden)
{
// Strip hidden argument off the values we return
Reg[] la_phys_locs_new = new Reg[la_phys_locs.Length - 1];
for (int i = 0; i < la_phys_locs_new.Length; i++)
la_phys_locs_new[i] = la_phys_locs[i + 1];
la_phys_locs = la_phys_locs_new;
int[] la_sizes = new int[la_phys_locs.Length];
for (int i = 0; i < la_phys_locs_new.Length; i++)
la_sizes[i] = c.la_sizes[i + 1];
c.la_sizes = la_sizes;
metadata.TypeSpec[] la_types = new metadata.TypeSpec[la_phys_locs.Length];
for (int i = 0; i < la_phys_locs_new.Length; i++)
la_types[i] = c.la_types[i + 1];
c.la_types = la_types;
}
c.incoming_args = la_phys_locs;
if (la_count != la_count2)
{
var this_size = GetCTSize(ir.Opcode.ct_object);
c.la_locs[laidx] = GetLALocation(cur_loc, this_size, c);
c.la_sizes[laidx] = this_size;
// value type methods have mptr to type as their this pointer
if (ms.type.IsValueType)
{
c.la_types[laidx] = ms.type.ManagedPointer;
}
else
c.la_types[laidx] = ms.type;
la_locs[laidx] = cur_loc;
//cur_loc += this_size;
laidx++;
}
idx = m.GetMethodDefSigRetTypeIndex(
ms.msig);
// pass by rettype
m.GetTypeSpec(ref idx, c.ms.gtparams, c.ms.gmparams);
for (int i = 0; i < la_count; i++)
{
var mreg = la_phys_locs[i];
metadata.TypeSpec type = m.SystemObject;
if (i > 0 || !m.GetMethodDefSigHasNonExplicitThis(c.ms.msig))
type = m.GetTypeSpec(ref idx, c.ms.gtparams, c.ms.gmparams);
if (mreg.type == rt_stack)
{
la_phys_locs[i] = GetLALocation(mreg.stack_loc, util.util.align(c.la_sizes[i], GetPointerSize()), c);
c.la_locs[i] = la_phys_locs[i];
c.la_needs_assign[i] = false;
}
else if(mreg.type == rt_contents)
{
c.la_locs[i] = la_phys_locs[i];
c.la_needs_assign[i] = false;
}
else
{
c.la_needs_assign[i] = true;
var la_size = util.util.align(GetSize(type), GetPointerSize());
c.la_locs[i] = GetLVLocation(cur_loc, la_size, c);
la_locs[i] = cur_loc;
cur_loc += la_size;
}
}
if (has_hidden)
cur_loc += psize;
c.lv_total_size = cur_loc;
}
internal virtual int GetCCStackReserve(string cc)
{
return 0;
}
}
}
<file_sep>Tysila
------
A CIL to native code compiler designed for building and as the JIT
compiler for tysos (https://github.com/jncronin/tysos)
Building
--------
Run 'msbuild' in the repository root
For dotnet on linux/windows:
dotnet publish -c Release -p:TargetLatestRuntimePatch=true -p:PublishDir=bin/Release -r <RID>
where RID is selected from
https://docs.microsoft.com/en-us/dotnet/core/rid-catalog
(e.g. linux-x64 or win10-x64)
Add the resultant 'publish' path for tysila4 (e.g. tysila4/bin/Release) to PATH)
Usage
-----
tysila4 -t arch [-L repository_path] [-i] [-o output_file] input_file
Currently, only arch=x86_64 is fully supported, with limited support for x86 and experimental arm support.
tysila expects mscorlib from coreclr (https://github.com/dotnet/coreclr) to
be available. Please specify the location with the -L option. Pre-built
copies of CoreCLR 2.0 (and parts of CoreFX) are available from
https://www.tysos.org/files/tools/coreclr-2.0.0.zip
libsupcs
--------
All native code files produced by tysila are expected to be linked with
libsupcs (also available in the repository). This contains various runtime
functions related to Reflection, string support and architecture-specific
extensions.
libsupcs can be compiled using the provided libsupcs.tmk tymake file.
This requires a functioning tymake (https://github.com/jncronin/tymake)
as well as cross compilers for the appropriate architecture and (for x86_64)
yasm.
For Windows hosts, the appropriate tools (excluding tymake) can be obtained
from https://www.tysos.org/files/tools/crossxwin-7.3.0.zip
For Linux, please obtain yasm from your distribution and follow the
instructions at https://wiki.osdev.org/GCC_Cross-Compiler to build appropriate
cross compilers for the 'x86_64-elf' target.
To build:
path_to_tymake/tymake.exe "libsupcs.tmk"
and answer the prompts with the appropriate paths (alternatively add all
executables to the PATH environment variable).
This buils script expects tysila4 to be installed under ./tysila4/bin/Release
(default if the above dotnet publish command is used). If not, please edit
libsupcs.tmk appropriately to set the TYSILA and GENMISSING variables, or set
them as environment variables prior to running.
<file_sep>/* Copyright (C) 2017-2018 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace typeforwards
{
class Program
{
static void Main(string[] args)
{
if(args.Length != 4)
{
disp_usage();
return;
}
libtysila5.libtysila.AssemblyLoader al = new libtysila5.libtysila.AssemblyLoader(
new tysila4.FileSystemFileLoader());
tysila4.Program.search_dirs.Add(args[0]);
tysila4.Program.search_dirs.Add(new System.IO.FileInfo(args[2]).DirectoryName);
/* Load up all types in corefx files */
Dictionary<string, string> map = new Dictionary<string, string>();
var indir = new System.IO.DirectoryInfo(args[0]);
var files = indir.GetFiles(args[1]);
foreach (var fi in files)
{
var m = al.GetAssembly(fi.FullName);
for (int i = 1; i <= m.table_rows[metadata.MetadataStream.tid_TypeDef]; i++)
{
var flags = m.GetIntEntry(metadata.MetadataStream.tid_TypeDef, i, 0);
metadata.TypeSpec ts = new metadata.TypeSpec { m = m, tdrow = i };
if((flags & 0x7) == 0x1 || (flags & 0x7) == 0x2)
{
// public
var nspace = ts.Namespace;
var name = ts.Name;
var fullname = nspace + "." + name;
map[fullname] = fi.Name;
}
}
}
/* Generate a mapping from type name/namespaces to the files they are contained in */
var infiledi = al.LoadAssembly(args[2]);
var infile = new metadata.PEFile().Parse(infiledi, al, false);
var o = new System.IO.StreamWriter(args[3]);
for (int i = 1; i <= infile.table_rows[metadata.MetadataStream.tid_TypeDef]; i++)
{
var flags = infile.GetIntEntry(metadata.MetadataStream.tid_TypeDef, i, 0);
metadata.TypeSpec ts = new metadata.TypeSpec { m = infile, tdrow = i };
if ((flags & 0x7) == 0x1 || (flags & 0x7) == 0x2)
{
// public
var nspace = ts.Namespace;
var name = ts.Name;
var fullname = nspace + "." + name;
if(map.ContainsKey(fullname))
{
o.WriteLine(infile.AssemblyName + "!" + fullname + "=" + map[fullname]);
}
}
}
for(int i = 1; i <= infile.table_rows[metadata.MetadataStream.tid_ExportedType]; i++)
{
var nspace = infile.GetStringEntry(metadata.MetadataStream.tid_ExportedType, i, 3);
var name = infile.GetStringEntry(metadata.MetadataStream.tid_ExportedType, i, 2);
var fullname = nspace + "." + name;
if(map.ContainsKey(fullname))
{
o.WriteLine(infile.AssemblyName + "!" + fullname + "=" + map[fullname]);
}
}
o.Close();
}
private static void disp_usage()
{
Console.WriteLine("Usage: typeforwards <input_dir> <pattern> <reference_assembly> <outfile>");
}
}
}
<file_sep>FROM mcr.microsoft.com/dotnet/core/sdk:2.1 AS dotnet
WORKDIR /app
COPY build.sh /tmp
RUN chmod 777 /tmp/build.sh && /tmp/build.sh
ENV PATH="/usr/local/cross/bin:/usr/local/tymake:/usr/local/tysila:${PATH}"
COPY barebones /app
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using libtysila5.ir;
namespace libtysila5.target
{
public abstract partial class Target
{
public static Dictionary<string, Target> targets =
new Dictionary<string, Target>(
new libtysila5.GenericEqualityComparer<string>());
public static Dictionary<int, string> pt_names
= new Dictionary<int, string>(
new GenericEqualityComparer<int>());
public static Dictionary<int, string> rt_map
= new Dictionary<int, string>(
new GenericEqualityComparer<int>());
protected static Dictionary<int, string> insts =
new Dictionary<int, string>(
new GenericEqualityComparer<int>());
internal Dictionary<int, long> ct_regs =
new Dictionary<int, long>(
new GenericEqualityComparer<int>());
public Dictionary<string, ulong> cc_callee_preserves_map
= new Dictionary<string, ulong>(
new GenericEqualityComparer<string>());
public Dictionary<string, ulong> cc_caller_preserves_map
= new Dictionary<string, ulong>(
new GenericEqualityComparer<string>());
public Dictionary<string, Dictionary<int, int[]>> cc_map
= new Dictionary<string, Dictionary<int, int[]>>(
new GenericEqualityComparer<string>());
public Dictionary<string, Dictionary<int, int>> cc_classmap
= new Dictionary<string, Dictionary<int, int>>(
new GenericEqualityComparer<string>());
public Dictionary<string, Dictionary<int, int[]>> retcc_map
= new Dictionary<string, Dictionary<int, int[]>>(
new GenericEqualityComparer<string>());
public Dictionary<string, Dictionary<int, int>> retcc_classmap
= new Dictionary<string, Dictionary<int, int>>(
new GenericEqualityComparer<string>());
protected internal abstract int GetCondCode(MCInst i);
protected internal abstract Reg GetMoveSrc(MCInst i);
protected internal abstract Reg GetMoveDest(MCInst i);
protected internal abstract bool IsBranch(MCInst i);
protected internal abstract bool IsCall(MCInst i);
protected internal abstract int GetBranchDest(MCInst i);
protected internal abstract void SetBranchDest(MCInst i, int d);
protected internal abstract Reg GetLVLocation(int lv_loc, int lv_size, Code c);
protected internal abstract Reg GetLALocation(int la_loc, int la_size, Code c);
protected internal abstract MCInst[] SetupStack(int lv_size);
protected internal abstract MCInst[] CreateMove(Reg src, Reg dest);
protected internal abstract binary_library.IRelocationType GetDataToDataReloc();
protected internal abstract binary_library.IRelocationType GetDataToCodeReloc();
protected internal abstract Code AssembleBoxedMethod(metadata.MethodSpec ms, TysilaState s);
protected internal abstract Code AssembleBoxRetTypeMethod(metadata.MethodSpec ms, TysilaState s);
protected internal abstract bool NeedsBoxRetType(metadata.MethodSpec ms);
protected internal abstract void AssemblePass(Code c);
protected internal virtual string MCInstToDebug(MCInst i) { return i.ToString(); }
protected internal virtual int GetCTFromTypeForCC(metadata.TypeSpec t) { return ir.Opcode.GetCTFromType(t); }
protected internal virtual void AddExtraVTableFields(metadata.TypeSpec ts, IList<byte> d, ref ulong offset) { }
protected internal virtual int ExtraVTableFieldsPointerLength { get { return 0; } }
public virtual void InitIntcalls() { }
TargetOptions opts = new TargetOptions();
public TargetOptions Options { get { return opts; } }
public virtual string GetCType(metadata.TypeSpec ts)
{
int b;
return GetCType(ts, out b);
}
public virtual string GetCType(metadata.TypeSpec ts, out int bytesize)
{
switch(ts.stype)
{
case metadata.TypeSpec.SpecialType.None:
switch(ts.SimpleType)
{
case 0x02:
case 0x08:
bytesize = 4;
return "int32_t";
case 0x03:
case 0x06:
bytesize = 2;
return "int16_t";
case 0x04:
bytesize = 1;
return "int8_t";
case 0x05:
bytesize = 1;
return "uint8_t";
case 0x07:
bytesize = 2;
return "uint16_t";
case 0x09:
bytesize = 4;
return "uint32_t";
case 0x0a:
bytesize = 8;
return "int64_t";
case 0x0b:
bytesize = 8;
return "uint64_t";
case 0x0c:
bytesize = 4;
return "float";
case 0x0d:
bytesize = 8;
return "double";
case 0x18:
bytesize = GetPointerSize();
return "INTPTR";
case 0x19:
bytesize = GetPointerSize();
return "UINTPTR";
}
break;
}
bytesize = GetPointerSize();
return "INTPTR";
}
protected internal virtual bool HasSideEffects(MCInst i)
{ return IsCall(i); }
//public binary_library.IBinaryFile bf;
//public binary_library.ISection text_section;
//public StringTable st;
//public SignatureTable sigt;
//public Requestor r;
protected internal virtual bool NeedsMregLiveness(MCInst i)
{
if (i.p.Length == 0)
return false;
if (i.p[0].t == ir.Opcode.vl_str)
{
switch (i.p[0].v)
{
case Generic.g_precall:
case Generic.g_postcall:
return true;
}
}
return false;
}
protected internal abstract MCInst SaveRegister(Reg r);
protected internal abstract MCInst RestoreRegister(Reg r);
public string name;
public int ptype;
protected internal int psize;
public Trie<InstructionHandler> instrs = new Trie<InstructionHandler>();
public Reg[] regs;
/** <summary>Return a hardware register that can be used for
a particular stack location, or -1 if the actual
stack should be used.</summary>*/
public virtual int GetRegStackLoc(int stack_loc, int ct) { return -1; }
static Target()
{
init_targets();
init_pt();
init_rtmap();
}
public int RationaliseCT(int ct)
{
switch (ct)
{
case Opcode.ct_intptr:
case Opcode.ct_object:
case Opcode.ct_ref:
return ptype;
default:
return ct;
}
}
public class ContentsReg : Reg, IEquatable<Reg>
{
public Reg basereg;
public long disp;
public ContentsReg()
{
type = rt_contents;
}
public override string ToString()
{
if (disp == 0)
return "[" + basereg.ToString() + "]";
else if (disp > 0)
return "[" + basereg.ToString() + " + " + disp.ToString() + "]";
else
return "[" + basereg.ToString() + " - " + (-disp).ToString() + "]";
}
public override bool Equals(Reg other)
{
var cr = other as ContentsReg;
if (cr == null)
return false;
if (basereg.Equals(cr.basereg) == false)
return false;
return disp == cr.disp;
}
public override Reg SubReg(int sroffset, int srsize, Target t = null)
{
if (sroffset + srsize > size)
throw new NotSupportedException();
return new ContentsReg
{
basereg = basereg,
disp = disp + sroffset,
size = srsize
};
}
}
public class AddrAndContentsReg : Reg, IEquatable<Reg>
{
public Reg Addr, Contents;
public override bool Equals(Reg other)
{
var acr = other as AddrAndContentsReg;
if (acr == null)
return false;
if (Addr.Equals(acr.Addr) == false)
return false;
return Contents.Equals(acr.Contents);
}
}
public class Reg : IEquatable<Reg>
{
public string name;
public int id;
public int type;
public int size;
public ulong mask;
public int stack_loc;
public virtual Reg SubReg(int sroffset, int srsize, Target t = null)
{
if(type == rt_multi)
{
List<Reg> comps = new List<Reg>();
for(int i = 0; i < 64; i++)
{
if((mask & (1UL << i)) != 0UL)
{
comps.Add(t.regs[i]);
}
}
int cur_pos = 0;
foreach(var r in comps)
{
if(cur_pos == sroffset)
{
return r;
}
cur_pos += r.size;
}
}
throw new NotSupportedException();
}
public override string ToString()
{
if (name == "stack")
return "stack(" + stack_loc.ToString() + ")";
else
return name;
}
public virtual bool Equals(Reg other)
{
if (other.type != type)
return false;
if (other.id != id)
return false;
if (other.stack_loc != stack_loc)
return false;
return true;
}
public static implicit operator Param(Reg r)
{
return new Param { t = Opcode.vl_mreg, mreg = r };
}
}
protected virtual Reg GetRegLoc(ir.Param csite,
ref int stack_loc,
int cc_next,
int ct,
metadata.TypeSpec ts,
string cc)
{
throw new NotSupportedException("Architecture does not support ct: " + Opcode.ct_names[ct]);
}
internal static List<MCInst> handle_mclabel(
Target t,
List<cil.CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
List<MCInst> r = new List<MCInst>();
r.Add(new MCInst
{
parent = n,
p = new Param[]
{
new Param { t = ir.Opcode.vl_str, v = Generic.g_mclabel, str = "mclabel" },
new Param { t = ir.Opcode.vl_br_target, v = n.imm_l }
}
});
return r;
}
internal int GetSize(metadata.TypeSpec ts)
{
switch (ts.stype)
{
case metadata.TypeSpec.SpecialType.None:
if (ts.m.is_corlib)
{
var simple = ts.m.simple_type_idx[ts.tdrow];
if (simple != -1)
return GetSTypeSize(simple);
}
if (ts.IsValueType)
{
return layout.Layout.GetTypeSize(ts, this, false);
}
return GetCTSize(Opcode.ct_object);
default:
return GetCTSize(Opcode.ct_object);
}
}
private int GetSTypeSize(int stype)
{
switch (stype)
{
case 0x02:
return 1;
case 0x03:
return 2;
case 0x04:
case 0x05:
return 1;
case 0x06:
case 0x07:
return 2;
case 0x08:
case 0x09:
return 4;
case 0x0a:
case 0x0b:
return 8;
case 0x0c:
return 4;
case 0x0d:
return 8;
case 0x0e:
case 0x16:
case 0x1c:
case 0x18:
case 0x19:
case 0x1b:
case 0x11:
return GetPointerSize();
default:
throw new NotSupportedException();
}
}
internal int GetSize(int ptype, uint token)
{
throw new NotSupportedException();
if (ptype == 0x11)
throw new NotImplementedException();
else
{
return GetCTSize(ir.Opcode.GetCTFromType(ptype));
}
}
public virtual int GetPointerSize()
{
return GetCTSize(ptype);
}
internal int GetCTSize(int ct)
{
switch (ct)
{
case ir.Opcode.ct_int32:
return 4;
case ir.Opcode.ct_int64:
return 8;
case ir.Opcode.ct_intptr:
case ir.Opcode.ct_object:
case ir.Opcode.ct_ref:
return GetCTSize(ptype);
case ir.Opcode.ct_float:
return 8;
default:
throw new NotSupportedException();
}
}
protected internal virtual Reg[] GetRegLocs(ir.Param csite,
ref int stack_loc,
Dictionary<int, int[]> cc,
Dictionary<int, int> cc_classmap,
string cc_name,
out int[] la_sizes,
out metadata.TypeSpec[] la_types,
metadata.TypeSpec has_hidden = null)
{
var m = csite.m;
var idx = (int)csite.v2;
metadata.TypeSpec[] gtparams = null;
metadata.TypeSpec[] gmparams = null;
if (csite.ms != null)
{
idx = csite.ms.msig;
m = csite.ms.m;
gtparams = csite.ms.gtparams;
gmparams = csite.ms.gmparams;
}
Dictionary<int, int> cc_next = new Dictionary<int, int>(
new GenericEqualityComparer<int>());
var act_pcount = m.GetMethodDefSigParamCount(idx);
var pcount = act_pcount;
bool has_this = m.GetMethodDefSigHasNonExplicitThis(idx);
idx = m.GetMethodDefSigRetTypeIndex(idx);
if (has_this)
pcount++;
if (has_hidden != null)
pcount++;
// Skip rettype
bool is_req;
uint token;
while (m.GetRetTypeCustomMod(ref idx, out is_req, out token)) ;
m.GetTypeSpec(ref idx, gtparams, gmparams);
// Read types of parameters
Target.Reg[] ret = new Target.Reg[pcount];
la_sizes = new int[pcount];
la_types = new metadata.TypeSpec[pcount];
List<metadata.TypeSpec> la_locs = new List<metadata.TypeSpec>();
if (has_hidden != null)
la_locs.Add(has_hidden);
if(has_this)
{
// value type methods have mptr to type as their this pointer
if (csite.ms.type.IsValueType)
{
la_locs.Add(csite.ms.type.ManagedPointer);
}
else
la_locs.Add(csite.ms.type);
}
for(int i = 0; i < act_pcount; i++)
{
while (m.GetRetTypeCustomMod(ref idx, out is_req, out token)) ;
la_locs.Add(m.GetTypeSpec(ref idx, gtparams, gmparams));
}
for (int i = 0; i < pcount; i++)
{
metadata.TypeSpec v = la_locs[i];
la_types[i] = v;
var size = GetSize(v);
la_sizes[i] = size;
var ct = GetCTFromTypeForCC(v); ir.Opcode.GetCTFromType(v);
if (cc_classmap.ContainsKey(ct))
ct = cc_classmap[ct];
else
ct = GetCCClassFromCT(ct, size, v, cc_name);
Reg r = null;
int cur_cc_next;
if (cc_next.TryGetValue(ct, out cur_cc_next) == false)
cur_cc_next = 0;
int[] cc_map;
if (cc.TryGetValue(ct, out cc_map))
{
if (cur_cc_next >= cc_map.Length)
cur_cc_next = cc_map.Length - 1;
var reg_id = cc_map[cur_cc_next];
if (regs[reg_id].type == rt_stack)
{
Reg rstack = new Reg()
{
type = rt_stack,
id = regs[reg_id].id,
size = size,
stack_loc = stack_loc,
name = regs[reg_id].name,
mask = regs[reg_id].mask
};
stack_loc += size;
var diff = stack_loc % size;
if (diff != 0)
stack_loc = stack_loc + size - diff;
r = rstack;
}
else
r = regs[reg_id];
}
else
{
r = GetRegLoc(csite, ref stack_loc,
cur_cc_next, ct, v, cc_name);
}
cc_next[ct] = cur_cc_next + 1;
ret[i] = r;
}
return ret;
}
public virtual int GetCCClassFromCT(int ct, int size, metadata.TypeSpec ts, string cc)
{
return ct;
}
public virtual bool IsLSB { get { return true; } }
public virtual byte[] IntPtrArray(byte[] v)
{
var ptr_size = GetPointerSize();
var isize = v.Length;
var r = new byte[ptr_size];
for (int i = 0; i < ptr_size; i++)
{
if (IsLSB)
{
if (i < isize)
r[i] = v[i];
else
r[i] = 0;
}
else
throw new NotImplementedException();
}
return r;
}
public virtual bool IsTypeValid(metadata.TypeSpec ts)
{
if (ts == null)
return true;
if (ts.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs19Bits32OnlyAttribute_7#2Ector_Rv_P1u1t") &&
GetPointerSize() != 4)
return false;
if (ts.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs19Bits64OnlyAttribute_7#2Ector_Rv_P1u1t") &&
GetPointerSize() != 8)
return false;
bool is_arch_dependent = false;
bool is_required_arch = false;
foreach (var idx in ts.CustomAttributes("_ZN14libsupcs#2Edll8libsupcs22ArchDependentAttribute_7#2Ector_Rv_P2u1tu1S"))
{
var sig_idx = ts.m.GetCustomAttrSigIdx(idx);
var arch = ts.m.ReadCustomAttrString(ref sig_idx);
is_arch_dependent = true;
if (arch.Equals(name))
is_required_arch = true;
}
if (is_arch_dependent && !is_required_arch)
return false;
return true;
}
public virtual bool IsMethodValid(metadata.MethodSpec ms)
{
if (!IsTypeValid(ms.type))
return false;
if (ms.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs19Bits32OnlyAttribute_7#2Ector_Rv_P1u1t") &&
GetPointerSize() != 4)
return false;
if (ms.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs19Bits64OnlyAttribute_7#2Ector_Rv_P1u1t") &&
GetPointerSize() != 8)
return false;
bool is_arch_dependent = false;
bool is_required_arch = false;
foreach (var idx in ms.CustomAttributes("_ZN14libsupcs#2Edll8libsupcs22ArchDependentAttribute_7#2Ector_Rv_P2u1tu1S"))
{
var sig_idx = ms.m.GetCustomAttrSigIdx(idx);
var arch = ms.m.ReadCustomAttrString(ref sig_idx);
is_arch_dependent = true;
if (arch.Equals(name))
is_required_arch = true;
}
if (is_arch_dependent && !is_required_arch)
return false;
return true;
}
public virtual Reg AllocateValueType(Code c, metadata.TypeSpec ts, ref long alloced, ref int cur_stack)
{
return AllocateStackLocation(c, GetSize(ts), ref cur_stack);
}
public abstract Reg AllocateStackLocation(Code c, int size, ref int cur_stack);
public virtual bool AddDwarfLocation(Reg r, IList<byte> d)
{
return false;
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class BackspaceAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (console.CursorPosition > 0)
{
console.CurrentLine = console.CurrentLine.Remove(console.CursorPosition - 1, 1);
console.CursorPosition--;
}
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class MoveCursorToEndAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
console.CursorPosition = console.CurrentLine.Length;
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs
{
class Enum
{
struct MonoEnumInfo
{
internal System.Type utype;
internal System.Array values;
internal string[] names;
}
[MethodAlias("_ZW6System4Enum_9get_value_Ru1O_P1u1t")]
[WeakLinkage]
[AlwaysCompile]
static unsafe void* get_value(void *obj)
{
/* we can copy the entire enum object to an instance
* of the underlying type and just change the
* vtbl
*/
byte* enum_vtbl = *(byte**)obj;
int enum_size = *(int*)(enum_vtbl + ClassOperations.GetVtblTypeSizeOffset());
void** enum_ti = *(void***)enum_vtbl;
void* ut_vtbl = *(enum_ti + 1);
void* new_obj = MemoryOperations.GcMalloc(enum_size);
MemoryOperations.MemCpy(new_obj, obj, enum_size);
*(void**)new_obj = ut_vtbl;
*(void**)((byte*)new_obj + ClassOperations.GetMutexLockOffset()) = null;
return new_obj;
}
[MethodAlias("_ZW6System4Enum_25InternalGetUnderlyingType_RV11RuntimeType_P1V11RuntimeType")]
[AlwaysCompile]
static internal unsafe TysosType GetUnderlyingEnumType(TysosType enum_type)
{
void* e_type_vtbl = *enum_type.GetImplOffset();
return TysosType.internal_from_vtbl(GetUnderlyingEnumTypeVtbl(*(void**)e_type_vtbl));
}
static internal unsafe void* GetUnderlyingEnumTypeVtbl(void* enum_ti)
{
return *((void**)enum_ti + 1);
}
[MethodAlias("_ZW6System4Enum_25InternalGetCorElementType_RU19System#2EReflection14CorElementType_P1u1t")]
[AlwaysCompile]
static unsafe byte InternalGetCorElementType(void *enum_obj)
{
var enum_type = GetUnderlyingEnumTypeVtbl(**(void***)enum_obj);
if (enum_type == OtherOperations.GetStaticObjectAddress("_Zi"))
return (byte)metadata.CorElementType.I4;
else if (enum_type == OtherOperations.GetStaticObjectAddress("_Zx"))
return (byte)metadata.CorElementType.I8;
throw new NotImplementedException();
}
[WeakLinkage]
[MethodAlias("_ZW6System4Enum_21GetEnumValuesAndNames_Rv_P4V17RuntimeTypeHandleU35System#2ERuntime#2ECompilerServices19ObjectHandleOnStackV19ObjectHandleOnStackb")]
[AlwaysCompile]
static unsafe void get_enum_values_and_names(TysosType enum_type, HandleOnStack values_ptr, HandleOnStack names_ptr, bool getNames)
{
//System.Diagnostics.Debugger.Log(0, "libsupcs", "get_enum_values_and_names: enum_type: " + ((ulong)enum_vtbl).ToString("X16"));
//var enum_type = TysosType.internal_from_vtbl(enum_vtbl);
MonoEnumInfo info;
get_enum_info(enum_type, out info);
ulong[] values = new ulong[info.values.Length];
int[] v = info.values as int[];
for (int i = 0; i < info.values.Length; i++)
values[i] = (ulong)v[i];
*values_ptr.ptr = CastOperations.ReinterpretAsPointer(values);
if(getNames)
{
*names_ptr.ptr = CastOperations.ReinterpretAsPointer(info.names);
}
}
[WeakLinkage]
[MethodAlias("_ZW6System12MonoEnumInfo_13get_enum_info_Rv_P2V4TypeRV12MonoEnumInfo")]
[AlwaysCompile]
static unsafe void get_enum_info(TysosType enumType, out MonoEnumInfo info)
{
MonoEnumInfo ret = new MonoEnumInfo();
ret.utype = GetUnderlyingEnumType(enumType);
if (!ret.utype.Equals(typeof(int)))
{
throw new Exception("get_enum_info: currently only enums with an underlying type of int are supported");
}
var ets = enumType.tspec;
/* Iterate through methods looking for requested
one */
var first_fdef = ets.m.GetIntEntry(metadata.MetadataStream.tid_TypeDef,
ets.tdrow, 4);
var last_fdef = ets.m.GetLastFieldDef(ets.tdrow);
// First iterate to get number of satic fields
int static_fields = 0;
for(uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
var flags = ets.m.GetIntEntry(metadata.MetadataStream.tid_Field,
(int)fdef_row, 0);
if ((flags & 0x10) == 0x10)
static_fields++;
}
ret.names = new string[static_fields];
int[] values = new int[static_fields];
System.Diagnostics.Debugger.Log(0, "libsupcs", "Enum.get_enum_info: found " + static_fields.ToString() + " entries");
static_fields = 0;
// Iterate again to get the details
for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
var flags = ets.m.GetIntEntry(metadata.MetadataStream.tid_Field,
(int)fdef_row, 0);
if ((flags & 0x10) == 0x10)
{
var name = ets.m.GetStringEntry(metadata.MetadataStream.tid_Field,
(int)fdef_row, 1);
ret.names[static_fields] = name;
System.Diagnostics.Debugger.Log(0, "libsupcs", "Enum.get_enum_info: field: " + name);
var const_row = ets.m.const_field_owners[fdef_row];
if(const_row != 0)
{
var const_offset = (int)ets.m.GetIntEntry(metadata.MetadataStream.tid_Constant,
const_row, 2);
ets.m.SigReadUSCompressed(ref const_offset);
var const_val = ets.m.sh_blob.di.ReadInt(const_offset);
values[static_fields] = const_val;
System.Diagnostics.Debugger.Log(0, "libsupcs", "Enum.get_enum_info: value: " + const_val.ToString());
}
static_fields++;
}
}
ret.values = values;
info = ret;
}
[WeakLinkage]
[MethodAlias("_ZW6System4Enum_6Equals_Rb_P2u1tu1O")]
[AlwaysCompile]
static unsafe bool Equals(void *a, void *b)
{
/* a is guaranteed to be a System.Enum, therefore just ensuring b
* is the same type ensures b is an enum */
void* avtbl = *(void**)a;
void* bvtbl = *(void**)b;
if (avtbl != bvtbl)
return false;
/* Get size of data to compare */
var tsize = *(int*)((byte*)avtbl + ClassOperations.GetVtblTypeSizeOffset()) - ClassOperations.GetBoxedTypeDataOffset();
int* adata = (int*)((byte*)a + ClassOperations.GetBoxedTypeDataOffset());
int* bdata = (int*)((byte*)b + ClassOperations.GetBoxedTypeDataOffset());
/* Use lowest common denominator of int32s for comparison (most enums are int32s) */
for(int i = 0; i < tsize; i+=4, adata++, bdata++)
{
if (*adata != *bdata)
return false;
}
return true;
}
#if false
[MethodAlias("_ZW6System4Enum_8ToObject_Ru1O_P2V4Typeu1O")]
[AlwaysCompile]
static unsafe object to_object(TysosType enum_type, object value)
{
/* Convert value (of an integral type) to an enum of type 'enum_type'
* and return its boxed value
*/
if (enum_type == null)
throw new ArgumentNullException("enumType");
if (value == null)
throw new ArgumentException("value");
/* The incoming value type 'value' is already boxed.
*
* We can therefore just copy its data to a new enum object
*/
void* value_obj = CastOperations.ReinterpretAsPointer(value);
void* value_vtbl = *(void**)value_obj;
int value_csize = *(int*)((byte*)value_vtbl + ClassOperations.GetVtblTypeSizeOffset());
void* ret_obj = MemoryOperations.GcMalloc(value_csize);
MemoryOperations.MemCpy(ret_obj, value_obj, value_csize);
void* ret_vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(enum_type) + ClassOperations.GetSystemTypeImplOffset());
*(void**)ret_obj = ret_vtbl;
*(void**)((byte*)ret_obj + ClassOperations.GetMutexLockOffset()) = null;
return CastOperations.ReinterpretAsObject(ret_obj);
}
#endif
}
}
<file_sep>/* Copyright (C) 2008 - 2013 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Runtime.CompilerServices;
namespace libsupcs
{
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited = false, AllowMultiple = false)]
public sealed class SpecialTypeAttribute : System.Attribute
{ }
/** <summary>This attribute is for use by the CMExpLib library to identify certain entries in TysosType structures etc which
* point to a null-terminated list of items of type 'type' (e.g. the Method list)</summary> */
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = false)]
public sealed class NullTerminatedListOfAttribute : System.Attribute
{
public NullTerminatedListOfAttribute(System.Type type) { }
}
/** <summary>Apply to an interface or method to have the call changed to one to invoke(void *mptr, object[] params, void *rettype_vtbl, uint flags) </summary> */
[System.AttributeUsage(System.AttributeTargets.Interface | System.AttributeTargets.Method, AllowMultiple = false)]
public sealed class AlwaysInvokeAttribute : System.Attribute
{ }
/** <summary>Have the class or method only be compiled for a particular architecture</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class ArchDependentAttribute : System.Attribute
{
public ArchDependentAttribute(string arch) { }
}
/** <summary>Have the class or method only be compiled for a particular OS</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class OSDependentAttribute : System.Attribute
{
public OSDependentAttribute(string os) { }
}
/** <summary>Have the class or method only be compiled for 64-bit targets</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class Bits64OnlyAttribute : System.Attribute
{
public Bits64OnlyAttribute() { }
}
/** <summary>Have the class or method only be compiled for 32-bit targets</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class Bits32OnlyAttribute : System.Attribute
{
public Bits32OnlyAttribute() { }
}
/** <summary>This marks a structure that is used to pass register contents to an interrupt handler</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Struct)]
public sealed class InterruptRegisterStructureAttribute : System.Attribute
{
public InterruptRegisterStructureAttribute() { }
}
/** <summary>Any calls to this method (declared as extern without a body in C#) will instead call the following label</summary>
*/
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class MethodReferenceAliasAttribute : System.Attribute
{
public MethodReferenceAliasAttribute(string alias) { }
}
/** <summary>Give this field a separate alias to allow easy access for unmanaged code. Only applicable to static fields (ignored for instance fields).</summary>
*/
[global::System.AttributeUsage(System.AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class FieldAliasAttribute : System.Attribute
{
public FieldAliasAttribute(string alias) { }
}
/** <summary>Any references to this field (declared as a static field) will instead reference the following label</summary>
*/
[global::System.AttributeUsage(System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public sealed class FieldReferenceAliasAttribute : System.Attribute
{
public FieldReferenceAliasAttribute(string alias) { }
}
/** <summary>Any references to this field (declared as a static field) will instead reference the address of following label (don't try to write to it)</summary>
*/
[global::System.AttributeUsage(System.AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public sealed class FieldReferenceAliasAddressAttribute : System.Attribute
{
public FieldReferenceAliasAddressAttribute(string alias) { }
}
/** <summary>Mark the method as a 'ReinterpretAs' method that performs a cast without type checking</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class ReinterpretAsMethodAttribute : System.Attribute
{
public ReinterpretAsMethodAttribute() { }
}
/** <summary>Generate another symbol name for the given method</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class MethodAliasAttribute : System.Attribute
{
public MethodAliasAttribute(string alias) { }
}
/** <summary>Override the calling convention used by a particular method</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class CallingConventionAttribute : System.Attribute
{
public CallingConventionAttribute(string callconv) { }
}
/** <summary>Mark the method to have weak linkage</summary> */
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class WeakLinkageAttribute : System.Attribute
{
public WeakLinkageAttribute() { }
}
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class ExtraArgumentAttribute : System.Attribute
{
public ExtraArgumentAttribute(int arg_no, int base_type) { }
}
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class IgnoreImplementationAttribute : System.Attribute
{ }
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AlwaysCompileAttribute : System.Attribute
{ }
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class SyscallAttribute : System.Attribute
{ }
[global::System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class OutputCHeaderAttribute : System.Attribute
{ }
[global::System.AttributeUsage(System.AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public sealed class ProfileAttribute : System.Attribute
{
public ProfileAttribute(bool profile) { }
}
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public sealed class VTableAliasAttribute : System.Attribute
{
public VTableAliasAttribute(string alias) { }
}
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public sealed class TypeInfoAliasAttribute : System.Attribute
{
public TypeInfoAliasAttribute(string alias) { }
}
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class ExtendsOverrideAttribute : System.Attribute
{
public ExtendsOverrideAttribute(string extends) { }
}
/** <summary> Marks the class as having no base class (not even System.Object)</summary> */
[System.AttributeUsage(System.AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public sealed class NoBaseClassAttribute : System.Attribute
{
public NoBaseClassAttribute() { }
}
public class MemoryOperations
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern byte PeekU1(System.UIntPtr addr);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern ushort PeekU2(System.UIntPtr addr);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern uint PeekU4(System.UIntPtr addr);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern ulong PeekU8(System.UIntPtr addr);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void Poke(System.UIntPtr addr, byte b);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void Poke(System.UIntPtr addr, ushort v);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void Poke(System.UIntPtr addr, uint v);
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void Poke(System.UIntPtr addr, ulong v);
[Bits64Only]
[WeakLinkage]
public static void QuickClearAligned16(ulong addr, ulong size)
{
unsafe
{
MemSet((void*)addr, 0, (int)size);
}
}
[MethodReferenceAlias("memset")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern void* MemSet(void* s, int c, int size);
[MethodReferenceAlias("memcpy")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern void* MemCpy(void* dest, void* src, int size);
[MethodReferenceAlias("memcmp")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int MemCmp(void* s1, void* s2, int size);
[MethodReferenceAlias("memmove")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern void* MemMove(void* dest, void* src, int size);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void * GetInternalArray(System.Array array);
[MethodReferenceAlias("gcmalloc")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern object GcMalloc(System.IntPtr size);
[MethodReferenceAlias("gcmalloc")]
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern void* GcMalloc(int size);
}
public class IoOperations
{
[ArchDependent("x86_64")]
[ArchDependent("x86")]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void PortOut(ushort port, byte v);
[ArchDependent("x86_64")]
[ArchDependent("x86")]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void PortOut(ushort port, ushort v);
[ArchDependent("x86_64")]
[ArchDependent("x86")]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern void PortOut(ushort port, uint v);
[ArchDependent("x86_64")]
[ArchDependent("x86")]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern byte PortInb(ushort port);
[ArchDependent("x86_64")]
[ArchDependent("x86")]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern ushort PortInw(ushort port);
[ArchDependent("x86_64")]
[ArchDependent("x86")]
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
public static extern uint PortInd(ushort port);
}
public class CastOperations
{
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern T ReinterpretAs<T>(object o);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public unsafe static extern T ReinterpretAs<T>(void* o);
[Bits64Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern ulong ReinterpretAsUlong(object o);
[Bits32Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern uint ReinterpretAsUInt(object o);
[Bits64Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern object ReinterpretAsObject(ulong addr);
[Bits32Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern object ReinterpretAsObject(uint addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public unsafe static extern object ReinterpretAsObject(void* addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public unsafe static extern string ReinterpretAsString(void* addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern System.UIntPtr ReinterpretAsUIntPtr(object o);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern System.IntPtr ReinterpretAsIntPtr(object o);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public unsafe static extern void* ReinterpretAsPointer(object o);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public unsafe static extern void* ReinterpretAsPointer(System.IntPtr o);
[Bits64Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public static extern ulong GetArg0U8();
}
public class ClassOperations
{
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetTypedReferenceTypeOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetTypedReferenceValueOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetMutexLockOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblFieldOffset();
//[MethodImpl(MethodImplOptions.InternalCall)]
//public static extern int GetObjectIdFieldOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblTypeInfoPtrOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblInterfacesPtrOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblExtendsVtblPtrOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblTypeSizeOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblFlagsOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblBaseTypeVtblOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetVtblTargetFieldsOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetBoxedTypeDataOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetSystemTypeImplOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public extern static int GetFieldOffset(string typename, string field);
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public extern static int GetStaticFieldOffset(string typename, string field);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetDelegateFPtrOffset();
}
public unsafe class JitOperations
{
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("jit_tm")]
public static extern void* JitCompile(metadata.MethodSpec ms);
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("jit_vtable")]
public static extern void* JitCompile(metadata.TypeSpec ts);
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("jit_addrof")]
public static extern void* GetAddressOfObject(string name);
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("jit_nameof")]
public static extern string GetNameOfAddress(void* addr, out void* offset);
}
public class OtherOperations
{
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void Halt();
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public static extern void Exit();
[Bits64Only]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void CallI(ulong address);
[Bits32Only]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void CallI(uint address);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static void CallI(System.UIntPtr address);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe extern static void CallI(void *address);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe extern static void CallI(void* obj, void* address);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe extern static T CallI<T>(void* address);
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public extern static int GetUsedStackSize();
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public unsafe extern static void* GetStaticObjectAddress(string name);
[MethodImpl(MethodImplOptions.InternalCall)]
[IgnoreImplementation]
public unsafe extern static void* GetFunctionAddress(string name);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static int GetPointerSize();
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static System.UIntPtr Add(System.UIntPtr a, System.UIntPtr b);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static System.IntPtr Add(System.IntPtr a, System.IntPtr b);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static System.UIntPtr Sub(System.UIntPtr a, System.UIntPtr b);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static System.IntPtr Sub(System.IntPtr a, System.IntPtr b);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static System.UIntPtr Mul(System.UIntPtr a, System.UIntPtr b);
[MethodImpl(MethodImplOptions.InternalCall)]
public extern static System.IntPtr Mul(System.IntPtr a, System.IntPtr b);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void* GetReturnAddress();
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void Spinlock(void* ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void Spinunlock(void* ptr);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern byte SyncValCompareAndSwap(byte* ptr, byte oldval, byte newval);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern ushort SyncValCompareAndSwap(ushort* ptr, ushort oldval, ushort newval);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern short SyncValCompareAndSwap(short* ptr, short oldval, short newval);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern uint SyncValCompareAndSwap(uint* ptr, uint oldval, uint newval);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern int SyncValCompareAndSwap(int* ptr, int oldval, int newval);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void SpinlockHint();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void AsmBreakpoint();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern System.IntPtr EnterUninterruptibleSection();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void ExitUninterruptibleSection(System.IntPtr state);
[MethodImpl(MethodImplOptions.InternalCall)]
public unsafe static extern void* CompareExchange(void** addr, void* value, void* comparand = null);
[MethodImpl(MethodImplOptions.InternalCall)]
[MethodReferenceAlias("__get_unwinder")]
public static extern Unwinder GetUnwinder();
}
public class ArrayOperations
{
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetRankOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetElemSizeOffset();
/** <summary>Get the number of items in the inner array (multiply by elemsize to get the byte length) */
//[MethodImpl(MethodImplOptions.InternalCall)]
//public static unsafe extern int GetInnerArrayLengthOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetElemTypeOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetLoboundsOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetSizesOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetInnerArrayOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern int GetArrayClassSize();
}
public class StringOperations
{
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetLengthOffset();
[MethodImpl(MethodImplOptions.InternalCall)]
public static unsafe extern int GetDataOffset();
internal static unsafe char* GetChars(string s)
{
byte* s2 = (byte*)CastOperations.ReinterpretAsPointer(s);
return (char*)(s2 + GetDataOffset());
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* This defines the TysosAssembly which is a subtype of System.Reflection.Assembly
*
* All AssemblyInfo structures produced by tysila2 follow this layout
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
using System.Reflection;
namespace libsupcs
{
/* System.Reflection.Assembly defines an internal constructor, so we cannot subclass
* it directly outside of corlib therefore we need to use the following attribute */
[ExtendsOverride("_ZW19System#2EReflection15RuntimeAssembly")]
[VTableAlias("__tysos_assembly_vt")]
public unsafe class TysosAssembly : System.Reflection.Assembly
{
TysosModule m;
string assemblyName;
internal TysosAssembly(TysosModule mod, string ass_name)
{
m = mod;
assemblyName = ass_name;
}
[MethodAlias("_ZW19System#2EReflection8Assembly_8GetTypes_Ru1ZU6System4Type_P2u1tb")]
System.Type[] GetTypes(bool exportedOnly)
{
throw new NotImplementedException();
}
[AlwaysCompile]
[MethodAlias("_ZW19System#2EReflection8Assembly_27GetManifestResourceInternal_Ru1I_P4u1tu1SRiRV6Module")]
static void* GetManifestResource(TysosAssembly ass, string name, out int size, out System.Reflection.Module mod)
{
// this always fails for now
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly: GetManifestResource(" + ass.assemblyName + ", " + name + ", out int size, out Module mod) called");
size = 0;
mod = null;
return null;
}
public override string FullName => assemblyName;
struct StackCrawlMarkHandle { internal void** ptr; }
[AlwaysCompile]
[MethodAlias("_ZW19System#2EReflection15RuntimeAssembly_20GetExecutingAssembly_Rv_P2U35System#2ERuntime#2ECompilerServices20StackCrawlMarkHandleV19ObjectHandleOnStack")]
static void GetExecutingAssembly(StackCrawlMarkHandle scmh, TysosModule.ObjectHandleOnStack ret)
{
int scm = *(int*)scmh.ptr;
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: scm: " + scm.ToString());
Unwinder u = OtherOperations.GetUnwinder();
u.UnwindOne();
u.UnwindOne(); // we are double-nested within coreclr so unwind this and calling method (GetExecutingAssembly(ref StackMarkHandle)) first
switch(scm)
{
case 0:
break;
case 1:
u.UnwindOne();
break;
case 2:
u.UnwindOne();
u.UnwindOne();
break;
default:
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: unsupported scm: " + scm.ToString());
throw new NotSupportedException();
}
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: requested pc " + ((ulong)u.GetInstructionPointer()).ToString("X"));
void* offset;
var name = JitOperations.GetNameOfAddress((void*)u.GetInstructionPointer(), out offset);
if(name == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: symbol not found");
*ret.ptr = null;
return;
}
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: found method " + name);
var ts = Metadata.MSCorlib.DemangleObject(name);
if(ts == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: demangler returned null");
*ret.ptr = null;
return;
}
var m = ts.Metadata;
if (m == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: returned ts had no assembly");
*ret.ptr = null;
return;
}
var aptr = (m.file as Metadata.BinaryInterface).b;
var retm = TysosModule.GetModule(aptr, m.AssemblyName);
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetExecutingAssembly: returning " + retm.ass.assemblyName);
*ret.ptr = CastOperations.ReinterpretAsPointer(retm.ass);
}
[MethodAlias("_ZW19System#2EReflection15RuntimeAssembly_11GetResource_RPh_P5V15RuntimeAssemblyu1SRyU35System#2ERuntime#2ECompilerServices20StackCrawlMarkHandleb")]
[AlwaysCompile]
static byte* GetResource(TysosAssembly ass, string resourceName, out ulong length, StackCrawlMarkHandle stackMark,
bool skipSecurityCheck)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetResource(" + ass.assemblyName + ", " + resourceName + ", out ulong length, " +
"StackCrawlMarkHandle stackMark, bool skipSecurityCheck) called");
var res_addr = JitOperations.GetAddressOfObject(ass.assemblyName + "_resources");
if(res_addr == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetResource: cannot find " + ass.assemblyName + "_resources");
length = 0;
return null;
}
uint* ret = (uint*)res_addr;
// length is the first int32
length = *ret++;
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosAssembly.GetResource: returning: " + ((ulong)ret).ToString("X") +
", length: " + length.ToString("X"));
return (byte*)ret;
}
[AlwaysCompile]
[MethodAlias("_ZW19System#2EReflection12AssemblyName_5nInit_Rv_P4u1tRV15RuntimeAssemblybb")]
static unsafe void AssemblyName_nInit(byte *obj, out TysosAssembly assembly, bool forIntrospection, bool raiseResolveEvent)
{
string name = CastOperations.ReinterpretAsString(*(void**)(obj + ClassOperations.GetFieldOffset("_ZW19System#2EReflection12AssemblyName", "_Name")));
System.Diagnostics.Debugger.Log(0, "libsupcs", "AssemblyName_nInit(" + name + ", out TysosAssembly, bool, bool) called");
// split assembly name off from other fields
int comma = name.IndexOf(',');
string Name;
if (comma != -1)
Name = name.Substring(0, comma);
else
Name = name;
if (Name.Equals("System.Private.CoreLib"))
Name = "mscorlib";
*(void**)(obj + ClassOperations.GetFieldOffset("_ZW19System#2EReflection12AssemblyName", "_Name")) =
CastOperations.ReinterpretAsPointer(Name);
System.Diagnostics.Debugger.Log(0, "libsupcs", "AssemblyName_nInit - setting _Name to " + Name);
assembly = null;
}
[AlwaysCompile]
[MethodAlias("_ZW19System#2EReflection12AssemblyName_18nGetPublicKeyToken_Ru1Zh_P1u1t")]
static unsafe byte[] AssemblyName_nGetPublicKeyToken(byte *obj)
{
return null;
}
}
[VTableAlias("__tysos_module_vt")]
[ExtendsOverride("_ZW19System#2EReflection13RuntimeModule")]
public unsafe class TysosModule
{
internal void* aptr; /* pointer to assembly */
long compile_time;
public DateTime CompileTime { get { return new DateTime(compile_time); } }
internal TysosAssembly ass;
internal TysosModule(void *_aptr, string ass_name)
{
aptr = _aptr;
ass = new TysosAssembly(this, ass_name);
}
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosModule ReinterpretAsTysosModule(System.Reflection.Module module);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
internal static extern Module ReinterpretAsModule(object o);
internal metadata.MetadataStream m { get { return Metadata.BAL.GetAssembly(aptr); } }
unsafe internal struct ObjectHandleOnStack { internal void** ptr; }
[MethodAlias("_ZW6System12ModuleHandle_13GetModuleType_Rv_P2U19System#2EReflection13RuntimeModuleU35System#2ERuntime#2ECompilerServices19ObjectHandleOnStack")]
[AlwaysCompile]
static void ModuleHandle_GetModuleType(TysosModule mod, ObjectHandleOnStack oh)
{
// Get the <Module> type name for the current module. This is always defined as tdrow 1.
var ts = (TysosType)mod.m.GetTypeSpec(metadata.MetadataStream.tid_TypeDef, 1);
*oh.ptr = CastOperations.ReinterpretAsPointer(ts);
}
static Dictionary<ulong, TysosModule> mod_cache = new Dictionary<ulong, TysosModule>(new metadata.GenericEqualityComparer<ulong>());
internal TysosAssembly GetAssembly()
{
return ass;
}
static internal TysosModule GetModule(void *aptr, string ass_name)
{
var mfile = CastOperations.ReinterpretAsUlong(CastOperations.ReinterpretAsObject(aptr));
lock (mod_cache)
{
if (!mod_cache.TryGetValue(mfile, out var ret))
{
ret = new TysosModule(aptr, ass_name);
mod_cache[mfile] = ret;
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: building new TysosModule for " + ass_name);
}
return ret;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5
{
public class TysilaState
{
public binary_library.IBinaryFile bf;
public binary_library.ISection text_section;
public StringTable st;
public SignatureTable sigt;
public Requestor r;
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class IgnoreAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
// Do nothing. "Ignore" the command
}
}
}
<file_sep>/* ===-- int_lib.h - configuration header for compiler-rt -----------------===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
* ===----------------------------------------------------------------------===
*
* This file is not part of the interface of this library.
*
* This file defines various standard types, most importantly a number of unions
* used to access parts of larger types.
*
* ===----------------------------------------------------------------------===
*/
#ifndef INT_TYPES_H
#define INT_TYPES_H
#include "int_endianness.h"
/* si_int is defined in Linux sysroot's asm-generic/siginfo.h */
#ifdef si_int
#undef si_int
#endif
typedef int si_int;
typedef unsigned su_int;
typedef long long di_int;
typedef unsigned long long du_int;
typedef union
{
di_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
su_int low;
si_int high;
#else
si_int high;
su_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} dwords;
typedef union
{
du_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
su_int low;
su_int high;
#else
su_int high;
su_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} udwords;
/* MIPS64 issue: PR 20098 */
#if (defined(__LP64__) || defined(__wasm__)) && \
!(defined(__mips__) && defined(__clang__))
#define CRT_HAS_128BIT
#endif
#ifdef CRT_HAS_128BIT
typedef int ti_int __attribute__ ((mode (TI)));
typedef unsigned tu_int __attribute__ ((mode (TI)));
typedef union
{
ti_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
du_int low;
di_int high;
#else
di_int high;
du_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} twords;
typedef union
{
tu_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
du_int low;
du_int high;
#else
du_int high;
du_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} utwords;
static __inline ti_int make_ti(di_int h, di_int l) {
twords r;
r.s.high = h;
r.s.low = l;
return r.all;
}
static __inline tu_int make_tu(du_int h, du_int l) {
utwords r;
r.s.high = h;
r.s.low = l;
return r.all;
}
#endif /* CRT_HAS_128BIT */
typedef union
{
su_int u;
float f;
} float_bits;
typedef union
{
udwords u;
double f;
} double_bits;
typedef struct
{
#if _YUGA_LITTLE_ENDIAN
udwords low;
udwords high;
#else
udwords high;
udwords low;
#endif /* _YUGA_LITTLE_ENDIAN */
} uqwords;
typedef union
{
uqwords u;
long double f;
} long_double_bits;
#if __STDC_VERSION__ >= 199901L
typedef float _Complex Fcomplex;
typedef double _Complex Dcomplex;
typedef long double _Complex Lcomplex;
#define COMPLEX_REAL(x) __real__(x)
#define COMPLEX_IMAGINARY(x) __imag__(x)
#else
typedef struct { float real, imaginary; } Fcomplex;
typedef struct { double real, imaginary; } Dcomplex;
typedef struct { long double real, imaginary; } Lcomplex;
#define COMPLEX_REAL(x) (x).real
#define COMPLEX_IMAGINARY(x) (x).imaginary
#endif
#endif /* INT_TYPES_H */
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace libtysila5.util
{
/** <summary>Simple and fast representation of a set as a
bitmap for quick setting an getting</summary> */
public class Set : IEnumerable<int>
{
int min_val;
int set_count;
List<ulong> b;
public Set(int length = 64, int min = 0)
{
min_val = min;
var ulongs = (length - 1) / 64 + 1;
b = new List<ulong>(ulongs);
set_count = 0;
}
private Set() { }
public void set(int bit)
{
if (bit < min_val)
throw new ArgumentOutOfRangeException();
int ul_idx = (bit - min_val) / 64;
int bit_idx = (bit - min_val) % 64;
while (ul_idx >= b.Count)
b.Add(0);
if ((b[ul_idx] & (1UL << bit_idx)) == 0)
set_count++;
b[ul_idx] |= (1UL << bit_idx);
}
public void set(IEnumerable<int> other)
{
foreach (var o in other)
set(o);
}
public void unset(int bit)
{
if (bit < min_val)
throw new ArgumentOutOfRangeException();
int ul_idx = (bit - min_val) / 64;
int bit_idx = (bit - min_val) % 64;
while (ul_idx >= b.Count)
b.Add(0);
if ((b[ul_idx] & (1UL << bit_idx)) != 0)
set_count--;
b[ul_idx] &= ~(1UL << bit_idx);
}
internal void Intersect(ulong v)
{
if (b.Count == 0)
return;
if (b.Count > 1)
b.RemoveRange(1, b.Count - 1);
b[0] = b[0] & v;
recalc_set_count();
}
public void Union(ulong v)
{
if (b.Count == 0)
b.Add(v);
else
b[0] |= v;
recalc_set_count();
}
public void unset(Set other) { AndNot(other); }
public void set(Set other) { Union(other); }
public bool get(int bit)
{
if (bit < min_val)
throw new ArgumentOutOfRangeException();
int ul_idx = (bit - min_val) / 64;
int bit_idx = (bit - min_val) % 64;
if (ul_idx >= b.Count)
return false;
var ret = b[ul_idx] & (1UL << bit_idx);
if (ret == 0)
return false;
return true;
}
public int get_first_unset()
{
for(int i = 0; i < b.Count; i++)
{
var ul = b[i];
if (ul == 0xffffffffffffffffUL)
continue;
for(int bit_idx = 0; bit_idx < 64; bit_idx++)
{
if (((ul >> bit_idx) & 1UL) == 1)
continue;
return min_val + i * 64 + bit_idx;
}
}
return -1;
}
public int get_first_set()
{
for (int i = 0; i < b.Count; i++)
{
var ul = b[i];
if (ul == 0)
continue;
for (int bit_idx = 0; bit_idx < 64; bit_idx++)
{
if (((ul >> bit_idx) & 1UL) == 0)
continue;
return min_val + i * 64 + bit_idx;
}
}
return -1;
}
public int get_last_set()
{
for (int i = b.Count - 1; i >= 0; i--)
{
var ul = b[i];
if (ul == 0)
continue;
for (int bit_idx = 63; bit_idx >= 0; bit_idx--)
{
if (((ul >> bit_idx) & 1UL) == 0)
continue;
return min_val + i * 64 + bit_idx;
}
}
return -1;
}
public Set Clone()
{
var ret = new Set();
ret.min_val = min_val;
ret.b = new List<ulong>(b);
ret.set_count = set_count;
return ret;
}
public int Count { get { return set_count; } }
public bool Empty { get { return set_count == 0; } }
public IEnumerator<int> GetEnumerator()
{
for(int ul_idx = 0; ul_idx < b.Count; ul_idx++)
{
var cur_b = b[ul_idx];
if (cur_b == 0)
continue;
for(int bit_idx = 0; bit_idx < 64; bit_idx++)
{
if ((cur_b & (1UL << bit_idx)) != 0)
yield return min_val + ul_idx * 64 + bit_idx;
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
void recalc_set_count()
{
set_count = 0;
for(int i = 0; i < b.Count; i++)
{
var cur_b = b[i];
for(int bit_idx = 0; bit_idx < 64; bit_idx++)
{
if ((cur_b & (1UL << bit_idx)) != 0)
set_count++;
}
}
}
public void Intersect(Set other)
{
int max_ulongs = b.Count;
if (other.b.Count > max_ulongs)
max_ulongs = other.b.Count;
while(b.Count < max_ulongs)
b.Add(0);
while(other.b.Count < max_ulongs)
other.b.Add(0);
for (int i = 0; i < b.Count; i++)
b[i] &= other.b[i];
recalc_set_count();
}
public void Union(Set other)
{
int max_ulongs = b.Count;
if (other.b.Count > max_ulongs)
max_ulongs = other.b.Count;
while (b.Count < max_ulongs)
b.Add(0);
while (other.b.Count < max_ulongs)
other.b.Add(0);
for (int i = 0; i < b.Count; i++)
b[i] |= other.b[i];
recalc_set_count();
}
public void AndNot(Set other)
{
int max_ulongs = b.Count;
if (other.b.Count > max_ulongs)
max_ulongs = other.b.Count;
while (b.Count < max_ulongs)
b.Add(0);
while (other.b.Count < max_ulongs)
other.b.Add(0);
for (int i = 0; i < b.Count; i++)
b[i] &= ~other.b[i];
recalc_set_count();
}
public override bool Equals(object obj)
{
var other = obj as Set;
if (other == null)
return false;
int max_ulongs = b.Count;
if (other.b.Count > max_ulongs)
max_ulongs = other.b.Count;
while (b.Count < max_ulongs)
b.Add(0);
while (other.b.Count < max_ulongs)
other.b.Add(0);
for (int i = 0; i < b.Count; i++)
{
if (b[i] != other.b[i])
return false;
}
return true;
}
public override int GetHashCode()
{
int hc = 0;
foreach (var u in b)
hc = (hc << 4) ^ u.GetHashCode();
return hc;
}
public void Clear()
{
for (int i = 0; i < b.Count; i++)
b[i] = 0;
set_count = 0;
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.ir
{
public partial class Opcode
{
public int oc = oc_null;
public int cc = cc_always;
/* parameters */
public Param[] uses;
public Param[] defs;
public int data_size = 0;
public int il_offset;
public bool empties_stack = false; // leave empties the entire stack
public int oc_idx; // used for SSA pass
public metadata.TypeSpec call_retval; // value returned by a call instruction
public int call_retval_stype;
public List<Opcode> phis = new List<Opcode>();
public List<Opcode> post_insts = new List<Opcode>();
public List<Opcode> pre_insts = new List<Opcode>();
public IEnumerable<Opcode> all_insts
{
get
{
foreach (var phi in phis)
yield return phi;
foreach (var pre in pre_insts)
yield return pre;
yield return this;
foreach (var post in post_insts)
yield return post;
}
}
public IEnumerable<Param> usesdefs
{
get
{
if (uses != null)
{
foreach (Param p in uses)
yield return p;
}
if (defs != null)
{
foreach (Param p in defs)
yield return p;
}
}
}
public bool is_mc = false;
public List<target.MCInst> mcinsts;
public static Dictionary<int, string> oc_names;
public static Dictionary<int, string> cc_names;
public static Dictionary<int, int> cc_invert_map;
public static Dictionary<int, string> ct_names;
public static Dictionary<cil.Opcode.SingleOpcodes, int> cc_single_map;
public static Dictionary<cil.Opcode.DoubleOpcodes,int> cc_double_map;
public static Dictionary<int, GetDefTypeHandler> oc_pushes_map
= new Dictionary<int, GetDefTypeHandler>(
new GenericEqualityComparer<int>());
public static Dictionary<int, string> vl_names
= new Dictionary<int, string>(
new GenericEqualityComparer<int>());
public delegate int GetDefTypeHandler(Opcode start, target.Target t);
static Opcode()
{
// Pull in mappings defined in IrOpcodes.td
oc_names = new Dictionary<int, string>();
cc_names = new Dictionary<int, string>();
ct_names = new Dictionary<int, string>();
cc_single_map = new Dictionary<cil.Opcode.SingleOpcodes, int>(
new metadata.GenericEqualityComparerEnum<cil.Opcode.SingleOpcodes>());
cc_double_map = new Dictionary<cil.Opcode.DoubleOpcodes, int>(
new metadata.GenericEqualityComparerEnum<cil.Opcode.DoubleOpcodes>());
cc_invert_map = new Dictionary<int, int>();
init_oc();
init_cc();
init_ct();
init_cc_single_map();
init_cc_double_map();
init_cc_invert();
init_oc_pushes_map();
init_vl();
}
public bool HasSideEffects
{
get
{
switch (oc)
{
case oc_call:
return true;
default:
return false;
}
}
}
}
public class Param
{
public int t;
public long v;
public long v2;
public string str;
public target.Target.Reg mreg;
public metadata.MetadataStream m;
public metadata.MethodSpec ms;
public metadata.TypeSpec ts;
public int ct = Opcode.ct_unknown;
public int ssa_idx = -1;
public bool stack_abs = false;
public bool want_address = false;
public enum UseDefType { Unknown, Use, Def };
public UseDefType ud = UseDefType.Unknown;
/* These are used for constant folding */
internal int cf_stype = 0;
internal metadata.TypeSpec cf_type = null;
internal long cf_intval = 0;
internal ulong cf_uintval = 0;
internal bool cf_hasval = false;
public bool IsStack { get { return t == Opcode.vl_stack || t == Opcode.vl_stack32 || t == Opcode.vl_stack64; } }
public bool IsLV { get { return t == Opcode.vl_lv || t == Opcode.vl_lv32 || t == Opcode.vl_lv64; } }
public bool IsLA { get { return t == Opcode.vl_arg || t == Opcode.vl_arg32 || t == Opcode.vl_arg64; } }
public bool IsMreg { get { return t == Opcode.vl_mreg; } }
public bool IsUse { get { return ud == UseDefType.Use; } }
public bool IsDef { get { return ud == UseDefType.Def; } }
public bool IsConstant { get { return t == Opcode.vl_c || t == Opcode.vl_c32 || t == Opcode.vl_c64; } }
/** <summary>Decorate the current type to include bitness</summary> */
public int DecoratedType(target.Target tgt)
{
int new_ct = ct;
if (new_ct == Opcode.ct_intptr)
new_ct = tgt.ptype;
switch(t)
{
case Opcode.vl_arg:
if (new_ct == Opcode.ct_int32)
return Opcode.vl_arg32;
else if (new_ct == Opcode.ct_int64)
return Opcode.vl_arg64;
return t;
case Opcode.vl_stack:
if (new_ct == Opcode.ct_int32)
return Opcode.vl_stack32;
else if (new_ct == Opcode.ct_int64)
return Opcode.vl_stack64;
return t;
case Opcode.vl_lv:
if (new_ct == Opcode.ct_int32)
return Opcode.vl_lv32;
else if (new_ct == Opcode.ct_int64)
return Opcode.vl_lv64;
return t;
case Opcode.vl_c:
if (new_ct == Opcode.ct_int32)
return Opcode.vl_c32;
else if (new_ct == Opcode.ct_int64)
return Opcode.vl_c64;
return t;
default:
return t;
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
switch(t)
{
case Opcode.vl_c:
case Opcode.vl_c32:
case Opcode.vl_c64:
sb.Append("$" + v.ToString());
break;
case Opcode.vl_arg:
case Opcode.vl_arg32:
case Opcode.vl_arg64:
sb.Append("la" + v.ToString());
break;
case Opcode.vl_lv:
case Opcode.vl_lv32:
case Opcode.vl_lv64:
sb.Append("lv" + v.ToString());
break;
case Opcode.vl_stack:
case Opcode.vl_stack32:
case Opcode.vl_stack64:
if (ssa_idx != -1)
sb.Append("vreg" + ssa_idx.ToString());
else
sb.Append("st" + v.ToString());
break;
case Opcode.vl_call_target:
sb.Append("callsite(");
if (str != null)
sb.Append(str);
else if(ms != null)
{
sb.Append(ms.mdrow.ToString());
sb.Append(" [");
sb.Append(ms.msig.ToString());
sb.Append("]");
}
else
{
sb.Append(v.ToString());
sb.Append(" [");
sb.Append(v2.ToString());
sb.Append("]");
}
sb.Append(")");
break;
case Opcode.vl_cc:
sb.Append(Opcode.cc_names[(int)v]);
break;
case Opcode.vl_str:
sb.Append(str);
if (v > 0)
{
sb.Append("+");
sb.Append(v.ToString());
}
else if (v < 0)
{
sb.Append("-");
sb.Append(v.ToString());
}
break;
case Opcode.vl_br_target:
sb.Append("IL" + v.ToString("X4"));
break;
case Opcode.vl_mreg:
sb.Append("%" + mreg.ToString());
break;
case Opcode.vl_ts_token:
sb.Append("TypeSpec: ");
sb.Append(ts.m.MangleType(ts));
break;
default:
return "{null}";
}
switch(ct)
{
case Opcode.ct_int32:
case Opcode.ct_int64:
case Opcode.ct_intptr:
case Opcode.ct_object:
case Opcode.ct_ref:
case Opcode.ct_float:
sb.Append(": ");
sb.Append(Opcode.ct_names[ct]);
break;
}
if (ud == UseDefType.Use)
sb.Append(" (use) ");
else if (ud == UseDefType.Def)
sb.Append(" (def) ");
sb.Append("}");
return sb.ToString();
}
public static implicit operator Param(long v)
{
return new Param { t = Opcode.vl_c, v = v };
}
public static implicit operator Param(string v)
{
return new Param { t = Opcode.vl_str, str = v };
}
}
}
<file_sep>using System.Collections.Generic;
namespace ConsoleUtils
{
public class PreviousLineBuffer
{
private bool _cyclingStarted;
private readonly List<string> _previousLines = new List<string>();
public bool HasLines { get { return _previousLines.Count > 0; } }
public string LastLine { get { return _previousLines.Count == 0 ? null : _previousLines[_previousLines.Count - 1]; } }
public string LineAtIndex { get { return _previousLines.Count == 0 ? null : _previousLines[Index]; } }
public int Index { get; set; }
public List<string> PreviousLines
{
get { return _previousLines; }
}
public void AddLine(string line)
{
if (!string.IsNullOrEmpty(line))
_previousLines.Add(line);
if (_previousLines.Count > 0 && _previousLines[Index] != line)
Index = _previousLines.Count - 1;
_cyclingStarted = false;
}
public bool CycleUp()
{
if (!HasLines)
return false;
if (!_cyclingStarted)
{
_cyclingStarted = true;
return true;
}
if (Index > 0)
{
Index--;
return true;
}
return false;
}
public void CycleUpAndAround()
{
if (!HasLines)
return;
if (!_cyclingStarted)
{
_cyclingStarted = true;
return;
}
Index--;
if (Index < 0)
Index = _previousLines.Count - 1;
}
public bool CycleDown()
{
if (!HasLines)
return false;
if (Index >= _previousLines.Count - 1)
return false;
Index++;
return true;
}
public bool CycleTop()
{
if (!HasLines || Index == 0)
return false;
Index = 0;
return true;
}
public bool CycleBottom()
{
if (!HasLines || Index >= _previousLines.Count - 1)
return false;
Index = _previousLines.Count - 1;
return true;
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class MoveCursorRightAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
console.CursorPosition = Math.Min(console.CurrentLine.Length, console.CursorPosition + 1);
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using metadata;
/* Array object is:
*
* vtbl pointer
* mutex lock
* elemtype vtbl pointer
* lobounds array pointer
* sizes array pointer
* data array pointer
* intptr rank
* int etsize
*
* followed by
* lobounds array
* sizes array
* data array
*/
namespace libtysila5.layout
{
public partial class Layout
{
public enum ArrayField
{
VtblPointer,
MutexLock,
ElemTypeVtblPointer,
LoboundsPointer,
SizesPointer,
DataArrayPointer,
Rank,
ElemTypeSize
}
public static int GetArrayObjectSize(target.Target t)
{
// round up to 8x intptr size so size is aligned to word size
return 8 * t.GetPointerSize();
}
public static int GetArrayFieldOffset(ArrayField af, target.Target t)
{
switch(af)
{
case ArrayField.VtblPointer:
return 0;
case ArrayField.MutexLock:
return 1 * t.GetPointerSize();
case ArrayField.ElemTypeVtblPointer:
return 2 * t.GetPointerSize();
case ArrayField.LoboundsPointer:
return 3 * t.GetPointerSize();
case ArrayField.SizesPointer:
return 4 * t.GetPointerSize();
case ArrayField.DataArrayPointer:
return 5 * t.GetPointerSize();
case ArrayField.Rank:
return 6 * t.GetPointerSize();
case ArrayField.ElemTypeSize:
return 7 * t.GetPointerSize();
default:
throw new NotSupportedException();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using ConsoleUtils.ConsoleActions;
namespace ConsoleUtils
{
public static class ConsoleExt
{
private static readonly object LockObj = new object();
private static int _maxLineLength;
internal static readonly PreviousLineBuffer PreviousLineBuffer = new PreviousLineBuffer();
private static readonly Dictionary<ConsoleModifiers, IConsoleAction> DefaultConsoleActions = new Dictionary<ConsoleModifiers, IConsoleAction>();
private static readonly Dictionary<ConsoleModifiers, Dictionary<ConsoleKey, IConsoleAction>> ConsoleActions = new Dictionary<ConsoleModifiers, Dictionary<ConsoleKey, IConsoleAction>>();
static ConsoleExt()
{
ResetConsoleBehaviour();
}
private static string _currentLine = string.Empty;
internal static string CurrentLine
{
get { return _currentLine; }
set
{
if (_currentLine == value)
return;
var prevLength = _currentLine.Length;
_currentLine = value;
if (value.Length > prevLength)
UpdateBufferWidth();
UpdateBuffer();
}
}
public static LineState LineState { get { return new LineState(CurrentLine, Console.CursorLeft); } }
public static string ReadLine()
{
while (true)
{
var result = ReadKey();
if (result.Key == ConsoleKey.Enter)
return result.LineBeforeKeyPress.Line;
}
}
public static KeyPressResult ReadKey()
{
return ReadKey(false);
}
public static KeyPressResult ReadKey(bool intercept, int start_cursor = 0)
{
while (true)
{
var lineStateBefore = LineState;
var keyInfo = Console.ReadKey(true);
if (!intercept)
SimulateKeyPress(keyInfo, start_cursor);
return new KeyPressResult(keyInfo, lineStateBefore, LineState);
}
}
public static void SimulateKeyPress(char keyChar)
{
ConsoleKey consoleKey;
if (!ConsoleKeyConverter.TryParseChar(keyChar, out consoleKey))
return;
SimulateKeyPress(new ConsoleKeyInfo(keyChar, consoleKey, false, false, false));
}
public static void SimulateKeyPress(ConsoleKey consoleKey)
{
SimulateKeyPress(new ConsoleKeyInfo((char)consoleKey, consoleKey, false, false, false));
}
public static void SimulateKeyPress(ConsoleKeyInfo keyInfo, int start_cursor = 0)
{
lock (LockObj)
{
if (keyInfo.Key == ConsoleKey.Enter)
{
StartNewLine();
return;
}
IConsoleAction action;
Dictionary<ConsoleKey, IConsoleAction> consoleKeyMapping;
if (ConsoleActions.TryGetValue(keyInfo.Modifiers, out consoleKeyMapping))
{
if (consoleKeyMapping.TryGetValue(keyInfo.Key, out action))
{
action.Execute(new ConsoleExtInstance { StartCursorPosition = start_cursor }, keyInfo);
return;
}
}
if (DefaultConsoleActions.TryGetValue(keyInfo.Modifiers, out action))
{
action.Execute(new ConsoleExtInstance { StartCursorPosition = start_cursor }, keyInfo);
}
}
}
public static void SetLine(string input)
{
lock (LockObj)
{
CurrentLine = input;
Console.CursorLeft = CurrentLine.Length;
}
}
public static void ClearLine()
{
lock (LockObj)
{
Console.CursorLeft = 0;
CurrentLine = string.Empty;
_maxLineLength = 0;
}
}
public static void StartNewLine()
{
lock (LockObj)
{
Console.CursorLeft = 0;
Console.WriteLine(CurrentLine);
PreviousLineBuffer.AddLine(CurrentLine);
_currentLine = string.Empty;
_maxLineLength = 0;
}
}
public static void PrependLine(string line)
{
lock (LockObj)
{
var currentLine = CurrentLine;
var cursorPos = Console.CursorLeft;
SetLine("");
Console.CursorLeft = 0;
Console.WriteLine(line);
CurrentLine = currentLine;
Console.CursorLeft = cursorPos;
}
}
public static void ResetConsoleBehaviour()
{
DefaultConsoleActions.Clear();
ConsoleActions.Clear();
SetDefaultConsoleActionForNonCtrlModifierCombinations(new InsertCharacterAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.F1, new AutoCompleteSingleCharacterAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.F3, new AutoCompleteRestOfLineAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.F5, new CycleUpAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.F6, new IgnoreAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.F8, new AutoCompleteUsingPreviousLinesAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.Escape, new ClearLineAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.Delete, new DeleteAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.Backspace, new BackspaceAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.LeftArrow, new MoveCursorLeftAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.RightArrow, new MoveCursorRightAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.Home, new MoveCursorToBeginAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.End, new MoveCursorToEndAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.Tab, new IgnoreAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.UpArrow, new CycleUpAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.PageUp, new CycleTopAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.DownArrow, new CycleDownAction());
SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey.PageDown, new CycleBottomAction());
SetDefaultConsoleActionForCtrlModifierCombinations(new IgnoreAction());
SetConsoleActionForCtrlModifierCombinations(ConsoleKey.H, new BackspaceAction());
SetConsoleActionForCtrlModifierCombinations(ConsoleKey.Backspace, new RemovePrecedingAction());
SetConsoleActionForCtrlModifierCombinations(ConsoleKey.LeftArrow, new MoveCursorToBeginAction());
SetConsoleActionForCtrlModifierCombinations(ConsoleKey.RightArrow, new MoveCursorToEndAction());
SetConsoleActionForCtrlModifierCombinations(ConsoleKey.Home, new RemovePrecedingAction());
SetConsoleActionForCtrlModifierCombinations(ConsoleKey.End, new RemoveSucceedingAction());
}
public static void SetConsoleActionForNonCtrlModifierCombinations(ConsoleKey consoleKey, IConsoleAction action)
{
SetConsoleAction(0, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Alt, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt, consoleKey, action);
}
public static void SetConsoleActionForCtrlModifierCombinations(ConsoleKey consoleKey, IConsoleAction action)
{
SetConsoleAction(ConsoleModifiers.Control, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Control, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey, action);
}
public static void SetConsoleActionForAllModifierCombinations(ConsoleKey consoleKey, IConsoleAction action)
{
SetConsoleAction(0, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Alt, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Control, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Control, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey, action);
SetConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey, action);
}
public static void SetConsoleAction(ConsoleModifiers modifiers, ConsoleKey consoleKey, IConsoleAction action)
{
Dictionary<ConsoleKey, IConsoleAction> consoleKeyMapping;
if (!ConsoleActions.TryGetValue(modifiers, out consoleKeyMapping))
{
consoleKeyMapping = new Dictionary<ConsoleKey, IConsoleAction>();
ConsoleActions.Add(modifiers, consoleKeyMapping);
}
consoleKeyMapping[consoleKey] = action;
}
public static void RemoveConsoleActionForNonCtrlModifierCombinations(ConsoleKey consoleKey)
{
RemoveConsoleAction(0, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Alt, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt, consoleKey);
}
public static void RemoveConsoleActionForCtrlModifierCombinations(ConsoleKey consoleKey)
{
RemoveConsoleAction(ConsoleModifiers.Control, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Control, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey);
}
public static void RemoveConsoleActionForAllModifierCombinations(ConsoleKey consoleKey)
{
RemoveConsoleAction(0, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Alt, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Control, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Control, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey);
RemoveConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, consoleKey);
}
public static void RemoveConsoleAction(ConsoleModifiers modifiers, ConsoleKey consoleKey)
{
Dictionary<ConsoleKey, IConsoleAction> consoleKeyMapping;
if (!ConsoleActions.TryGetValue(modifiers, out consoleKeyMapping))
return;
consoleKeyMapping.Remove(consoleKey);
}
public static void SetDefaultConsoleActionForNonCtrlModifierCombinations(IConsoleAction action)
{
SetDefaultConsoleAction(0, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift, action);
SetDefaultConsoleAction(ConsoleModifiers.Alt, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt, action);
}
public static void SetDefaultConsoleActionForCtrlModifierCombinations(IConsoleAction action)
{
SetDefaultConsoleAction(ConsoleModifiers.Control, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Control, action);
SetDefaultConsoleAction(ConsoleModifiers.Alt | ConsoleModifiers.Control, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, action);
}
public static void SetDefaultConsoleActionForAllModifierCombinations(IConsoleAction action)
{
SetDefaultConsoleAction(0, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift, action);
SetDefaultConsoleAction(ConsoleModifiers.Alt, action);
SetDefaultConsoleAction(ConsoleModifiers.Control, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Control, action);
SetDefaultConsoleAction(ConsoleModifiers.Alt | ConsoleModifiers.Control, action);
SetDefaultConsoleAction(ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control, action);
}
public static void SetDefaultConsoleAction(ConsoleModifiers modifiers, IConsoleAction action)
{
DefaultConsoleActions[modifiers] = action;
}
private static void UpdateBufferWidth()
{
Console.BufferWidth = Math.Max(Console.BufferWidth, Math.Min(byte.MaxValue, Math.Max(_maxLineLength, CurrentLine.Length + 1)));
}
private static void UpdateBuffer()
{
_maxLineLength = Math.Max(_maxLineLength, CurrentLine.Length);
var pos = Console.CursorLeft;
Console.CursorLeft = 0;
Console.Write(CurrentLine.PadRight(_maxLineLength));
Console.CursorLeft = pos;
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.ir
{
partial class Opcode
{
internal static int GetCTFromType(metadata.TypeSpec ts)
{
if (ts == null)
return ct_unknown;
switch(ts.stype)
{
case metadata.TypeSpec.SpecialType.None:
if (ts.m.is_corlib && ts.m.simple_type_idx[ts.tdrow] != -1)
return GetCTFromType(ts.m.simple_type_idx[ts.tdrow]);
if (ts.IsEnum)
return GetCTFromType(ts.UnderlyingType);
if (ts.IsValueType)
return ct_vt;
return ct_object;
case metadata.TypeSpec.SpecialType.SzArray:
case metadata.TypeSpec.SpecialType.Array:
return ct_object;
case metadata.TypeSpec.SpecialType.MPtr:
return ct_ref;
case metadata.TypeSpec.SpecialType.Ptr:
return ct_intptr;
case metadata.TypeSpec.SpecialType.Boxed:
return ct_object;
default:
throw new NotSupportedException();
}
}
internal static metadata.TypeSpec GetTypeFromCT(int ct, metadata.MetadataStream m)
{
switch(ct)
{
case ct_int32:
return m.GetSimpleTypeSpec(0x08);
case ct_int64:
return m.GetSimpleTypeSpec(0x0a);
case ct_intptr:
return m.GetSimpleTypeSpec(0x18);
case ct_object:
return m.GetSimpleTypeSpec(0x1c);
case ct_float:
return m.GetSimpleTypeSpec(0x0d);
}
return null;
}
internal static bool IsTLSCT(int ct)
{
switch(ct)
{
case ct_tls_int32:
case ct_tls_int64:
case ct_tls_intptr:
return true;
default:
return false;
}
}
internal static int TLSCT(int ct)
{
switch(ct)
{
case ct_int32:
return ct_tls_int32;
case ct_int64:
return ct_tls_int64;
case ct_intptr:
case ct_ref:
return ct_tls_intptr;
default:
return ct;
}
}
internal static int UnTLSCT(int ct)
{
switch(ct)
{
case ct_tls_int32:
return ct_int32;
case ct_tls_int64:
return ct_int64;
case ct_tls_intptr:
return ct_intptr;
default:
return ct;
}
}
internal static int GetCTFromType(int type)
{
switch (type)
{
case 0x02:
case 0x03:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
case 0x08:
case 0x09:
return ct_int32;
case 0x0a:
case 0x0b:
return ct_int64;
case 0x0c:
case 0x0d:
return ct_float;
case 0x0e:
return ct_object;
case 0x0f:
return ct_ref;
case 0x11:
return ct_object; // System.ValueType itself is a reference type
case 0x12:
case 0x14:
case 0x16:
return ct_object;
case 0x18:
case 0x19:
return ct_intptr;
case 0x1c:
case 0x1d:
return ct_object;
default:
throw new NotImplementedException();
}
}
static int get_call_rettype(Opcode n, target.Target t)
{
// Determine the return type from the method signature
var cs = n.uses[0];
var ms = cs.ms;
if (ms == null)
throw new NotSupportedException();
var msig = ms.msig;
var rt_idx = ms.m.GetMethodDefSigRetTypeIndex(msig);
throw new NotImplementedException();
/*var ret_ts = ms.m.GetTypeSpec(ref rt_idx,
n.n.g.ms.gtparams, n.n.g.ms.gmparams);
var ct = GetCTFromType(ret_ts);
return ct;*/
}
static int get_store_pushtype(Opcode n, target.Target t)
{
// Determine from the type of operand 1
var o1 = n.uses[0];
switch (o1.t)
{
case vl_stack32:
case vl_arg32:
case vl_lv32:
case vl_stack64:
case vl_arg64:
case vl_lv64:
case vl_c32:
case vl_c64:
case vl_stack:
case vl_arg:
case vl_lv:
case vl_c:
return o1.ct;
default:
throw new NotImplementedException();
}
}
static int get_binnumop_pushtype(Opcode n, target.Target t)
{
var a = n.uses[0].ct;
var b = n.uses[1].ct;
switch(a)
{
case ct_int32:
switch(b)
{
case ct_int32:
return ct_int32;
case ct_intptr:
return ct_intptr;
case ct_ref:
if (n.oc == oc_add)
return ct_ref;
break;
}
break;
case ct_int64:
switch(b)
{
case ct_int64:
return ct_int64;
}
break;
case ct_intptr:
switch(b)
{
case ct_int32:
return ct_intptr;
case ct_intptr:
return ct_intptr;
case ct_ref:
if (n.oc == oc_add)
return ct_ref;
break;
}
break;
case ct_float:
switch(b)
{
case ct_float:
return ct_float;
}
break;
case ct_ref:
switch(b)
{
case ct_int32:
if (n.oc == oc_add || n.oc == oc_sub)
return ct_ref;
break;
case ct_intptr:
if (n.oc == oc_add || n.oc == oc_sub)
return ct_ref;
break;
case ct_ref:
if (n.oc == oc_sub)
return ct_intptr;
break;
}
break;
}
throw new NotSupportedException("Invalid opcode:" + n.ToString());
}
static int get_conv_pushtype(Opcode n, target.Target t)
{
var dt = n.uses[1].v;
switch(dt)
{
case 1:
case 2:
case 4:
case -1:
case -2:
case -4:
return ct_int32;
case 8:
case -8:
return ct_int64;
case 14:
case 18:
return ct_float;
}
throw new NotSupportedException("Invalid opcode: " + n.ToString());
}
static int get_object_pushtype(Opcode n, target.Target t)
{
return ct_intptr;
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.cil;
namespace libtysila5.target.x86
{
partial class x86_Assembler
{
private static void handle_briff(Reg srca, Reg srcb, int cc, int target, List<MCInst> r, CilNode.IRNode n)
{
if (srca is ContentsReg && !(srcb is ContentsReg))
cc = ir.Opcode.cc_invert_map[cc];
int oc;
switch(cc)
{
case ir.Opcode.cc_a:
cc = ir.Opcode.cc_a;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_ae:
cc = ir.Opcode.cc_ae;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_b:
cc = ir.Opcode.cc_b;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_be:
cc = ir.Opcode.cc_be;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_eq:
cc = ir.Opcode.cc_eq;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_ge:
cc = ir.Opcode.cc_ae;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_gt:
cc = ir.Opcode.cc_a;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_le:
cc = ir.Opcode.cc_be;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_lt:
cc = ir.Opcode.cc_b;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_ne:
cc = ir.Opcode.cc_ne;
oc = x86_comisd_xmm_xmmm64;
break;
default:
throw new NotImplementedException();
}
if (!(srca is ContentsReg))
r.Add(inst(oc, srca, srcb, n));
else if (!(srcb is ContentsReg))
{
r.Add(inst(oc, srcb, srca, n));
cc = ir.Opcode.cc_invert_map[cc];
}
else
{
r.Add(inst(x86_movsd_xmm_xmmm64, r_xmm7, srca, n));
r.Add(inst(oc, srca, srcb, n));
}
r.Add(inst_jmp(x86_jcc_rel32, target, cc, n));
}
private void extern_append(StringBuilder sb, int ct)
{
switch (ct)
{
case ir.Opcode.ct_int32:
case ir.Opcode.ct_object:
case ir.Opcode.ct_ref:
case ir.Opcode.ct_intptr:
sb.Append("i");
break;
case ir.Opcode.ct_int64:
sb.Append("l");
break;
case ir.Opcode.ct_float:
sb.Append("f");
break;
}
}
private static void handle_stind(Reg val, Reg addr, int disp, int vt_size, List<MCInst> r, CilNode.IRNode n, Code c, bool is_tls = false)
{
if (is_tls)
throw new NotImplementedException();
if (addr is ContentsReg || ((addr.Equals(r_esi) || addr.Equals(r_edi)) && vt_size != 4))
{
r.Add(inst(x86_mov_r32_rm32, r_eax, addr, n));
addr = r_eax;
}
var act_val = val;
if (val is ContentsReg || ((val.Equals(r_esi) || val.Equals(r_edi)) && n.vt_size == 1))
{
val = r_edx;
r.Add(inst(x86_mov_r32_rm32, val, act_val, n));
}
if((addr.Equals(r_esi) || addr.Equals(r_edi)) && n.vt_size == 1 && c.t.psize == 4)
{
throw new NotImplementedException();
}
switch (vt_size)
{
case 1:
r.Add(inst(x86_mov_rm8disp_r8, addr, disp, val, n));
break;
case 2:
r.Add(inst(x86_mov_rm16disp_r16, addr, disp, val, n));
break;
case 4:
r.Add(inst(x86_mov_rm32disp_r32, addr, disp, val, n));
break;
default:
throw new NotImplementedException();
}
}
private static void handle_brifi32(Reg srca, Reg srcb, int cc, int target, List<MCInst> r, CilNode.IRNode n)
{
if (!(srca is ContentsReg))
r.Add(inst(x86_cmp_r32_rm32, srca, srcb, n));
else if (!(srcb is ContentsReg))
r.Add(inst(x86_cmp_rm32_r32, srca, srcb, n));
else
{
r.Add(inst(x86_mov_r32_rm32, r_eax, srca, n));
r.Add(inst(x86_cmp_r32_rm32, r_eax, srcb, n));
}
r.Add(inst_jmp(x86_jcc_rel32, target, cc, n));
}
private static void handle_brifi64(Reg srca, Reg srcb, int cc, int target, List<MCInst> r, CilNode.IRNode n)
{
if (!(srca is ContentsReg))
r.Add(inst(x86_cmp_r64_rm64, srca, srcb, n));
else if (!(srcb is ContentsReg))
r.Add(inst(x86_cmp_rm64_r64, srca, srcb, n));
else
{
r.Add(inst(x86_mov_r64_rm64, r_eax, srca, n));
r.Add(inst(x86_cmp_r64_rm64, r_eax, srcb, n));
}
r.Add(inst_jmp(x86_jcc_rel32, target, cc, n));
}
private static void handle_brifi32(Reg srca, long v, int cc, int target, List<MCInst> r, CilNode.IRNode n)
{
if (v >= -128 && v < 127)
r.Add(inst(x86_cmp_rm32_imm8, srca, v, n));
else if (v >= int.MinValue && v <= int.MaxValue)
r.Add(inst(x86_cmp_rm32_imm32, srca, v, n));
else
throw new NotImplementedException();
r.Add(inst_jmp(x86_jcc_rel32, target, cc, n));
}
protected static void handle_move(Reg dest, Reg src, List<MCInst> r, CilNode.IRNode n, Code c, Reg temp_reg = null, int size = -1,
bool src_is_tls = false, bool dest_is_tls = false)
{
if (src_is_tls || dest_is_tls)
throw new NotImplementedException();
if (dest.Equals(src))
return;
if(src.type == rt_stack)
{
src = new ContentsReg { basereg = r_esp, size = src.size, disp = src.stack_loc };
}
if(dest.type == rt_stack)
{
dest = new ContentsReg { basereg = r_esp, size = dest.size, disp = dest.stack_loc };
}
if (src is ContentsReg && dest is ContentsReg)
{
var crs = src as ContentsReg;
var crd = dest as ContentsReg;
var vt_size = crs.size;
vt_size = util.util.align(vt_size, c.t.psize);
if (vt_size != util.util.align(crd.size, c.t.psize))
throw new Exception("Differing size in move");
if (temp_reg == null)
{
if (crs.basereg.Equals(r_eax) || crd.basereg.Equals(r_eax))
temp_reg = r_edx;
else
temp_reg = r_eax;
}
if (vt_size > 4 * c.t.psize)
{
// emit call to memcpy(dest, src, n)
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.memcpy),
new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_mreg, mreg = dest, want_address = true },
new ir.Param { t = ir.Opcode.vl_mreg, mreg = src, want_address = true },
vt_size
},
null, "memcpy", temp_reg));
}
else if(c.t.psize == 4)
{
for (int i = 0; i < vt_size; i += 4)
{
var new_crs = new ContentsReg { basereg = crs.basereg, disp = crs.disp + i, size = 4 };
var new_crd = new ContentsReg { basereg = crd.basereg, disp = crd.disp + i, size = 4 };
// first store to rax
r.Add(inst(x86_mov_r32_rm32, temp_reg, new_crs, n));
r.Add(inst(x86_mov_rm32_r32, new_crd, temp_reg, n));
}
}
else
{
for (int i = 0; i < vt_size; i += 8)
{
var new_crs = new ContentsReg { basereg = crs.basereg, disp = crs.disp + i, size = 8 };
var new_crd = new ContentsReg { basereg = crd.basereg, disp = crd.disp + i, size = 8 };
// first store to rax
r.Add(inst(x86_mov_r64_rm64, temp_reg, new_crs, n));
r.Add(inst(x86_mov_rm64_r64, new_crd, temp_reg, n));
}
}
}
else if (src is ContentsReg)
{
if (dest.type == rt_gpr)
{
if (src.size == 4 || size == 4)
r.Add(inst(x86_mov_r32_rm32, dest, src, n));
else if (c.t.psize == 8)
r.Add(inst(x86_mov_r64_rm64, dest, src, n));
else
throw new NotImplementedException();
}
else if (dest.type == rt_float)
r.Add(inst(x86_movsd_xmm_xmmm64, dest, src, n));
else if (dest.type == rt_multi)
{
for (int i = 0; i < src.size; i += c.t.psize)
{
var sa = src.SubReg(i, c.t.psize, c.t);
var da = dest.SubReg(i, c.t.psize, c.t);
handle_move(da, sa, r, n, c, temp_reg);
}
}
else
throw new NotImplementedException();
}
else
{
if (src.type == rt_gpr)
{
if (c.t.psize == 4)
r.Add(inst(x86_mov_rm32_r32, dest, src, n));
else
r.Add(inst(x86_mov_rm64_r64, dest, src, n));
}
else if (src.type == rt_float)
{
if (src.Equals(r_st0))
{
// Need to copy via the stack
r.Add(inst(c.t.psize == 4 ? x86_sub_rm32_imm8 : x86_sub_rm64_imm8, r_esp, 8, n));
r.Add(inst(x86_fstp_m64, new ContentsReg { basereg = r_esp, disp = 0, size = 8 }, n));
r.Add(inst(x86_movsd_xmm_xmmm64, dest, new ContentsReg { basereg = r_esp, disp = 0, size = 8 }, n));
r.Add(inst(c.t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, r_esp, 8, n));
}
else if(dest.Equals(r_st0))
{
// Need to copy via the stack
r.Add(inst(c.t.psize == 4 ? x86_sub_rm32_imm8 : x86_sub_rm64_imm8, r_esp, 8, n));
r.Add(inst(x86_movsd_xmmm64_xmm, new ContentsReg { basereg = r_esp, disp = 0, size = 8 }, src, n));
r.Add(inst(x86_fld_m64, new ContentsReg { basereg = r_esp, disp = 0, size = 8 }, n));
r.Add(inst(c.t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, r_esp, 8, n));
}
else
{
r.Add(inst(x86_movsd_xmmm64_xmm, dest, src, n));
}
}
else if (src.type == rt_multi)
{
for (int i = 0; i < dest.size; i += c.t.psize)
{
var sa = src.SubReg(i, c.t.psize, c.t);
var da = dest.SubReg(i, c.t.psize, c.t);
handle_move(da, sa, r, n, c, temp_reg);
}
}
else
throw new NotImplementedException();
}
}
private static void handle_sub(Target t, Reg srca, Reg srcb, Reg dest, List<MCInst> r, CilNode.IRNode n, bool with_borrow = false)
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
if (with_borrow)
r.Add(inst(t.psize == 4 ? x86_sbb_r32_rm32 : x86_sbb_r64_rm64, srca, srcb, n));
else
r.Add(inst(t.psize == 4 ? x86_sub_r32_rm32 : x86_sub_r64_rm64, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
if (with_borrow)
r.Add(inst(t.psize == 4 ? x86_sbb_rm32_r32 : x86_sbb_rm64_r64, srca, srcb, n));
else
r.Add(inst(t.psize == 4 ? x86_sub_rm32_r32 : x86_sub_rm64_r64, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_eax, srca, n));
if (with_borrow)
r.Add(inst(t.psize == 4 ? x86_sbb_r32_rm32 : x86_sbb_r64_rm64, r_eax, srcb, n));
else
r.Add(inst(t.psize == 4 ? x86_sub_r32_rm32 : x86_sub_r64_rm64, r_eax, srcb, n));
r.Add(inst(t.psize == 4 ? x86_mov_rm32_r32 : x86_mov_rm64_r64, dest, r_eax, n));
}
}
private static void handle_add(Target t, Reg srca, Reg srcb, Reg dest, List<MCInst> r, CilNode.IRNode n, bool with_carry = false)
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
if (with_carry)
r.Add(inst(t.psize == 4 ? x86_adc_r32_rm32 : x86_adc_r64_rm64, srca, srcb, n));
else
r.Add(inst(t.psize == 4 ? x86_add_r32_rm32 : x86_add_r64_rm64, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
if (with_carry)
r.Add(inst(t.psize == 4 ? x86_adc_rm32_r32 : x86_adc_rm64_r64, srca, srcb, n));
else
r.Add(inst(t.psize == 4 ? x86_add_rm32_r32 : x86_add_rm64_r64, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_eax, srca, n));
if (with_carry)
r.Add(inst(t.psize == 4 ? x86_adc_r32_rm32 : x86_adc_r64_rm64, r_eax, srcb, n));
else
r.Add(inst(t.psize == 4 ? x86_add_r32_rm32 : x86_add_r64_rm64, r_eax, srcb, n));
r.Add(inst(t.psize == 4 ? x86_mov_rm32_r32 : x86_mov_rm64_r64, dest, r_eax, n));
}
}
private static void handle_and(Reg srca, Reg srcb, Reg dest, List<MCInst> r, CilNode.IRNode n)
{
if (srca.size == 4)
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_and_r32_rm32, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_and_rm32_r32, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(x86_mov_r32_rm32, r_eax, srca, n));
r.Add(inst(x86_and_r32_rm32, r_eax, srcb, n));
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
}
}
else
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_and_r64_rm64, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_and_rm64_r64, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(x86_mov_r64_rm64, r_eax, srca, n));
r.Add(inst(x86_and_r64_rm64, r_eax, srcb, n));
r.Add(inst(x86_mov_rm64_r64, dest, r_eax, n));
}
}
}
private static void handle_or(Reg srca, Reg srcb, Reg dest, List<MCInst> r, CilNode.IRNode n)
{
if (srca.size == 4)
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_or_r32_rm32, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_or_rm32_r32, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(x86_mov_r32_rm32, r_eax, srca, n));
r.Add(inst(x86_or_r32_rm32, r_eax, srcb, n));
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
}
}
else
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_or_r64_rm64, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_or_rm64_r64, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(x86_mov_r64_rm64, r_eax, srca, n));
r.Add(inst(x86_or_r64_rm64, r_eax, srcb, n));
r.Add(inst(x86_mov_rm64_r64, dest, r_eax, n));
}
}
}
private static void handle_xor(Reg srca, Reg srcb, Reg dest, List<MCInst> r, CilNode.IRNode n)
{
if (srca.size == 4)
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_xor_r32_rm32, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_xor_rm32_r32, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(x86_mov_r32_rm32, r_eax, srca, n));
r.Add(inst(x86_xor_r32_rm32, r_eax, srcb, n));
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
}
}
else
{
if (!(srca is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_xor_r64_rm64, srca, srcb, n));
}
else if (!(srcb is ContentsReg) && srca.Equals(dest))
{
r.Add(inst(x86_xor_rm64_r64, srca, srcb, n));
}
else
{
// complex way, do calc in rax, then store
r.Add(inst(x86_mov_r64_rm64, r_eax, srca, n));
r.Add(inst(x86_xor_r64_rm64, r_eax, srcb, n));
r.Add(inst(x86_mov_rm64_r64, dest, r_eax, n));
}
}
}
private static void handle_ldind(Reg val, Reg addr, int disp, int vt_size,
List<MCInst> r, CilNode.IRNode n, Target t, Code c, bool is_tls = false)
{
if (addr is ContentsReg)
{
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_eax, addr, n));
addr = r_eax;
}
else if(vt_size == 1 && t.psize == 4 && (addr.Equals(r_edi) || addr.Equals(r_esi)))
{
handle_move(r_eax, addr, r, n, c);
addr = r_eax;
}
var act_val = val;
if (val is ContentsReg)
{
val = r_edx;
}
else if (vt_size == 1 && t.psize == 4 && (val.Equals(r_edi) || val.Equals(r_esi)))
{
val = r_edx;
}
switch (vt_size)
{
case 1:
if (n.imm_l == 1)
r.Add(inst(t.psize == 4 ? x86_movsxbd_r32_rm8disp : x86_movsxbq_r64_rm8disp, val, addr, disp, n, is_tls));
else
r.Add(inst(t.psize == 4 ? x86_movzxbd_r32_rm8disp : x86_movzxbq_r64_rm8disp, val, addr, disp, n, is_tls));
break;
case 2:
if (n.imm_l == 1)
r.Add(inst(t.psize == 4 ? x86_movsxwd_r32_rm16disp : x86_movsxwq_r64_rm16disp, val, addr, disp, n, is_tls));
else
r.Add(inst(t.psize == 4 ? x86_movzxwd_r32_rm16disp : x86_movzxwq_r64_rm16disp, val, addr, disp, n, is_tls));
break;
case 4:
r.Add(inst(x86_mov_r32_rm32disp, val, addr, disp, n, is_tls));
break;
case 8:
if (t.psize != 8)
throw new NotImplementedException();
r.Add(inst(x86_mov_r64_rm64disp, val, addr, disp, n, is_tls));
break;
default:
throw new NotImplementedException();
}
if (!val.Equals(act_val))
{
r.Add(inst(t.psize == 4 ? x86_mov_rm32_r32 : x86_mov_rm64_r64, act_val, val, n));
}
}
private static List<MCInst> handle_ret(CilNode.IRNode n, Code c, Target t)
{
List<MCInst> r = new List<MCInst>();
/* Put a local label here so we can jmp here at will */
int ret_lab = c.cctor_ret_tag;
if(ret_lab == -1)
{
ret_lab = c.next_mclabel--;
c.cctor_ret_tag = ret_lab;
}
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = ret_lab }, n));
if (n.stack_before.Count == 1)
{
var reg = n.stack_before.Peek().reg;
switch (n.ct)
{
case ir.Opcode.ct_int32:
case ir.Opcode.ct_intptr:
case ir.Opcode.ct_object:
case ir.Opcode.ct_ref:
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_eax, n.stack_before[0].reg, n));
break;
case ir.Opcode.ct_int64:
if (t.psize == 4)
{
var dra = reg.SubReg(0, 4, c.t);
var drb = reg.SubReg(4, 4, c.t);
r.Add(inst(x86_mov_r32_rm32, r_eax, dra, n));
r.Add(inst(x86_mov_r32_rm32, r_edx, drb, n));
}
else
r.Add(inst(x86_mov_r64_rm64, r_eax, reg, n));
break;
case ir.Opcode.ct_vt:
// move address to save to to eax
handle_move(r_eax, new ContentsReg { basereg = r_ebp, disp = -t.psize, size = t.psize },
r, n, c);
// move struct to [eax]
var vt_size = c.t.GetSize(c.ret_ts);
handle_move(new ContentsReg { basereg = r_eax, size = vt_size },
reg, r, n, c);
break;
case ir.Opcode.ct_float:
var retccmap = c.t.retcc_map["ret_" + c.ms.CallingConvention];
var retreg = t.regs[retccmap[n.ct][0]];
handle_move(retreg, reg, r, n, c);
break;
default:
throw new NotImplementedException(ir.Opcode.ct_names[n.ct]);
}
}
// Restore used regs
if (!n.parent.is_in_excpt_handler)
{
// we use values relative to rbp here in case the function
// did a localloc which has changed the stack pointer
for (int i = 0; i < c.regs_saved.Count; i++)
{
ContentsReg cr = new ContentsReg { basereg = r_ebp, disp = -c.lv_total_size - c.stack_total_size - t.psize * (i + 1), size = t.psize };
handle_move(c.regs_saved[i], cr, r, n, c);
}
}
else
{
// in exception handler we have to pop the values off the stack
// because rsp is not by default restored so we may return to the
// wrong place
// this works because we do not allow localloc in exception handlers
int x = 0;
for (int i = c.regs_saved.Count - 1; i >= 0; i--)
handle_pop(c.regs_saved[i], ref x, r, n, c);
}
if(!n.parent.is_in_excpt_handler)
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_esp, r_ebp, n));
r.Add(inst(x86_pop_r32, r_ebp, n));
// Insert a code sequence here if this is a static constructor
if(c.is_cctor)
{
/* Sequence is:
*
* Load static field pointer
* mov rcx, lab_addr
*
* Set done flag
* mov_rm8_imm8 [rcx], 2
*
* Get return eip
* mov_r32_rm32/64 rcx, [rsp]
*
* Is this cctor was called by a direct call (i.e. [rcx-6] == 0xe8) then:
*
* Overwrite the preceeding 5 bytes with nops
* mov_rm32_imm32 [rcx - 5], 0x00401f0f ; 4 byte nop
* mov_rm8_imm8 [rcx - 1], 0x90 ; 1 byte nop
*
* Else skip to here (this is the case where we were called indirectly from
* System.Runtime.CompilerServices._RunClassConstructor())
*/
r.Add(inst(x86_mov_rm32_imm32, r_ecx, new ir.Param { t = ir.Opcode.vl_str, str = c.ms.type.MangleType() + "S" }, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, 0, 2, n));
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_ecx, new ContentsReg { basereg = r_esp }, n));
r.Add(inst(x86_cmp_rm8_imm8, new ContentsReg { basereg = r_ecx, disp = -6, size = 1 }, 0xe8, n));
int end_lab = c.next_mclabel--;
r.Add(inst_jmp(x86_jcc_rel32, end_lab, ir.Opcode.cc_ne, n));
//r.Add(inst(x86_mov_rm32disp_imm32, r_ecx, -5, 0x00401f0f, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -1, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -2, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -3, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -4, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -5, 0x90, n));
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = end_lab }, n));
}
if (c.ms.CallingConvention == "isrec")
{
// pop error code from stack
r.Add(inst(t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8,
r_esp, 8, n));
}
if (c.ms.CallingConvention == "isr" || c.ms.CallingConvention == "isrec")
{
r.Add(inst(t.psize == 4 ? x86_iret : x86_iretq, n));
}
else
{
r.Add(inst(x86_ret, n));
}
return r;
}
static List<Reg> get_push_list(CilNode.IRNode n, Code c,
metadata.MethodSpec call_ms, out metadata.TypeSpec rt,
ref Reg dest, out int rct, bool want_return = true)
{
/* Determine which registers we need to save */
var caller_preserves = c.t.cc_caller_preserves_map[call_ms.CallingConvention];
ulong defined = 0;
foreach (var si in n.stack_after)
defined |= si.reg.mask;
foreach (var si in n.stack_before)
defined |= si.reg.mask;
var rt_idx = call_ms.m.GetMethodDefSigRetTypeIndex(call_ms.msig);
rt = call_ms.m.GetTypeSpec(ref rt_idx, call_ms.gtparams, call_ms.gmparams);
rct = ir.Opcode.ct_unknown;
if (rt != null && want_return)
{
defined &= ~n.stack_after.Peek().reg.mask;
if(dest == null)
dest = n.stack_after.Peek().reg;
rct = ir.Opcode.GetCTFromType(rt);
}
var to_push = new util.Set();
to_push.Union(defined);
to_push.Intersect(caller_preserves);
List<Reg> push_list = new List<Reg>();
while (!to_push.Empty)
{
var first_set = to_push.get_first_set();
push_list.Add(c.t.regs[first_set]);
to_push.unset(first_set);
}
return push_list;
}
private static List<MCInst> handle_call(CilNode.IRNode n,
Code c, metadata.MethodSpec call_ms, ir.Param[] p,
Reg dest, string target = null, Reg temp_reg = null)
{
/* used for handling calls to utility functions
* (e.g. memcpy/memset etc) whilst ensuring that
* all required registers are saved around the
* call */
return handle_call(n, c, false, c.t, target, call_ms, p, dest, dest != null);
}
private static List<MCInst> handle_call(CilNode.IRNode n, Code c, bool is_calli, Target t,
string target = null, metadata.MethodSpec call_ms = null,
ir.Param[] p = null, Reg dest = null, bool want_return = true)
{
List<MCInst> r = new List<MCInst>();
if(call_ms == null)
call_ms = n.imm_ms;
if(target == null && is_calli == false)
target = call_ms.m.MangleMethod(call_ms);
Reg act_dest = null;
metadata.TypeSpec rt;
int rct;
var push_list = get_push_list(n, c, call_ms,
out rt, ref dest, out rct, want_return);
// Store the current index, we will insert instructions
// to save clobbered registers here
int push_list_index = r.Count;
/* Push arguments */
int push_length = 0;
int vt_push_length = 0;
bool vt_dest_adjust = false;
if (rct == ir.Opcode.ct_vt)
{
if (dest is ContentsReg)
{
act_dest = dest;
}
else
{
throw new NotImplementedException();
var rsize = c.t.GetSize(rt);
rsize = util.util.align(rsize, 4);
vt_dest_adjust = true;
act_dest = new ContentsReg { basereg = r_esp, disp = 0, size = rsize };
r.Add(inst(rsize <= 127 ? x86_sub_rm32_imm8 : x86_sub_rm32_imm32, r_esp, rsize, n));
vt_push_length += rsize;
}
}
var sig_idx = call_ms.msig;
var pcount = call_ms.m.GetMethodDefSigParamCountIncludeThis(sig_idx);
sig_idx = call_ms.m.GetMethodDefSigRetTypeIndex(sig_idx);
var rt2 = call_ms.m.GetTypeSpec(ref sig_idx, call_ms.gtparams == null ? c.ms.gtparams : call_ms.gtparams, c.ms.gmparams);
int calli_adjust = is_calli ? 1 : 0;
metadata.TypeSpec[] push_tss = new metadata.TypeSpec[pcount];
for (int i = 0; i < pcount; i++)
{
if (i == 0 && call_ms.m.GetMethodDefSigHasNonExplicitThis(call_ms.msig))
push_tss[i] = call_ms.type;
else
push_tss[i] = call_ms.m.GetTypeSpec(ref sig_idx, call_ms.gtparams, call_ms.gmparams);
}
/* Push value type address if required */
metadata.TypeSpec hidden_loc_type = null;
if (rct == ir.Opcode.ct_vt)
{
var act_dest_cr = act_dest as ContentsReg;
if(act_dest_cr == null)
throw new NotImplementedException();
if (vt_dest_adjust)
{
throw new NotImplementedException();
act_dest_cr.disp += push_length;
}
//r.Add(inst(x86_lea_r32, r_eax, act_dest, n));
//r.Add(inst(x86_push_r32, r_eax, n));
hidden_loc_type = call_ms.m.SystemIntPtr;
}
// Build list of source and destination registers for parameters
int cstack_loc = 0;
var cc = t.cc_map[call_ms.CallingConvention];
var cc_class = t.cc_classmap[call_ms.CallingConvention];
int[] la_sizes;
metadata.TypeSpec[] la_types;
var to_locs = t.GetRegLocs(new ir.Param
{
m = call_ms.m,
v2 = call_ms.msig,
ms = call_ms
},
ref cstack_loc, cc, cc_class, call_ms.CallingConvention,
out la_sizes, out la_types,
hidden_loc_type
);
Reg calli_reg = null;
if(is_calli)
{
if (t.psize == 4)
calli_reg = r_edx; // not used as a parameter register on ia32
else
calli_reg = x86_64.x86_64_Assembler.r_r15;
// Add the target register to those we want to pass
Reg[] new_to_locs = new Reg[to_locs.Length + calli_adjust];
for (int i = 0; i < to_locs.Length; i++)
new_to_locs[i] = to_locs[i];
new_to_locs[to_locs.Length] = calli_reg;
to_locs = new_to_locs;
}
// Append the register arguments to the push list
foreach (var arg in to_locs)
{
if (arg.type == rt_gpr || arg.type == rt_float)
{
if (!push_list.Contains(arg))
push_list.Add(arg);
}
}
List<MCInst> r2 = new List<MCInst>();
// Insert the push instructions at the start of the stream
int x = 0;
foreach (var push_reg in push_list)
handle_push(push_reg, ref x, r2, n, c);
foreach (var r2inst in r2)
r.Insert(push_list_index++, r2inst);
// Get from locs
ir.Param[] from_locs;
int hidden_adjust = hidden_loc_type == null ? 0 : 1;
if (p == null)
{
from_locs = new ir.Param[pcount + hidden_adjust + calli_adjust];
for (int i = 0; i < pcount; i++)
{
var stack_loc = pcount - i - 1;
if (n.arg_list != null)
stack_loc = n.arg_list[i];
from_locs[i + hidden_adjust] = n.stack_before.Peek(stack_loc + calli_adjust).reg;
}
if (is_calli)
from_locs[pcount + hidden_adjust] = n.stack_before.Peek(0).reg;
}
else
{
from_locs = p;
// adjust any rsp relative registers dependent on how many registers we have saved
foreach (var l in from_locs)
{
if (l != null &&
l.t == ir.Opcode.vl_mreg &&
l.mreg is ContentsReg)
{
var l2 = l.mreg as ContentsReg;
if (l2.basereg.Equals(r_esp))
{
l2.disp += x;
}
}
}
}
// Reserve any required stack space
if (cstack_loc != 0)
{
push_length += cstack_loc;
r.Add(inst(cstack_loc <= 127 ? x86_sub_rm32_imm8 : x86_sub_rm32_imm32,
r_esp, cstack_loc, n));
}
// Move from the from list to the to list such that
// we never overwrite a from loc that hasn't been
// transfered yet
pcount += hidden_adjust;
pcount += calli_adjust;
var to_do = pcount;
bool[] done = new bool[pcount];
if(hidden_adjust != 0)
{
// load up the address of the return value
// we store to rax so we don't overwrite any stack variables, and then use the
// allocation logic below to move it to where it should go
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, r_eax, act_dest, n));
from_locs[0] = r_eax;
}
while (to_do > 0)
{
int done_this_iter = 0;
for(int to_i = 0; to_i < pcount; to_i++)
{
if(!done[to_i])
{
var to_reg = to_locs[to_i];
if(to_reg.type == rt_stack)
{
to_reg = new ContentsReg
{
basereg = r_esp,
disp = to_reg.stack_loc,
size = to_reg.size
};
}
bool possible = true;
// determine if this to register is the source of a from
for(int from_i = 0; from_i < pcount; from_i++)
{
if (to_i == from_i)
continue;
if (!done[from_i] && from_locs[from_i].mreg != null &&
from_locs[from_i].mreg.Equals(to_reg))
{
possible = false;
break;
}
}
if(possible)
{
var from_reg = from_locs[to_i];
switch(from_reg.t)
{
case ir.Opcode.vl_mreg:
if (from_reg.want_address)
{
Reg lea_to = to_reg;
if (to_reg is ContentsReg)
lea_to = r_eax;
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64,
lea_to, from_reg.mreg, n));
handle_move(to_reg, lea_to, r, n, c);
}
else
handle_move(to_reg, from_reg.mreg, r, n, c);
break;
case ir.Opcode.vl_c:
case ir.Opcode.vl_c32:
case ir.Opcode.vl_c64:
if (from_reg.v > int.MaxValue ||
from_reg.v < int.MinValue)
{
throw new NotImplementedException();
}
else
{
r.Add(inst(to_reg.size == 8 ? x86_mov_rm64_imm32 : x86_mov_rm32_imm32,
to_reg, from_reg, n));
}
break;
default:
throw new NotSupportedException();
}
to_do--;
done_this_iter++;
done[to_i] = true;
}
}
}
if (done_this_iter == 0)
{
// find two gprs/xmms we can swap to put them both
// in the correct locations
for (int i = 0; i < pcount; i++)
{
if (done[i])
continue;
var from_i = from_locs[i].mreg;
var to_i = to_locs[i];
if (from_i == null)
continue;
if (from_i.type != rt_gpr &&
from_i.type != rt_float)
continue;
if (to_i.type != rt_gpr &&
to_i.type != rt_float)
continue;
for (int j = 0; j < pcount; j++)
{
if (j == i)
continue;
if (done[j])
continue;
var from_j = from_locs[j].mreg;
if (from_j == null)
continue;
var to_j = to_locs[j];
if (from_i.Equals(to_j) &&
from_j.Equals(to_i))
{
// we can swap these
if (from_i.type == rt_gpr)
{
r.Add(inst(t.psize == 4 ? x86_xchg_r32_rm32 :
x86_xchg_r64_rm64, to_i, to_j, n));
}
else
{
handle_move(r_xmm7, to_i, r, n, c);
handle_move(to_i, to_j, r, n, c);
handle_move(to_j, r_xmm7, r, n, c);
}
done_this_iter += 2;
to_do -= 2;
done[i] = true;
done[j] = true;
break;
}
}
}
}
if (done_this_iter == 0)
{
// find two unassigned gprs/xmms we can swap, which
// may not necessarily put them in the correct place
bool shift_found = false;
// try with gprs first
int a = -1;
int b = -1;
for (int i = 0; i < pcount; i++)
{
if (done[i] == false && from_locs[i].mreg != null &&
from_locs[i].mreg.type == rt_gpr)
{
if (a == -1)
a = i;
else
{
b = i;
shift_found = true;
}
}
}
if(shift_found)
{
r.Add(inst(t.psize == 4 ? x86_xchg_r32_rm32 :
x86_xchg_r64_rm64, from_locs[a].mreg, from_locs[b].mreg, n));
var tmp = from_locs[a];
from_locs[a] = from_locs[b];
from_locs[b] = from_locs[a];
}
else
{
a = -1;
b = -1;
for (int i = 0; i < pcount; i++)
{
if (done[i] == false && from_locs[i].mreg != null &&
from_locs[i].mreg.type == rt_float)
{
if (a == -1)
a = i;
else
{
b = i;
shift_found = true;
}
}
}
if(shift_found)
{
handle_move(r_xmm7, from_locs[a].mreg, r, n, c);
handle_move(from_locs[a].mreg, from_locs[b].mreg, r, n, c);
handle_move(from_locs[b].mreg, r_xmm7, r, n, c);
var tmp = from_locs[a];
from_locs[a] = from_locs[b];
from_locs[b] = from_locs[a];
}
}
if(!shift_found)
throw new NotImplementedException();
}
}
// Do the call
if (is_calli)
{
r.Add(inst(x86_call_rm32, calli_reg, n));
}
else
r.Add(inst(x86_call_rel32, new ir.Param { t = ir.Opcode.vl_call_target, str = target }, n));
// Restore stack
if (push_length != 0)
{
var add_oc = t.psize == 4 ? x86_add_rm32_imm32 : x86_add_rm64_imm32;
if (push_length < 128)
add_oc = t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8;
r.Add(inst(add_oc, r_esp, push_length, n));
}
// Get vt return value
if (rct == ir.Opcode.ct_vt && !act_dest.Equals(dest))
{
handle_move(dest, act_dest, r, n, c);
}
// Restore saved registers
for (int i = push_list.Count - 1; i >= 0; i--)
handle_pop(push_list[i], ref x, r, n, c);
// Get other return value
if (rt != null && rct != ir.Opcode.ct_vt && rct != ir.Opcode.ct_unknown)
{
var rt_size = c.t.GetSize(rt);
var retccmap = c.t.retcc_map["ret_" + call_ms.CallingConvention];
if (rct == ir.Opcode.ct_float)
{
if (t.psize == 4)
{
var from = t.regs[retccmap[rct][0]];
handle_move(dest, from, r, n, c);
}
else
{
if (!dest.Equals(r_xmm0))
{
r.Add(inst(x86_movsd_xmmm64_xmm, dest, r_xmm0, n));
}
}
}
else if (rt_size <= 4)
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
else if (rt_size == 8)
{
if (t.psize == 4)
{
var drda = dest.SubReg(0, 4, c.t);
var drdb = dest.SubReg(4, 4, c.t);
r.Add(inst(x86_mov_rm32_r32, drda, r_eax, n));
r.Add(inst(x86_mov_rm32_r32, drdb, r_edx, n));
}
else
{
r.Add(inst(x86_mov_rm64_r64, dest, r_eax, n));
}
}
else
throw new NotImplementedException();
}
return r;
}
private static void handle_push(Reg reg, ref int push_length, List<MCInst> r, CilNode.IRNode n, Code c)
{
if (reg is ContentsReg)
{
ContentsReg cr = reg as ContentsReg;
if (cr.size < 4)
throw new NotImplementedException();
else if (cr.size == 4)
r.Add(inst(x86_push_rm32, reg, n));
else if (cr.size == 8 && c.t.psize == 8)
r.Add(inst(x86_push_rm32, reg, n));
else
{
var psize = util.util.align(cr.size, 4);
if (psize <= 127)
r.Add(inst(c.t.psize == 4 ? x86_sub_rm32_imm8 : x86_sub_rm64_imm8, r_esp, psize, n));
else
r.Add(inst(c.t.psize == 4 ? x86_sub_rm32_imm32 : x86_sub_rm64_imm32, r_esp, psize, n));
handle_move(new ContentsReg { basereg = r_esp, size = cr.size },
cr, r, n, c);
}
push_length += util.util.align(cr.size, c.t.psize);
}
else
{
if (reg.type == rt_gpr)
{
r.Add(inst(x86_push_r32, reg, n));
push_length += c.t.psize;
}
else if (reg.type == rt_float)
{
r.Add(inst(c.t.psize == 4 ? x86_sub_rm32_imm8 : x86_sub_rm64_imm8, r_esp, 8, n));
r.Add(inst(x86_movsd_xmmm64_xmm, new ContentsReg { basereg = r_esp, size = 8 }, reg, n));
push_length += 8;
}
}
}
private static void handle_pop(Reg reg, ref int pop_length, List<MCInst> r, CilNode.IRNode n, Code c)
{
if (reg is ContentsReg)
{
ContentsReg cr = reg as ContentsReg;
if (cr.size < 4)
throw new NotImplementedException();
else if (cr.size == 4)
r.Add(inst(x86_pop_rm32, reg, n));
else
{
handle_move(cr, new ContentsReg { basereg = r_esp, size = cr.size },
r, n, c);
var psize = util.util.align(cr.size, 4);
if (psize <= 127)
r.Add(inst(c.t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, r_esp, psize, n));
else
r.Add(inst(c.t.psize == 4 ? x86_add_rm32_imm32 : x86_add_rm64_imm32, r_esp, psize, n));
}
pop_length += 4;
}
else
{
if (reg.type == rt_gpr)
{
r.Add(inst(x86_pop_r32, reg, n));
pop_length += 4;
}
else if (reg.type == rt_float)
{
r.Add(inst(x86_movsd_xmm_xmmm64, reg, new ContentsReg { basereg = r_esp, size = 8 }, n));
r.Add(inst(c.t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, r_esp, 8, n));
pop_length += 8;
}
}
}
static protected MCInst inst_jmp(int idx, int jmp_target, CilNode.IRNode p)
{
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = insts[idx] },
new ir.Param { t = ir.Opcode.vl_br_target, v = jmp_target },
},
parent = p
};
}
static protected MCInst inst_jmp(int idx, int jmp_target, int cc, CilNode.IRNode p)
{
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = insts[idx] },
new ir.Param { t = ir.Opcode.vl_cc, v = cc },
new ir.Param { t = ir.Opcode.vl_br_target, v = jmp_target }
},
parent = p
};
}
protected static MCInst inst(int idx, ir.Param v1, ir.Param v2, ir.Param v3, CilNode.IRNode p, bool is_tls = false)
{
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = insts[idx], v2 = is_tls ? 1 : 0 },
v1,
v2,
v3
},
parent = p
};
}
protected static MCInst inst(int idx, ir.Param v1, ir.Param v2, ir.Param v3, ir.Param v4, ir.Param v5, CilNode.IRNode p, bool is_tls = false)
{
if (is_tls)
throw new NotImplementedException();
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = insts[idx] },
v1,
v2,
v3,
v4,
v5
},
parent = p
};
}
protected static MCInst inst(int idx, ir.Param v1, ir.Param v2, CilNode.IRNode p, bool is_tls = false)
{
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = insts[idx], v2 = is_tls ? 1 : 0 },
v1,
v2
},
parent = p
};
}
protected static MCInst inst(int idx, ir.Param v1, CilNode.IRNode p, bool is_tls = false)
{
if (is_tls)
throw new NotImplementedException();
string str = null;
insts.TryGetValue(idx, out str);
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = str },
v1
},
parent = p
};
}
protected static MCInst inst(int idx, CilNode.IRNode p, bool is_tls = false)
{
if (is_tls)
throw new NotImplementedException();
string str = null;
insts.TryGetValue(idx, out str);
return new MCInst
{
p = new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_str, v = idx, str = str },
},
parent = p
};
}
internal static List<MCInst> handle_add(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
switch (n_ct)
{
case ir.Opcode.ct_int32:
handle_add(t, srca, srcb, dest, r, n);
return r;
case ir.Opcode.ct_int64:
{
if (t.psize == 4)
{
var srcaa = srca.SubReg(0, 4);
var srcab = srca.SubReg(4, 4);
var srcba = srcb.SubReg(0, 4);
var srcbb = srcb.SubReg(4, 4);
var desta = dest.SubReg(0, 4);
var destb = dest.SubReg(4, 4);
handle_add(t, srcaa, srcba, desta, r, n);
handle_add(t, srcab, srcbb, destb, r, n, true);
return r;
}
else
{
handle_add(t, srca, srcb, dest, r, n);
return r;
}
}
case ir.Opcode.ct_float:
{
var actdest = dest;
if(dest is ContentsReg)
actdest = r_xmm7;
handle_move(actdest, srca, r, n, c);
r.Add(inst(x86_addsd_xmm_xmmm64,
actdest, srcb, n));
handle_move(dest, actdest, r, n, c);
return r;
}
}
return null;
}
internal static List<MCInst> handle_sub(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
switch (n_ct)
{
case ir.Opcode.ct_int32:
handle_sub(t, srca, srcb, dest, r, n);
return r;
case ir.Opcode.ct_int64:
if(t.psize == 8)
{
handle_sub(t, srca, srcb, dest, r, n);
return r;
}
else
{
var draa = srca.SubReg(0, 4, c.t);
var drab = srca.SubReg(4, 4, c.t);
var drba = srcb.SubReg(0, 4, c.t);
var drbb = srcb.SubReg(4, 4, c.t);
var drda = dest.SubReg(0, 4, c.t);
var drdb = dest.SubReg(4, 4, c.t);
handle_sub(t, draa, drba, drda, r, n);
handle_sub(t, drab, drbb, drdb, r, n, true);
return r;
}
case ir.Opcode.ct_float:
{
var actdest = dest;
if (dest is ContentsReg)
actdest = r_xmm7;
handle_move(actdest, srca, r, n, c);
r.Add(inst(x86_subsd_xmm_xmmm64,
actdest, srcb, n));
handle_move(dest, actdest, r, n, c);
return r;
}
}
return null;
}
internal static List<MCInst> handle_mul(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
if (n_ct == ir.Opcode.ct_int32)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
if (srca.Equals(dest) && !(srca is ContentsReg))
{
return new List<MCInst>
{
inst(x86_imul_r32_rm32, dest, srcb, n)
};
}
else
{
var r = new List<MCInst>();
handle_move(r_eax, srca, r, n, c);
r.Add(inst(x86_imul_r32_rm32, r_eax, srcb, n));
handle_move(dest, r_eax, r, n, c);
return r;
}
}
else if (n_ct == ir.Opcode.ct_float)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
if (srca.Equals(dest) && !(srca is ContentsReg))
{
return new List<MCInst>
{
inst(x86_mulsd_xmm_xmmm64, dest, srcb, n)
};
}
else
{
var r = new List<MCInst>();
handle_move(r_xmm7, srca, r, n, c);
r.Add(inst(x86_mulsd_xmm_xmmm64, r_xmm7, srcb, n));
handle_move(dest, r_xmm7, r, n, c);
return r;
}
}
else if (n_ct == ir.Opcode.ct_int64)
{
if (t.psize == 8)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
if (srca.Equals(dest) && !(srca is ContentsReg))
{
return new List<MCInst>
{
inst(x86_imul_r64_rm64, dest, srcb, n)
};
}
else
{
var r = new List<MCInst>();
handle_move(x86_64.x86_64_Assembler.r_rax, srca, r, n, c);
r.Add(inst(x86_imul_r64_rm64, x86_64.x86_64_Assembler.r_rax, srcb, n));
handle_move(dest, x86_64.x86_64_Assembler.r_rax, r, n, c);
return r;
}
}
else
{
return t.handle_external(t, nodes, start, count, c,
"__muldi3");
}
}
return null;
}
internal static List<MCInst> handle_div(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
var n_ct = n.ct;
switch(n_ct)
{
case ir.Opcode.ct_int32:
{
List<MCInst> r = new List<MCInst>();
handle_move(r_eax, srca, r, n, c);
r.Add(inst(x86_xor_r32_rm32, r_edx, r_edx, n));
r.Add(inst(x86_idiv_rm32, srcb, n));
handle_move(dest, r_eax, r, n, c);
return r;
}
case ir.Opcode.ct_float:
{
List<MCInst> r = new List<MCInst>();
if(!srca.Equals(dest) &&
!(dest is ContentsReg))
{
handle_move(dest, srca, r, n, c);
dest = srca;
}
var act_dest = dest;
if(dest is ContentsReg)
{
handle_move(r_xmm7, srca, r, n, c);
act_dest = r_xmm7;
}
r.Add(inst(x86_divsd_xmm_xmmm64, act_dest, srcb, n));
handle_move(dest, act_dest, r, n, c);
return r;
}
case ir.Opcode.ct_int64:
if (t.psize == 8)
{
List<MCInst> r = new List<MCInst>();
handle_move(x86_64.x86_64_Assembler.r_rax, srca, r, n, c);
r.Add(inst(x86_xor_r64_rm64, x86_64.x86_64_Assembler.r_rdx, x86_64.x86_64_Assembler.r_rdx, n));
r.Add(inst(x86_idiv_rm64, srcb, n));
handle_move(dest, x86_64.x86_64_Assembler.r_rax, r, n, c);
return r;
}
else
{
return t.handle_external(t, nodes, start, count, c,
"__divdi3");
}
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_and(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
switch (n_ct)
{
case ir.Opcode.ct_int32:
handle_and(srca, srcb, dest, r, n);
return r;
case ir.Opcode.ct_int64:
if(t.psize == 8)
{
handle_and(srca, srcb, dest, r, n);
return r;
}
else
{
var draa = srca.SubReg(0, 4, c.t);
var drab = srca.SubReg(4, 4, c.t);
var drba = srcb.SubReg(0, 4, c.t);
var drbb = srcb.SubReg(4, 4, c.t);
var drda = dest.SubReg(0, 4, c.t);
var drdb = dest.SubReg(4, 4, c.t);
handle_and(draa, drba, drda, r, n);
handle_and(drab, drbb, drdb, r, n);
return r;
}
}
return null;
}
internal static List<MCInst> handle_or(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
switch (n_ct)
{
case ir.Opcode.ct_int32:
handle_or(srca, srcb, dest, r, n);
return r;
case ir.Opcode.ct_int64:
if(t.psize == 8)
{
handle_or(srca, srcb, dest, r, n);
return r;
}
else
{
var draa = srca.SubReg(0, 4, c.t);
var drab = srca.SubReg(4, 4, c.t);
var drba = srcb.SubReg(0, 4, c.t);
var drbb = srcb.SubReg(4, 4, c.t);
var drda = dest.SubReg(0, 4, c.t);
var drdb = dest.SubReg(4, 4, c.t);
handle_or(draa, drba, drda, r, n);
handle_or(drab, drbb, drdb, r, n);
return r;
}
}
return null;
}
internal static List<MCInst> handle_xor(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
switch (n_ct)
{
case ir.Opcode.ct_int32:
handle_xor(srca, srcb, dest, r, n);
return r;
case ir.Opcode.ct_int64:
if (t.psize == 8)
{
handle_xor(srca, srcb, dest, r, n);
return r;
}
else
{
var draa = srca.SubReg(0, 4, c.t);
var drab = srca.SubReg(4, 4, c.t);
var drba = srcb.SubReg(0, 4, c.t);
var drbb = srcb.SubReg(4, 4, c.t);
var drda = dest.SubReg(0, 4, c.t);
var drdb = dest.SubReg(4, 4, c.t);
handle_xor(draa, drba, drda, r, n);
handle_xor(drab, drbb, drdb, r, n);
return r;
}
}
return null;
}
internal static List<MCInst> handle_not(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var src = n.stack_before.Peek(n.arg_a).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
if (n_ct == ir.Opcode.ct_int32)
{
List<MCInst> r = new List<MCInst>();
if (src != dest)
handle_move(dest, src, r, n, c);
r.Add(inst(x86_not_rm32, dest, n));
return r;
}
else if(n_ct == ir.Opcode.ct_int64)
{
if (t.psize == 8)
{
List<MCInst> r = new List<MCInst>();
if (src != dest)
handle_move(dest, src, r, n, c);
r.Add(inst(x86_not_rm64, dest, n));
return r;
}
else
{
var sa = src.SubReg(0, 4);
var sb = src.SubReg(4, 4);
var da = dest.SubReg(0, 4);
var db = dest.SubReg(4, 4);
List<MCInst> r = new List<MCInst>();
if (!sa.Equals(da))
handle_move(da, sa, r, n, c);
r.Add(inst(x86_not_rm32, da, n));
if (!sb.Equals(db))
handle_move(db, sb, r, n, c);
r.Add(inst(x86_not_rm32, db, n));
return r;
}
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_nop(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var r = new List<MCInst>();
r.Add(inst(x86_nop, n));
return r;
}
internal static List<MCInst> handle_neg(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var src = n.stack_before.Peek(n.arg_a).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
if (n_ct == ir.Opcode.ct_int32)
{
List<MCInst> r = new List<MCInst>();
if (src != dest)
handle_move(dest, src, r, n, c);
r.Add(inst(x86_neg_rm32, dest, n));
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
if (t.psize == 8)
{
List<MCInst> r = new List<MCInst>();
if (src != dest)
handle_move(dest, src, r, n, c);
r.Add(inst(x86_neg_rm64, dest, n));
return r;
}
else
{
return t.handle_external(t, nodes, start, count,
c, "__negdi2");
}
}
else if (n_ct == ir.Opcode.ct_float)
{
// first get 0.0 in xmm7 by performing cmpneqsd
List<MCInst> r = new List<MCInst>();
r.Add(inst(x86_cmpsd_xmm_xmmm64_imm8,
r_xmm7, r_xmm7, 4, n));
// now subtract input value from it (0.0)
r.Add(inst(x86_subsd_xmm_xmmm64, r_xmm7, src, n));
handle_move(dest, r_xmm7, r, n, c);
return r;
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_cctor_runonce(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
/* We emit a complex instruction sequence:
First, load address of static object
mov rdx, [lab_addr]
Now, execute a loop testing for [rdx] being either:
0 - cctor has not been run and is not running,
therefore try and acquire the lock and run
it
1 - cctor is running in this or another thread
2 - cctor has finished
CIL II 10.5.3.3 allows the cctor to return if the
cctor is already running in the current thread or
any thread that is blocking on the current.
TODO: we don't support the second part yet, but
return if [rdx] == 1 too.
.t1:
cmp_rm8_imm8 [rdx], 2
je .ret
cmp_rm8_imm8 [rdx], 1 // TODO: should check thread id here
je .ret
Attempt to acquire the lock here. AL is the value
to test, CL is the value to set if we acquire it,
ZF reports success.
xor_rm32_r32 rax, rax
mov_r32_imm32 rcx, 1
lock_cmpxchg_rm8_r8 [rdx], cl
jnz .t1
*/
// Assign local labels
var t1 = c.next_mclabel--;
int ret = c.cctor_ret_tag;
if (ret == -1)
{
ret = c.next_mclabel--;
c.cctor_ret_tag = ret;
}
List<MCInst> r = new List<MCInst>();
r.Add(inst(x86_mov_rm32_imm32, r_edx, new ir.Param { t = ir.Opcode.vl_str, str = n.imm_ts.MangleType() + "S" }, n));
// t1
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = t1 }, n));
r.Add(inst(x86_cmp_rm8_imm8, new ContentsReg { basereg = r_edx }, 2, n));
r.Add(inst_jmp(x86_jcc_rel32, ret, ir.Opcode.cc_eq, n));
r.Add(inst(x86_cmp_rm8_imm8, new ContentsReg { basereg = r_edx }, 1, n));
r.Add(inst_jmp(x86_jcc_rel32, ret, ir.Opcode.cc_eq, n));
r.Add(inst(x86_xor_r32_rm32, r_eax, r_eax, n));
r.Add(inst(x86_mov_rm32_imm32, r_ecx, 1, n));
r.Add(inst(x86_lock_cmpxchg_rm8_r8, new ContentsReg { basereg = r_edx }, r_ecx, n));
r.Add(inst_jmp(x86_jcc_rel32, t1, ir.Opcode.cc_ne, n));
return r;
}
internal static List<MCInst> handle_memset(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var dr = n.stack_before.Peek(n.arg_a).reg;
var cv = n.stack_before.Peek(n.arg_b);
var cr = cv.reg;
List<MCInst> r = new List<MCInst>();
if (cv.min_l == cv.max_l && cv.min_l <= t.psize * 4 &&
cv.min_l % t.psize == 0 &&
dr.type == rt_gpr)
{
// can optimise call away
for(int i = 0; i < cv.min_l; i+= t.psize)
{
var cdr = new ContentsReg { basereg = dr, disp = i, size = t.psize };
r.Add(inst(t.psize == 4 ? x86_mov_rm32_imm32 : x86_mov_rm64_imm32,
cdr, new ir.Param { t = ir.Opcode.vl_c32, v = 0 }, n));
}
return r;
}
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.memset),
new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_mreg, mreg = dr },
0,
new ir.Param { t = ir.Opcode.vl_mreg, mreg = cr },
},
null, "memset"));
return r;
}
internal static List<MCInst> handle_memcpy(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var dr = n.stack_before.Peek(n.arg_a).reg;
var sr = n.stack_before.Peek(n.arg_b).reg;
var cv = n.stack_before.Peek(n.arg_c);
var cr = cv.reg;
List<MCInst> r = new List<MCInst>();
if(cv.min_l == cv.max_l && cv.min_l <= t.psize * 4 &&
dr.type == rt_gpr && sr.type == rt_gpr)
{
// can optimise call away
sr = new ContentsReg { basereg = sr, size = (int)cv.min_l };
dr = new ContentsReg { basereg = dr, size = (int)cv.min_l };
handle_move(dr, sr, r, n, c);
return r;
}
// emit call to memcpy(dest, src, n)
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.memcpy),
new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_mreg, mreg = dr },
new ir.Param { t = ir.Opcode.vl_mreg, mreg = sr },
new ir.Param { t = ir.Opcode.vl_mreg, mreg = cr },
},
null, "memcpy"));
return r;
}
internal static List<MCInst> handle_call(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return handle_call(n, c, false, t);
}
internal static List<MCInst> handle_calli(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return handle_call(n, c, true, t);
}
internal static List<MCInst> handle_ret(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return handle_ret(n, c, t);
}
internal static List<MCInst> handle_cmp(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
if (n_ct == ir.Opcode.ct_int32)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
if (!(srca is ContentsReg))
r.Add(inst(x86_cmp_r32_rm32, srca, srcb, n));
else if (!(srcb is ContentsReg))
r.Add(inst(x86_cmp_rm32_r32, srca, srcb, n));
else
{
r.Add(inst(x86_mov_r32_rm32, r_eax, srca, n));
r.Add(inst(x86_cmp_r32_rm32, r_eax, srcb, n));
}
r.Add(inst(x86_set_rm32, new ir.Param { t = ir.Opcode.vl_cc, v = (int)n.imm_ul }, r_eax, n));
if (dest is ContentsReg)
{
r.Add(inst(x86_movzxbd, r_eax, r_eax, n));
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
}
else
r.Add(inst(x86_movzxbd, dest, r_eax, n));
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
if (t.psize == 8)
{
if (!(srca is ContentsReg))
r.Add(inst(x86_cmp_r64_rm64, srca, srcb, n));
else if (!(srcb is ContentsReg))
r.Add(inst(x86_cmp_rm64_r64, srca, srcb, n));
else
{
r.Add(inst(x86_mov_r32_rm32, r_eax, srca, n));
r.Add(inst(x86_cmp_r64_rm64, r_eax, srcb, n));
}
r.Add(inst(x86_set_rm32, new ir.Param { t = ir.Opcode.vl_cc, v = (int)n.imm_ul }, r_eax, n));
if (dest is ContentsReg)
{
r.Add(inst(x86_movzxbd, r_eax, r_eax, n));
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
}
else
r.Add(inst(x86_movzxbd, dest, r_eax, n));
}
else
{
var sal = srca.SubReg(0, 4);
var sah = srca.SubReg(4, 4);
var sbl = srcb.SubReg(0, 4);
var sbh = srcb.SubReg(4, 4);
var cc = (int)n.imm_ul;
/* For equal/not equal do a simple compare of
* low and high halves.
*
* For other comparisons its a bit more complex:
*
* cmp sah, sbh
* j1 L2 <- opposite, excluding equal of comparison
* j2 L1 <- original comparison, excluding equal
* cmp sal, sbl <- this is only performed if sah == sbh
* j3 L2 <- opposite, including complement of equal, unsigned
* L1: <- success path
* mov dest, 1
* jmp L3
* L2: <- fail path
* mov dest, 0
* L3: <- end
*/
var fail_path = c.next_mclabel--;
var end_path = c.next_mclabel--;
if (cc == ir.Opcode.cc_eq ||
cc == ir.Opcode.cc_ne)
{
var other_cc = ir.Opcode.cc_invert_map[cc];
// invert the comparison
if (sbh is ContentsReg)
{
handle_move(r_edx, sbh, r, n, c);
sbh = r_edx;
}
r.Add(inst(x86_cmp_rm32_r32, sah, sbh, n));
r.Add(inst_jmp(x86_jcc_rel32, fail_path, other_cc, n));
if (sbl is ContentsReg)
{
handle_move(r_edx, sbl, r, n, c);
sbl = r_edx;
}
r.Add(inst(x86_cmp_rm32_r32, sal, sbl, n));
r.Add(inst_jmp(x86_jcc_rel32, fail_path, other_cc, n));
// success
r.Add(inst(x86_mov_rm32_imm32, dest, 1, n));
r.Add(inst_jmp(x86_jmp_rel32, end_path, n));
// fail
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = fail_path }, n));
r.Add(inst(x86_mov_rm32_imm32, dest, 0, n));
// end
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = end_path }, n));
}
else
{
var success_path = c.next_mclabel--;
int j1_cc = 0;
int j2_cc = 0;
int j3_cc = 0;
switch (cc)
{
case ir.Opcode.cc_a:
j1_cc = ir.Opcode.cc_b;
j2_cc = ir.Opcode.cc_a;
j3_cc = ir.Opcode.cc_be;
break;
case ir.Opcode.cc_ae:
j1_cc = ir.Opcode.cc_b;
j2_cc = ir.Opcode.cc_a;
j3_cc = ir.Opcode.cc_b;
break;
case ir.Opcode.cc_b:
j1_cc = ir.Opcode.cc_a;
j2_cc = ir.Opcode.cc_b;
j3_cc = ir.Opcode.cc_ae;
break;
case ir.Opcode.cc_be:
j1_cc = ir.Opcode.cc_a;
j2_cc = ir.Opcode.cc_b;
j3_cc = ir.Opcode.cc_a;
break;
case ir.Opcode.cc_ge:
j1_cc = ir.Opcode.cc_lt;
j2_cc = ir.Opcode.cc_gt;
j3_cc = ir.Opcode.cc_b;
break;
case ir.Opcode.cc_gt:
j1_cc = ir.Opcode.cc_lt;
j2_cc = ir.Opcode.cc_gt;
j3_cc = ir.Opcode.cc_be;
break;
case ir.Opcode.cc_le:
j1_cc = ir.Opcode.cc_gt;
j2_cc = ir.Opcode.cc_lt;
j3_cc = ir.Opcode.cc_a;
break;
case ir.Opcode.cc_lt:
j1_cc = ir.Opcode.cc_gt;
j2_cc = ir.Opcode.cc_lt;
j3_cc = ir.Opcode.cc_ae;
break;
default:
throw new NotSupportedException();
}
if (sbh is ContentsReg)
{
handle_move(r_edx, sbh, r, n, c);
sbh = r_edx;
}
r.Add(inst(x86_cmp_rm32_r32, sah, sbh, n));
r.Add(inst_jmp(x86_jcc_rel32, fail_path, j1_cc, n));
r.Add(inst_jmp(x86_jcc_rel32, success_path, j2_cc, n));
if (sbl is ContentsReg)
{
handle_move(r_edx, sbl, r, n, c);
sbl = r_edx;
}
r.Add(inst(x86_cmp_rm32_r32, sal, sbl, n));
r.Add(inst_jmp(x86_jcc_rel32, fail_path, j3_cc, n));
// success
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = success_path }, n));
r.Add(inst(x86_mov_rm32_imm32, dest, 1, n));
r.Add(inst_jmp(x86_jmp_rel32, end_path, n));
// fail
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = fail_path }, n));
r.Add(inst(x86_mov_rm32_imm32, dest, 0, n));
// end
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = end_path }, n));
}
}
return r;
}
else if(n_ct == ir.Opcode.ct_float)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
if(srca is ContentsReg)
{
handle_move(r_xmm7, srca, r, n, c);
srca = r_xmm7;
}
var cc = (int)n.imm_ul;
int oc = 0;
int act_cc = 0;
switch(cc)
{
case ir.Opcode.cc_a:
act_cc = ir.Opcode.cc_a;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_ae:
act_cc = ir.Opcode.cc_ae;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_b:
act_cc = ir.Opcode.cc_b;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_be:
act_cc = ir.Opcode.cc_be;
oc = x86_ucomisd_xmm_xmmm64;
break;
case ir.Opcode.cc_eq:
act_cc = ir.Opcode.cc_eq;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_ge:
act_cc = ir.Opcode.cc_ae;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_gt:
act_cc = ir.Opcode.cc_a;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_le:
act_cc = ir.Opcode.cc_be;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_lt:
act_cc = ir.Opcode.cc_b;
oc = x86_comisd_xmm_xmmm64;
break;
case ir.Opcode.cc_ne:
act_cc = ir.Opcode.cc_ne;
oc = x86_comisd_xmm_xmmm64;
break;
default:
throw new NotImplementedException();
}
r.Add(inst(oc, srca, srcb, n));
r.Add(inst(x86_set_rm32, new ir.Param { t = ir.Opcode.vl_cc, v = act_cc }, r_eax, n));
if (dest is ContentsReg)
{
r.Add(inst(x86_movzxbd, r_eax, r_eax, n));
r.Add(inst(x86_mov_rm32_r32, dest, r_eax, n));
}
else
r.Add(inst(x86_movzxbd, dest, r_eax, n));
return r;
}
return null;
}
internal static List<MCInst> handle_br(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return new List<MCInst> { inst_jmp(x86_jmp_rel32, (int)n.imm_l, n) };
}
internal static List<MCInst> handle_brif(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
if (n_ct == ir.Opcode.ct_int32)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
List<MCInst> r = new List<MCInst>();
var cc = (int)n.imm_ul;
var target = (int)n.imm_l;
handle_brifi32(srca, srcb, cc, target, r, n);
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
if (t.psize == 4)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var srcaa = srca.SubReg(0, 4, c.t);
var srcab = srca.SubReg(4, 4, c.t);
var srcba = srcb.SubReg(0, 4, c.t);
var srcbb = srcb.SubReg(4, 4, c.t);
List<MCInst> r = new List<MCInst>();
var cc = (int)n.imm_ul;
var target = (int)n.imm_l;
// the following is untested
var other_cc = ir.Opcode.cc_invert_map[cc];
var neq_path = c.next_mclabel--;
handle_brifi32(srcab, srcbb, other_cc, neq_path, r, n);
handle_brifi32(srcaa, srcba, cc, target, r, n);
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = neq_path }, n));
return r;
}
else
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
List<MCInst> r = new List<MCInst>();
var cc = (int)n.imm_ul;
var target = (int)n.imm_l;
handle_brifi64(srca, srcb, cc, target, r, n);
return r;
}
}
else if (n_ct == ir.Opcode.ct_float)
{
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
List<MCInst> r = new List<MCInst>();
var cc = (int)n.imm_ul;
var target = (int)n.imm_l;
handle_briff(srca, srcb, cc, target, r, n);
return r;
}
return null;
}
internal static List<MCInst> handle_enter(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
List<MCInst> r = new List<MCInst>();
var n = nodes[start];
var lv_size = c.lv_total_size + c.stack_total_size;
if (ir.Opcode.GetCTFromType(c.ret_ts) == ir.Opcode.ct_vt)
{
if (t.psize == 4)
{
r.Add(inst(x86_pop_r32, r_eax, n));
r.Add(inst(x86_xchg_r32_rm32, r_eax, new ContentsReg { basereg = r_esp, disp = 0, size = 4 }, n));
}
}
r.Add(inst(x86_push_r32, r_ebp, n));
handle_move(r_ebp, r_esp, r, n, c);
if (lv_size != 0)
{
if (lv_size <= 127)
r.Add(inst(t.psize == 4 ? x86_sub_rm32_imm8 : x86_sub_rm64_imm8, r_esp, lv_size, n));
else
r.Add(inst(t.psize == 4 ? x86_sub_rm32_imm32 : x86_sub_rm64_imm32, r_esp, lv_size, n));
}
/* Move incoming arguments to the appropriate locations */
for(int i = 0; i < c.la_needs_assign.Length; i++)
{
if(c.la_needs_assign[i])
{
var from = c.incoming_args[i];
var to = c.la_locs[i];
handle_move(to, from, r, n, c);
}
}
var regs_to_save = c.regs_used & c.t.cc_callee_preserves_map[c.ms.CallingConvention];
// all registers are saved in isrs
if (c.ms.CallingConvention == "isr" || c.ms.CallingConvention == "isrec")
regs_to_save = c.t.cc_callee_preserves_map[c.ms.CallingConvention];
var regs_set = new util.Set();
regs_set.Union(regs_to_save);
int y = 0;
while (regs_set.Empty == false)
{
var reg = regs_set.get_first_set();
regs_set.unset(reg);
var cur_reg = t.regs[reg];
handle_push(cur_reg, ref y, r, n, c);
c.regs_saved.Add(cur_reg);
}
if (ir.Opcode.GetCTFromType(c.ret_ts) == ir.Opcode.ct_vt)
{
handle_move(new ContentsReg { basereg = r_ebp, disp = -t.psize, size = t.psize },
t.psize == 4 ? r_eax : r_edi, r, n, c);
}
if(c.ms.CallingConvention == "isr" || c.ms.CallingConvention == "isrec")
{
// store the current stack pointer as the 'regs' parameter
handle_move(c.la_locs[c.la_locs.Length - 1], r_esp, r, n, c);
}
return r;
}
internal static List<MCInst> handle_break(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
List<MCInst> r = new List<MCInst>();
var br_target = c.next_mclabel--;
r.Add(inst(x86_mov_rm32_imm32, r_eax, 0, n));
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = br_target }, n));
r.Add(inst(x86_cmp_rm32_imm32, r_eax, 1, n));
r.Add(inst_jmp(x86_jcc_rel32, br_target, ir.Opcode.cc_ne, n));
//r.Add(inst(x86_int3, n));
return r;
}
internal static List<MCInst> handle_enter_handler(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var r = new List<MCInst>();
string eh_str = "EH";
if (n.imm_ul == 1UL)
eh_str = "EHF"; // filter block
r.Add(inst(Generic.g_label, c.ms.MangleMethod() + eh_str + n.imm_l.ToString(), n));
// store current frame pointer (we need to restore it at the
// end in order to return properly to the exception handling
// mechanism)
r.Add(inst(x86_push_r32, r_ebp, n));
// extract our frame pointer from the passed argument
if (t.psize == 8)
{
r.Add(inst(x86_mov_r64_rm64, r_ebp, r_edi, n));
}
else
{
r.Add(inst(x86_mov_r32_rm32, r_ebp, new ContentsReg { basereg = r_esp, disp = 4, size = 4 }, n));
}
// store registers used by function
int y = 0;
foreach (var reg in c.regs_saved)
handle_push(reg, ref y, r, n, c);
return r;
}
internal static List<MCInst> handle_conv(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
bool is_un = (n.imm_l & 0x1) != 0;
bool is_ovf = (n.imm_l & 0x2) != 0;
if (n_ct == ir.Opcode.ct_int32)
{
var r = new List<MCInst>();
var si = n.stack_before.Peek(n.arg_a);
var di = n.stack_after.Peek(n.res_a);
var to_type = di.ts.SimpleType;
var sreg = si.reg;
var dreg = di.reg;
var actdreg = dreg;
if (dreg is ContentsReg)
{
if (actdreg.size == 8 && t.psize == 4)
dreg = r_eaxedx;
else
dreg = r_edx;
}
if(to_type == 0x18)
{
if (t.psize == 4)
to_type = 0x08;
else
to_type = 0x0a;
}
else if(to_type == 0x19)
{
if (t.psize == 4)
to_type = 0x09;
else
to_type = 0x0b;
}
switch (to_type)
{
case 0x04:
if (sreg.Equals(r_esi) || sreg.Equals(r_edi))
{
r.Add(inst(x86_mov_r32_rm32, r_eax, sreg, n));
sreg = r_eax;
}
r.Add(inst(x86_movsxbd, dreg, sreg, n));
break;
case 0x05:
if (sreg.Equals(r_esi) || sreg.Equals(r_edi))
{
r.Add(inst(x86_mov_r32_rm32, r_eax, sreg, n));
sreg = r_eax;
}
r.Add(inst(x86_movzxbd, dreg, sreg, n));
break;
case 0x06:
// int16
r.Add(inst(x86_movsxwd, dreg, sreg, n));
break;
case 0x07:
// uint16
r.Add(inst(x86_movzxwd, dreg, sreg, n));
break;
case 0x08:
case 0x09:
// nop
if (!sreg.Equals(dreg))
handle_move(dreg, sreg, r, n, c);
else
r.Add(inst(x86_nop, n)); // in case this is a br target
return r;
case 0x0a:
// conv to i8
{
if (t.psize == 4)
{
if (dreg.type != rt_multi)
throw new NotSupportedException();
List<Reg> set_regs = new List<Reg>();
for(int i = 0; i < 63; i++)
{
if ((dreg.mask & (1UL << i)) != 0UL)
set_regs.Add(t.regs[i]);
}
if (!(set_regs[0].Equals(sreg)))
{
handle_move(set_regs[0], sreg, r, n, c);
}
handle_move(set_regs[1], sreg, r, n, c);
r.Add(inst(x86_sar_rm32_imm8, set_regs[1], 31, n));
}
else
{
r.Add(inst(x86_movsxdq_r64_rm64, dreg, sreg, n));
}
}
break;
case 0x0b:
// conv to u8
if(t.psize == 4)
{
var dra = dreg.SubReg(0, 4, c.t);
var drb = dreg.SubReg(4, 4, c.t);
if (!(dra.Equals(sreg)))
{
handle_move(dra, sreg, r, n, c);
}
r.Add(inst(x86_mov_rm32_imm32, drb, new ir.Param { t = ir.Opcode.vl_c, v = 0 }, n));
}
else
{
if (dreg is ContentsReg)
throw new NotImplementedException();
r.Add(inst(x86_mov_r32_rm32, dreg, sreg, n));
}
break;
case 0x0c:
case 0x0d:
// conv to r4/8 (internal representation is the same)
{
if (dreg == r_edx)
dreg = r_xmm7;
r.Add(inst(x86_cvtsi2sd_xmm_rm32, dreg, sreg, n));
break;
}
default:
throw new NotImplementedException("Convert to " + to_type.ToString());
}
if (!dreg.Equals(actdreg))
handle_move(actdreg, dreg, r, n, c);
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
var r = new List<MCInst>();
var si = n.stack_before.Peek(n.arg_a);
var di = n.stack_after.Peek(n.res_a);
var to_type = di.ts.SimpleType;
var sreg = si.reg;
var dreg = di.reg;
Reg srca, srcb;
if (t.psize == 4)
{
srca = sreg.SubReg(0, 4);
srcb = sreg.SubReg(4, 4);
}
else
srca = sreg;
var actdreg = dreg;
if (dreg is ContentsReg)
{
if ((to_type == 0x0a || to_type == 0x0b) && t.psize == 4)
{
dreg = r_eaxedx;
}
else
{
dreg = r_edx;
}
}
if((to_type == 0x04 || to_type == 0x05) && t.psize == 4)
{
if (sreg.Equals(r_esi) || sreg.Equals(r_edi))
throw new NotImplementedException();
}
switch (to_type)
{
case 0x04:
// i1
if (dreg.Equals(r_edi) || dreg.Equals(r_esi))
dreg = r_edx;
handle_move(dreg, srca, r, n, c);
r.Add(inst(x86_movsxbd, dreg, dreg, n));
break;
case 0x05:
// u1
if (dreg.Equals(r_edi) || dreg.Equals(r_esi))
dreg = r_edx;
if (!srca.Equals(dreg))
handle_move(dreg, srca, r, n, c);
r.Add(inst(x86_movzxbd, dreg, dreg, n));
break;
case 0x06:
// i2
handle_move(dreg, srca, r, n, c);
r.Add(inst(x86_movsxwd, dreg, dreg, n));
break;
case 0x07:
// u2
handle_move(dreg, srca, r, n, c);
r.Add(inst(x86_movzxwd, dreg, dreg, n));
break;
case 0x08:
case 0x09:
case 0x18:
case 0x19:
if (!srca.Equals(dreg))
{
handle_move(dreg, sreg.SubReg(0, 4, c.t), r, n, c);
}
// nop - ignore high 32 bits
else
r.Add(inst(x86_nop, n)); // this could be a br target
return r;
case 0x0a:
// conv to i8
handle_move(dreg, sreg, r, n, c);
return r;
case 0x0b:
// conv to u8
handle_move(dreg, sreg, r, n, c);
return r;
case 0x0c:
case 0x0d:
// conv to float
if (dreg.Equals(r_edx))
dreg = r_xmm7;
if (is_un)
{
return t.handle_external(t, nodes,
start, count, c, "__floatundidf");
}
else
{
if (t.psize == 8)
{
r.Add(inst(x86_cvtsi2sd_xmm_rm64, dreg, sreg, n));
break;
}
else
{
return t.handle_external(t, nodes,
start, count, c, "__floatdidf");
}
}
default:
throw new NotImplementedException("Convert to " + to_type.ToString());
}
if (!dreg.Equals(actdreg))
{
if (dreg.Equals(r_edx))
r.Add(inst(x86_mov_rm32_r32, actdreg, dreg, n));
else if (dreg.Equals(r_xmm7))
r.Add(inst(x86_movsd_xmmm64_xmm, actdreg, dreg, n));
}
return r;
}
else if (n_ct == ir.Opcode.ct_float)
{
var r = new List<MCInst>();
var si = n.stack_before.Peek(n.arg_a);
var di = n.stack_after.Peek(n.res_a);
var to_type = di.ts.SimpleType;
var sreg = si.reg;
var dreg = di.reg;
var act_dreg = dreg;
switch (to_type)
{
case 0x04:
// int8
if (dreg is ContentsReg)
act_dreg = r_eax;
r.Add(inst(x86_cvtsd2si_r32_xmmm64, act_dreg, sreg, n));
r.Add(inst(x86_movsxbd, act_dreg, act_dreg, n));
handle_move(dreg, act_dreg, r, n, c);
return r;
case 0x05:
// uint8
if (dreg is ContentsReg)
act_dreg = r_eax;
r.Add(inst(x86_cvtsd2si_r32_xmmm64, act_dreg, sreg, n));
r.Add(inst(x86_movzxbd, act_dreg, act_dreg, n));
handle_move(dreg, act_dreg, r, n, c);
return r;
case 0x06:
// int16
if (dreg is ContentsReg)
act_dreg = r_eax;
r.Add(inst(x86_cvtsd2si_r32_xmmm64, act_dreg, sreg, n));
r.Add(inst(x86_movsxwd, act_dreg, act_dreg, n));
handle_move(dreg, act_dreg, r, n, c);
return r;
case 0x07:
// uint16
if (dreg is ContentsReg)
act_dreg = r_eax;
r.Add(inst(x86_cvtsd2si_r32_xmmm64, act_dreg, sreg, n));
r.Add(inst(x86_movzxwd, act_dreg, act_dreg, n));
handle_move(dreg, act_dreg, r, n, c);
return r;
case 0x08:
// int32
if (dreg is ContentsReg)
act_dreg = r_eax;
r.Add(inst(x86_cvtsd2si_r32_xmmm64, act_dreg, sreg, n));
handle_move(dreg, act_dreg, r, n, c);
return r;
case 0x09:
// uint32
//fc_override = "__fixunsdfsi";
return t.handle_external(t, nodes, start, count, c,
"__fixunsdfsi");
case 0x0a:
// int64
//fc_override = "__fixdfti";
if (t.psize == 8)
{
if (dreg is ContentsReg)
act_dreg = x86_64.x86_64_Assembler.r_rax;
r.Add(inst(x86_cvtsd2si_r64_xmmm64, act_dreg, sreg, n));
handle_move(dreg, act_dreg, r, n, c);
return r;
}
else
{
return t.handle_external(t, nodes, start, count, c,
"__fixdfdi");
}
case 0x0b:
// uint64
//fc_override = "__fixunsdfti";
return t.handle_external(t, nodes, start, count, c,
"__fixunsdfdi");
case 0x0c:
case 0x0d:
// float to float (all floats are 64-bit internally)
if (!dreg.Equals(sreg))
handle_move(dreg, sreg, r, n, c);
else
r.Add(inst(x86_nop, n)); // this could be a br target
return r;
default:
throw new NotImplementedException();
}
}
return null;
}
internal static List<MCInst> handle_stind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct2 = n.ct2;
var addr = n.stack_before.Peek(n.arg_a).reg;
var val = n.stack_before.Peek(n.arg_b).reg;
bool is_tls = n.imm_ul == 1UL;
if (n_ct2 == ir.Opcode.ct_int32 && t.psize == 4)
{
List<MCInst> r = new List<MCInst>();
if (addr is ContentsReg)
{
r.Add(inst(x86_mov_r32_rm32, r_eax, addr, n));
addr = r_eax;
}
if (val is ContentsReg || ((val.Equals(r_esi) || val.Equals(r_edi) && n.vt_size != 4)))
{
r.Add(inst(x86_mov_r32_rm32, r_edx, val, n));
val = r_edx;
}
if(n.vt_size == 1 && c.t.psize == 4) // r8 and r/m8 can only be al/bl/cl/dl on x86_32
{
if (addr.Equals(r_edi) || addr.Equals(r_esi))
{
handle_move(r_eax, addr, r, n, c);
addr = r_eax;
}
if (val.Equals(r_edi) || val.Equals(r_esi))
{
handle_move(r_edx, val, r, n, c);
val = r_edx;
}
}
switch (n.vt_size)
{
case 1:
r.Add(inst(x86_mov_rm8disp_r8, addr, 0, val, n, is_tls));
break;
case 2:
r.Add(inst(x86_mov_rm16disp_r16, addr, 0, val, n, is_tls));
break;
case 4:
r.Add(inst(x86_mov_rm32disp_r32, addr, 0, val, n, is_tls));
break;
default:
throw new NotImplementedException();
}
return r;
}
else if((n_ct2 == ir.Opcode.ct_int64 ||
n_ct2 == ir.Opcode.ct_int32)
&& t.psize == 8)
{
List<MCInst> r = new List<MCInst>();
if (addr is ContentsReg)
{
r.Add(inst(x86_mov_r64_rm64, r_eax, addr, n));
addr = r_eax;
}
if (val is ContentsReg || ((val.Equals(r_esi) || val.Equals(r_edi) && n.vt_size < 4)))
{
r.Add(inst(x86_mov_r64_rm64, r_edx, val, n));
val = r_edx;
}
if (n.vt_size == 1 && c.t.psize == 4)
{
if (addr.Equals(r_edi) || addr.Equals(r_esi))
throw new NotImplementedException();
if (val.Equals(r_edi) || addr.Equals(r_esi))
throw new NotImplementedException();
}
switch (n.vt_size)
{
case 1:
r.Add(inst(x86_mov_rm8disp_r8, addr, 0, val, n, is_tls));
break;
case 2:
r.Add(inst(x86_mov_rm16disp_r16, addr, 0, val, n, is_tls));
break;
case 4:
r.Add(inst(x86_mov_rm32disp_r32, addr, 0, val, n, is_tls));
break;
case 8:
r.Add(inst(x86_mov_rm64disp_r64, addr, 0, val, n, is_tls));
break;
default:
throw new NotImplementedException();
}
return r;
}
else if (n_ct2 == ir.Opcode.ct_int64 &&
t.psize == 4)
{
var dra = val.SubReg(0, 4, c.t);
var drb = val.SubReg(4, 4, c.t);
List<MCInst> r = new List<MCInst>();
if (addr is ContentsReg)
{
r.Add(inst(x86_mov_r32_rm32, r_eax, addr, n));
addr = r_eax;
}
handle_stind(dra, addr, 0, 4, r, n, c, is_tls);
handle_stind(drb, addr, 4, 4, r, n, c, is_tls);
return r;
}
else if (n_ct2 == ir.Opcode.ct_vt)
{
if (n.vt_size <= 16 && val is ContentsReg)
{
// handle as a bunch of moves
List<MCInst> r = new List<MCInst>();
if (addr is ContentsReg)
{
handle_move(r_edx, addr, r, n, c);
addr = r_edx;
}
addr = new ContentsReg { basereg = addr, size = n.vt_size };
handle_move(addr, val, r, n, c, r_eax, -1, false, is_tls);
return r;
}
else
{
if (is_tls)
throw new NotImplementedException();
// emit call to memcpy(dest, src, n)
List<MCInst> r = new List<MCInst>();
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.memcpy),
new ir.Param[] {
addr,
new ir.Param { t = ir.Opcode.vl_mreg, mreg = val, want_address = true },
n.vt_size },
null, "memcpy"));
return r;
}
}
else if(n_ct2 == ir.Opcode.ct_float)
{
List<MCInst> r = new List<MCInst>();
if (addr is ContentsReg)
{
handle_move(r_edx, addr, r, n, c);
addr = r_edx;
}
if(val is ContentsReg)
{
handle_move(r_xmm7, val, r, n, c);
val = r_xmm7;
}
addr = new ContentsReg { basereg = addr, size = n.vt_size };
if (n.vt_size == 4)
{
// convert to r4, then store
r.Add(inst(x86_cvtsd2ss_xmm_xmmm64, val, val, n, is_tls));
r.Add(inst(x86_movss_xmmm32_xmm, addr, val, n, is_tls));
}
else if (n.vt_size == 8)
{
// direct store
r.Add(inst(x86_movsd_xmmm64_xmm, addr, val, n, is_tls));
}
else
throw new NotSupportedException();
return r;
}
return null;
}
internal static List<MCInst> handle_ldind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ctret;
var addr = n.stack_before.Peek(n.arg_a).reg;
var val = n.stack_after.Peek(n.res_a).reg;
bool is_tls = n.imm_ul == 1UL;
if (n_ct == ir.Opcode.ct_int32 ||
(n_ct == ir.Opcode.ct_int64 && t.psize == 8))
{
List<MCInst> r = new List<MCInst>();
handle_ldind(val, addr, 0, n.vt_size, r, n, t, c, is_tls);
return r;
}
else if (n_ct == ir.Opcode.ct_int64 && t.psize == 4)
{
List<MCInst> r = new List<MCInst>();
var dra = val.SubReg(0, 4, c.t);
var drb = val.SubReg(4, 4, c.t);
/* Do this here so its only done once. We don't need the [esi]/[edi]
* check as the vt_size is guaranteed to be 4. However, the address
* used in the second iteration may overwrite the return value in
* the first, so we need to check for that. We do it backwards
* so that this is less likely (e.g. stack goes from
* ..., esi to ..., esi, edi thus assigning first to edi won't
* cause a problem */
if (addr is ContentsReg || addr.Equals(drb))
{
r.Add(inst(x86_mov_r32_rm32, r_eax, addr, n));
addr = r_eax;
}
handle_ldind(drb, addr, 4, 4, r, n, t, c, is_tls);
handle_ldind(dra, addr, 0, 4, r, n, t, c, is_tls);
return r;
}
else if(n_ct == ir.Opcode.ct_vt)
{
// handle as a bunch of moves
List<MCInst> r = new List<MCInst>();
if(addr is ContentsReg)
{
handle_move(r_edx, addr, r, n, c);
addr = r_edx;
}
addr = new ContentsReg { basereg = addr, size = n.vt_size };
handle_move(val, addr, r, n, c, r_eax, -1, is_tls);
return r;
}
else if(n_ct == ir.Opcode.ct_float)
{
List<MCInst> r = new List<MCInst>();
if(addr is ContentsReg)
{
handle_move(r_edx, addr, r, n, c);
addr = r_edx;
}
var act_dest = val;
if(act_dest is ContentsReg)
{
act_dest = r_xmm7;
}
addr = new ContentsReg { basereg = addr, size = n.vt_size };
switch(n.vt_size)
{
case 4:
r.Add(inst(x86_cvtss2sd_xmm_xmmm32, act_dest, addr, n, is_tls));
break;
case 8:
r.Add(inst(x86_movsd_xmm_xmmm64, act_dest, addr, n, is_tls));
break;
default:
throw new NotSupportedException();
}
handle_move(val, act_dest, r, n, c);
return r;
}
return null;
}
internal static List<MCInst> handle_ldfp(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
r.Add(inst(t.psize == 4 ? x86_mov_rm32_r32 : x86_mov_rm64_r64, dest, r_ebp, n));
return r;
}
internal static List<MCInst> handle_ldlabaddr(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var dest = n.stack_after.Peek(n.res_a).reg;
int oc = x86_mov_rm32_imm32;
if (n.imm_ul == 1 && t.psize == 8)
oc = x86_mov_rm64_imm32; // ensure TLS address loads are sign-extended
if ((string)t.Options["mcmodel"] == "large")
oc = x86_mov_r64_imm64;
List<MCInst> r = new List<MCInst>();
if (dest is ContentsReg)
{
r.Add(inst(oc, r_eax, new ir.Param { t = ir.Opcode.vl_str, str = n.imm_lab, v = n.imm_l, v2 = (long)n.imm_ul }, n));
handle_move(dest, r_eax, r, n, c);
}
else
r.Add(inst(oc, dest, new ir.Param { t = ir.Opcode.vl_str, str = n.imm_lab, v = n.imm_l, v2 = (long)n.imm_ul }, n));
return r;
}
internal static List<MCInst> handle_zeromem(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var sizev = n.stack_before.Peek(n.arg_a);
var dest = n.stack_before.Peek(n.arg_b).reg;
int size = (int)n.imm_l;
if(size == 0)
{
if (sizev.min_l == sizev.max_l)
size = (int)sizev.min_l;
}
if (size == 0)
{
// emit call to memset here
throw new NotImplementedException();
}
List<MCInst> r = new List<MCInst>();
handle_zeromem(t, dest, size, r, n, c);
return r;
}
internal static List<MCInst> handle_ldelem(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n1 = nodes[start + 1];
var n2 = nodes[start + 2];
var n3 = nodes[start + 3];
var n4 = nodes[start + 4];
var n5 = nodes[start + 5];
var n6 = nodes[start + 6];
var n7 = nodes[start + 7];
var n8 = nodes[start + 8];
// sanity checks
if (n.res_a != 0)
return null;
if (n1.arg_a != 1 || n1.arg_b != 0 || n1.res_a != 0)
return null;
if (n2.arg_a != 1 || n2.res_a != 0)
return null;
if (n3.res_a != 0)
return null;
if (n4.arg_a != 1 || n4.arg_b != 0 || n4.res_a != 0)
return null;
if (n5.arg_a != 0 || n5.res_a != 0)
return null;
if (n6.arg_a != 1 || n6.arg_b != 0 || n6.res_a != 0)
return null;
if (n7.arg_a != 0 || n7.res_a != 0)
return null;
if (n8.arg_a != 0 || n8.res_a != 0)
return null;
// extract values
var arr = n.stack_before.Peek(1).reg;
var index = n.stack_before.Peek(0).reg;
var tsize = n.imm_l;
var dataoffset = n3.imm_l;
var dest = n8.stack_after.Peek(0).reg;
// ensure this is possible
if (arr is ContentsReg)
return null;
if (index is ContentsReg)
return null;
if (tsize > t.psize)
return null;
if (tsize != 1 && tsize != 2 && tsize != 4 && tsize != 8)
return null;
if (dest is ContentsReg)
return null;
if (dataoffset > int.MaxValue)
return null;
if (dest.Equals(index))
return null;
/* handle as:
*
* mov dest, [arr + dataoffset]
* mov(szbwx) dest, [dest + index * tsize]
*/
List<MCInst> r = new List<MCInst>();
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32disp : x86_mov_r64_rm64disp,
dest, arr, dataoffset, n));
// get correct ld opcode
int oc = 0;
switch (tsize)
{
case 1:
if (n7.imm_l == 1)
oc = t.psize == 4 ? x86_movsxbd_r32_rm8sibscaledisp : x86_movsxbq_r64_rm8sibscaledisp;
else
oc = t.psize == 4 ? x86_movzxbd_r32_rm8sibscaledisp : x86_movzxbq_r64_rm8sibscaledisp;
break;
case 2:
if (n7.imm_l == 1)
oc = t.psize == 4 ? x86_movsxwd_r32_rm16sibscaledisp : x86_movsxwq_r64_rm16sibscaledisp;
else
oc = t.psize == 4 ? x86_movzxwd_r32_rm16sibscaledisp : x86_movzxwq_r64_rm16sibscaledisp;
break;
case 4:
if (n7.imm_l == 1)
oc = t.psize == 4 ? x86_mov_r32_rm32sibscaledisp : x86_movsxdq_r64_rm32sibscaledisp;
else
oc = x86_mov_r32_rm32sibscaledisp;
break;
case 8:
if (t.psize != 8)
return null;
oc = x86_mov_r64_rm64sibscaledisp;
break;
default:
return null;
}
var act_dest = dest;
if (tsize == 1 && t.psize == 4 && (dest.Equals(r_esi) || dest.Equals(r_edi)))
{
handle_move(r_eax, dest, r, n, c);
dest = r_eax;
}
if (tsize == 1 && t.psize == 4 && (index.Equals(r_esi) || index.Equals(r_edi)))
{
handle_move(r_edx, index, r, n, c);
index = r_edx;
}
r.Add(inst(oc, dest, dest, index, tsize, 0, n));
handle_move(act_dest, dest, r, n, c);
return r;
}
internal static List<MCInst> handle_ldc_add(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n2 = nodes[start + 1];
var obj = n2.stack_before.Peek(n2.arg_a).reg;
if (n2.arg_b != 0)
return null;
var res = n2.stack_after.Peek(n2.res_a).reg;
var val = n.imm_l;
if (val < int.MinValue || val > int.MaxValue)
return null;
List<MCInst> r = new List<MCInst>();
handle_move(res, obj, r, n, c);
if(val != 0)
{
if (val <= 127 && val >= -128)
r.Add(inst(t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, res, val, n));
else
r.Add(inst(t.psize == 4 ? x86_add_rm32_imm32 : x86_add_rm64_imm32, res, val, n));
}
return r;
}
internal static List<MCInst> handle_ldc_add_ldind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n2 = nodes[start + 1];
var n3 = nodes[start + 2];
var obj = n2.stack_before.Peek(n2.arg_a).reg;
if (n2.arg_b != 0)
return null;
var val = n3.stack_after.Peek(n3.res_a).reg;
if (n3.arg_a != 0)
return null;
if (n3.imm_ul == 1) // TLS
throw new NotImplementedException();
var disp = n.imm_l;
if (disp < int.MinValue || disp > int.MaxValue)
return null;
if (obj is ContentsReg)
return null;
if (val is ContentsReg)
return null;
int size = n3.vt_size;
if (size > t.psize)
return null;
int oc = 0;
switch (n3.ctret)
{
case ir.Opcode.ct_int32:
case ir.Opcode.ct_int64:
case ir.Opcode.ct_intptr:
switch (size)
{
case 1:
if (n3.imm_l == 1)
oc = t.psize == 4 ? x86_movsxbd_r32_rm8disp : x86_movsxbq_r64_rm8disp;
else
oc = t.psize == 4 ? x86_movzxbd_r32_rm8disp : x86_movzxbq_r64_rm8disp;
break;
case 2:
if (n3.imm_l == 1)
oc = t.psize == 4 ? x86_movsxwd_r32_rm16disp : x86_movsxwq_r64_rm16disp;
else
oc = t.psize == 4 ? x86_movzxwd_r32_rm16disp : x86_movzxwq_r64_rm16disp;
break;
case 4:
oc = x86_mov_r32_rm32disp;
break;
case 8:
if (t.psize != 8)
return null;
oc = x86_mov_r64_rm64disp;
break;
default:
return null;
}
break;
case ir.Opcode.ct_float:
switch (size)
{
case 4:
oc = x86_cvtss2sd_xmm_xmmm32disp;
break;
case 8:
oc = x86_movsd_xmm_xmmm64disp;
break;
default:
return null;
}
break;
default:
return null;
}
List<MCInst> r = new List<MCInst>();
if(size == 1 && t.psize == 4 && (val.Equals(r_esi) || val.Equals(r_edi)))
{
handle_move(r_eax, val, r, n, c);
val = r_eax;
}
if(size == 1 && t.psize == 4 && (obj.Equals(r_esi) || obj.Equals(r_edi)))
{
handle_move(r_edx, obj, r, n, c);
obj = r_edx;
}
r.Add(inst(oc, val, obj, disp, n));
return r;
}
internal static List<MCInst> handle_ldc_ldc_add_stind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n2 = nodes[start + 1];
var n3 = nodes[start + 2];
var n4 = nodes[start + 3];
var obj = n3.stack_before.Peek(n3.arg_a).reg;
if (n2.arg_b != 0)
return null;
if (n4.arg_a != 0)
return null;
if (n4.arg_b != 1)
return null;
if (n4.imm_ul == 1) // TLS
throw new NotImplementedException();
var disp = n2.imm_l;
if (disp < int.MinValue || disp > int.MaxValue)
return null;
var val = n.imm_l;
if (val < int.MinValue || val > int.MaxValue)
return null;
if (obj is ContentsReg)
return null;
int size = n4.vt_size;
if (size > t.psize)
return null;
var actobj = obj;
if((obj.Equals(r_edi) || obj.Equals(r_esi)) && t.psize == 4)
{
obj = r_eax;
}
int oc = 0;
switch (size)
{
case 1:
oc = x86_mov_rm8disp_imm32;
break;
case 2:
oc = x86_mov_rm16disp_imm32;
break;
case 4:
oc = x86_mov_rm32disp_imm32;
break;
case 8:
oc = x86_mov_rm64disp_imm32;
break;
default:
return null;
}
List<MCInst> r = new List<MCInst>();
r.Add(inst(oc, obj, disp, val, n));
handle_move(actobj, obj, r, n, c);
return r;
}
internal static List<MCInst> handle_ldc_add_stind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n2 = nodes[start + 1];
var n3 = nodes[start + 2];
var n_ct = n3.ct2;
var obj = n2.stack_before.Peek(n2.arg_a).reg;
if (n2.arg_b != 0)
return null;
var val = n3.stack_before.Peek(n3.arg_b).reg;
if (n3.arg_a != 0)
return null;
var disp = n.imm_l;
if (n3.imm_ul == 1) // TLS
throw new NotImplementedException();
if (disp < int.MinValue || disp > int.MaxValue)
return null;
if (obj is ContentsReg)
return null;
if (val is ContentsReg)
return null;
int size = n3.vt_size;
if (size > t.psize)
return null;
List<MCInst> r = new List<MCInst>();
int oc = 0;
switch (n_ct)
{
case ir.Opcode.ct_int32:
case ir.Opcode.ct_int64:
case ir.Opcode.ct_intptr:
switch (size)
{
case 1:
oc = x86_mov_rm8disp_r8;
break;
case 2:
oc = x86_mov_rm16disp_r16;
break;
case 4:
oc = x86_mov_rm32disp_r32;
break;
case 8:
oc = x86_mov_rm64disp_r64;
break;
default:
return null;
}
break;
case ir.Opcode.ct_float:
if (size == 4)
{
// convert to r4 first
r.Add(inst(x86_cvtsd2ss_xmm_xmmm64, r_xmm7, val, n));
val = r_xmm7;
oc = x86_movss_xmmm32disp_xmm;
}
else
oc = x86_movsd_xmmm64disp_xmm;
break;
default:
return null;
}
if (size == 1 && t.psize == 4 && (val.Equals(r_esi) || val.Equals(r_edi)))
{
handle_move(r_eax, val, r, n, c);
val = r_eax;
}
if (size == 1 && t.psize == 4 && (obj.Equals(r_esi) || obj.Equals(r_edi)))
{
handle_move(r_edx, obj, r, n, c);
obj = r_edx;
}
r.Add(inst(oc, obj, disp, val, n));
return r;
}
internal static List<MCInst> handle_ldc_zeromem(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n2 = nodes[start + 1];
if (n2.arg_a != 0)
return null;
var dest = n2.stack_before.Peek(n.arg_b).reg;
var size = n.imm_l;
List<MCInst> r = new List<MCInst>();
handle_zeromem(t, dest, (int)size, r, n2, c);
return r;
}
private static void handle_zeromem(Target t, Reg dest, int size,
List<MCInst> r, CilNode.IRNode n, Code c)
{
if (size > t.psize * 4)
{
// emit call to memset(void *s, int c, size_t n) here
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.memset),
new ir.Param[]
{
new ir.Param { t = ir.Opcode.vl_mreg, mreg = dest },
0,
size
},
null, "memset"));
return;
}
if(dest is ContentsReg)
{
handle_move(r_edx, dest, r, n, c);
dest = r_edx;
}
size = util.util.align(size, t.psize);
var cr = new ContentsReg { basereg = dest, size = size };
for(int i = 0; i < size; i += t.psize)
{
var d = cr.SubReg(i, t.psize);
r.Add(inst(t.psize == 4 ? x86_mov_rm32_imm32 : x86_mov_rm64_imm32, d, 0, n));
}
}
internal static List<MCInst> handle_ldc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ctret;
switch(n_ct)
{
case ir.Opcode.ct_int32:
return new List<MCInst> { inst(x86_mov_rm32_imm32, n.stack_after.Peek(n.res_a).reg, (int)n.imm_l, n) };
case ir.Opcode.ct_float:
if (n.vt_size == 4)
{
var dest = n.stack_after.Peek(n.res_a).reg;
var act_dest = dest;
var r = new List<MCInst>();
if (dest is ContentsReg)
act_dest = r_xmm7;
r.Add(inst(x86_push_imm32, n.imm_l, n));
r.Add(inst(x86_cvtss2sd_xmm_xmmm32, act_dest,
new ContentsReg { basereg = r_esp, size = 4 }, n));
r.Add(inst(t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8, r_esp, t.psize, n));
handle_move(dest, act_dest, r, n, c);
return r;
}
else if (n.vt_size == 8)
{
if (t.psize == 4)
{
var high_val = BitConverter.ToInt32(n.imm_val, 4);
var low_val = BitConverter.ToInt32(n.imm_val, 0);
var dest = n.stack_after.Peek(n.res_a).reg;
var act_dest = dest;
var r = new List<MCInst>();
if (dest is ContentsReg)
act_dest = r_xmm7;
r.Add(inst(x86_push_imm32, high_val, n));
r.Add(inst(x86_push_imm32, low_val, n));
r.Add(inst(x86_movsd_xmm_xmmm64, act_dest,
new ContentsReg { basereg = r_esp, size = 8 }, n));
r.Add(inst(x86_add_rm32_imm8, r_esp, 8, n));
handle_move(dest, act_dest, r, n, c);
return r;
}
else
{
var dest = n.stack_after.Peek(n.res_a).reg;
var act_dest = dest;
if (dest is ContentsReg)
act_dest = r_xmm7;
var r = new List<MCInst>();
r.Add(inst(x86_mov_r64_imm64, r_eax, n.imm_l, n));
r.Add(inst(x86_push_r32, r_eax, n));
r.Add(inst(x86_movsd_xmm_xmmm64, act_dest,
new ContentsReg { basereg = r_esp, size = 8 }, n));
r.Add(inst(x86_add_rm64_imm8, r_esp, 8, n));
handle_move(dest, act_dest, r, n, c);
return r;
}
}
else
throw new NotSupportedException();
case ir.Opcode.ct_int64:
{
var dest = n.stack_after.Peek(n.res_a).reg;
var da = dest.SubReg(0, 4);
var db = dest.SubReg(4, 4);
var sa = BitConverter.ToInt32(n.imm_val, 0);
var sb = BitConverter.ToInt32(n.imm_val, 4);
var r = new List<MCInst>();
r.Add(inst(x86_mov_rm32_imm32, da, sa, n));
r.Add(inst(x86_mov_rm32_imm32, db, sb, n));
return r;
}
default:
throw new NotImplementedException();
}
return null;
}
internal static List<MCInst> handle_ldloc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ctret;
var src = c.lv_locs[(int)n.imm_l];
var dest = n.stack_after.Peek(n.res_a).reg;
var vt_size = n.vt_size;
var r = new List<MCInst>();
if (n_ct == ir.Opcode.ct_int32 ||
n_ct == ir.Opcode.ct_float ||
n_ct == ir.Opcode.ct_vt ||
(n_ct == ir.Opcode.ct_int64 && t.psize == 8))
{
if (vt_size < 4)
{
// perform a sign/zero extension load
int oc = 0;
if (vt_size == 1)
{
if (n.imm_ul == 0)
oc = x86_movzxbd;
else
oc = x86_movsxbd;
}
else if (vt_size == 2)
{
if (n.imm_ul == 0)
oc = x86_movzxwd;
else
oc = x86_movsxwd;
}
else
throw new NotSupportedException("Invalid vt_size");
if (dest is ContentsReg)
{
r.Add(inst(oc, r_eax, src, n));
handle_move(dest, r_eax, r, n, c);
}
else
{
r.Add(inst(oc, dest, src, n));
}
}
else
{
handle_move(dest, src, r, n, c, null,
n_ct == ir.Opcode.ct_int32 ? 4 : -1);
}
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
var desta = dest.SubReg(0, 4);
var destb = dest.SubReg(4, 4);
var srca = src.SubReg(0, 4);
var srcb = src.SubReg(4, 4);
handle_move(desta, srca, r, n, c);
handle_move(destb, srcb, r, n, c);
return r;
}
return null;
}
internal static List<MCInst> handle_stloc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var src = n.stack_before.Peek(n.arg_a).reg;
var dest = c.lv_locs[(int)n.imm_l];
var r = new List<MCInst>();
if (n_ct == ir.Opcode.ct_int32 ||
n_ct == ir.Opcode.ct_float ||
n_ct == ir.Opcode.ct_vt ||
(n_ct == ir.Opcode.ct_int64 && t.psize == 8))
{
handle_move(dest, src, r, n, c);
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
var srca = src.SubReg(0, 4);
var srcb = src.SubReg(4, 4);
var desta = dest.SubReg(0, 4);
var destb = dest.SubReg(4, 4);
handle_move(desta, srca, r, n, c);
handle_move(destb, srcb, r, n, c);
return r;
}
return null;
}
internal static List<MCInst> handle_rem(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
var n_ct = n.ct;
switch(n_ct)
{
case ir.Opcode.ct_int32:
{
List<MCInst> r = new List<MCInst>();
handle_move(r_eax, srca, r, n, c);
r.Add(inst(x86_xor_r32_rm32, r_edx, r_edx, n));
r.Add(inst(x86_idiv_rm32, srcb, n));
handle_move(dest, r_edx, r, n, c);
return r;
}
case ir.Opcode.ct_int64:
if(t.psize == 8)
{
List<MCInst> r = new List<MCInst>();
handle_move(x86_64.x86_64_Assembler.r_rax, srca, r, n, c);
r.Add(inst(x86_xor_r64_rm64, x86_64.x86_64_Assembler.r_rdx, x86_64.x86_64_Assembler.r_rdx, n));
r.Add(inst(x86_idiv_rm64, srcb, n));
handle_move(dest, x86_64.x86_64_Assembler.r_rdx, r, n, c);
return r;
}
else
return t.handle_external(t, nodes, start, count, c, "__moddi3");
case ir.Opcode.ct_float:
{
// (a - b * floor(a / b))
// 1) do work in xmm7
List<MCInst> r = new List<MCInst>();
handle_move(r_xmm7, srca, r, n, c);
// 2) xmm7 <- a/b
r.Add(inst(x86_divsd_xmm_xmmm64, r_xmm7, srcb, n));
// 3) xmm 7 <- floor(a/b)
if ((bool)t.Options["sse4_1"] == true)
{
r.Add(inst(x86_roundsd_xmm_xmmm64_imm8, r_xmm7, r_xmm7, 3, n));
}
else
{
int pl = 0;
handle_push(r_xmm7, ref pl, r, n, c);
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.rint),
new ir.Param[] { r_xmm7 }, dest, "floor"));
handle_pop(r_xmm7, ref pl, r, n, c);
}
// 4) xmm7 <- b * floor(a/b)
r.Add(inst(x86_mulsd_xmm_xmmm64, r_xmm7, srcb, n));
if (!(dest is ContentsReg))
{
// 5) dest <- a
handle_move(dest, srca, r, n, c);
// 6) dest <- a - xmm7
r.Add(inst(x86_subsd_xmm_xmmm64, dest, r_xmm7, n));
}
else
{
// 5) dest <- xmm7 - a
r.Add(inst(x86_subsd_xmm_xmmm64, r_xmm7, srca, n));
handle_move(dest, r_xmm7, r, n, c);
// 6) xmm7 <- 0
r.Add(inst(x86_xorpd_xmm_xmmm128, r_xmm7, r_xmm7, n));
// 7) xmm7 <- -(dest)
r.Add(inst(x86_subsd_xmm_xmmm64, r_xmm7, dest, n));
// 8) dest <- -dest
handle_move(dest, r_xmm7, r, n, c);
}
return r;
}
return t.handle_external(t, nodes, start, count, c, "fmod");
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldarga(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = c.la_locs[(int)n.imm_l];
var dest = n.stack_after.Peek(n.res_a).reg;
if (!(src is ContentsReg))
throw new Exception("ldarga from " + src.ToString());
var act_dest = dest;
if (dest is ContentsReg)
dest = r_eax;
List<MCInst> r = new List<MCInst>();
if (!(src is ContentsReg))
throw new NotImplementedException();
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, dest, src, n));
handle_move(act_dest, dest, r, n, c);
return r;
}
internal static List<MCInst> handle_ldloca(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = c.lv_locs[(int)n.imm_l];
var dest = n.stack_after.Peek(n.res_a).reg;
if (!(src is ContentsReg))
throw new Exception("ldloca from " + src.ToString());
var act_dest = dest;
if (dest is ContentsReg)
dest = r_eax;
List<MCInst> r = new List<MCInst>();
if (!(src is ContentsReg))
throw new NotImplementedException();
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, dest, src, n));
handle_move(act_dest, dest, r, n, c);
return r;
}
internal static List<MCInst> handle_starg(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var dest = c.la_locs[(int)n.imm_l];
var src = n.stack_before.Peek(n.arg_a).reg;
var r = new List<MCInst>();
if (n_ct == ir.Opcode.ct_int32 ||
n_ct == ir.Opcode.ct_float ||
n_ct == ir.Opcode.ct_vt ||
n_ct == ir.Opcode.ct_int64)
{
handle_move(dest, src, r, n, c);
return r;
}
return null;
}
internal static List<MCInst> handle_syncvalswap(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var r = new List<MCInst>();
var size = n.imm_l;
var ptr = n.stack_before.Peek(n.arg_a).reg;
var newval = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
bool is_tls = ir.Opcode.IsTLSCT(n.stack_before.Peek(n.arg_a).ct);
if (size == 8 && t.psize == 4)
return t.handle_external(t, nodes, start, count, c, "__sync_val_swap_8");
if ((ptr is ContentsReg) && (newval is ContentsReg))
{
// we need another spare register for this
throw new NotImplementedException();
}
if (ptr is ContentsReg)
{
handle_move(r_edx, ptr, r, n, c);
ptr = r_edx;
}
if (newval is ContentsReg)
{
handle_move(r_edx, newval, r, n, c);
newval = r_edx;
}
int oc = 0;
int oc2 = 0;
switch (size)
{
case 1:
oc = x86_lock_xchg_rm8ptr_r8;
//if (issigned)
// throw new NotImplementedException();
//else
oc2 = t.psize == 4 ? x86_movzxbd : x86_movzxbq;
break;
case 4:
oc = x86_lock_xchg_rm32ptr_r32;
oc2 = 0;
break;
case 8:
oc = x86_lock_xchg_rm64ptr_r64;
oc2 = 0;
break;
default:
throw new NotImplementedException();
}
r.Add(inst(oc, new ContentsReg { basereg = ptr }, newval, n, is_tls));
if (dest is ContentsReg)
{
if (oc2 != 0)
r.Add(inst(oc2, r_eax, newval, n));
handle_move(dest, r_eax, r, n, c);
}
else if (oc2 != 0)
r.Add(inst(oc2, dest, newval, n));
else
handle_move(dest, newval, r, n, c);
return r;
}
internal static List<MCInst> handle_syncvalcompareandswap(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var r = new List<MCInst>();
var size = n.imm_l;
var issigned = n.imm_ul == 0 ? false : true;
var ptr = n.stack_before.Peek(n.arg_c).reg;
var oldval = n.stack_before.Peek(n.arg_b).reg;
var newval = n.stack_before.Peek(n.arg_a).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
bool is_tls = ir.Opcode.IsTLSCT(n.stack_before.Peek(n.arg_c).ct);
int oc = 0;
int oc2 = 0;
switch(size)
{
case 1:
oc = x86_lock_cmpxchg_rm8_r8;
if (issigned)
throw new NotImplementedException();
else
oc2 = t.psize == 4 ? x86_movzxbd : x86_movzxbq;
break;
case 4:
oc = x86_lock_cmpxchg_rm32_r32;
oc2 = 0;
break;
case 8:
if (t.psize == 4)
return handle_syncvalcompareandswap_8b(t, r, n, c, issigned, is_tls,
ptr, oldval, newval, dest);
oc = x86_lock_cmpxchg_rm64_r64;
oc2 = 0;
break;
default:
throw new NotImplementedException();
}
// lock cmpxchg takes the old value in rax,
// ptr in first argument and new val in second
// the old value is returned in rax regardless of
// success or failure
if((ptr is ContentsReg) && (newval is ContentsReg))
{
// we need another spare register for this
throw new NotImplementedException();
}
if(ptr is ContentsReg)
{
handle_move(r_edx, ptr, r, n, c);
ptr = r_edx;
}
if(newval is ContentsReg)
{
handle_move(r_edx, newval, r, n, c);
newval = r_edx;
}
handle_move(r_eax, oldval, r, n, c);
r.Add(inst(oc, new ContentsReg { basereg = ptr }, newval, n, is_tls));
if (dest is ContentsReg)
{
if (oc2 != 0)
r.Add(inst(oc2, r_eax, r_eax, n));
handle_move(dest, r_eax, r, n, c);
}
else if (oc2 != 0)
r.Add(inst(oc2, dest, r_eax, n));
else
handle_move(dest, r_eax, r, n, c);
return r;
}
internal static List<MCInst> handle_syncvalexchangeandadd(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var r = new List<MCInst>();
var size = n.imm_l;
var issigned = n.imm_ul == 0 ? false : true;
var ptr = n.stack_before.Peek(n.arg_b).reg;
var val = n.stack_before.Peek(n.arg_a).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
bool is_tls = ir.Opcode.IsTLSCT(n.stack_before.Peek(n.arg_b).ct);
if (size == 8 && t.psize == 4)
{
throw new NotImplementedException("64-bit XADD on 32-bit platform");
}
var actdest = dest;
if(!dest.Equals(val))
{
actdest = r_eax;
handle_move(r_eax, val, r, n, c);
}
if(ptr is ContentsReg)
{
handle_move(r_edx, ptr, r, n, c);
ptr = r_edx;
}
int oc = 0;
switch(size)
{
case 8:
oc = x86_lock_xadd_rm64_r64;
break;
default:
throw new NotImplementedException("XADD with size " + size.ToString());
}
r.Add(inst(oc, new ContentsReg { basereg = ptr }, val, n, is_tls));
if(!dest.Equals(actdest))
{
handle_move(dest, actdest, r, n, c);
}
return r;
}
private static List<MCInst> handle_syncvalcompareandswap_8b(Target t, List<MCInst> r, CilNode.IRNode n, Code c, bool issigned, bool is_tls, Reg ptr, Reg oldval, Reg newval, Reg dest)
{
/* we need to use cmpxchg8b here
* This assumes oldval is in eaxedx and newval is in ecxebx
* dest will be returned in eaxedx
*/
handle_move(r_eaxedx, oldval, r, n, c);
r.Add(inst(x86_push_r32, r_ebx, n));
r.Add(inst(x86_push_r32, r_ecx, n));
r.Add(inst(x86_mov_r32_rm32, r_ebx, newval.SubReg(0, 4, t), n));
r.Add(inst(x86_mov_r32_rm32, r_ecx, newval.SubReg(4, 4, t), n));
r.Add(inst(x86_lock_cmpxchg8b_m64, ptr, n, is_tls));
r.Add(inst(x86_pop_r32, r_ecx, n));
r.Add(inst(x86_pop_r32, r_ebx, n));
handle_move(dest, r_eaxedx, r, n, c);
return r;
}
internal static List<MCInst> handle_target_specific(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
switch(n.imm_l)
{
case x86_roundsd_xmm_xmmm64_imm8:
return handle_roundsd(t, nodes, start, count, c);
case x86_enter_cli:
return handle_enter_cli(t, nodes, start, count, c);
case x86_exit_cli:
return handle_exit_cli(t, nodes, start, count, c);
default:
throw new NotImplementedException("Invalid target specific operation");
}
}
internal static List<MCInst> handle_enter_cli(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var dest = n.stack_after.Peek(n.res_a).reg;
var r = new List<MCInst>();
r.Add(inst(x86_pushf, n));
if (dest is ContentsReg)
r.Add(inst(x86_pop_rm32, dest, n));
else
r.Add(inst(x86_pop_r32, dest, n));
r.Add(inst(x86_cli, n));
return r;
}
internal static List<MCInst> handle_exit_cli(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = n.stack_before.Peek(n.arg_a).reg;
var r = new List<MCInst>();
if (src is ContentsReg)
r.Add(inst(x86_push_rm32, src, n));
else
r.Add(inst(x86_push_r32, src, n));
if (t.psize == 4)
r.Add(inst(x86_popf, n));
else
r.Add(inst(x86_popfq, n));
return r;
}
internal static List<MCInst> handle_roundsd(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = n.stack_before[n.arg_a].reg;
var dest = n.stack_after[n.res_a].reg;
var act_dest = dest;
var r = new List<MCInst>();
if ((bool)t.Options["sse4_1"] == true)
{
if (dest is ContentsReg)
act_dest = r_xmm7;
r.Add(inst(x86_roundsd_xmm_xmmm64_imm8, act_dest, src, 0, n));
handle_move(dest, act_dest, r, n, c);
}
else
{
r.AddRange(handle_call(n, c,
c.special_meths.GetMethodSpec(c.special_meths.rint),
new ir.Param[] { src }, dest, "rint"));
}
return r;
}
internal static List<MCInst> handle_spinlockhint(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var r = new List<MCInst>();
r.Add(inst(x86_pause, n));
return r;
}
internal static List<MCInst> handle_ldarg(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ctret;
var src = c.la_locs[(int)n.imm_l];
var dest = n.stack_after.Peek(n.res_a).reg;
var r = new List<MCInst>();
if (n_ct == ir.Opcode.ct_int32 ||
n_ct == ir.Opcode.ct_float ||
n_ct == ir.Opcode.ct_vt ||
n_ct == ir.Opcode.ct_int64)
{
handle_move(dest, src, r, n, c, null,
n_ct == ir.Opcode.ct_int32 ? 4 : -1);
return r;
}
return null;
}
internal static List<MCInst> handle_stackcopy(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = n.stack_before.Peek(n.arg_a).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
handle_move(dest, src, r, n, c);
return r;
}
internal static List<MCInst> handle_localloc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var size = n.stack_before.Peek(n.arg_a).reg;
var addr = n.stack_after.Peek(n.res_a).reg;
var act_dest = addr;
if (act_dest is ContentsReg)
act_dest = r_edx;
if (n.parent.is_in_excpt_handler)
throw new Exception("localloc not allowed in exception handlers");
List<MCInst> r = new List<MCInst>();
handle_sub(t, r_esp, size, r_esp, r, n);
r.Add(inst(t.psize == 4 ? x86_and_rm32_imm8 :
x86_and_rm64_imm8, r_esp, t.psize == 4 ? 0xfc : 0xf8, n));
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, act_dest,
new ContentsReg { basereg = r_esp }, n));
handle_move(addr, act_dest, r, n, c);
return r;
}
internal static List<MCInst> handle_ldobja(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = n.stack_before.Peek(n.arg_a).reg;
var addr = n.stack_after.Peek(n.res_a).reg;
var act_addr = addr;
if (addr is ContentsReg)
addr = r_edx;
List<MCInst> r = new List<MCInst>();
if (!(src is ContentsReg))
throw new NotImplementedException();
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, addr, src, n));
handle_move(act_addr, addr, r, n, c);
return r;
}
internal static List<MCInst> handle_shift(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var srca = n.stack_before.Peek(n.arg_a).reg;
var srcb = n.stack_before.Peek(n.arg_b).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
if (n_ct == ir.Opcode.ct_int32 ||
(n_ct == ir.Opcode.ct_int64 && t.psize == 8))
{
handle_shift(srca, srcb, dest, r, n, c,
n_ct == ir.Opcode.ct_int32 ? 4 : 8);
return r;
}
else if (n_ct == ir.Opcode.ct_int64)
{
var sb = n.stack_before.Peek(n.arg_b);
if (sb.min_l == sb.max_l &&
sb.min_l == 1)
{
// handle as a shift through cf using two
// calls to handle_shift_i32 - NB need
// to change handle_shift_i32 to handle
// use_cf = true
throw new NotImplementedException();
}
else
{
// handle as a function call
string fname = null;
switch(n.opcode)
{
case ir.Opcode.oc_shl:
fname = "__ashldi3";
break;
case ir.Opcode.oc_shr:
fname = "__ashrdi3";
break;
case ir.Opcode.oc_shr_un:
fname = "__lshrdi3";
break;
}
return t.handle_external(t, nodes, start,
count, c, fname);
}
}
return null;
}
private static void handle_shift(Reg srca, Reg srcb,
Reg dest, List<MCInst> r, CilNode.IRNode n, Code c,
int size,
bool use_cf = false)
{
bool cl_in_use_before = false;
bool cl_in_use_after = false;
var orig_srca = srca;
if (!srca.Equals(dest) || srca.Equals(r_ecx))
{
// if either of the above is true, we need to move
// the source to eax
if (size == 4)
{
handle_move(r_eax, srca, r, n, c);
srca = r_eax;
}
else
{
handle_move(x86_64.x86_64_Assembler.r_rax, srca, r, n, c);
srca = x86_64.x86_64_Assembler.r_rax;
}
}
if (!srcb.Equals(r_ecx))
{
// need to assign the number to move to cl
// first determine if it is in use
ulong defined = 0;
foreach (var si in n.stack_before)
defined |= si.reg.mask;
if ((defined & r_ecx.mask) != 0)
cl_in_use_before = true;
if (orig_srca.Equals(r_ecx))
cl_in_use_before = false; // we have moved srca out of cl
defined = 0;
foreach (var si in n.stack_after)
defined |= si.reg.mask;
if ((defined & r_ecx.mask) != 0)
cl_in_use_after = true;
if (dest.Equals(r_ecx))
cl_in_use_after = false; // we don't need to save rcx here as we are assigning to it
}
bool cl_pushed = false;
if (cl_in_use_before && cl_in_use_after)
{
r.Add(inst(x86_push_r32, r_ecx, n));
cl_pushed = true;
}
if(!srcb.Equals(r_ecx))
{
handle_move(r_ecx, srcb, r, n, c);
srcb = r_ecx;
}
int oc = 0;
if (size == 4)
{
switch (n.opcode)
{
case ir.Opcode.oc_shl:
oc = x86_sal_rm32_cl;
break;
case ir.Opcode.oc_shr:
oc = x86_sar_rm32_cl;
break;
case ir.Opcode.oc_shr_un:
oc = x86_shr_rm32_cl;
break;
}
}
else
{
switch (n.opcode)
{
case ir.Opcode.oc_shl:
oc = x86_sal_rm64_cl;
break;
case ir.Opcode.oc_shr:
oc = x86_sar_rm64_cl;
break;
case ir.Opcode.oc_shr_un:
oc = x86_shr_rm64_cl;
break;
}
}
r.Add(inst(oc, srca, n));
if (!srca.Equals(dest))
handle_move(dest, srca, r, n, c);
if (cl_pushed)
r.Add(inst(x86_pop_r32, r_ecx, n));
}
internal static List<MCInst> handle_switch(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = n.stack_before.Peek(n.arg_a).reg;
List<MCInst> r = new List<MCInst>();
/* Implement as a series of brifs for now */
for(int i = 0; i < n.arg_list.Count; i++)
handle_brifi32(src, i, ir.Opcode.cc_eq, n.arg_list[i], r, n);
return r;
}
internal static List<MCInst> handle_getCharSeq(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var ldc_scale = nodes[start];
var conv = nodes[start + 2];
var ldc_offset = nodes[start + 4];
var ldind = nodes[start + 6];
var offset = ldc_offset.imm_l;
var scale = ldc_scale.imm_l;
// only handle valid scales
switch(scale)
{
case 1:
case 2:
case 4:
case 8:
break;
default:
return null;
}
// ensure the types are valid
if (conv.ctret != ir.Opcode.ct_int32)
return null;
// only handle valid data sizes
switch(ldind.vt_size)
{
case 1:
case 2:
case 4:
break;
default:
return null;
}
var obj = n.stack_before.Peek(1).reg;
var idx = n.stack_before.Peek(0).reg;
var dest = ldind.stack_after.Peek().reg;
// emit as mov[sz]x[bw]d dest, [obj + offset + idx * scale]
List<MCInst> r = new List<MCInst>();
if(obj is ContentsReg)
{
handle_move(r_edx, obj, r, n, c);
obj = r_edx;
}
if(idx is ContentsReg)
{
handle_move(r_eax, idx, r, n, c);
idx = r_eax;
}
var act_dest = dest;
if (dest is ContentsReg)
dest = r_edx;
switch(ldind.vt_size)
{
case 1:
if (ldind.imm_l == 1)
r.Add(inst(x86_movsxbd_r32_rm8sibscaledisp, dest, obj, idx, scale, offset, n));
else
r.Add(inst(x86_movzxbd_r32_rm8sibscaledisp, dest, obj, idx, scale, offset, n));
break;
case 2:
if (ldind.imm_l == 1)
r.Add(inst(x86_movsxwd_r32_rm16sibscaledisp, dest, obj, idx, scale, offset, n));
else
r.Add(inst(x86_movzxwd_r32_rm16sibscaledisp, dest, obj, idx, scale, offset, n));
break;
case 4:
r.Add(inst(x86_mov_r32_rm32sibscaledisp, dest, obj, idx, scale, offset, n));
break;
}
handle_move(act_dest, dest, r, n, c);
return r;
}
internal static List<MCInst> handle_portin(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var port = n.stack_before.Peek(n.arg_a).reg;
var v = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
handle_move(r_edx, port, r, n, c);
int oc = 0;
int oc_movzx = 0;
switch (n.vt_size)
{
case 1:
oc = x86_in_al_dx;
oc_movzx = x86_movzxbd;
break;
case 2:
oc = x86_in_ax_dx;
oc_movzx = x86_movzxwd;
break;
case 4:
oc = x86_in_eax_dx;
break;
default:
throw new NotImplementedException();
}
r.Add(inst(oc, n));
if (oc_movzx != 0)
{
if (v is ContentsReg)
{
r.Add(inst(oc_movzx, r_eax, r_eax, n));
handle_move(v, r_eax, r, n, c);
}
else
r.Add(inst(oc_movzx, v, r_eax, n));
}
else
handle_move(v, r_eax, r, n, c);
return r;
}
internal static List<MCInst> handle_portout(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var port = n.stack_before.Peek(n.arg_a).reg;
var v = n.stack_before.Peek(n.arg_b).reg;
List<MCInst> r = new List<MCInst>();
handle_move(r_eax, v, r, n, c);
handle_move(r_edx, port, r, n, c, r_edx);
int oc = 0;
switch(n.vt_size)
{
case 1:
oc = x86_out_dx_al;
break;
case 2:
oc = x86_out_dx_ax;
break;
case 4:
oc = x86_out_dx_eax;
break;
default:
throw new NotImplementedException();
}
r.Add(inst(oc, n));
return r;
}
}
}
namespace libtysila5.target.x86_64
{
public partial class x86_64_Assembler
{
internal static List<MCInst> handle_ldc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ctret;
if(n_ct == ir.Opcode.ct_int64)
{
var dest = n.stack_after.Peek(n.res_a).reg;
var s = n.imm_l;
var r = new List<MCInst>();
if(s <= Int32.MaxValue && s >= Int32.MinValue)
{
r.Add(inst(x86_mov_rm64_imm32, dest, s, n));
}
else
{
var act_dest = dest;
if (dest is ContentsReg)
dest = r_rax;
r.Add(inst(x86_mov_r64_imm64, dest, s, n));
handle_move(act_dest, dest, r, n, c);
}
return r;
}
return x86.x86_Assembler.handle_ldc(t, nodes, start, count, c);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.dwarf
{
/** <summary>A DIE defining a method</summary> */
public class DwarfMethodDIE : DwarfParentDIE
{
public metadata.MethodSpec ms { get; set; }
public Code cil { get; set; }
public binary_library.ISymbol sym { get; set; }
public int SourceFileId { get; set; }
public int StartLine { get; set; }
public int StartColumn { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
var ms = cil.ms;
int abbrev = 5;
if (ms.ReturnType != null)
abbrev += 1;
if (!ms.IsStatic)
{
abbrev += 2;
if (ms.IsVirtual)
abbrev += 2;
}
d.Add((byte)abbrev);
w(d, ms.Name, ds.smap);
var low_r = ds.bf.CreateRelocation();
low_r.Type = t.GetDataToDataReloc();
low_r.Offset = (ulong)d.Count;
low_r.References = ds.bf.FindSymbol(ms.MangleMethod());
low_r.DefinedIn = ds.info;
ds.bf.AddRelocation(low_r);
wp(d); // low_pc
wp(d, low_r.References.Size); // high_pc
// Update first/last sym if necessary
if (dcu.first_sym == null || low_r.References.Offset < dcu.first_sym.Offset)
dcu.first_sym = low_r.References;
if (dcu.last_sym == null || low_r.References.Offset > dcu.last_sym.Offset)
dcu.last_sym = low_r.References;
var mflags = ms.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
ms.mdrow, 2);
var access = mflags & 0x07;
if (access == 0x6)
d.Add(0x1); // public
else if (access >= 0x4)
d.Add(0x2); // protected
else
d.Add(0x3); // private
w(d, ms.MangleMethod(), ds.smap);
if(ms.ReturnType != null)
{
dcu.fmap[d.Count] = (ms.ReturnType.stype == metadata.TypeSpec.SpecialType.None && !ms.ReturnType.IsValueType) ?
dcu.GetTypeDie(ms.ReturnType.Pointer) :
dcu.GetTypeDie(ms.ReturnType);
// add return type
for (int i = 0; i < 4; i++)
d.Add(0);
}
int fparam_ref_loc = 0;
if(!ms.IsStatic)
{
// reference for first parameter
fparam_ref_loc = d.Count;
for (int i = 0; i < 4; i++)
d.Add(0);
}
if (ms.IsVirtual)
{
d.Add(0x1); // virtual
}
// Add parameters
int sig_idx = ms.mdrow == 0 ? ms.msig :
(int)ms.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef, ms.mdrow, 4);
var pc_nonthis = ms.m.GetMethodDefSigParamCount(sig_idx);
var rt_idx = ms.m.GetMethodDefSigRetTypeIndex(sig_idx);
ms.m.GetTypeSpec(ref rt_idx, ms.gtparams, ms.gmparams);
if (ms.m.GetMethodDefSigHasNonExplicitThis(ms.msig))
{
var fparam = new DwarfParamDIE();
fparam.dcu = dcu;
fparam.t = t;
fparam.IsThis = true;
fparam.ts = ms.type.Pointer;
Children.Add(fparam);
}
for(int i = 0; i < pc_nonthis; i++)
{
var fparam = new DwarfParamDIE();
fparam.dcu = dcu;
fparam.t = t;
fparam.IsThis = false;
fparam.ts = ms.m.GetTypeSpec(ref rt_idx, ms.gtparams, ms.gmparams);
if (fparam.ts.stype == metadata.TypeSpec.SpecialType.None &&
!fparam.ts.IsValueType)
fparam.ts = fparam.ts.Pointer;
Children.Add(fparam);
}
// Get param names
if (ms.mdrow != 0)
{
int param_start = (int)ms.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
ms.mdrow, 5);
int param_last_row = ms.m.GetRowCount(metadata.MetadataStream.tid_Param);
int next_param = int.MaxValue;
if(ms.mdrow < ms.m.GetRowCount(metadata.MetadataStream.tid_MethodDef))
{
next_param = (int)ms.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
ms.mdrow + 1, 5) - 1;
}
int param_end = param_last_row > next_param ? next_param : param_last_row;
for(int i = param_start; i <= param_end; i++)
{
var seq = ms.m.GetIntEntry(metadata.MetadataStream.tid_Param,
i, 1);
var name = ms.m.GetStringEntry(metadata.MetadataStream.tid_Param,
i, 2);
seq--;
if (ms.m.GetMethodDefSigHasNonExplicitThis(ms.msig))
seq++;
((DwarfParamDIE)Children[(int)seq]).name = name;
}
}
if (!ms.IsStatic)
{
// Patch the .this pointer to the first child
dcu.fmap[fparam_ref_loc] = Children[0];
}
// Param locations
if(cil != null && cil.la_locs != null && cil.la_locs.Length == Children.Count)
{
for (int i = 0; i < cil.la_locs.Length; i++)
((DwarfParamDIE)Children[i]).loc = cil.la_locs[i];
}
// Get param names
if (ms.mdrow != 0)
{
string[] pnames = new string[cil.lv_types.Length];
if(ms.m.pdb != null)
{
for(int i = 1; i < ms.m.pdb.table_rows[(int)metadata.MetadataStream.TableId.LocalScope]; i++)
{
var lv_mdrow = (int)ms.m.pdb.GetIntEntry((int)metadata.MetadataStream.TableId.LocalScope,
i, 0);
if(lv_mdrow == ms.mdrow)
{
var lv_start = (int)ms.m.pdb.GetIntEntry((int)metadata.MetadataStream.TableId.LocalScope,
i, 2);
int lv_last_row = ms.m.pdb.GetRowCount((int)metadata.MetadataStream.TableId.LocalVariable);
int next_lv = int.MaxValue;
if(i < ms.m.pdb.GetRowCount((int)metadata.MetadataStream.TableId.LocalScope))
{
next_lv = (int)ms.m.pdb.GetIntEntry((int)metadata.MetadataStream.TableId.LocalScope,
i + 1, 2) - 1;
}
int lv_end = lv_last_row > next_lv ? next_lv : lv_last_row;
for(int j = lv_start; j <= lv_end; j++)
{
var pindex = (int)ms.m.pdb.GetIntEntry((int)metadata.MetadataStream.TableId.LocalVariable,
j, 1);
var pname = ms.m.pdb.GetStringEntry((int)metadata.MetadataStream.TableId.LocalVariable,
j, 2);
pnames[pindex] = pname;
}
}
}
}
for (int i = 0; i < pnames.Length; i++)
{
var pname = pnames[i];
if (pname != null)
{
var ptype = cil.lv_types[i];
var ploc = cil.lv_locs[i];
var vparam = new DwarfVarDIE();
vparam.dcu = dcu;
vparam.t = t;
vparam.ts = ptype;
vparam.name = pname;
vparam.loc = ploc;
if (vparam.ts.stype == metadata.TypeSpec.SpecialType.None &&
!vparam.ts.IsValueType)
vparam.ts = vparam.ts.Pointer;
Children.Add(vparam);
}
}
}
base.WriteToOutput(ds, d, parent);
}
}
public class DwarfParamDIE : DwarfDIE
{
public string name { get; set; }
public metadata.TypeSpec ts { get; set; }
public bool IsThis { get; set; }
public target.Target.Reg loc { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
if (IsThis)
{
d.Add(19);
dcu.fmap[d.Count] = dcu.GetTypeDie(ts);
for (int i = 0; i < 4; i++)
d.Add(0);
// implicit artifical flag
}
else
{
w(d, 11);
w(d, name, ds.smap);
dcu.fmap[d.Count] = dcu.GetTypeDie(ts);
for (int i = 0; i < 4; i++)
d.Add(0);
}
// location as exprloc
var b = new List<byte>();
if (t.AddDwarfLocation(loc, b))
{
DwarfDIE.w(d, (uint)b.Count);
foreach (var c in b)
d.Add(c);
}
else
{
throw new NotImplementedException();
}
}
}
public class DwarfVarDIE : DwarfDIE
{
public string name { get; set; }
public metadata.TypeSpec ts { get; set; }
public target.Target.Reg loc { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
w(d, 21);
w(d, name, ds.smap);
dcu.fmap[d.Count] = dcu.GetTypeDie(ts);
for (int i = 0; i < 4; i++)
d.Add(0);
// location as exprloc
var b = new List<byte>();
if (t.AddDwarfLocation(loc, b))
{
DwarfDIE.w(d, (uint)b.Count);
foreach (var c in b)
d.Add(c);
}
else
{
throw new NotImplementedException();
}
}
}
public class DwarfMethodDefDIE : DwarfDIE
{
public DwarfMethodDIE decl { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
w(d, 22);
dcu.fmap[d.Count] = decl;
for (int i = 0; i < 4; i++)
d.Add(0);
var low_r = ds.bf.CreateRelocation();
low_r.Type = t.GetDataToDataReloc();
low_r.Offset = (ulong)d.Count;
low_r.References = ds.bf.FindSymbol(decl.ms.MangleMethod());
low_r.DefinedIn = ds.info;
ds.bf.AddRelocation(low_r);
wp(d); // low_pc
wp(d, low_r.References.Size); // high_pc
foreach (var child in decl.Children)
child.WriteToOutput(ds, d, this);
d.Add(0);
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.util;
using metadata;
namespace libtysila5
{
public partial class libtysila
{
public static bool AssembleMethod(metadata.MethodSpec ms,
binary_library.IBinaryFile bf, target.Target t,
TysilaState s,
StringBuilder debug_passes = null,
MetadataStream base_m = null,
Code code_override = null,
binary_library.ISection ts = null,
binary_library.ISection data_sect = null,
dwarf.DwarfCU dcu = null)
{
if(ms.ret_type_needs_boxing)
{
throw new Exception("AssembleMethod called for box rettype stub - use AssembleBoxedMethod instead");
}
if (ms.is_boxed)
{
throw new Exception("AssembleMethod called for boxed method - use AssembleBoxedMethod instead");
}
if (ts == null)
{
ts = bf.GetTextSection();
}
s.bf = bf;
s.text_section = ts;
binary_library.SymbolType sym_st = binary_library.SymbolType.Global;
var csite = ms.msig;
var mdef = ms.mdrow;
var m = ms.m;
/* Don't compile if not for this architecture */
if (!t.IsMethodValid(ms))
return false;
// Get method RVA, don't compile if no body
var rva = m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
mdef, 0);
// New signature table
s.sigt = new SignatureTable(ms.MangleMethod());
/* Is this an array method? */
if (rva == 0 &&
ms.type != null &&
ms.type.stype == TypeSpec.SpecialType.Array &&
code_override == null)
{
if (ms.name_override == "Get")
{
code_override = ir.ConvertToIR.CreateArrayGet(ms, t, s);
}
else if (ms.name_override == ".ctor")
{
// there are two constructors, choose the correct one
var pcount = ms.m.GetMethodDefSigParamCount(ms.msig);
if (pcount == ms.type.arr_rank)
code_override = ir.ConvertToIR.CreateArrayCtor1(ms, t, s);
else if (pcount == 2 * ms.type.arr_rank)
code_override = ir.ConvertToIR.CreateArrayCtor2(ms, t, s);
else
throw new NotSupportedException("Invalid number of parameters to " + ms.MangleMethod() + " for array of rank " + ms.type.arr_rank.ToString());
}
else if (ms.name_override == "Set")
code_override = ir.ConvertToIR.CreateArraySet(ms, t, s);
else if (ms.name_override == "Address")
code_override = ir.ConvertToIR.CreateArrayAddress(ms, t, s);
else
throw new NotImplementedException(ms.name_override);
sym_st = binary_library.SymbolType.Weak;
}
/* Is this a vector method? */
if (rva == 0 &&
ms.type != null &&
ms.type.stype == TypeSpec.SpecialType.SzArray &&
code_override == null)
{
if (ms.Name == "IndexOf")
code_override = ir.ConvertToIR.CreateVectorIndexOf(ms, t, s);
else if (ms.Name == "Insert")
code_override = ir.ConvertToIR.CreateVectorInsert(ms, t, s);
else if (ms.Name == "RemoveAt")
code_override = ir.ConvertToIR.CreateVectorRemoveAt(ms, t, s);
else if (ms.Name == "get_Item")
code_override = ir.ConvertToIR.CreateVectorget_Item(ms, t, s);
else if (ms.Name == "set_Item")
code_override = ir.ConvertToIR.CreateVectorset_Item(ms, t, s);
else if (ms.Name == "get_Count")
code_override = ir.ConvertToIR.CreateVectorget_Count(ms, t, s);
else if (ms.Name == "CopyTo")
code_override = ir.ConvertToIR.CreateVectorCopyTo(ms, t, s);
/*else if (ms.Name == "GetEnumerator")
code_override = ir.ConvertToIR.CreateVectorGetEnumerator(ms, t);*/
else if (ms.Name == "Add" ||
ms.Name == "Clear" ||
ms.Name == "Contains" ||
ms.Name == "Remove" ||
ms.Name == "get_IsReadOnly" ||
ms.Name == "get_IsSynchronized" ||
ms.Name == "get_SyncRoot" ||
ms.Name == "get_IsFixedSize" ||
ms.Name == "Clone" ||
ms.Name == "CompareTo" ||
ms.Name == "GetHashCode" ||
ms.Name == "Equals")
code_override = ir.ConvertToIR.CreateVectorUnimplemented(ms, t, s);
else
return false;
sym_st = binary_library.SymbolType.Weak;
}
if (rva == 0 && code_override == null)
return false;
// Get mangled name for defining a symbol
List<binary_library.ISymbol> meth_syms = new List<binary_library.ISymbol>();
var mangled_name = m.MangleMethod(ms);
var meth_sym = bf.CreateSymbol();
meth_sym.Name = mangled_name;
meth_sym.ObjectType = binary_library.SymbolObjectType.Function;
meth_sym.Offset = (ulong)ts.Data.Count;
meth_sym.Type = binary_library.SymbolType.Global;
ts.AddSymbol(meth_sym);
meth_syms.Add(meth_sym);
foreach (var alias in ms.MethodAliases)
{
var alias_sym = bf.CreateSymbol();
alias_sym.Name = alias;
alias_sym.ObjectType = binary_library.SymbolObjectType.Function;
alias_sym.Offset = (ulong)ts.Data.Count;
alias_sym.Type = binary_library.SymbolType.Global;
ts.AddSymbol(alias_sym);
meth_syms.Add(alias_sym);
}
if (ms.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs20WeakLinkageAttribute_7#2Ector_Rv_P1u1t"))
sym_st = binary_library.SymbolType.Weak;
if (base_m != null && ms.m != base_m)
sym_st = binary_library.SymbolType.Weak;
foreach (var sym in meth_syms)
sym.Type = sym_st;
// Get signature if not specified
if (csite == 0)
{
csite = (int)m.GetIntEntry(metadata.MetadataStream.tid_MethodDef,
mdef, 4);
}
Code cil;
if (code_override == null)
{
var meth = m.GetRVA(rva);
var flags = meth.ReadByte(0);
int max_stack = 0;
long code_size = 0;
long lvar_sig_tok = 0;
int boffset = 0;
List<metadata.ExceptionHeader> ehdrs = null;
bool has_exceptions = false;
if ((flags & 0x3) == 0x2)
{
// Tiny header
code_size = flags >> 2;
max_stack = 8;
boffset = 1;
}
else if ((flags & 0x3) == 0x3)
{
// Fat header
uint fat_flags = meth.ReadUShort(0) & 0xfffU;
int fat_hdr_len = (meth.ReadUShort(0) >> 12) * 4;
max_stack = meth.ReadUShort(2);
code_size = meth.ReadUInt(4);
lvar_sig_tok = meth.ReadUInt(8);
boffset = fat_hdr_len;
if ((flags & 0x8) == 0x8)
{
has_exceptions = true;
ehdrs = new List<metadata.ExceptionHeader>();
int ehdr_offset = boffset + (int)code_size;
ehdr_offset = util.util.align(ehdr_offset, 4);
while (true)
{
int kind = meth.ReadByte(ehdr_offset);
if ((kind & 0x1) != 0x1)
throw new Exception("Invalid exception header");
bool is_fat = false;
if ((kind & 0x40) == 0x40)
is_fat = true;
int data_size = meth.ReadInt(ehdr_offset);
data_size >>= 8;
if (is_fat)
data_size &= 0xffffff;
else
data_size &= 0xff;
int clause_count;
if (is_fat)
clause_count = (data_size - 4) / 24;
else
clause_count = (data_size - 4) / 12;
ehdr_offset += 4;
for (int i = 0; i < clause_count; i++)
{
var ehdr = ParseExceptionHeader(meth,
ref ehdr_offset, is_fat, ms);
ehdr.EhdrIdx = i;
ehdrs.Add(ehdr);
}
if ((kind & 0x80) != 0x80)
break;
}
}
}
else
throw new Exception("Invalid method header flags");
/* Parse CIL code */
cil = libtysila5.cil.CilParser.ParseCIL(meth,
ms, boffset, (int)code_size, lvar_sig_tok,
has_exceptions, ehdrs);
cil.s = s;
/* Allocate local vars and args */
t.AllocateLocalVarsArgs(cil);
/* Convert to IR */
cil.t = t;
ir.ConvertToIR.DoConversion(cil);
}
else
cil = code_override;
/* Allocate registers */
ir.AllocRegs.DoAllocation(cil);
/* Choose instructions */
target.ChooseInstructions.DoChoosing(cil);
t.AssemblePass(cil);
//((target.x86.x86_Assembler)cil.t).AssemblePass(cil);
foreach (var sym in meth_syms)
sym.Size = ts.Data.Count - (int)sym.Offset;
foreach (var extra_sym in cil.extra_labels)
{
var esym = bf.CreateSymbol();
esym.Name = extra_sym.Name;
esym.ObjectType = binary_library.SymbolObjectType.Function;
esym.Offset = (ulong)extra_sym.Offset;
esym.Type = sym_st;
ts.AddSymbol(esym);
}
/* Dump debug */
DumpDebug(debug_passes, meth_syms, cil);
/* Signature table */
if (data_sect == null)
data_sect = bf.GetDataSection();
s.sigt.WriteToOutput(bf, ms.m, t, data_sect);
/* DWARF output */
if (dcu != null)
{
var ddie = dcu.GetMethodDie(ms);
ddie.sym = meth_syms[0];
ddie.cil = cil;
var ddts = dcu.GetTypeDie(ms.type) as dwarf.DwarfParentDIE;
ddts.Children.Add(ddie);
if(ms.ReturnType != null)
{
dcu.GetTypeDie(ms.ReturnType);
if (ms.ReturnType.stype == TypeSpec.SpecialType.None && !ms.ReturnType.IsValueType)
dcu.GetTypeDie(ms.ReturnType.Pointer);
}
foreach(var la in cil.la_types)
{
dcu.GetTypeDie(la);
if (la.stype == TypeSpec.SpecialType.None && !la.IsValueType)
dcu.GetTypeDie(la.Pointer);
}
foreach(var lv in cil.lv_types)
{
dcu.GetTypeDie(lv);
if (lv.stype == TypeSpec.SpecialType.None && !lv.IsValueType)
dcu.GetTypeDie(lv.Pointer);
}
if(!ms.IsStatic)
{
dcu.GetTypeDie(ms.type.Pointer);
}
// do we have source lines?
if(ms.m.pdb != null && ms.mdrow > 0)
{
var sps = ms.m.pdb.DebugGetSeqPtForMDRow(ms.mdrow);
if (sps != null && cil.cil != null && cil.cil.Count > 0)
{
/* Start building a Line Number Program
*
* We follow the example in DWARF4 D.5 (p251), with a few changes
*
* header - defined per CU
* - add this/these source files to it if necessary
*
* DW_LNE_set_address - psize 0s, reloc to mangled name
* DW_LNS_advance_pc - mc_offset of first cil instruction
* DW_LNS_set_prologue_end
* DW_LNS_set_file - source file
* SPECIAL(0,0) - add first opcode
* SPECIAL(x,y) - add rest of opcodes
* DW_LNE_end_sequence
*
*/
string cur_file = null;
int cur_line = 1;
int cur_mc = 0;
int cur_col = 0;
var lnp = dcu.lnp;
// DW_LNE_set_address
lnp.AddRange(new byte[] { 0x00, (byte)(t.psize + 1), 0x02 });
dcu.lnp_relocs.Add(lnp.Count, meth_syms[0]);
for (int i = 0; i < t.psize; i++)
lnp.Add(0);
// DW_LNS_advance_pc
lnp.Add(0x02);
dwarf.DwarfDIE.w(lnp, (uint)cil.cil[0].mc_offset);
cur_mc = cil.cil[0].mc_offset;
// DW_LNS_set_prologue_end
lnp.Add(0x0a);
foreach(var cn in cil.cil)
{
var mc_advance = cn.mc_offset - cur_mc;
// get current line number
MetadataStream.SeqPt csp = null;
foreach(var sp in sps)
{
if(sp.IlOffset == cn.il_offset &
!sp.IsHidden)
{
csp = sp;
break;
}
}
if(csp != null)
{
var line_advance = csp.StartLine - cur_line;
if (ddie.StartLine == 0)
ddie.StartLine = csp.StartLine;
if (ddie.StartColumn == 0)
ddie.StartColumn = csp.StartCol;
if(csp.DocName != cur_file)
{
// DW_LNS_set_file
lnp.Add(0x04);
uint file_no;
if(!dcu.lnp_files.TryGetValue(csp.DocName, out file_no))
{
file_no = (uint)(dcu.lnp_files.Count + 1);
dcu.lnp_files[csp.DocName] = file_no;
dcu.lnp_fnames.Add(csp.DocName);
}
if (ddie.SourceFileId == 0)
ddie.SourceFileId = (int)file_no;
dwarf.DwarfDIE.w(lnp, file_no);
cur_file = csp.DocName;
}
if(csp.StartCol != cur_col)
{
// DW_LNS_set_column
lnp.Add(0x05);
dwarf.DwarfDIE.w(lnp, (uint)csp.StartCol);
cur_col = csp.StartCol;
}
/* SPECIAL if possible
* Use example on DWARF4 p132:
* opcode_base = 13, line_base = -3, line_range = 12
*
* Gives a line advance range of [-3,8] and op_advance [0,19]
*/
if((line_advance >= dcu.line_base && line_advance < (dcu.line_base + dcu.line_range)) &&
(mc_advance >= 0 && mc_advance < dcu.mc_advance_max))
{
var spec_opcode = (line_advance - dcu.line_base) +
(dcu.line_range * mc_advance) + dcu.opcode_base;
lnp.Add((byte)spec_opcode);
}
else
{
// DW_LNS_advance_pc
lnp.Add(0x02);
dwarf.DwarfDIE.w(lnp, (uint)mc_advance);
// DW_LNS_advance_line
lnp.Add(0x03);
dwarf.DwarfDIE.w(lnp, line_advance);
// SPECIAL(0,0)
var spec_opcode = (0 - dcu.line_base) + dcu.opcode_base;
lnp.Add((byte)spec_opcode);
}
cur_line += line_advance;
cur_mc += mc_advance;
}
}
// Advance to end
var to_advance = (int)meth_syms[0].Size - cur_mc;
lnp.Add(0x02);
dwarf.DwarfDIE.w(lnp, to_advance);
// DW_LNE_end_sequence
lnp.Add(0x00);
lnp.Add(0x01);
lnp.Add(0x01);
}
}
}
return true;
}
private static void DumpDebug(StringBuilder debug_passes,
List<binary_library.ISymbol> meth_syms,
Code cil)
{
if (debug_passes != null)
{
libtysila5.cil.CilNode cur_cil_node = null;
libtysila5.cil.CilNode.IRNode cur_ir_node = null;
foreach (var sym in meth_syms)
debug_passes.AppendLine(sym.Name + ":");
foreach (var mc in cil.mc)
{
if (mc.parent != cur_ir_node)
{
cur_ir_node = mc.parent;
if (cur_ir_node.parent != cur_cil_node)
{
cur_cil_node = cur_ir_node.parent;
debug_passes.Append(" IL");
debug_passes.Append(cur_cil_node.il_offset.ToString("X4"));
debug_passes.Append(": ");
debug_passes.AppendLine(cur_cil_node.ToString());
}
debug_passes.Append(" ");
debug_passes.AppendLine(cur_ir_node.ToString());
}
debug_passes.Append(" ");
debug_passes.Append(mc.offset.ToString("X8"));
debug_passes.Append(": ");
debug_passes.AppendLine(cil.t.MCInstToDebug(mc));
if (cil.s != null && cil.s.text_section != null && cil.s.text_section.Data != null)
{
debug_passes.Append(" ");
int idx = 0;
for (int i = mc.addr; i < mc.end_addr; i++, idx++)
{
if (idx > 0)
debug_passes.Append(", ");
debug_passes.Append(cil.s.text_section.Data[i].ToString("X2"));
}
debug_passes.AppendLine();
}
}
debug_passes.AppendLine();
debug_passes.AppendLine();
}
}
private static metadata.ExceptionHeader ParseExceptionHeader(metadata.DataInterface di,
ref int ehdr_offset, bool is_fat,
metadata.MethodSpec ms)
{
metadata.ExceptionHeader ehdr = new metadata.ExceptionHeader();
int flags = 0;
if (is_fat)
{
flags = di.ReadInt(ehdr_offset);
ehdr.TryILOffset = di.ReadInt(ehdr_offset + 4);
ehdr.TryLength = di.ReadInt(ehdr_offset + 8);
ehdr.HandlerILOffset = di.ReadInt(ehdr_offset + 12);
ehdr.HandlerLength = di.ReadInt(ehdr_offset + 16);
}
else
{
flags = di.ReadShort(ehdr_offset);
ehdr.TryILOffset = di.ReadShort(ehdr_offset + 2);
ehdr.TryLength = di.ReadByte(ehdr_offset + 4);
ehdr.HandlerILOffset = di.ReadShort(ehdr_offset + 5);
ehdr.HandlerLength = di.ReadByte(ehdr_offset + 7);
}
switch (flags)
{
case 0:
ehdr.EType = metadata.ExceptionHeader.ExceptionHeaderType.Catch;
uint mtoken;
if (is_fat)
mtoken = di.ReadUInt(ehdr_offset + 20);
else
mtoken = di.ReadUInt(ehdr_offset + 8);
int table_id, row;
ms.m.InterpretToken(mtoken, out table_id, out row);
ehdr.ClassToken = ms.m.GetTypeSpec(table_id, row,
ms.gtparams, ms.gmparams);
break;
case 1:
ehdr.EType = metadata.ExceptionHeader.ExceptionHeaderType.Filter;
if (is_fat)
ehdr.FilterOffset = di.ReadInt(ehdr_offset + 20);
else
ehdr.FilterOffset = di.ReadInt(ehdr_offset + 8);
break;
case 2:
ehdr.EType = metadata.ExceptionHeader.ExceptionHeaderType.Finally;
break;
case 4:
ehdr.EType = metadata.ExceptionHeader.ExceptionHeaderType.Fault;
break;
default:
throw new Exception("Invalid exception type: " + flags.ToString());
}
if (is_fat)
ehdr_offset += 24;
else
ehdr_offset += 12;
return ehdr;
}
public static bool AssembleBoxedMethod(metadata.MethodSpec ms,
binary_library.IBinaryFile bf, target.Target t,
TysilaState s,
StringBuilder debug_passes = null,
binary_library.ISection ts = null)
{
if(ts == null)
ts = bf.GetTextSection();
s.bf = bf;
s.text_section = ts;
// Symbol
List<binary_library.ISymbol> meth_syms = new List<binary_library.ISymbol>();
var mangled_name = ms.MangleMethod();
var meth_sym = bf.CreateSymbol();
meth_sym.Name = mangled_name;
meth_sym.ObjectType = binary_library.SymbolObjectType.Function;
meth_sym.Offset = (ulong)ts.Data.Count;
meth_sym.Type = binary_library.SymbolType.Weak;
ts.AddSymbol(meth_sym);
meth_syms.Add(meth_sym);
Code c = ms.ret_type_needs_boxing ? t.AssembleBoxRetTypeMethod(ms, s) : t.AssembleBoxedMethod(ms, s);
c.t = t;
t.AssemblePass(c);
foreach (var sym in meth_syms)
sym.Size = ts.Data.Count - (int)sym.Offset;
DumpDebug(debug_passes, meth_syms, c);
return true;
}
}
}
<file_sep>/* Copyright (C) 2015 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs.x86_64
{
[ArchDependent("x86_64")]
class x86_64_invoke
{
[MethodReferenceAlias("__x86_64_invoke")]
[MethodImpl(MethodImplOptions.InternalCall)]
static unsafe extern void* asm_invoke(void *maddr, int p_length,
void* parameters, void* plocs);
[MethodAlias("__invoke")]
[AlwaysCompile]
[Bits64Only]
static unsafe void* InternalInvoke(void* maddr, int pcnt, void **parameters, void **types, void *ret_vtbl, uint flags)
{
/* Modify the types array to contain the call locations of each parameter
*
* 0 - INTEGER (pass as-is)
* 1 - INTEGER (unbox in asm)
* 2 - SSE (unbox in asm)
* 3 - MEMORY (upper 24 bits give length of object)
* 4 - INTEGER (unbox low 32 bits in asm)
* 5 - INTEGER (unbox to byref in asm)
*/
for(int i = 0; i < pcnt; i++)
{
// handle this pointer
if(i == 0 && ((flags & TysosMethod.invoke_flag_instance) != 0))
{
if ((flags & TysosMethod.invoke_flag_vt) != 0)
{
// we need to unbox the this pointer to a managed pointer
types[i] = (void*)5;
}
else
{
types[i] = (void*)0;
}
}
else
{
// the type we need is encoded in the vtable
var vtbl = types[i];
var cur_class = *((byte*)vtbl + 0x1 + ClassOperations.GetVtblTargetFieldsOffset());
types[i] = (void*)cur_class;
}
}
var ret = asm_invoke(maddr, pcnt, parameters, types);
// See if we have to box the return type
if (ret_vtbl != null && ((flags & TysosMethod.invoke_flag_vt_ret) != 0))
{
// Get the size of the return type
var tsize = *(int*)((byte*)ret_vtbl + ClassOperations.GetVtblTypeSizeOffset())
- ClassOperations.GetBoxedTypeDataOffset();
/* TODO: handle VTypes that don't fit in a register */
if(tsize > 8)
throw new NotImplementedException("InternalInvoke: return type not supported (size " +
tsize.ToString() + ")");
// Build a new boxed version of the type
var obj = (void**)MemoryOperations.GcMalloc(tsize + ClassOperations.GetBoxedTypeDataOffset());
*obj = ret_vtbl;
*(int*)((byte*)obj + ClassOperations.GetMutexLockOffset()) = 0;
System.Diagnostics.Debugger.Log(0, "libsupcs", "x86_64_invoke: returning boxed type of size " + tsize.ToString());
if (tsize > 4)
*(long*)((byte*)obj + ClassOperations.GetBoxedTypeDataOffset()) = (long)ret;
else
*(int*)((byte*)obj + ClassOperations.GetBoxedTypeDataOffset()) = (int)((long)ret & 0xffffffff);
return obj;
}
else if (ret_vtbl == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "x86_64_invoke: returning void");
return ret;
}
else
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "x86_64_invoke: returning object");
return ret;
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern int ReinterpretAsInt(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern uint ReinterpretAsUInt(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern long ReinterpretAsLong(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern ulong ReinterpretAsULong(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern short ReinterpretAsShort(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern ushort ReinterpretAsUShort(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern byte ReinterpretAsByte(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern sbyte ReinterpretAsSByte(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern char ReinterpretAsChar(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern IntPtr ReinterpretAsIntPtr(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern UIntPtr ReinterpretAsUIntPtr(object addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern bool ReinterpretAsBoolean(object addr);
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Text;
using libtysila5.cil;
using metadata;
using libtysila5.util;
namespace libtysila5.ir
{
public class StackItem
{
public TypeSpec ts;
public int _ct = 0;
public MethodSpec ms;
public Spec.FullySpecSignature fss;
public int ct { get { if (_ct == Opcode.ct_tls_int32 || _ct == Opcode.ct_tls_int64 || _ct == Opcode.ct_tls_intptr || ts == null) return _ct; return Opcode.GetCTFromType(ts); } }
public long min_l = long.MinValue;
public long max_l = long.MaxValue;
public ulong min_ul = ulong.MinValue;
public ulong max_ul = ulong.MaxValue;
public string str_val = null;
public target.Target.Reg reg;
public bool has_address_taken = false;
public override string ToString()
{
if (ms != null)
return "fnptr: " + ms.MangleMethod();
StringBuilder sb = new StringBuilder();
if (ts != null)
{
sb.Append(ts.ToString());
sb.Append(" ");
}
sb.Append("(");
sb.Append(ir.Opcode.ct_names[ct]);
sb.Append(")");
return sb.ToString();
}
internal StackItem Clone()
{
return new StackItem
{
max_l = max_l,
max_ul = max_ul,
min_l = min_l,
min_ul = min_ul,
reg = reg,
str_val = str_val,
ts = ts,
_ct = _ct,
ms = ms,
has_address_taken = has_address_taken
};
}
}
public partial class ConvertToIR
{
static ConvertToIR()
{
init_intcalls();
}
public static void DoConversion(Code c)
{
foreach (var n in c.starts)
{
if (n.il_offset == 0)
n.is_meth_start = true;
else if(n.is_filter_start == false)
n.is_eh_start = true;
}
int unconverted = 0;
do
{
unconverted = 0;
foreach(var n in c.cil)
{
if (n.is_meth_start)
DoConversion(n, c, new Stack<StackItem>(c.lv_types.Length));
else if(n.is_filter_start)
{
var stack = new Stack<StackItem>(c.lv_types.Length);
stack.Push(new StackItem { ts = c.ms.m.SystemObject });
DoConversion(n, c, stack);
}
else if (n.is_eh_start)
{
if (n.is_filter_start)
System.Diagnostics.Debugger.Break();
var stack = new Stack<StackItem>(c.lv_types.Length);
if (n.handler_starts.Count != 0)
{
if (n.handler_starts.Count > 1)
throw new Exception("too many catch handlers");
var ts = n.handler_starts[0].ClassToken;
if (ts != null)
{
stack.Push(new StackItem
{
ts = ts
});
}
}
DoConversion(n, c, stack);
}
else if (n.try_starts.Count > 0)
DoConversion(n, c, new Stack<StackItem>(c.lv_types.Length));
else
{
bool any_prev_visited = false;
Stack<StackItem> prev_stack = null;
foreach (var prev in n.prev)
{
if(prev.opcode.opcode1 == cil.Opcode.SingleOpcodes.leave ||
prev.opcode.opcode1 == cil.Opcode.SingleOpcodes.leave_s)
{
// leave empties stack
any_prev_visited = true;
prev_stack = new Stack<StackItem>(c.lv_types.Length);
break;
}
else if (prev.visited)
{
any_prev_visited = true;
prev_stack = prev.stack_after;
break;
}
}
if (any_prev_visited)
{
if (prev_stack == null)
throw new Exception("no stack defined");
DoConversion(n, c, prev_stack);
}
else
unconverted++;
}
}
} while (unconverted != 0);
// Determine if this method is a static constructor
if(MetadataStream.CompareSignature(c.ms.m, c.ms.msig, c.ms.gtparams, c.ms.gmparams,
c.special_meths, c.special_meths.static_Rv_P0, null, null))
{
var meth_name = c.ms.name_override;
if(meth_name == null)
{
meth_name = c.ms.m.GetStringEntry(MetadataStream.tid_MethodDef,
c.ms.mdrow, 3);
}
if(meth_name != null && meth_name == ".cctor")
c.is_cctor = true;
}
// Insert special code
if (c.static_types_referenced.Count > 0 || c.is_cctor)
{
foreach (var n in c.cil)
{
if (n.is_meth_start)
{
// If this is not a static constructor, call others we may have referenced
if (c.is_cctor == false)
{
foreach (var static_type in c.static_types_referenced)
{
var cctor = static_type.m.GetMethodSpec(static_type, ".cctor", c.special_meths.static_Rv_P0, c.special_meths, false);
if (cctor != null)
{
n.irnodes.Insert(1,
new CilNode.IRNode { parent = n, opcode = Opcode.oc_call, imm_ms = cctor, stack_before = n.irnodes[0].stack_after, stack_after = n.irnodes[0].stack_after, ignore_for_mcoffset = true });
c.s.r.MethodRequestor.Request(cctor);
}
}
}
else
{
// This is a static constructor, so we need to put some special code to
// ensure it is only run once
n.irnodes.Insert(1,
new CilNode.IRNode { parent = n, opcode = Opcode.oc_cctor_runonce, imm_ts = c.ms.type, stack_before = n.irnodes[0].stack_after, stack_after = n.irnodes[0].stack_after, ignore_for_mcoffset = true });
}
}
}
}
c.ir = new System.Collections.Generic.List<CilNode.IRNode>();
foreach (var n in c.cil)
c.ir.AddRange(n.irnodes);
}
private static void DoConversion(CilNode n, Code c, Stack<StackItem> stack_before)
{
// TODO ensure stack integrity
if (n.visited)
return;
Stack<StackItem> stack_after = null;
StackItem si = null;
long imm = 0;
TypeSpec ts = null;
if (n.is_meth_start)
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
foreach(var ehdr in n.try_starts)
ehdr_trycatch_start(n, c, stack_before, ehdr.EhdrIdx);
foreach (var ehdr in n.handler_starts)
{
ehdr_trycatch_start(n, c, stack_before, ehdr.EhdrIdx, true, n.is_filter_start);
}
switch (n.opcode.opcode1)
{
case cil.Opcode.SingleOpcodes.nop:
stack_after = stack_before;
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_nop, stack_after = stack_after, stack_before = stack_before });
break;
case cil.Opcode.SingleOpcodes.ldc_i4_0:
case cil.Opcode.SingleOpcodes.ldc_i4_1:
case cil.Opcode.SingleOpcodes.ldc_i4_2:
case cil.Opcode.SingleOpcodes.ldc_i4_3:
case cil.Opcode.SingleOpcodes.ldc_i4_4:
case cil.Opcode.SingleOpcodes.ldc_i4_5:
case cil.Opcode.SingleOpcodes.ldc_i4_6:
case cil.Opcode.SingleOpcodes.ldc_i4_7:
case cil.Opcode.SingleOpcodes.ldc_i4_8:
case cil.Opcode.SingleOpcodes.ldc_i4_m1:
case cil.Opcode.SingleOpcodes.ldc_i4_s:
case cil.Opcode.SingleOpcodes.ldc_i4:
stack_after = new Stack<StackItem>(stack_before);
si = new StackItem();
si.ts = c.ms.m.GetSimpleTypeSpec(0x08);
stack_after.Add(si);
switch(n.opcode.opcode1)
{
case cil.Opcode.SingleOpcodes.ldc_i4:
case cil.Opcode.SingleOpcodes.ldc_i4_s:
imm = n.inline_long;
break;
case cil.Opcode.SingleOpcodes.ldc_i4_m1:
imm = -1;
break;
default:
imm = n.opcode.opcode1 - cil.Opcode.SingleOpcodes.ldc_i4_0;
break;
}
n.irnodes.Add(new CilNode.IRNode { parent = n, imm_l = imm, imm_val = n.inline_val, opcode = Opcode.oc_ldc, ctret = Opcode.ct_int32, vt_size = 4, stack_after = stack_after, stack_before = stack_before });
break;
case cil.Opcode.SingleOpcodes.ldc_i8:
stack_after = ldc(n, c, stack_before, n.inline_long, n.inline_val, 0x0a);
break;
case cil.Opcode.SingleOpcodes.ldc_r4:
stack_after = ldc(n, c, stack_before, n.inline_long, n.inline_val, 0x0c);
break;
case cil.Opcode.SingleOpcodes.ldc_r8:
stack_after = ldc(n, c, stack_before, n.inline_long, n.inline_val, 0x0d);
break;
case cil.Opcode.SingleOpcodes.ldnull:
stack_after = new Stack<StackItem>(stack_before);
si = new StackItem();
si.ts = c.ms.m.GetSimpleTypeSpec(0x1c);
stack_after.Add(si);
imm = 0;
n.irnodes.Add(new CilNode.IRNode { parent = n, imm_l = imm, opcode = Opcode.oc_ldc, ctret = Opcode.ct_object, vt_size = c.t.GetPointerSize(), stack_after = stack_after, stack_before = stack_before });
break;
case cil.Opcode.SingleOpcodes.stloc_0:
stack_after = stloc(n, c, stack_before, 0);
break;
case cil.Opcode.SingleOpcodes.stloc_1:
stack_after = stloc(n, c, stack_before, 1);
break;
case cil.Opcode.SingleOpcodes.stloc_2:
stack_after = stloc(n, c, stack_before, 2);
break;
case cil.Opcode.SingleOpcodes.stloc_3:
stack_after = stloc(n, c, stack_before, 3);
break;
case cil.Opcode.SingleOpcodes.stloc_s:
stack_after = stloc(n, c, stack_before, (int)n.inline_uint);
break;
case cil.Opcode.SingleOpcodes.ldloc_0:
stack_after = ldloc(n, c, stack_before, 0);
break;
case cil.Opcode.SingleOpcodes.ldloc_1:
stack_after = ldloc(n, c, stack_before, 1);
break;
case cil.Opcode.SingleOpcodes.ldloc_2:
stack_after = ldloc(n, c, stack_before, 2);
break;
case cil.Opcode.SingleOpcodes.ldloc_3:
stack_after = ldloc(n, c, stack_before, 3);
break;
case cil.Opcode.SingleOpcodes.ldloc_s:
stack_after = ldloc(n, c, stack_before, (int)n.inline_uint);
break;
case cil.Opcode.SingleOpcodes.ldarg_s:
stack_after = ldarg(n, c, stack_before, n.inline_int);
break;
case cil.Opcode.SingleOpcodes.ldarg_0:
stack_after = ldarg(n, c, stack_before, 0);
break;
case cil.Opcode.SingleOpcodes.ldarg_1:
stack_after = ldarg(n, c, stack_before, 1);
break;
case cil.Opcode.SingleOpcodes.ldarg_2:
stack_after = ldarg(n, c, stack_before, 2);
break;
case cil.Opcode.SingleOpcodes.ldarg_3:
stack_after = ldarg(n, c, stack_before, 3);
break;
case cil.Opcode.SingleOpcodes.ldarga_s:
stack_after = ldarga(n, c, stack_before, n.inline_int);
break;
case cil.Opcode.SingleOpcodes.starg_s:
stack_after = starg(n, c, stack_before, n.inline_int);
break;
case cil.Opcode.SingleOpcodes.ldloca_s:
stack_after = ldloca(n, c, stack_before, n.inline_int);
break;
case cil.Opcode.SingleOpcodes.ldsfld:
stack_after = ldflda(n, c, stack_before, true, out ts);
stack_after = ldind(n, c, stack_after, ts);
break;
case cil.Opcode.SingleOpcodes.ldfld:
stack_after = ldvtaddr(n, c, stack_before);
stack_after = ldflda(n, c, stack_after, false, out ts);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ts);
break;
case cil.Opcode.SingleOpcodes.ldsflda:
stack_after = ldflda(n, c, stack_before, true, out ts);
break;
case cil.Opcode.SingleOpcodes.ldflda:
stack_after = ldvtaddr(n, c, stack_before);
stack_after = ldflda(n, c, stack_after, false, out ts);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after.Peek().ts = ts.ManagedPointer;
break;
case cil.Opcode.SingleOpcodes.stfld:
//stack_after = copy_to_front(n, c, stack_before, 1);
stack_after = ldvtaddr(n, c, stack_before, 1, 1);
stack_after = ldflda(n, c, stack_after, false, out ts, 1);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr, 2);
stack_after = stind(n, c, stack_after, c.t.GetSize(ts), 1, 0);
stack_after.Pop();
break;
case cil.Opcode.SingleOpcodes.stsfld:
stack_after = ldflda(n, c, stack_before, true, out ts);
stack_after = stind(n, c, stack_after, c.t.GetSize(ts), 1, 0);
break;
case cil.Opcode.SingleOpcodes.ldelem:
stack_after = ldelem(n, c, stack_before, n.GetTokenAsTypeSpec(c));
break;
case cil.Opcode.SingleOpcodes.ldelem_i:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x18));
break;
case cil.Opcode.SingleOpcodes.ldelem_i1:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x04));
break;
case cil.Opcode.SingleOpcodes.ldelem_i2:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x06));
break;
case cil.Opcode.SingleOpcodes.ldelem_i4:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x08));
break;
case cil.Opcode.SingleOpcodes.ldelem_i8:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0a));
break;
case cil.Opcode.SingleOpcodes.ldelem_r4:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0c));
break;
case cil.Opcode.SingleOpcodes.ldelem_r8:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0d));
break;
case cil.Opcode.SingleOpcodes.ldelem_ref:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x1c));
break;
case cil.Opcode.SingleOpcodes.ldelem_u1:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x05));
break;
case cil.Opcode.SingleOpcodes.ldelem_u2:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x07));
break;
case cil.Opcode.SingleOpcodes.ldelem_u4:
stack_after = ldelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x09));
break;
case cil.Opcode.SingleOpcodes.ldelema:
stack_after = ldelema(n, c, stack_before, n.GetTokenAsTypeSpec(c));
break;
case cil.Opcode.SingleOpcodes.stelem:
stack_after = stelem(n, c, stack_before, n.GetTokenAsTypeSpec(c));
break;
case cil.Opcode.SingleOpcodes.stelem_i:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x18));
break;
case cil.Opcode.SingleOpcodes.stelem_i1:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x04));
break;
case cil.Opcode.SingleOpcodes.stelem_i2:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x06));
break;
case cil.Opcode.SingleOpcodes.stelem_i4:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x08));
break;
case cil.Opcode.SingleOpcodes.stelem_i8:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0a));
break;
case cil.Opcode.SingleOpcodes.stelem_r4:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0c));
break;
case cil.Opcode.SingleOpcodes.stelem_r8:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0d));
break;
case cil.Opcode.SingleOpcodes.stelem_ref:
stack_after = stelem(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x1c));
break;
case cil.Opcode.SingleOpcodes.br:
case cil.Opcode.SingleOpcodes.br_s:
stack_after = br(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.brtrue:
case cil.Opcode.SingleOpcodes.brtrue_s:
case cil.Opcode.SingleOpcodes.brfalse:
case cil.Opcode.SingleOpcodes.brfalse_s:
// first push zero
stack_after = new Stack<StackItem>(stack_before);
var brtf_ct = get_brtf_type(n.opcode, stack_before.Peek().ct);
stack_after.Push(new StackItem { ts = ir.Opcode.GetTypeFromCT(brtf_ct, c.ms.m), min_l = 0, max_l = 0, min_ul = 0, max_ul = 0 });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldc, ctret = brtf_ct, imm_l = 0, imm_ul = 0, imm_val = new byte[8], stack_before = stack_before, stack_after = stack_after });
switch(n.opcode.opcode1)
{
case cil.Opcode.SingleOpcodes.brtrue:
case cil.Opcode.SingleOpcodes.brtrue_s:
stack_after = brif(n, c, stack_after, Opcode.cc_ne);
break;
case cil.Opcode.SingleOpcodes.brfalse:
case cil.Opcode.SingleOpcodes.brfalse_s:
stack_after = brif(n, c, stack_after, Opcode.cc_eq);
break;
}
break;
case cil.Opcode.SingleOpcodes.beq:
case cil.Opcode.SingleOpcodes.beq_s:
stack_after = brif(n, c, stack_before, Opcode.cc_eq);
break;
case cil.Opcode.SingleOpcodes.bge:
case cil.Opcode.SingleOpcodes.bge_s:
stack_after = brif(n, c, stack_before, Opcode.cc_ge);
break;
case cil.Opcode.SingleOpcodes.bge_un:
case cil.Opcode.SingleOpcodes.bge_un_s:
stack_after = brif(n, c, stack_before, Opcode.cc_ae);
break;
case cil.Opcode.SingleOpcodes.bgt:
case cil.Opcode.SingleOpcodes.bgt_s:
stack_after = brif(n, c, stack_before, Opcode.cc_gt);
break;
case cil.Opcode.SingleOpcodes.bgt_un:
case cil.Opcode.SingleOpcodes.bgt_un_s:
stack_after = brif(n, c, stack_before, Opcode.cc_a);
break;
case cil.Opcode.SingleOpcodes.ble:
case cil.Opcode.SingleOpcodes.ble_s:
stack_after = brif(n, c, stack_before, Opcode.cc_le);
break;
case cil.Opcode.SingleOpcodes.ble_un:
case cil.Opcode.SingleOpcodes.ble_un_s:
stack_after = brif(n, c, stack_before, Opcode.cc_be);
break;
case cil.Opcode.SingleOpcodes.blt:
case cil.Opcode.SingleOpcodes.blt_s:
stack_after = brif(n, c, stack_before, Opcode.cc_lt);
break;
case cil.Opcode.SingleOpcodes.blt_un:
case cil.Opcode.SingleOpcodes.blt_un_s:
stack_after = brif(n, c, stack_before, Opcode.cc_b);
break;
case cil.Opcode.SingleOpcodes.bne_un:
case cil.Opcode.SingleOpcodes.bne_un_s:
stack_after = brif(n, c, stack_before, Opcode.cc_ne);
break;
case cil.Opcode.SingleOpcodes.ldstr:
stack_after = ldstr(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.call:
stack_after = call(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.calli:
stack_after = call(n, c, stack_before, true);
break;
case cil.Opcode.SingleOpcodes.callvirt:
{
var call_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
var call_ms_flags = call_ms.m.GetIntEntry(MetadataStream.tid_MethodDef,
call_ms.mdrow, 2);
uint sig_idx = call_ms.m.GetIntEntry(MetadataStream.tid_MethodDef, call_ms.mdrow,
4);
var pc = call_ms.m.GetMethodDefSigParamCountIncludeThis((int)sig_idx);
stack_after = stack_before;
if (n.constrained)
{
var cts = c.ms.m.GetTypeSpec(n.constrained_tok, c.ms.gtparams, c.ms.gmparams);
if (!cts.ManagedPointer.Equals(stack_before.Peek(pc - 1).ts))
throw new Exception("Invalid constrained prefix: " +
cts.ManagedPointer.MangleType() + " vs " +
stack_before.Peek(pc - 1).ts);
if (cts.IsValueType == false)
{
// dereference ptr
stack_after = ldind(n, c, stack_before, cts, pc - 1);
// copy value at box entry in stack to ptr entry and remove boxed type from stack
stack_after = stackcopy(n, c, stack_after, 0, pc);
stack_after = new Stack<StackItem>(stack_after);
stack_after.Pop();
}
else if (!call_ms.type.Equals(cts))
{
// dereference ptr then box it
// create a new top of stack object that is the new boxed object
stack_after = newobj(n, c, stack_after, null, cts.Box);
// get the address of its data member
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetTypeSize(cts.m.SystemObject, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
// copy from the managed pointer address to the boxed type address
stack_after = ldc(n, c, stack_after, c.t.GetSize(cts));
stack_after = memcpy(n, c, stack_after, 1, pc + 2, 0);
// remove count and data member ptr entries
stack_after = new Stack<StackItem>(stack_after);
stack_after.Pop();
stack_after.Pop();
// copy value at box entry in stack to ptr entry and remove boxed type from stack
stack_after = stackcopy(n, c, stack_after, 0, pc);
stack_after = new Stack<StackItem>(stack_after);
stack_after.Pop();
}
// else do nothing if this is a value type which implements call_ms
}
if((call_ms_flags & 0x40) == 0x40)
{
// Calling a virtual function
stack_after = get_virt_ftn_ptr(n, c, stack_after, pc - 1);
if (call_ms.IsAlwaysInvoke)
{
stack_after = params_to_invoke_array(n, c, stack_after, call_ms);
stack_after = call(n, c, stack_after, false, "invoke",
c.special_meths, c.special_meths.invoke);
if(call_ms.ReturnType != null)
{
stack_after = unbox_any(n, c, stack_after, call_ms.ReturnType);
}
else
{
// pop the unwanted return type
stack_after = pop(n, c, stack_after);
}
}
else
{
stack_after = call(n, c, stack_after, true);
}
}
else
{
// Calling an instance function
if (call_ms.IsAlwaysInvoke)
throw new NotImplementedException(); // Implement as above
stack_after = call(n, c, stack_after);
}
}
break;
case cil.Opcode.SingleOpcodes.ret:
stack_after = ret(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.add:
case cil.Opcode.SingleOpcodes.add_ovf:
case cil.Opcode.SingleOpcodes.add_ovf_un:
case cil.Opcode.SingleOpcodes.sub:
case cil.Opcode.SingleOpcodes.sub_ovf:
case cil.Opcode.SingleOpcodes.sub_ovf_un:
case cil.Opcode.SingleOpcodes.mul:
case cil.Opcode.SingleOpcodes.mul_ovf:
case cil.Opcode.SingleOpcodes.mul_ovf_un:
case cil.Opcode.SingleOpcodes.div:
case cil.Opcode.SingleOpcodes.div_un:
case cil.Opcode.SingleOpcodes.rem:
case cil.Opcode.SingleOpcodes.rem_un:
case cil.Opcode.SingleOpcodes.and:
case cil.Opcode.SingleOpcodes.or:
case cil.Opcode.SingleOpcodes.xor:
stack_after = binnumop(n, c, stack_before, n.opcode.opcode1);
break;
case cil.Opcode.SingleOpcodes.neg:
case cil.Opcode.SingleOpcodes.not:
stack_after = unnumop(n, c, stack_before, n.opcode.opcode1);
break;
case cil.Opcode.SingleOpcodes.shl:
case cil.Opcode.SingleOpcodes.shr:
case cil.Opcode.SingleOpcodes.shr_un:
stack_after = shiftop(n, c, stack_before, n.opcode.opcode1);
break;
case cil.Opcode.SingleOpcodes.conv_i:
stack_after = conv(n, c, stack_before, 0x18);
break;
case cil.Opcode.SingleOpcodes.conv_i1:
stack_after = conv(n, c, stack_before, 0x04);
break;
case cil.Opcode.SingleOpcodes.conv_i2:
stack_after = conv(n, c, stack_before, 0x06);
break;
case cil.Opcode.SingleOpcodes.conv_i4:
stack_after = conv(n, c, stack_before, 0x08);
break;
case cil.Opcode.SingleOpcodes.conv_i8:
stack_after = conv(n, c, stack_before, 0x0a);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i:
stack_after = conv(n, c, stack_before, 0x18, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i1:
stack_after = conv(n, c, stack_before, 0x04, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i1_un:
stack_after = conv(n, c, stack_before, 0x04, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i2:
stack_after = conv(n, c, stack_before, 0x06, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i2_un:
stack_after = conv(n, c, stack_before, 0x06, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i4:
stack_after = conv(n, c, stack_before, 0x08, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i4_un:
stack_after = conv(n, c, stack_before, 0x08, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i8:
stack_after = conv(n, c, stack_before, 0x0a, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i8_un:
stack_after = conv(n, c, stack_before, 0x0a, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_i_un:
stack_after = conv(n, c, stack_before, 0x18, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u:
stack_after = conv(n, c, stack_before, 0x19, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u1:
stack_after = conv(n, c, stack_before, 0x05, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u1_un:
stack_after = conv(n, c, stack_before, 0x05, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u2:
stack_after = conv(n, c, stack_before, 0x07, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u2_un:
stack_after = conv(n, c, stack_before, 0x07, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u4:
stack_after = conv(n, c, stack_before, 0x09, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u4_un:
stack_after = conv(n, c, stack_before, 0x09, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u8:
stack_after = conv(n, c, stack_before, 0x0b, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u8_un:
stack_after = conv(n, c, stack_before, 0x0b, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_ovf_u_un:
stack_after = conv(n, c, stack_before, 0x19, true, true);
break;
case cil.Opcode.SingleOpcodes.conv_r4:
stack_after = conv(n, c, stack_before, 0x0c);
break;
case cil.Opcode.SingleOpcodes.conv_r8:
stack_after = conv(n, c, stack_before, 0x0d);
break;
case cil.Opcode.SingleOpcodes.conv_r_un:
stack_after = conv(n, c, stack_before, 0x0d, false, true);
break;
case cil.Opcode.SingleOpcodes.conv_u:
stack_after = conv(n, c, stack_before, 0x19);
break;
case cil.Opcode.SingleOpcodes.conv_u1:
stack_after = conv(n, c, stack_before, 0x05);
break;
case cil.Opcode.SingleOpcodes.conv_u2:
stack_after = conv(n, c, stack_before, 0x07);
break;
case cil.Opcode.SingleOpcodes.conv_u4:
stack_after = conv(n, c, stack_before, 0x09);
break;
case cil.Opcode.SingleOpcodes.conv_u8:
stack_after = conv(n, c, stack_before, 0x0b);
break;
case cil.Opcode.SingleOpcodes.stind_i:
case cil.Opcode.SingleOpcodes.stind_ref:
stack_after = stind(n, c, stack_before, c.t.GetPointerSize());
break;
case cil.Opcode.SingleOpcodes.stind_i1:
stack_after = stind(n, c, stack_before, 1);
break;
case cil.Opcode.SingleOpcodes.stind_i2:
stack_after = stind(n, c, stack_before, 2);
break;
case cil.Opcode.SingleOpcodes.stind_i4:
case cil.Opcode.SingleOpcodes.stind_r4:
stack_after = stind(n, c, stack_before, 4);
break;
case cil.Opcode.SingleOpcodes.stind_i8:
case cil.Opcode.SingleOpcodes.stind_r8:
stack_after = stind(n, c, stack_before, 8);
break;
case cil.Opcode.SingleOpcodes.stobj:
stack_after = stind(n, c, stack_before, c.t.GetSize(n.GetTokenAsTypeSpec(c)));
break;
case cil.Opcode.SingleOpcodes.ldind_i:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x18));
break;
case cil.Opcode.SingleOpcodes.ldind_ref:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x1c));
break;
case cil.Opcode.SingleOpcodes.ldind_i1:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x04));
break;
case cil.Opcode.SingleOpcodes.ldind_i2:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x06));
break;
case cil.Opcode.SingleOpcodes.ldind_i4:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x08));
break;
case cil.Opcode.SingleOpcodes.ldind_i8:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0a));
break;
case cil.Opcode.SingleOpcodes.ldind_r4:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0c));
break;
case cil.Opcode.SingleOpcodes.ldind_r8:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x0d));
break;
case cil.Opcode.SingleOpcodes.ldind_u1:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x05));
break;
case cil.Opcode.SingleOpcodes.ldind_u2:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x07));
break;
case cil.Opcode.SingleOpcodes.ldind_u4:
stack_after = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x09));
break;
case cil.Opcode.SingleOpcodes.ldobj:
stack_after = ldobj(n, c, stack_before, n.GetTokenAsTypeSpec(c));
break;
case cil.Opcode.SingleOpcodes.isinst:
stack_after = castclass(n, c, stack_before, true);
break;
case cil.Opcode.SingleOpcodes.castclass:
stack_after = castclass(n, c, stack_before, false);
break;
case cil.Opcode.SingleOpcodes.pop:
stack_after = pop(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.newarr:
stack_after = newarr(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.newobj:
stack_after = newobj(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.throw_:
stack_after = throw_(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.switch_:
stack_after = switch_(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.unbox_any:
stack_after = unbox_any(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.unbox:
stack_after = unbox(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.box:
stack_after = box(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.ldlen:
stack_after = ldlen(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.dup:
stack_after = copy_to_front(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.ldtoken:
stack_after = ldtoken(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.leave:
case cil.Opcode.SingleOpcodes.leave_s:
stack_after = leave(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.endfinally:
stack_after = endfinally(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.mkrefany:
stack_after = mkrefany(n, c, stack_before);
break;
case cil.Opcode.SingleOpcodes.double_:
switch(n.opcode.opcode2)
{
case cil.Opcode.DoubleOpcodes.ceq:
stack_after = cmp(n, c, stack_before, Opcode.cc_eq);
break;
case cil.Opcode.DoubleOpcodes.cgt:
stack_after = cmp(n, c, stack_before, Opcode.cc_gt);
break;
case cil.Opcode.DoubleOpcodes.cgt_un:
stack_after = cmp(n, c, stack_before, Opcode.cc_a);
break;
case cil.Opcode.DoubleOpcodes.clt:
stack_after = cmp(n, c, stack_before, Opcode.cc_lt);
break;
case cil.Opcode.DoubleOpcodes.clt_un:
stack_after = cmp(n, c, stack_before, Opcode.cc_b);
break;
case cil.Opcode.DoubleOpcodes.localloc:
{
stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
si = new StackItem { ts = c.ms.m.GetSimpleTypeSpec(0x18) };
stack_after.Push(si);
// don't allow localloc in exception handlers
if (n.is_in_excpt_handler)
throw new NotSupportedException("localloc in exception handler");
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_localloc, stack_before = stack_before, stack_after = stack_after });
// TODO: if localsinit set then initialize to zero
break;
}
case cil.Opcode.DoubleOpcodes._sizeof:
stack_after = ldc(n, c, stack_before, c.t.GetSize(n.GetTokenAsTypeSpec(c)));
break;
case cil.Opcode.DoubleOpcodes.ldftn:
stack_after = ldftn(n, c, stack_before);
break;
case cil.Opcode.DoubleOpcodes.initobj:
stack_after = initobj(n, c, stack_before);
break;
case cil.Opcode.DoubleOpcodes.rethrow:
stack_after = rethrow(n, c, stack_before);
break;
case cil.Opcode.DoubleOpcodes.arglist:
stack_after = arglist(n, c, stack_before);
break;
case cil.Opcode.DoubleOpcodes.ldvirtftn:
stack_after = get_virt_ftn_ptr(n, c, stack_before);
break;
case cil.Opcode.DoubleOpcodes.endfilter:
stack_after = endfilter(n, c, stack_before);
break;
case cil.Opcode.DoubleOpcodes.refanytype:
stack_after = refanytype(n, c, stack_before);
break;
default:
throw new NotImplementedException(n.ToString());
}
break;
default:
throw new NotImplementedException(n.ToString());
}
n.visited = true;
n.stack_after = stack_after;
//foreach (var after in n.il_offsets_after)
// DoConversion(c.offset_map[after], c, stack_after);
}
private static Stack<StackItem> params_to_invoke_array(CilNode n, Code c, Stack<StackItem> stack_after, MethodSpec call_ms)
{
// On entry to this function, the stack is ..., param_0, param_1, ..., param_n, mptr
// On exit it should be ..., mptr, param_array, rettype_vtbl, flags
// Package the parameters into an object[] array
var pcount = call_ms.m.GetMethodDefSigParamCountIncludeThis(call_ms.msig);
stack_after = ldc(n, c, stack_after, pcount);
stack_after = newarr(n, c, stack_after, call_ms.m.SystemObject.Type);
var psig_idx = call_ms.msig;
psig_idx = call_ms.m.GetMethodDefSigRetTypeIndex(psig_idx);
call_ms.m.GetTypeSpec(ref psig_idx, call_ms.gtparams == null ? c.ms.gtparams : call_ms.gtparams, c.ms.gmparams);
for (int i = 0; i < pcount; i++)
{
// Make the top of stack be ..., array, index, value
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, i);
stack_after = copy_to_front(n, c, stack_after, pcount + 3 - i);
// Get param type
TypeSpec ptype;
if (i == 0 && call_ms.m.GetMethodDefSigHasNonExplicitThis(call_ms.msig))
ptype = call_ms.type;
else
ptype = call_ms.m.GetTypeSpec(ref psig_idx, call_ms.gtparams, call_ms.gmparams);
if (ptype.IsValueType && !ptype.IsBoxed)
stack_after = box(n, c, stack_after, ptype);
stack_after = stelem(n, c, stack_after, call_ms.m.SystemObject.Type);
}
// Make the fnptr and object[] array replace the parameters
stack_after = stackcopy(n, c, stack_after, 1, pcount + 1);
stack_after = stackcopy(n, c, stack_after, 0, pcount);
stack_after = new Stack<StackItem>(stack_after);
for (int i = 0; i < pcount; i++)
{
stack_after.Pop();
}
// Add a rettype vtbl ptr
if(call_ms.ReturnType != null)
{
stack_after = ldlab(n, c, stack_after, call_ms.ReturnType.MangleType());
}
else
{
stack_after = ldc(n, c, stack_after, 0, 0x18);
}
// Add flags
uint flags = 0;
if (!call_ms.IsStatic)
flags |= 1;
if (call_ms.type != null && call_ms.type.IsValueType)
flags |= 2;
if (call_ms.ReturnType != null && call_ms.ReturnType.IsValueType)
flags |= 4;
stack_after = ldc(n, c, stack_after, flags, 0x9);
return stack_after;
}
private static Stack<StackItem> refanytype(CilNode n, Code c, Stack<StackItem> stack_before)
{
// extract the 'Type' member as a RuntimeTypeHandle
var typed_ref = c.ms.m.al.GetAssembly("mscorlib").GetTypeSpec("System", "TypedReference");
var stack_after = ldc(n, c, stack_before, layout.Layout.GetFieldOffset(typed_ref, "Type", c.t, out var is_tls), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemRuntimeTypeHandle);
return stack_after;
}
private static Stack<StackItem> mkrefany(CilNode n, Code c, Stack<StackItem> stack_before)
{
var ts = n.GetTokenAsTypeSpec(c);
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
c.s.r.VTableRequestor.Request(ts.Box);
// Ensure the stack type is a managed pointer to push_ts
var stack_type = stack_after.Peek().ts;
if (!stack_type.Equals(ts.ManagedPointer))
throw new Exception("mkrefany ptr is not managed pointer to " + ts.MangleType());
// Build the new System.TypedReference object on the stack
var typed_ref = ts.m.al.GetAssembly("mscorlib").GetTypeSpec("System", "TypedReference");
stack_after.Push(new StackItem { ts = typed_ref });
// Save the 'Type' member
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetFieldOffset(typed_ref, "Type", c.t, out var is_tls), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldlab(n, c, stack_after, ts.MangleType());
stack_after = call(n, c, stack_after, false, "__type_from_vtbl", c.special_meths, c.special_meths.type_from_vtbl);
stack_after = stind(n, c, stack_after, c.t.GetPointerSize());
// Save the 'Value' member
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetFieldOffset(typed_ref, "Value", c.t, out is_tls), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = copy_to_front(n, c, stack_after, 2);
stack_after = stind(n, c, stack_after, c.t.psize);
// Rearrange stack ..., ptr, typedRef. -> ..., typedRef
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = typed_ref });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, arg_a = 0, res_a = 0, stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
private static Stack<StackItem> memcpy(CilNode n, Code c, Stack<StackItem> stack_before, int dest = 2, int src = 1, int count = 0)
{
var stack_after = new Stack<StackItem>(stack_before);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_memcpy, stack_before = stack_before, stack_after = stack_after, arg_a = dest, arg_b = src, arg_c = count });
return stack_after;
}
private static Stack<StackItem> memset(CilNode n, Code c, Stack<StackItem> stack_before, int dest = 1, int length = 0)
{
var stack_after = new Stack<StackItem>(stack_before);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_memset, stack_before = stack_before, stack_after = stack_after, arg_a = dest, arg_b = length });
return stack_after;
}
private static Stack<StackItem> pop(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
return stack_after;
}
/* Gets the address of a stack entry that is a value type.
* Used by ldfld, ldflda, stfld to calculate the address of
* a field in a value type.
* If the stack object is not a value type it does nothing. */
private static Stack<StackItem> ldvtaddr(CilNode n, Code c, Stack<StackItem> stack_before, int arg_a = -1, int res_a = -1)
{
var act_arg_a = arg_a;
if (arg_a == -1)
arg_a = 0;
var si = stack_before.Peek(arg_a);
if (si.ct != ir.Opcode.ct_vt)
return stack_before;
var stack_after = new Stack<StackItem>(stack_before);
si.has_address_taken = true;
var si_r = new StackItem { ts = si.ts.ManagedPointer };
if (act_arg_a == -1)
stack_after.Pop();
if (res_a == -1)
{
stack_after.Push(si_r);
res_a = 0;
}
else
stack_after[stack_after.Count - 1 - res_a] = si_r;
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_ldobja, arg_a = arg_a, res_a = res_a, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> arglist(CilNode n, Code c, Stack<StackItem> stack_before)
{
// arglist is currently not implemented - throw a runtime exception
var stack_after = ldstr(n, c, stack_before, "arglist is not supported");
var ni_ts = c.ms.m.al.GetAssembly("mscorlib").GetTypeSpec("System", "NotImplementedException");
var ni_ctor_row = ni_ts.m.GetMethodDefRow(ni_ts, ".ctor",
c.special_meths.inst_Rv_s, c.special_meths);
var ni_ctor_ms = new MethodSpec
{
m = ni_ts.m,
type = ni_ts,
mdrow = ni_ctor_row,
msig = (int)ni_ts.m.GetIntEntry(MetadataStream.tid_MethodDef, ni_ctor_row, 4),
};
stack_after = newobj(n, c, stack_after, ni_ctor_ms);
stack_after = throw_(n, c, stack_after);
// push a System.RuntimeArgumentHandle anyway as further instructions will expect it
var srah_ts = c.ms.m.al.GetAssembly("mscorlib").GetTypeSpec("System", "RuntimeArgumentHandle");
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Push(new StackItem { ts = srah_ts });
return stack_after2;
}
private static Stack<StackItem> rethrow(CilNode n, Code c, Stack<StackItem> stack_before)
{
bool in_catch = false;
foreach(var ehdr in c.ehdrs)
{
if(ehdr.EType == ExceptionHeader.ExceptionHeaderType.Catch)
{
if((n.il_offset >= ehdr.HandlerILOffset) &&
(n.il_offset <= (ehdr.HandlerILOffset + ehdr.HandlerLength)))
{
in_catch = true;
break;
}
}
}
if (!in_catch)
throw new Exception("rethrow called not in catch handler");
var stack_after = call(n, c, stack_before, false, "rethrow",
c.special_meths, c.special_meths.rethrow);
return stack_after;
}
private static Stack<StackItem> initobj(CilNode n, Code c, Stack<StackItem> stack_before)
{
var t = n.GetTokenAsTypeSpec(c);
var ts = stack_before.Peek().ts;
if (ts.stype == TypeSpec.SpecialType.MPtr || ts.stype == TypeSpec.SpecialType.Ptr)
{
if (!t.IsAssignmentCompatibleWith(ts.other))
throw new Exception("initobj verification failed");
}
else if(!ts.Equals(c.ms.m.SystemIntPtr))
throw new Exception("initobj stack value is not managed pointer");
if(t.IsValueType)
{
var tsize = layout.Layout.GetTypeSize(t, c.t);
var stack_after = ldc(n, c, stack_before, tsize);
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_zeromem, imm_l = layout.Layout.GetTypeSize(t, c.t), stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
else
{
var stack_after = ldc(n, c, stack_before, 0, 0x1c);
stack_after = stind(n, c, stack_after, c.t.GetPointerSize());
return stack_after;
}
}
private static Stack<StackItem> ldftn(CilNode n, Code c, Stack<StackItem> stack_before)
{
var ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
var m = ms.m;
var mangled_meth = m.MangleMethod(ms);
c.s.r.MethodRequestor.Request(ms);
var stack_after = ldlab(n, c, stack_before, mangled_meth);
return stack_after;
}
private static Stack<StackItem> ehdr_trycatch_start(CilNode n, Code c, Stack<StackItem> stack_before, int ehdrIdx,
bool is_catch = false, bool is_filter = false)
{
if (is_catch)
{
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_enter_handler, imm_l = ehdrIdx, imm_ul = is_filter ? 1UL : 0UL, stack_after = stack_before, stack_before = stack_before });
}
if (is_filter)
return new Stack<StackItem>(stack_before);
var stack_after = ldlab(n, c, stack_before, c.ms.m.MangleMethod(c.ms) + "EH",
ehdrIdx * layout.Layout.GetEhdrSize(c.t));
stack_after = ldfp(n, c, stack_after);
c.s.r.EHRequestor.Request(c);
if(is_catch)
{
stack_after = call(n, c, stack_after, false, "enter_catch",
c.special_meths, c.special_meths.catch_enter);
}
else
{
stack_after = call(n, c, stack_after, false, "enter_try",
c.special_meths, c.special_meths.try_enter);
}
return stack_after;
}
private static Stack<StackItem> ldfp(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Push(new StackItem { ts = c.ms.m.SystemIntPtr });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldfp, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> endfinally(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, stack_before = stack_after, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> endfilter(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, stack_before = stack_after, stack_after = stack_after, ct = Opcode.ct_int32 });
return stack_after;
}
private static Stack<StackItem> br(CilNode n, Code c, Stack<StackItem> stack_before, int il_target = int.MaxValue)
{
var stack_after = stack_before;
if (il_target == int.MaxValue)
il_target = n.il_offsets_after[0];
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_br, imm_l = il_target, stack_after = stack_after, stack_before = stack_before });
return stack_after;
}
private static Stack<StackItem> leave(CilNode n, Code c, Stack<StackItem> stack_before)
{
// ensure we are in a try, filter or catch block
if(c.ehdrs != null)
{
c.s.r.EHRequestor.Request(c);
foreach(var ehdr in c.ehdrs)
{
if (n.il_offset >= ehdr.TryILOffset &&
n.il_offset < (ehdr.TryILOffset + ehdr.TryLength) &&
(n.il_offsets_after[0] < ehdr.TryILOffset ||
n.il_offsets_after[0] >= (ehdr.TryILOffset + ehdr.TryLength)))
{
// invoke the exception handler to leave the most deeply nested block but
// only up until the shallowest nested block
var stack_after2 = new Stack<StackItem>(c.lv_types.Length);
stack_after2 = ldlab(n, c, stack_after2, c.ms.m.MangleMethod(c.ms) + "EH",
ehdr.EhdrIdx * layout.Layout.GetEhdrSize(c.t));
call(n, c, stack_after2, false, "leave_try",
c.special_meths, c.special_meths.leave);
}
else if (n.il_offset >= ehdr.HandlerILOffset &&
n.il_offset < (ehdr.HandlerILOffset + ehdr.HandlerLength) &&
(ehdr.EType == ExceptionHeader.ExceptionHeaderType.Catch ||
ehdr.EType == ExceptionHeader.ExceptionHeaderType.Fault ||
ehdr.EType == ExceptionHeader.ExceptionHeaderType.Filter))
{
// invoke the exception handler to leave the most deeply nested block
var stack_after2 = new Stack<StackItem>(c.lv_types.Length);
stack_after2 = ldlab(n, c, stack_after2, c.ms.m.MangleMethod(c.ms) + "EH",
ehdr.EhdrIdx * layout.Layout.GetEhdrSize(c.t));
call(n, c, stack_after2, false, "leave_handler",
c.special_meths, c.special_meths.leave);
}
}
}
// empty execution stack
var stack_after = new Stack<StackItem>(c.lv_types.Length);
// jump to the targetted instruction
return br(n, c, stack_after);
}
private static Stack<StackItem> ldtoken(CilNode n, Code c, Stack<StackItem> stack_before)
{
var ts = n.GetTokenAsTypeSpec(c);
var ms = n.GetTokenAsMethodSpec(c);
TypeSpec push_ts = null;
TypeSpec.FullySpecSignature sig_val = null;
Stack<StackItem> stack_after;
if (ts != null)
{
push_ts = ts.m.SystemRuntimeTypeHandle;
sig_val = ts.Signature;
c.s.r.VTableRequestor.Request(ts.Box);
stack_after = ldlab(n, c, stack_before, ts.MangleType());
//stack_after = call(n, c, stack_after, false, "__type_from_vtbl", c.special_meths, c.special_meths.type_from_vtbl);
}
else if (ms != null)
{
// decide if method or field ref
if (ms.is_field)
push_ts = ms.m.SystemRuntimeFieldHandle;
else
push_ts = ms.m.SystemRuntimeMethodHandle;
sig_val = ms.Signature;
int sig_offset = c.s.sigt.GetSignatureAddress(sig_val, c.t, c.s);
// build the object
stack_after = ldlab(n, c, stack_before, c.s.sigt.GetStringTableName(), sig_offset);
}
else throw new Exception("Bad token");
stack_after[stack_after.Count - 1] = new StackItem
{
ts = push_ts,
fss = sig_val
};
return stack_after;
}
private static Stack<StackItem> ldobj(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts = null)
{
if (ts == null)
ts = n.GetTokenAsTypeSpec(c);
if(ts.IsValueType)
{
var esize = c.t.GetSize(ts);
return ldind(n, c, stack_before, ts);
}
var ret = ldind(n, c, stack_before, c.ms.m.GetSimpleTypeSpec(0x1c));
ret.Peek().ts = ts;
return ret;
}
private static Stack<StackItem> ldobja(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts = null)
{
if (ts == null)
ts = n.GetTokenAsTypeSpec(c);
if (!ts.IsValueType)
{
throw new Exception("ldobja on reference type");
}
stack_before.Peek().has_address_taken = true;
var ret = new Stack<StackItem>(stack_before);
ret.Add(new StackItem { ts = ts.ManagedPointer });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldobja, ct = Opcode.ct_vt, ctret = Opcode.ct_ref, stack_before = stack_before, stack_after = ret });
return ret;
}
private static Stack<StackItem> ldlen(CilNode n, Code c, Stack<StackItem> stack_before)
{
// dereference sizes pointer
var stack_after = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.SizesPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x18));
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x08));
return stack_after;
}
private static Stack<StackItem> stelem(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts)
{
// todo: type and array bounds checks
var tsize = c.t.GetSize(ts);
// build offset
var stack_after = ldc(n, c, stack_before, tsize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_intptr, 2, -1, 1);
// check object is a szarray to ts
stack_after = copy_to_front(n, c, stack_after, 2);
stack_after = castclass(n, c, stack_after, false, null,
new TypeSpec { m = c.ms.m.al.GetAssembly("mscorlib"), stype = TypeSpec.SpecialType.SzArray, other = ts });
// dereference data pointer
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x18));
// get pointer to actual data
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr, -1, 2, -1);
// load data
stack_after = stind(n, c, stack_after, tsize, 1, 0);
stack_after = new Stack<StackItem>(stack_after);
stack_after.Pop();
stack_after.Pop();
return stack_after;
}
private static Stack<StackItem> box(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts = null)
{
if (ts == null) ts = n.GetTokenAsTypeSpec(c);
if (ts.IsValueType)
{
if(!stack_before.Peek().ts.IsVerifierAssignableTo(ts))
throw new Exception("Box called with invalid parameter: " + ts.ToString() +
" vs " + stack_before.Peek().ts);
var boxed_ts = ts.Box;
c.s.r.VTableRequestor.Request(boxed_ts);
var ptr_size = c.t.GetPointerSize();
var sysobj_size = layout.Layout.GetTypeSize(c.ms.m.SystemObject, c.t);
var data_size = c.t.GetSize(ts);
var boxed_size = util.util.align(sysobj_size + data_size, ptr_size);
// create boxed object
var stack_after = ldc(n, c, stack_before, boxed_size, 0x18);
stack_after = call(n, c, stack_after, false, "gcmalloc", c.special_meths, c.special_meths.gcmalloc);
// set vtbl
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldlab(n, c, stack_after, c.ms.m.MangleType(ts));
stack_after = stind(n, c, stack_after, ptr_size);
/* Store mutex lock */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.MutexLock, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldc(n, c, stack_after, 0, 0x18);
stack_after = stind(n, c, stack_after, ptr_size);
// set object
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, sysobj_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = stind(n, c, stack_after, data_size, 2, 0);
// get return value
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = boxed_ts });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_stackcopy, stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
else
{
c.s.r.VTableRequestor.Request(ts);
return stack_before;
}
}
private static Stack<StackItem> unbox(CilNode n, Code c, Stack<StackItem> stack_before)
{
var ts = n.GetTokenAsTypeSpec(c);
// TODO: ensure stack item is a boxed instance of ts
// simply add the offset to the boxed instance to the original pointer
var stack_after = ldc(n, c, stack_before, layout.Layout.GetTypeSize(c.ms.m.SystemObject, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after[stack_after.Count - 1] = new StackItem { ts = ts.ManagedPointer };
return stack_after;
}
private static Stack<StackItem> unbox_any(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts = null)
{
if (ts == null) ts = n.GetTokenAsTypeSpec(c);
if (ts.IsValueType)
{
// TODO ensure stack item is a boxed instance of ts
var sysobj_size = layout.Layout.GetTypeSize(c.ms.m.SystemObject, c.t);
var stack_after = ldc(n, c, stack_before, sysobj_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ts);
return stack_after;
}
else
{
return castclass(n, c, stack_before, false, stack_before.Peek().ts, ts);
}
}
private static Stack<StackItem> ldelem(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts)
{
// todo: type and array bounds checks
var tsize = c.t.GetSize(ts);
// build offset
var stack_after = ldc(n, c, stack_before, tsize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_intptr);
// check object is a szarray to ts
stack_after = copy_to_front(n, c, stack_after, 1);
stack_after = castclass(n, c, stack_after, false, null,
new TypeSpec { m = c.ms.m.al.GetAssembly("mscorlib"), stype = TypeSpec.SpecialType.SzArray, other = ts });
// dereference data pointer
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x18));
// get pointer to actual data
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
// load data
stack_after = ldind(n, c, stack_after, ts);
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = ts });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, arg_a = 0, res_a = 0, stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
private static Stack<StackItem> ldelema(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts)
{
// todo: type and array bounds checks
var tsize = c.t.GetSize(ts);
// build offset
var stack_after = ldc(n, c, stack_before, tsize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_intptr);
// check object is a szarray to ts
stack_after = copy_to_front(n, c, stack_after, 1);
stack_after = castclass(n, c, stack_after, false, null,
new TypeSpec { m = c.ms.m.al.GetAssembly("mscorlib"), stype = TypeSpec.SpecialType.SzArray, other = ts });
// dereference data pointer
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x18));
// get pointer to actual data
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = ts.ManagedPointer });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, arg_a = 0, res_a = 0, stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
private static Stack<StackItem> switch_(CilNode n, Code c, Stack<StackItem> stack_before)
{
// TODO: optimize for architectures that support jump tables
int[] targets = new int[n.il_offsets_after.Count - 1];
for (int i = 0; i < n.il_offsets_after.Count - 1; i++)
targets[i] = n.il_offsets_after[i];
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_switch, arg_list = new System.Collections.Generic.List<int>(targets), stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
internal static Stack<StackItem> throw_(CilNode n, Code c, Stack<StackItem> stack_before)
{
return call(n, c, stack_before, false, "throw", c.special_meths, c.special_meths.throw_);
}
private static int get_brtf_type(cil.Opcode opcode, int ct)
{
switch(opcode.opcode1)
{
case cil.Opcode.SingleOpcodes.brtrue:
case cil.Opcode.SingleOpcodes.brtrue_s:
switch(ct)
{
case ir.Opcode.ct_intptr:
case ir.Opcode.ct_object:
// following added for mono csc compatibility
case ir.Opcode.ct_int32:
case ir.Opcode.ct_int64:
case ir.Opcode.ct_ref:
return ct;
}
break;
case cil.Opcode.SingleOpcodes.brfalse:
case cil.Opcode.SingleOpcodes.brfalse_s:
switch (ct)
{
case ir.Opcode.ct_int32:
case ir.Opcode.ct_int64:
case ir.Opcode.ct_object:
case ir.Opcode.ct_ref:
case ir.Opcode.ct_intptr:
return ct;
}
break;
}
throw new Exception("Invalid argument to " + opcode.ToString() + ": " + ir.Opcode.ct_names[ct]);
}
internal static Stack<StackItem> newobj(CilNode n, Code c, Stack<StackItem> stack_before,
MethodSpec ctor = null, TypeSpec objtype = null)
{
if(ctor == null && objtype == null)
ctor = n.GetTokenAsMethodSpec(c);
if(objtype == null)
objtype = ctor.type;
c.s.r.VTableRequestor.Request(objtype.Box);
if(ctor != null)
c.s.r.MethodRequestor.Request(ctor);
var stack_after = new Stack<StackItem>(stack_before);
int vt_adjust = 0;
/* is this a value type? */
if (objtype.IsValueType)
{
vt_adjust = 1;
/* Create storage space on the stack for the object */
stack_after.Push(new StackItem { ts = objtype });
/* Load up the address of the object for passing to the constructor */
stack_after = ldobja(n, c, stack_after, objtype);
/* Clear the memory */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetTypeSize(objtype, c.t));
stack_after = memset(n, c, stack_after);
stack_after = pop(n, c, stack_after);
stack_after = pop(n, c, stack_after);
}
else
{
/* Its a reference type */
/* check if this is system.string */
var objsize = layout.Layout.GetTypeSize(objtype, c.t);
var vtname = objtype.MangleType();
var intptrsize = c.t.GetPointerSize();
/* create object */
bool is_string = false;
if (objtype.Equals(c.ms.m.GetSimpleTypeSpec(0x0e)))
{
stack_after = newstr(n, c, stack_after, ctor);
// create a copy of the character length, multiply 2 and add string object length
// and 4 extra bytes to ensure coreclr String.EqualsHelper works correctly
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, 2);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_int32);
stack_after = ldc(n, c, stack_after, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Start_Char, c) + 4);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_int32);
is_string = true;
}
else
stack_after = ldc(n, c, stack_after, objsize, 0x18);
stack_after = call(n, c, stack_after, false, "gcmalloc", c.special_meths, c.special_meths.gcmalloc);
if(is_string)
{
/* now stack is ..., ctor_args, length, obj
*
* we need to store length to the appropriate part then
* adject the stack so length is no longer present
*/
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Length, c), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = stind(n, c, stack_after, 4, 2, 0);
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = c.ms.m.SystemIntPtr });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, stack_before = stack_after, stack_after = stack_after2, arg_a = 0, res_a = 0 });
stack_after = new Stack<StackItem>(stack_after2);
}
/* store vtbl pointer */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldlab(n, c, stack_after, vtname);
stack_after = stind(n, c, stack_after, intptrsize);
/* Store mutex lock */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.MutexLock, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldc(n, c, stack_after, 0, 0x18);
stack_after = stind(n, c, stack_after, intptrsize);
}
if (ctor != null)
{
/* call constructor. Arguments are 0 for object, then
* for the other pcount - 1 arguments, they are at
* pcount - 1, pcount - 2, pcount - 3 etc */
System.Collections.Generic.List<int> p = new System.Collections.Generic.List<int>();
var pcount = ctor.m.GetMethodDefSigParamCountIncludeThis(ctor.msig);
p.Add(0);
for (int i = 0; i < (pcount - 1); i++)
p.Add(pcount - 1 - i + vt_adjust);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_call, imm_ms = ctor, arg_list = p, stack_before = stack_after, stack_after = stack_after });
/* pop all arguments and leave object on the stack */
var stack_after2 = new Stack<StackItem>(stack_after);
for (int i = 0; i < (pcount + vt_adjust); i++)
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = objtype });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_stackcopy, arg_a = vt_adjust, res_a = 0, stack_before = stack_after, stack_after = stack_after2 });
stack_after = stack_after2;
}
else
{
stack_after.Peek(0).ts = objtype;
}
return stack_after;
}
private static Stack<StackItem> newstr(CilNode n, Code c, Stack<StackItem> stack_before,
MethodSpec ctor)
{
// Generates an instruction stream to determine the number of bytes
// required for the entire string object (object size is added
// at end).
// Decide on the particular constructor
Stack<StackItem> stack_after = null;
if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_ci, null, null))
{
// string(char c, int32 count)
stack_after = copy_to_front(n, c, stack_before);
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_Zc, null, null))
{
// string(char[] value)
stack_after = copy_to_front(n, c, stack_before);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.SizesPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x18));
stack_after = ldind(n, c, stack_after, c.ms.m.GetSimpleTypeSpec(0x08));
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_Pcii, null, null))
{
// string(char* value, int32 startIndex, int32 length)
stack_after = copy_to_front(n, c, stack_before);
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_Pa, null, null))
{
// string(int8* value)
stack_after = copy_to_front(n, c, stack_before);
stack_after = call(n, c, stack_after, false,
"strlen", c.special_meths, c.special_meths.strlen);
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_Zcii, null, null))
{
// string(char[] value, int32 startIndex, int32 length)
stack_after = copy_to_front(n, c, stack_before);
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_Pc, null, null))
{
// string(char* value)
stack_after = copy_to_front(n, c, stack_before);
stack_after = call(n, c, stack_after, false,
"wcslen", c.special_meths, c.special_meths.wcslen);
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_PaiiEncoding, null, null))
{
// string(int8* value, int32 startIndex, int32 length, Encoding)
stack_after = copy_to_front(n, c, stack_before, 1);
}
else if (MetadataStream.CompareSignature(ctor,
c.special_meths,
c.special_meths.string_Paii, null, null))
{
// string(int8* value, int32 startIndex, int32 length)
stack_after = copy_to_front(n, c, stack_before, 1);
}
else
throw new NotSupportedException();
return stack_after;
}
private static Stack<StackItem> shiftop(CilNode n, Code c, Stack<StackItem> stack_before, cil.Opcode.SingleOpcodes oc,
int ct_ret = Opcode.ct_unknown,
int src_a = -1, int src_b = -1, int res_a = -1)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
if (src_a == -1)
{
stack_after.Pop();
src_a = 1;
}
if (src_b == -1)
{
stack_after.Pop();
src_b = 0;
}
var si_b = stack_before.Peek(src_b);
var si_a = stack_before.Peek(src_a);
var ct_a = si_a.ct;
var ct_b = si_b.ct;
if (ct_ret == Opcode.ct_unknown)
{
ct_ret = int_op_valid(ct_a, ct_a, oc);
if (ct_ret == Opcode.ct_unknown)
throw new Exception("Invalid shift operation between " + Opcode.ct_names[ct_a] + " and " + Opcode.ct_names[ct_b]);
}
StackItem si = new StackItem();
si._ct = ct_ret;
switch (ct_ret)
{
case Opcode.ct_int32:
si.ts = c.ms.m.GetSimpleTypeSpec(0x8);
break;
case Opcode.ct_int64:
si.ts = c.ms.m.GetSimpleTypeSpec(0xa);
break;
case Opcode.ct_intptr:
si.ts = c.ms.m.GetSimpleTypeSpec(0x18);
break;
case Opcode.ct_float:
si.ts = c.ms.m.GetSimpleTypeSpec(0xd);
break;
case Opcode.ct_object:
si.ts = c.ms.m.GetSimpleTypeSpec(0x1c);
break;
}
if (res_a == -1)
{
stack_after.Push(si);
res_a = 0;
}
else
{
stack_after[stack_after.Count - 1 - res_a] = si;
}
int noc = 0;
switch (oc)
{
case cil.Opcode.SingleOpcodes.shl:
noc = Opcode.oc_shl;
break;
case cil.Opcode.SingleOpcodes.shr:
noc = Opcode.oc_shr;
break;
case cil.Opcode.SingleOpcodes.shr_un:
noc = Opcode.oc_shr_un;
break;
case cil.Opcode.SingleOpcodes.mul:
case cil.Opcode.SingleOpcodes.mul_ovf:
case cil.Opcode.SingleOpcodes.mul_ovf_un:
noc = Opcode.oc_mul;
break;
}
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = noc, ct = ct_a, ct2 = ct_b, stack_before = stack_before, stack_after = stack_after, arg_a = src_a, arg_b = src_b, res_a = res_a });
return stack_after;
}
private static Stack<StackItem> newarr(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec arr_elem_type = null)
{
if(arr_elem_type == null) arr_elem_type = n.GetTokenAsTypeSpec(c);
var arr_type = new metadata.TypeSpec { m = arr_elem_type.m, stype = TypeSpec.SpecialType.SzArray, other = arr_elem_type };
var et_size = c.t.GetSize(arr_elem_type);
c.s.r.VTableRequestor.Request(arr_elem_type.Box);
c.s.r.VTableRequestor.Request(arr_type);
/* Determine size of array object.
*
* Layout =
*
* Array object layout
* Lobounds array (4 * rank)
* Sizes array (4 * rank)
* Data array (numElems * et_size)
*/
var int32_size = c.t.GetCTSize(Opcode.ct_int32);
var intptr_size = c.t.GetPointerSize();
var arr_obj_size = layout.Layout.GetTypeSize(arr_type, c.t);
var total_static_size = arr_obj_size +
2 * int32_size;
var stack_after = copy_to_front(n, c, stack_before, 0);
stack_after = ldc(n, c, stack_after, et_size);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul);
stack_after = ldc(n, c, stack_after, total_static_size);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = conv(n, c, stack_after, 0x18);
/* Allocate object */
stack_after = call(n, c, stack_after, false, "gcmalloc", c.special_meths, c.special_meths.gcmalloc);
/* Store lobounds */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, arr_obj_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldc(n, c, stack_after, 0);
stack_after = stind(n, c, stack_after, int32_size);
/* Store size */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, arr_obj_size + int32_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = stind(n, c, stack_after, int32_size, 2, 0);
/* Store vtbl pointer */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldlab(n, c, stack_after, c.ms.m.MangleType(arr_type));
stack_after = stind(n, c, stack_after, intptr_size);
/* Store mutex lock */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.MutexLock, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldc(n, c, stack_after, 0, 0x18);
stack_after = stind(n, c, stack_after, intptr_size);
/* Store etype vtbl pointer */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.ElemTypeVtblPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldlab(n, c, stack_after, c.ms.m.MangleType(arr_elem_type));
stack_after = stind(n, c, stack_after, intptr_size);
/* Store lobounds pointer */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.LoboundsPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = copy_to_front(n, c, stack_after, 1);
stack_after = ldc(n, c, stack_after, arr_obj_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = stind(n, c, stack_after, intptr_size);
/* Store sizes pointer */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.SizesPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = copy_to_front(n, c, stack_after, 1);
stack_after = ldc(n, c, stack_after, arr_obj_size + int32_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = stind(n, c, stack_after, intptr_size);
/* Store data pointer */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = copy_to_front(n, c, stack_after, 1);
stack_after = ldc(n, c, stack_after, arr_obj_size + 2 * int32_size, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = stind(n, c, stack_after, intptr_size);
/* Store elem type size */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.ElemTypeSize, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldc(n, c, stack_after, et_size);
stack_after = stind(n, c, stack_after, int32_size);
/* Store rank */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.Rank, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add);
stack_after = ldc(n, c, stack_after, 1);
stack_after = stind(n, c, stack_after, int32_size);
/* Convert to an object on the stack of the appropriate size */
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = arr_type });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, ct = ir.Opcode.ct_object, vt_size = intptr_size, stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
private static Stack<StackItem> castclass(CilNode n, Code c, Stack<StackItem> stack_before, bool isinst = false,
metadata.TypeSpec from_type = null,
metadata.TypeSpec to_type = null)
{
if(from_type == null)
from_type = stack_before.Peek().ts;
if(to_type == null)
to_type = n.GetTokenAsTypeSpec(c);
if (to_type.IsValueType)
to_type = to_type.Box;
if(from_type != null &&
from_type.Equals(to_type) ||
from_type.IsAssignmentCompatibleWith(to_type) ||
from_type.IsSubclassOf(to_type))
{
/* We can statically prove the cast will succeed */
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Push(new StackItem { ts = to_type });
return stack_after;
}
else
{
/* There is a chance the cast will succeed but we
need to resort to a runtime check */
var to_str = to_type.MangleType();
var stack_after = ldlab(n, c, stack_before, to_str);
stack_after = ldc(n, c, stack_after, isinst ? 0 : 1);
stack_after = call(n, c, stack_after, false, "castclassex", c.special_meths, c.special_meths.castclassex);
stack_after.Peek().ts = to_type;
c.s.r.VTableRequestor.Request(to_type);
return stack_after;
}
throw new NotImplementedException();
}
private static Stack<StackItem> ldc(CilNode n,
Code c, Stack<StackItem> stack_before,
long v, int stype = 0x08)
{
var val = BitConverter.GetBytes(v);
return ldc(n, c, stack_before, v, val, stype);
}
private static Stack<StackItem> ldc(CilNode n,
Code c, Stack<StackItem> stack_before,
long v, byte[] val, int stype = 0x08)
{
var stack_after = new Stack<StackItem>(stack_before);
var si = new StackItem();
si.ts = c.ms.m.GetSimpleTypeSpec(stype);
si.min_l = v;
si.max_l = v;
stack_after.Add(si);
n.irnodes.Add(new CilNode.IRNode { parent = n, imm_l = v, imm_val = val, opcode = Opcode.oc_ldc, ctret = Opcode.GetCTFromType(si.ts), vt_size = c.t.GetSize(si.ts), stack_after = stack_after, stack_before = stack_before });
return stack_after;
}
private static Stack<StackItem> ldlab(CilNode n, Code c, Stack<StackItem> stack_before, string v, int disp = 0)
{
var stack_after = new Stack<StackItem>(stack_before);
var si = new StackItem();
si.ts = c.ms.m.GetSimpleTypeSpec(0x18);
si.str_val = v;
stack_after.Add(si);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldlabaddr, ct = Opcode.ct_object, imm_l = disp, imm_lab = v, stack_after = stack_after, stack_before = stack_before });
return stack_after;
}
internal static Stack<StackItem> ldind(CilNode n, Code c, Stack<StackItem> stack_before, TypeSpec ts, int src = -1, bool check_type = true, int res = -1)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
StackItem st_src;
if (src == -1)
{
st_src = stack_after.Pop();
src = 0;
}
else
st_src = stack_after.Peek(src);
if (res == -1)
{
stack_after.Push(new StackItem { ts = ts });
res = 0;
}
else
stack_after[stack_after.Count - 1 - res] = new StackItem { ts = ts };
var ct_src = st_src.ct;
ulong is_tls = 0;
if (check_type)
{
switch (ct_src)
{
case Opcode.ct_intptr:
case Opcode.ct_ref:
break;
case Opcode.ct_tls_intptr:
is_tls = 1;
break;
default:
throw new Exception("Cannot perform " + n.opcode.ToString() + " from address type " + Opcode.ct_names[ct_src]);
}
}
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldind, ct = Opcode.GetCTFromType(ts), vt_size = c.t.GetSize(ts), imm_ul = is_tls, imm_l = ts.IsSigned ? 1 : 0, stack_before = stack_before, stack_after = stack_after, arg_a = src, res_a = res });
return stack_after;
}
internal static Stack<StackItem> ldflda(CilNode n, Code c, Stack<StackItem> stack_before, bool is_static, out TypeSpec fld_ts, int src_a = 0,
MethodSpec fs = null)
{
TypeSpec ts;
if(fs == null)
fs = n.GetTokenAsMethodSpec(c);
ts = fs.type;
//if (!c.ms.m.GetFieldDefRow(table_id, row, out ts, out fs))
//throw new Exception("Field not found");
if (is_static)
c.static_types_referenced.Add(ts);
fld_ts = c.ms.m.GetFieldType(fs, ts.gtparams, c.ms.gmparams);
var fld_addr = layout.Layout.GetFieldOffset(ts, fs, c.t, out var is_tls, is_static);
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
StackItem si = new StackItem
{
_ct = Opcode.ct_intptr,
ts = fld_ts.ManagedPointer,
max_l = fld_addr,
max_ul = (ulong)fld_addr,
min_l = fld_addr,
min_ul = (ulong)fld_addr
};
if(is_static)
{
var static_name = c.ms.m.MangleType(ts) + "S";
if (is_tls)
{
static_name = static_name + "T";
si._ct = Opcode.ct_tls_intptr;
}
si.str_val = static_name;
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldlabaddr, ct = si._ct, imm_lab = static_name, imm_l = fld_addr, imm_ul = is_tls ? 1UL : 0UL, stack_before = stack_before, stack_after = stack_after });
c.s.r.StaticFieldRequestor.Request(ts.Unbox);
}
else
{
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldc, ctret = Opcode.ct_intptr, imm_l = fld_addr, stack_before = stack_before, stack_after = stack_after, arg_a = src_a, arg_b = 0 });
}
stack_after.Push(si);
return stack_after;
}
private static Stack<StackItem> ret(CilNode n, Code c, Stack<StackItem> stack_before)
{
var rt_idx = c.ms.m.GetMethodDefSigRetTypeIndex(c.ms.msig);
var rt_ts = c.ms.m.GetTypeSpec(ref rt_idx, c.ms.gtparams, c.ms.gmparams);
int ret_ct = ir.Opcode.ct_unknown;
int ret_vt_size = 0;
if (rt_ts == null && stack_before.Count != 0)
throw new Exception("Inconsistent stack on ret");
else if (rt_ts != null)
{
if (stack_before.Count != 1)
throw new Exception("Inconsistent stack on ret");
ret_ct = ir.Opcode.GetCTFromType(rt_ts);
ret_vt_size = c.t.GetSize(rt_ts);
}
var stack_after = new Stack<StackItem>(c.lv_types.Length);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ret_ct, vt_size = ret_vt_size, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> get_virt_ftn_ptr(CilNode n, Code c, Stack<StackItem> stack_before, int arg_a = -2)
{
var ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
var ts = ms.type;
var l = layout.Layout.GetVTableOffset(ms, c.t) * c.t.psize;
Stack<StackItem> stack_after = stack_before;
if (arg_a != -2) // used for ldvirtftn where -2 actually means 0 ie top of stack
stack_after = copy_to_front(n, c, stack_before, arg_a);
// load vtable
stack_after = conv(n, c, stack_after, 0x18);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemIntPtr);
if (ms.type.IsInterface)
{
c.s.r.VTableRequestor.Request(ms.type);
// load interface map
stack_after = ldc(n, c, stack_after, c.t.psize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, ir.Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ms.m.SystemIntPtr);
// iterate through interface map looking for requested interface
var t1 = c.next_mclabel--;
var t2 = c.next_mclabel--;
var t3 = c.next_mclabel--;
stack_after = mclabel(n, c, stack_after, t1);
stack_after = copy_to_front(n, c, stack_after);
// dereference ifacemap pointer
stack_after = ldind(n, c, stack_after, ms.m.SystemIntPtr);
// first check if it is null
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, 0, 0x18);
stack_after = brif(n, c, stack_after, Opcode.cc_ne, t2);
var t2_stack_in = new Stack<StackItem>(stack_after);
// if it is, throw missing method exception
// break point first
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_break, stack_before = stack_after, stack_after = stack_after });
stack_after = pop(n, c, stack_after);
stack_after = pop(n, c, stack_after);
var corlib = ms.m.al.GetAssembly("mscorlib");
stack_after = ldstr(n, c, stack_before, ms.MangleMethod());
stack_after = newobj(n, c, stack_after,
corlib.GetMethodSpec(corlib.GetTypeSpec("System", "MissingMethodException"), ".ctor",
c.special_meths.inst_Rv_s, c.special_meths));
stack_after = throw_(n, c, stack_after);
// it is not null at this point, check against the search string
stack_after = mclabel(n, c, t2_stack_in, t2);
stack_after = ldlab(n, c, stack_after, ms.type.MangleType());
stack_after = brif(n, c, stack_after, Opcode.cc_eq, t3);
var t3_stack_in = new Stack<StackItem>(stack_after);
// it is not the correct interface at this point, so increment ifacemapptr by 2
stack_after = ldc(n, c, stack_after, c.t.psize * 2, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = br(n, c, stack_after, t1);
// it is the correct interface, get the implementation of it (at offset +1)
stack_after = mclabel(n, c, t3_stack_in, t3);
stack_after = ldc(n, c, stack_after, c.t.psize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ms.m.SystemIntPtr);
}
// get the correct method within the current vtable/interface implementation
stack_after = ldc(n, c, stack_after, l, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemIntPtr);
stack_after.Peek().ms = ms;
return stack_after;
}
private static Stack<StackItem> mclabel(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = ir.Opcode.oc_mclabel, imm_l = v, stack_after = stack_before, stack_before = stack_before });
return stack_before;
}
private static Stack<StackItem> copy_this_to_front(CilNode n, Code c, Stack<StackItem> stack_before)
{
var ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
uint sig_idx = ms.m.GetIntEntry(MetadataStream.tid_MethodDef, ms.mdrow,
4);
var pc = ms.m.GetMethodDefSigParamCountIncludeThis((int)sig_idx);
var stack_after = copy_to_front(n, c, stack_before, pc - 1);
return stack_after;
}
static Stack<StackItem> stackcopy(CilNode n, Code c, Stack<StackItem> stack_before, int src, int dest)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = stack_before.Peek(src);
stack_after[stack_after.Count - 1 - dest] = si.Clone();
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, ct = Opcode.GetCTFromType(si.ts), vt_size = c.t.GetSize(si.ts), arg_a = src, res_a = dest, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> copy_to_front(CilNode n, Code c, Stack<StackItem> stack_before, int v = 0)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = stack_before.Peek(v);
var sidest = si.Clone();
stack_after.Push(sidest);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, ct = Opcode.GetCTFromType(si.ts), vt_size = c.t.GetSize(si.ts), arg_a = v, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
internal static Stack<StackItem> ldarg(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = new StackItem();
var ts = c.la_types[v];
si.ts = ts;
stack_after.Push(si);
var vt_size = c.t.GetSize(ts);
var ct = Opcode.GetCTFromType(ts);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldarg, ct = ct, vt_size = vt_size, imm_l = v, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> starg(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
var ts = c.la_types[v];
var vt_size = c.t.GetSize(ts);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_starg, ct = ir.Opcode.GetCTFromType(ts), vt_size = vt_size, imm_l = v, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> ldarga(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = new StackItem();
var ts = c.la_types[v];
ts = new TypeSpec { m = ts.m, stype = TypeSpec.SpecialType.MPtr, other = ts };
si.ts = ts;
stack_after.Push(si);
var vt_size = c.t.GetSize(ts);
var ct = Opcode.GetCTFromType(ts);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldarga, ct = ct, vt_size = vt_size, imm_l = v, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> ldloca(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = new StackItem();
var ts = c.lv_types[v];
ts = new TypeSpec { m = ts.m, stype = TypeSpec.SpecialType.MPtr, other = ts };
si.ts = ts;
stack_after.Push(si);
var vt_size = c.t.GetSize(ts);
var ct = Opcode.GetCTFromType(ts);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldloca, ct = ct, vt_size = vt_size, imm_l = v, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
internal static Stack<StackItem> stind(CilNode n, Code c, Stack<StackItem> stack_before, int vt_size, int val = 0, int addr = 1)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var st_src = stack_after.Peek(val);
var st_dest = stack_after.Peek(addr);
if ((addr == 0 && val == 1) || (addr == 1 && val == 0))
{
stack_after.Pop();
stack_after.Pop();
}
else if (addr == 0 || val == 0)
stack_after.Pop();
var ct_dest = st_dest.ct;
ulong is_tls = 0;
switch(ct_dest)
{
case Opcode.ct_intptr:
case Opcode.ct_ref:
break;
case Opcode.ct_tls_intptr:
is_tls = 1;
break;
default:
throw new Exception("Cannot perform " + n.opcode.ToString() + " to address type " + Opcode.ct_names[ct_dest]);
}
var ct_src = st_src.ct;
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stind, ct = ir.Opcode.ct_intptr, ct2 = ct_src, ctret = ir.Opcode.ct_unknown, imm_ul = is_tls, vt_size = vt_size, stack_before = stack_before, stack_after = stack_after, arg_a = addr, arg_b = val });
return stack_after;
}
private static Stack<StackItem> conv(CilNode n, Code c, Stack<StackItem> stack_before, int to_stype, bool is_ovf = false, bool is_un = false)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var st = stack_after.Pop();
var ct = st.ct;
var to_ct = Opcode.GetCTFromType(to_stype);
if (!conv_op_valid(ct, to_stype))
throw new Exception("Cannot perform " + n.opcode.ToString() + " with " + Opcode.ct_names[ct]);
StackItem si = new StackItem();
si.ts = c.ms.m.GetSimpleTypeSpec(to_stype);
stack_after.Push(si);
long imm = 0;
if (is_un)
imm |= 1;
if (is_ovf)
imm |= 2;
if(Opcode.IsTLSCT(ct))
{
ct = Opcode.UnTLSCT(ct);
si._ct = Opcode.TLSCT(ct);
}
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_conv, imm_l = imm, ct = ct, ctret = to_ct, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static bool conv_op_valid(int ct, int to_stype)
{
switch(ct)
{
case Opcode.ct_int32:
case Opcode.ct_int64:
case Opcode.ct_intptr:
case Opcode.ct_float:
case Opcode.ct_tls_intptr:
case Opcode.ct_tls_int32:
case Opcode.ct_tls_int64:
return true;
case Opcode.ct_ref:
case Opcode.ct_object:
switch(to_stype)
{
case 0x0a:
case 0x0b:
case 0x18:
case 0x19:
return true;
default:
return false;
}
default:
return false;
}
}
public static Stack<StackItem> call(CilNode n, Code c, Stack<StackItem> stack_before, bool is_calli = false, string override_name = null, MetadataStream override_m = null, int override_msig = 0,
int calli_ftn = 0, MethodSpec override_ms = null)
{
if (calli_ftn != 0)
throw new NotImplementedException();
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
MetadataStream m;
string mangled_meth;
int sig_idx;
MethodSpec ms;
bool is_reinterpret_as = false;
if(override_ms != null)
{
m = override_ms.m;
mangled_meth = override_ms.MangleMethod();
sig_idx = override_ms.msig;
ms = override_ms;
}
else if (override_name != null)
{
m = override_m;
mangled_meth = override_name;
sig_idx = override_msig;
ms = new MethodSpec { m = m, msig = sig_idx, mangle_override = override_name };
}
else
{
ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
m = ms.m;
mangled_meth = c.ms.m.MangleMethod(ms);
if (ms.mdrow != 0)
{
sig_idx = (int)ms.m.GetIntEntry(MetadataStream.tid_MethodDef, ms.mdrow,
4);
}
else
sig_idx = ms.msig;
if (ms.HasCustomAttribute("_ZN14libsupcs#2Edll8libsupcs28ReinterpretAsMethodAttribute_7#2Ector_Rv_P1u1t"))
{
// This is a 'Reinterpret As' method - handle accordingly
is_reinterpret_as = true;
if (is_calli)
throw new Exception("calli/callvirt to ReinterpretAs method");
}
else
{
intcall_delegate intcall;
/* mangle a non-generic version of the function to support generic method intcalls */
string ic_mangled_meth = mangled_meth;
if(ms.IsInstantiatedGenericMethod)
{
var non_g_ms = new metadata.MethodSpec { type = ms.type, gmparams = null, m = ms.m, mdrow = ms.mdrow, msig = ms.msig };
ic_mangled_meth = non_g_ms.m.MangleMethod(non_g_ms);
}
if (is_calli == false && intcalls.TryGetValue(ic_mangled_meth, out intcall))
{
var r = intcall(n, c, stack_before);
if (r != null)
return r;
}
var ca_mra = ms.GetCustomAttribute("_ZN14libsupcs#2Edll8libsupcs29MethodReferenceAliasAttribute_7#2Ector_Rv_P2u1tu1S");
if(ca_mra != -1)
{
// This is a call to a method that has a different name
int val_idx = (int)m.GetIntEntry(MetadataStream.tid_CustomAttribute,
ca_mra, 2);
m.SigReadUSCompressed(ref val_idx);
var prolog = m.sh_blob.di.ReadUShort(val_idx);
if (prolog == 0x0001)
{
val_idx += 2;
var str_len = m.SigReadUSCompressed(ref val_idx);
StringBuilder sb = new StringBuilder();
for (uint i = 0; i < str_len; i++)
{
sb.Append((char)m.sh_blob.di.ReadByte(val_idx++));
}
mangled_meth = sb.ToString();
ms = new MethodSpec { m = ms.m, msig = ms.msig, gmparams = ms.gmparams, mdrow = ms.mdrow, mangle_override = mangled_meth, type = ms.type };
}
}
c.s.r.MethodRequestor.Request(ms);
}
}
int imm_l = ms.IsAlwaysInvoke ? 1 : 0;
var pc = m.GetMethodDefSigParamCountIncludeThis((int)sig_idx);
var rt_idx = m.GetMethodDefSigRetTypeIndex((int)sig_idx);
var rt = m.GetTypeSpec(ref rt_idx, ms.gtparams, ms.gmparams);
if(is_reinterpret_as)
{
// Handle specially
var popped_st = stack_after.Pop();
var new_st = popped_st.Clone();
new_st.ts = rt;
stack_after.Push(new_st);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, arg_a = 0, res_a = 0, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
while (pc-- > 0)
stack_after.Pop();
if (is_calli)
stack_after.Pop();
int ct = Opcode.ct_unknown;
if(rt != null)
{
StackItem r = new StackItem();
r.ts = rt;
stack_after.Push(r);
ct = Opcode.GetCTFromType(rt);
}
int oc = Opcode.oc_call;
if (is_calli)
oc = Opcode.oc_calli;
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = oc, imm_ms = ms, imm_l = imm_l, ct = ct, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
public static Stack<StackItem> ldstr(CilNode n, Code c, Stack<StackItem> stack_before,
string str = null)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
if (str == null)
{
var tok = n.inline_uint;
if ((tok & 0x70000000) != 0x70000000)
throw new Exception("Invalid string token");
str = c.ms.m.GetUserString((int)(tok & 0x00ffffffUL));
}
var str_addr = c.s.st.GetStringAddress(str, c.t);
var st_name = c.s.st.GetStringTableName();
StackItem si = new StackItem();
si.ts = c.ms.m.GetSimpleTypeSpec(0x0e);
si.str_val = str;
stack_after.Push(si);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldlabaddr, ct = Opcode.ct_object, imm_l = str_addr, imm_lab = st_name, stack_after = stack_after, stack_before = stack_before });
return stack_after;
}
private static Stack<StackItem> brif(CilNode n, Code c, Stack<StackItem> stack_before, int cc, int target = int.MaxValue)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
if (target == int.MaxValue)
target = n.il_offsets_after[1];
var si_b = stack_after.Pop();
var si_a = stack_after.Pop();
var ct_a = si_a.ct;
var ct_b = si_b.ct;
if (!bin_comp_valid(ct_a, ct_b, cc, false))
throw new Exception("Invalid comparison between " + Opcode.ct_names[ct_a] + " and " + Opcode.ct_names[ct_b]);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_brif, imm_l = target, imm_ul = (uint)cc, ct = ct_a, ct2 = ct_b, stack_after = stack_after, stack_before = stack_before, arg_a = 1, arg_b = 0 });
return stack_after;
}
private static Stack<StackItem> cmp(CilNode n, Code c, Stack<StackItem> stack_before, int cc)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si_b = stack_after.Pop();
var si_a = stack_after.Pop();
var ct_a = si_a.ct;
var ct_b = si_b.ct;
if (!bin_comp_valid(ct_a, ct_b, cc, true))
throw new Exception("Invalid comparison between " + Opcode.ct_names[ct_a] + " and " + Opcode.ct_names[ct_b]);
var si = new StackItem();
TypeSpec ts = c.ms.m.GetSimpleTypeSpec(0x8);
si.ts = ts;
stack_after.Push(si);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_cmp, ct = ct_a, ct2 = ct_b, ctret = Opcode.ct_unknown, imm_ul = (uint)cc, stack_after = stack_after, stack_before = stack_before, arg_a = 1, arg_b = 0 });
return stack_after;
}
private static Stack<StackItem> unnumop(CilNode n, Code c,
Stack<StackItem> stack_before,
cil.Opcode.SingleOpcodes oc)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
var si_a = stack_before.Peek();
var ct_a = si_a.ct;
var ct_ret = un_op_valid(ct_a, oc);
if (ct_ret == Opcode.ct_unknown)
throw new Exception("Invalid unary operation on " + Opcode.ct_names[ct_a]);
StackItem si = new StackItem();
si._ct = ct_ret;
switch (ct_ret)
{
case Opcode.ct_int32:
si.ts = c.ms.m.GetSimpleTypeSpec(0x8);
break;
case Opcode.ct_int64:
si.ts = c.ms.m.GetSimpleTypeSpec(0xa);
break;
case Opcode.ct_intptr:
si.ts = c.ms.m.GetSimpleTypeSpec(0x18);
break;
case Opcode.ct_float:
si.ts = c.ms.m.GetSimpleTypeSpec(0xd);
break;
case Opcode.ct_object:
si.ts = c.ms.m.GetSimpleTypeSpec(0x1c);
break;
}
stack_after.Push(si);
int noc = 0;
switch(oc)
{
case cil.Opcode.SingleOpcodes.neg:
noc = Opcode.oc_neg;
break;
case cil.Opcode.SingleOpcodes.not:
noc = Opcode.oc_not;
break;
default:
throw new NotImplementedException();
}
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = noc, ct = ct_a, ctret = ct_ret, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static int un_op_valid(int ct, cil.Opcode.SingleOpcodes oc)
{
switch(ct)
{
case Opcode.ct_int32:
case Opcode.ct_int64:
case Opcode.ct_intptr:
return ct;
case Opcode.ct_float:
if (oc == cil.Opcode.SingleOpcodes.neg)
return ct;
else
return Opcode.ct_unknown;
default:
return Opcode.ct_unknown;
}
}
internal static Stack<StackItem> binnumop(CilNode n, Code c, Stack<StackItem> stack_before, cil.Opcode.SingleOpcodes oc,
int ct_ret = Opcode.ct_unknown,
int src_a = -1, int src_b = -1, int res_a = -1)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
if(src_a == -1)
{
stack_after.Pop();
if (src_b == -1)
src_a = 1;
else
src_a = 0;
}
if(src_b == -1)
{
stack_after.Pop();
src_b = 0;
}
var si_b = stack_before.Peek(src_b);
var si_a = stack_before.Peek(src_a);
var ct_a = si_a.ct;
var ct_b = si_b.ct;
if (ct_ret == Opcode.ct_unknown)
{
ct_ret = bin_op_valid(ct_a, ct_b, oc);
if (ct_ret == Opcode.ct_unknown)
throw new Exception("Invalid binary operation between " + Opcode.ct_names[ct_a] + " and " + Opcode.ct_names[ct_b]);
}
bool is_un = false;
bool is_ovf = false;
switch(oc)
{
case cil.Opcode.SingleOpcodes.add_ovf:
is_ovf = true;
break;
case cil.Opcode.SingleOpcodes.add_ovf_un:
is_ovf = true;
is_un = true;
break;
case cil.Opcode.SingleOpcodes.sub_ovf:
is_ovf = true;
break;
case cil.Opcode.SingleOpcodes.sub_ovf_un:
is_ovf = true;
is_un = true;
break;
case cil.Opcode.SingleOpcodes.mul_ovf:
is_ovf = true;
break;
case cil.Opcode.SingleOpcodes.mul_ovf_un:
is_ovf = true;
is_un = true;
break;
case cil.Opcode.SingleOpcodes.div_un:
is_un = true;
break;
case cil.Opcode.SingleOpcodes.rem_un:
is_un = true;
break;
}
long imm = 0;
if (is_un)
imm |= 1;
if (is_ovf)
imm |= 2;
StackItem si = new StackItem();
si._ct = ct_ret;
switch(ct_ret)
{
case Opcode.ct_int32:
si.ts = c.ms.m.GetSimpleTypeSpec(0x8);
break;
case Opcode.ct_int64:
si.ts = c.ms.m.GetSimpleTypeSpec(0xa);
break;
case Opcode.ct_intptr:
si.ts = c.ms.m.GetSimpleTypeSpec(0x18);
break;
case Opcode.ct_float:
si.ts = c.ms.m.GetSimpleTypeSpec(0xd);
break;
case Opcode.ct_object:
si.ts = c.ms.m.GetSimpleTypeSpec(0x1c);
break;
}
if (res_a == -1)
{
stack_after.Push(si);
res_a = 0;
}
else
{
stack_after[stack_after.Count - 1 - res_a] = si;
}
int noc = 0;
switch(oc)
{
case cil.Opcode.SingleOpcodes.add:
case cil.Opcode.SingleOpcodes.add_ovf:
case cil.Opcode.SingleOpcodes.add_ovf_un:
noc = Opcode.oc_add;
break;
case cil.Opcode.SingleOpcodes.sub:
case cil.Opcode.SingleOpcodes.sub_ovf:
case cil.Opcode.SingleOpcodes.sub_ovf_un:
noc = Opcode.oc_sub;
break;
case cil.Opcode.SingleOpcodes.mul:
case cil.Opcode.SingleOpcodes.mul_ovf:
case cil.Opcode.SingleOpcodes.mul_ovf_un:
noc = Opcode.oc_mul;
break;
case cil.Opcode.SingleOpcodes.div:
case cil.Opcode.SingleOpcodes.div_un:
noc = Opcode.oc_div;
break;
case cil.Opcode.SingleOpcodes.rem:
case cil.Opcode.SingleOpcodes.rem_un:
noc = Opcode.oc_rem;
break;
case cil.Opcode.SingleOpcodes.and:
noc = Opcode.oc_and;
break;
case cil.Opcode.SingleOpcodes.or:
noc = Opcode.oc_or;
break;
case cil.Opcode.SingleOpcodes.xor:
noc = Opcode.oc_xor;
break;
}
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = noc, ct = ct_a, ct2 = ct_b, stack_before = stack_before, stack_after = stack_after, arg_a = src_a, arg_b = src_b, res_a = res_a });
return stack_after;
}
private static int bin_op_valid(int ct_a, int ct_b, cil.Opcode.SingleOpcodes oc)
{
if (oc == cil.Opcode.SingleOpcodes.and ||
oc == cil.Opcode.SingleOpcodes.or ||
oc == cil.Opcode.SingleOpcodes.xor)
return int_op_valid(ct_a, ct_b, oc);
switch(ct_a)
{
case Opcode.ct_int32:
switch(ct_b)
{
case Opcode.ct_int32:
return Opcode.ct_int32;
case Opcode.ct_intptr:
return Opcode.ct_intptr;
case Opcode.ct_ref:
if (oc == cil.Opcode.SingleOpcodes.add)
return Opcode.ct_ref;
break;
}
return Opcode.ct_unknown;
case Opcode.ct_int64:
if (ct_b == Opcode.ct_int64)
return Opcode.ct_int64;
break;
case Opcode.ct_intptr:
switch (ct_b)
{
case Opcode.ct_int32:
return Opcode.ct_intptr;
case Opcode.ct_intptr:
return Opcode.ct_intptr;
case Opcode.ct_ref:
if (oc == cil.Opcode.SingleOpcodes.add)
return Opcode.ct_ref;
break;
}
return Opcode.ct_unknown;
case Opcode.ct_float:
if (ct_b == Opcode.ct_float)
return Opcode.ct_float;
return Opcode.ct_unknown;
case Opcode.ct_ref:
switch(ct_b)
{
case Opcode.ct_int32:
case Opcode.ct_intptr:
switch(oc)
{
case cil.Opcode.SingleOpcodes.add:
case cil.Opcode.SingleOpcodes.sub:
return Opcode.ct_ref;
}
break;
case Opcode.ct_ref:
if (oc == cil.Opcode.SingleOpcodes.sub)
return Opcode.ct_intptr;
break;
}
break;
}
return Opcode.ct_unknown;
}
private static int int_op_valid(int ct_a, int ct_b, cil.Opcode.SingleOpcodes oc)
{
switch (ct_a)
{
case Opcode.ct_int32:
case Opcode.ct_intptr:
switch (ct_b)
{
case Opcode.ct_int32:
return Opcode.ct_int32;
case Opcode.ct_intptr:
return Opcode.ct_intptr;
}
break;
case Opcode.ct_int64:
if (ct_b == Opcode.ct_int64)
return Opcode.ct_int64;
break;
}
return Opcode.ct_unknown;
}
private static bool bin_comp_valid(int ct_a, int ct_b, int cc, bool is_cmp)
{
switch(ct_a)
{
case Opcode.ct_int32:
switch(ct_b)
{
case Opcode.ct_int32:
return true;
case Opcode.ct_intptr:
return true;
}
return false;
case Opcode.ct_int64:
switch(ct_b)
{
case Opcode.ct_int64:
return true;
}
return false;
case Opcode.ct_intptr:
switch (ct_b)
{
case Opcode.ct_int32:
return true;
case Opcode.ct_intptr:
return true;
case Opcode.ct_ref:
if (!is_cmp &&
(cc == Opcode.cc_eq || cc == Opcode.cc_ne))
return true;
if (is_cmp &&
(cc == Opcode.cc_eq))
return true;
return false;
}
return false;
case Opcode.ct_float:
return ct_b == Opcode.ct_float;
case Opcode.ct_ref:
switch (ct_b)
{
case Opcode.ct_intptr:
if (!is_cmp &&
(cc == Opcode.cc_eq || cc == Opcode.cc_ne))
return true;
if (is_cmp &&
(cc == Opcode.cc_eq))
return true;
return false;
case Opcode.ct_ref:
return true;
}
return false;
case Opcode.ct_object:
if (ct_b != Opcode.ct_object)
return false;
if (is_cmp &&
(cc == Opcode.cc_eq || cc == Opcode.cc_a))
return true;
if (!is_cmp &&
(cc == Opcode.cc_eq || cc == Opcode.cc_ne))
return true;
return false;
}
return false;
}
private static Stack<StackItem> ldloc(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = new StackItem();
var ts = c.lv_types[v];
si.ts = ts;
stack_after.Push(si);
var vt_size = c.t.GetSize(ts);
var ct = Opcode.GetCTFromType(ts);
if (stack_before.lv_tls_addrs[v])
{
switch(si.ct)
{
case Opcode.ct_ref:
case Opcode.ct_intptr:
si._ct = Opcode.ct_tls_intptr;
break;
case Opcode.ct_int32:
si._ct = Opcode.ct_tls_int32;
break;
case Opcode.ct_int64:
si._ct = Opcode.ct_tls_int64;
break;
default:
throw new NotSupportedException();
}
}
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldloc, ctret = ct, vt_size = vt_size, imm_l = v, imm_ul = ts.IsSigned ? 1UL : 0UL, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> stloc(CilNode n, Code c, Stack<StackItem> stack_before, int v)
{
Stack<StackItem> stack_after = new Stack<StackItem>(stack_before);
var si = stack_after.Pop();
var ts = si.ts;
var to_ts = c.lv_types[v];
// TODO: ensure top of stack can be assigned to lv
if(si._ct == Opcode.ct_tls_int32 || si._ct == Opcode.ct_tls_int64 ||
si._ct == Opcode.ct_tls_intptr)
{
// we need to mark the current lv entry as being a pointer to a TLS object
stack_after.lv_tls_addrs[v] = true;
}
var vt_size = c.t.GetSize(ts);
var ct = Opcode.GetCTFromType(ts);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stloc, ct = ct, ctret = Opcode.ct_unknown, vt_size = vt_size, imm_l = v, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class InsertStringAction : IConsoleAction
{
private readonly string _string;
public InsertStringAction(string str)
{
_string = str;
}
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (string.IsNullOrEmpty(_string))
return;
if (console.CurrentLine.Length >= byte.MaxValue - _string.Length)
return;
console.CurrentLine = console.CurrentLine.Insert(console.CursorPosition, _string);
console.CursorPosition += _string.Length;
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.target;
using libtysila5.util;
using metadata;
using libtysila5.ir;
using libtysila5.cil;
namespace libtysila5.ir
{
public partial class ConvertToIR
{
internal static Code CreateArrayCtor1(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
List<cil.CilNode.IRNode> ret = new List<cil.CilNode.IRNode>();
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Set elem type vtbl pointer
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.ElemTypeVtblPointer, t), 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ldlab(n, c, stack_before, ms.type.other.MangleType());
s.r.VTableRequestor.Request(ms.type.other.Box);
stack_before = stind(n, c, stack_before, t.GetPointerSize());
// Set lobounds array and pointer
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.LoboundsPointer, t), 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ldc(n, c, stack_before, t.GetSize(ms.m.SystemInt32) * ms.type.arr_rank);
stack_before = call(n, c, stack_before, false, "gcmalloc", c.special_meths, c.special_meths.gcmalloc);
for (int i = 0; i < ms.type.arr_rank; i++)
{
stack_before = copy_to_front(n, c, stack_before);
if (i != 0)
{
stack_before = ldc(n, c, stack_before, t.GetSize(ms.m.SystemInt32) * i, 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
}
stack_before = ldc(n, c, stack_before, 0); // lobounds implied to be 0
stack_before = stind(n, c, stack_before, t.GetSize(ms.m.SystemInt32));
}
stack_before = stind(n, c, stack_before, t.GetPointerSize());
// Set sizes array and pointer
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.SizesPointer, t), 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ldc(n, c, stack_before, t.GetSize(ms.m.SystemInt32) * ms.type.arr_rank);
stack_before = call(n, c, stack_before, false, "gcmalloc", c.special_meths, c.special_meths.gcmalloc);
for (int i = 0; i < ms.type.arr_rank; i++)
{
stack_before = copy_to_front(n, c, stack_before);
if (i != 0)
{
stack_before = ldc(n, c, stack_before, t.GetSize(ms.m.SystemInt32) * i, 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
}
stack_before = ldarg(n, c, stack_before, 1 + i);
stack_before = stind(n, c, stack_before, t.GetSize(ms.m.SystemInt32));
}
stack_before = stind(n, c, stack_before, t.GetPointerSize());
// Set data array pointer
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, t), 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
if (ms.type.arr_rank == 0)
stack_before = ldc(n, c, stack_before, 0);
else
stack_before = ldarg(n, c, stack_before, 1); // don't need to subtract lobounds for ctor1
for (int i = 1; i < ms.type.arr_rank; i++)
{
stack_before = ldarg(n, c, stack_before, 1 + i); // load size
// don't need to subtract lobounds here
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.mul);
}
var et_size = t.GetSize(ms.type.other);
if (et_size > 1)
{
stack_before = ldc(n, c, stack_before, et_size);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.mul);
}
stack_before = call(n, c, stack_before, false, "gcmalloc", c.special_meths, c.special_meths.gcmalloc);
stack_before = stind(n, c, stack_before, t.GetPointerSize());
// Set Rank
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.Rank, t), 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ldc(n, c, stack_before, ms.type.arr_rank);
stack_before = stind(n, c, stack_before, t.GetSize(ms.m.SystemInt32));
// Set Elem Size
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.ElemTypeSize, t), 0x18);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ldc(n, c, stack_before, et_size);
stack_before = stind(n, c, stack_before, t.GetSize(ms.m.SystemInt32));
// Ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateArrayCtor2(MethodSpec ms,
Target t, TysilaState s)
{
throw new NotImplementedException();
}
internal static Code CreateArrayAddress(MethodSpec ms,
Target t, TysilaState s)
{
throw new NotImplementedException();
}
internal static Code CreateArraySet(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
// Returns void
c.ret_ts = ms.m.SystemVoid;
// Get array item type
var given_type = c.la_types[c.la_types.Length - 1];
if (!given_type.Equals(ms.type.other))
{
throw new Exception("Array Set given type not the same as element type");
}
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Get offset to the data item
stack_before = ArrayGetDataItemPtr(n, c, stack_before, ms);
// Load given value and store to the address
stack_before = ldarg(n, c, stack_before, c.la_types.Length - 1);
stack_before = stind(n, c, stack_before, t.GetSize(given_type));
// Ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateArrayGet(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
if (!ret_ts.Equals(ms.type.other))
{
throw new Exception("Array Get return type not the same as element type");
}
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Get offset to the data item
stack_before = ArrayGetDataItemPtr(n, c, stack_before, ms);
// Load it
stack_before = ldind(n, c, stack_before, ret_ts);
// Ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ((ret_ts == null) ? ir.Opcode.ct_unknown : Opcode.GetCTFromType(ret_ts)), stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
private static util.Stack<StackItem> ArrayGetDataItemPtr(CilNode n, Code c, util.Stack<StackItem> stack_before, MethodSpec ms)
{
var t = c.t;
// Get array index
stack_before = ArrayGetIndex(c, n, ms, stack_before, t);
// Multiply by elem size
var esize = layout.Layout.GetTypeSize(ms.type.other, t);
if (esize > 1)
{
stack_before = ldc(n, c, stack_before, esize);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.mul, Opcode.ct_int32);
}
// Add data pointer address
stack_before = ldarg(n, c, stack_before, 0);
stack_before = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, t));
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ldind(n, c, stack_before, ms.m.SystemIntPtr);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
return stack_before;
}
private static util.Stack<StackItem> ArrayGetIndex(Code c, cil.CilNode n, MethodSpec ms, util.Stack<StackItem> stack_before, Target t)
{
/* For a rank 4 array this simplifies to:
*
* (r4-r4lb) + r4len[(r3-r3lb) + r3len[(r2-r2lb) + r2len[(r1-r1lb)]]]
*
* where len is the 'size' member and lb is the lobounds
*
* in ir:
*
* ldc r1
* sub r1lb
*
* mul r2len
* add r2
* sub r2lb
*
* mul r3len
* add r3
* sub r3lb
*
* mul r4len
* add r4
* sub r4lb
*
* and we can simplify lobounds/sizes lookups if we know them
*/
var stack_after = new util.Stack<StackItem>(stack_before);
// ldc r1
stack_after = ldarg(n, c, stack_after, 1);
// sub r1lb
bool lbzero, szone; // optimize away situation where lobounds is zero
stack_after = ArrayGetLobounds(n, c, stack_after, ms, 1, out lbzero);
if (!lbzero)
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.sub, ir.Opcode.ct_int32);
for (int rank = 2; rank <= ms.type.arr_rank; rank++)
{
// mul rnlen
stack_after = ArrayGetSize(n, c, stack_after, ms, rank, out szone);
if (!szone)
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_int32);
// add rn
stack_after = ldarg(n, c, stack_after, rank);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_int32);
// sub rnlb
stack_after = ArrayGetLobounds(n, c, stack_after, ms, rank, out lbzero);
if (!lbzero)
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.sub, ir.Opcode.ct_int32);
}
return stack_after;
}
private static util.Stack<StackItem> ArrayGetLobounds(CilNode n, Code c, util.Stack<StackItem> stack_before, MethodSpec ms, int rank,
out bool is_zero)
{
var stack_after = new util.Stack<StackItem>(stack_before);
is_zero = false;
var t = c.t;
// if we have the lobounds in the signature we can use that, else do a run-time lookup
if (ms.type.arr_lobounds != null &&
ms.type.arr_lobounds.Length >= rank)
{
var lb = ms.type.arr_lobounds[rank - 1];
if (lb == 0)
is_zero = true;
else
stack_after = ldc(n, c, stack_after, ms.type.arr_lobounds[rank - 1]);
}
else
{
// Load pointer to lobounds array
stack_after = ldarg(n, c, stack_after, 0);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.LoboundsPointer, t));
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ms.m.SystemIntPtr);
// it's a simple array of int32s, so size is 4
if (rank > 1)
{
stack_after = ldc(n, c, stack_after, 4 * (rank - 1), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
}
stack_after = ldind(n, c, stack_after, ms.m.SystemInt32);
}
return stack_after;
}
private static util.Stack<StackItem> ArrayGetSize(CilNode n, Code c, util.Stack<StackItem> stack_before, MethodSpec ms, int rank,
out bool isone)
{
var stack_after = new util.Stack<StackItem>(stack_before);
isone = false;
var t = c.t;
// if we have the size in the signature we can use that, else do a run-time lookup
if (ms.type.arr_sizes != null &&
ms.type.arr_sizes.Length >= rank)
{
var sz = ms.type.arr_sizes[rank - 1];
if (sz == 1)
isone = true;
else
stack_after = ldc(n, c, stack_after, ms.type.arr_sizes[rank - 1]);
}
else
{
// Load pointer to sizes array
stack_after = ldarg(n, c, stack_after, 0);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.SizesPointer, t));
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ms.m.SystemIntPtr);
// it's a simple array of int32s, so size is 4
if (rank > 1)
{
stack_after = ldc(n, c, stack_after, 4 * (rank - 1), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
}
stack_after = ldind(n, c, stack_after, ms.m.SystemInt32);
}
return stack_after;
}
internal static Code CreateVectorIndexOf(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// break
var stack_after = debugger_Break(n, c, stack_before);
// load 0
stack_after = ldc(n, c, stack_after, 0);
// ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateVectorInsert(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// break
var stack_after = debugger_Break(n, c, stack_before);
// ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateVectorRemoveAt(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// break
var stack_after = debugger_Break(n, c, stack_before);
// ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateVectorCopyTo(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// We call a libsupcs method here that expects arguments in the order
// srcInnerArr, dstArr, startIndex (in dstArr), count
var stack_after = ldarg(n, c, stack_before, 0);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t));
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, ms.m.SystemIntPtr);
stack_after = ldarg(n, c, stack_after, 1);
stack_after = ldarg(n, c, stack_after, 2);
stack_after = ldarg(n, c, stack_after, 0);
stack_after = ldlen(n, c, stack_after);
//stack_after = ldarg(n, c, stack_after, 2);
//stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.sub, Opcode.ct_int32);
//stack_after = debugger_Break(n, c, stack_after);
stack_after = call(n, c, stack_after, false,
"_ZW34System#2ERuntime#2EInteropServices7Marshal_13CopyToManaged_Rv_P4u1Iu1Oii",
c.special_meths, c.special_meths.array_copyToManaged);
// ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_after, stack_after = stack_after });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateVectorget_Count(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// ldarg, ldlen
var stack_after = ldarg(n, c, stack_before, 0);
stack_after = ldlen(n, c, stack_after);
// ret
var stack_after2 = new util.Stack<StackItem>(stack_after);
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_int32, stack_before = stack_after, stack_after = stack_after2 });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
/*internal static Code CreateVectorGetEnumerator(MethodSpec ms,
Target t)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
}
*/
internal static Code CreateVectorget_Item(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
// implement with ldelem
var stack_after = ldarg(n, c, stack_before, 0);
stack_after = ldarg(n, c, stack_after, 1);
stack_after = ldelem(n, c, stack_after, ms.type.other);
// ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateVectorset_Item(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// break
var stack_after = debugger_Break(n, c, stack_before);
// ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ir.Opcode.ct_unknown, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
internal static Code CreateVectorUnimplemented(MethodSpec ms,
Target t, TysilaState s)
{
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// Get return type
var sig_idx = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
c.ret_ts = ret_ts;
// enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// break
var stack_after = debugger_Break(n, c, stack_before);
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
return c;
}
}
}<file_sep>/* Copyright (C) 2014 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
/* System.Buffer internal calls */
namespace libsupcs
{
class Buffer
{
[MethodAlias("_ZW6System6Buffer_17BlockCopyInternal_Rb_P5V5ArrayiV5Arrayii")]
static unsafe bool BlockCopyInternal(byte* src, int srcOffset, byte* dest, int destOffset,
int count)
{
/* Return false on overflow within src or dest */
int srcElemSize = *(int*)(src + ArrayOperations.GetElemSizeOffset());
//int srcIALength = *(int*)(src + ArrayOperations.GetInnerArrayLengthOffset());
int srcIALength = 0;
throw new NotImplementedException();
int srcByteSize = srcElemSize * srcIALength;
if ((srcOffset + count) > srcByteSize)
return false;
int destElemSize = *(int *)(dest + ArrayOperations.GetElemSizeOffset());
//int destIALength = *(int*)(dest + ArrayOperations.GetInnerArrayLengthOffset());
int destIALength = 0;
int destByteSize = destElemSize * destIALength;
if ((destOffset + count) > destByteSize)
return false;
/* Get source and dest addresses */
byte* srcAddr = *(byte**)(src + ArrayOperations.GetInnerArrayOffset()) + srcOffset;
byte* destAddr = *(byte**)(dest + ArrayOperations.GetInnerArrayOffset()) + destOffset;
/* Execute a memmove */
MemoryOperations.MemMove((void*)destAddr, (void*)srcAddr, count);
return true;
}
[MethodAlias("_ZW6System6Buffer_18ByteLengthInternal_Ri_P1V5Array")]
static unsafe int ByteLengthInternal(byte* arr)
{
int elemSize = *(int*)(arr + ArrayOperations.GetElemSizeOffset());
//int iaLength = *(int*)(arr + ArrayOperations.GetInnerArrayLengthOffset());
throw new NotImplementedException();
//return elemSize * iaLength;
}
}
}
<file_sep>/* Copyright (C) 2008 - 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.target;
using metadata;
namespace libtysila5
{
public class SignatureTable
{
public string GetStringTableName()
{
return Label;
}
Dictionary<object, binary_library.ISymbol> st_cache =
new Dictionary<object, binary_library.ISymbol>(
new GenericEqualityComparerRef<object>());
public int GetSignatureAddress(IEnumerable<byte> sig, target.Target t, TysilaState s)
{
var ptr_size = t.GetCTSize(ir.Opcode.ct_object);
while (str_tab.Count % ptr_size != 0)
str_tab.Add(0);
int ret = str_tab.Count;
foreach (byte b in sig)
str_tab.Add(b);
return ret;
}
public int GetSignatureAddress(metadata.TypeSpec.FullySpecSignature sig, target.Target t, TysilaState s)
{
var ptr_size = t.GetCTSize(ir.Opcode.ct_object);
while (str_tab.Count % ptr_size != 0)
str_tab.Add(0);
int ret = str_tab.Count;
// first is type of signature
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes((int)sig.Type)));
// then any extra data if necessary
switch(sig.Type)
{
case metadata.Spec.FullySpecSignature.FSSType.Field:
// For fields with static data we insert it here
AddFieldSpecFields(sig.OriginalSpec as MethodSpec, str_tab, t, s);
break;
case Spec.FullySpecSignature.FSSType.Type:
AddTypeSpecFields(sig.OriginalSpec as TypeSpec, str_tab, t, s);
break;
}
// then is length of module references
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes(sig.Modules.Count)));
// then module references
foreach(var mod in sig.Modules)
{
sig_metadata_addrs[str_tab.Count] = mod.AssemblyName;
for (int i = 0; i < ptr_size; i++)
str_tab.Add(0);
}
// then signature
str_tab.AddRange(sig.Signature);
return ret;
}
private void AddTypeSpecFields(TypeSpec ts, List<byte> str_tab, Target t, TysilaState s)
{
/* For types we add four special fields:
*
* First: If this is an enum, its a pointer to the vtable for the underlying type
* If it is a zero-based array, its a pointer to the vtable for the element type
* If its a boxed value type, its the size of the value type
* Else zero if non-generic type, -1 if generic definition, -2 if instantiated
*
* Second special field is initialized to zero, and is used at runtime
* to hold the pointer to the System.Type instance
*
* Third is a pointer to the static class constructor (.cctor) if any - this is
* used to implement System.Runtime.CompilerServices.RunClassConstructor(vtbl)
*
* Fourth is a flag field (TypeAttributes from metadata)
*/
if (ts.Unbox.IsEnum)
{
var ut = ts.Unbox.UnderlyingType;
sig_metadata_addrs[str_tab.Count] = ut.MangleType();
for (int i = 0; i < t.psize; i++)
str_tab.Add(0);
}
else if (ts.IsBoxed && !ts.Unbox.IsGenericTemplate)
{
var vt_size = layout.Layout.GetTypeSize(ts.Unbox, t);
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes(vt_size)));
}
else if (ts.stype == TypeSpec.SpecialType.SzArray)
{
sig_metadata_addrs[str_tab.Count] = ts.other.MangleType();
for (int i = 0; i < t.psize; i++)
str_tab.Add(0);
}
else if (ts.IsGenericTemplate)
{
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes(-1L)));
}
else if(ts.IsGeneric)
{
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes(-2L)));
}
else
{
for (int i = 0; i < t.psize; i++)
str_tab.Add(0);
}
// 2nd field
for (int i = 0; i < t.psize; i++)
str_tab.Add(0);
// 3rd field
if(ts.stype == TypeSpec.SpecialType.None && !ts.IsGenericTemplate)
{
var cctor = ts.m.GetMethodSpec(ts, ".cctor", 0, null, false);
if (cctor != null)
{
sig_metadata_addrs[str_tab.Count] = cctor.MangleMethod();
s.r.MethodRequestor.Request(cctor);
}
}
for (int i = 0; i < t.psize; i++)
str_tab.Add(0);
// 4th field - flags
var flags = ts.m.GetIntEntry(MetadataStream.tid_TypeDef, ts.tdrow, 0);
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes(flags)));
}
private void AddFieldSpecFields(MethodSpec fs, List<byte> str_tab, target.Target t, TysilaState s)
{
/* Field specs have two special fields:
*
* IntPtr field_size
* IntPtr field_data
*
* where field_data may be null if no .data member is specified for the field
*/
// read field signature to get the type of the field
var sig_idx = fs.msig;
sig_idx = fs.m.GetFieldSigTypeIndex(sig_idx);
var ts = fs.m.GetTypeSpec(ref sig_idx, fs.gtparams, null);
var fsize = t.GetSize(ts);
str_tab.AddRange(t.IntPtrArray(BitConverter.GetBytes(fsize)));
// now determine if the field has an rva associated with it
int rva_id = 0;
for(int i = 1; i <= fs.m.table_rows[MetadataStream.tid_FieldRVA]; i++)
{
var field_idx = fs.m.GetIntEntry(MetadataStream.tid_FieldRVA, i, 1);
if(field_idx == fs.mdrow)
{
rva_id = i;
break;
}
}
// rva id
if(rva_id != 0)
{
// TODO checks in CIL II 22.18
var rva = fs.m.GetIntEntry(MetadataStream.tid_FieldRVA, rva_id, 0);
var offset = fs.m.ResolveRVA(rva);
sig_metadata_addrs[str_tab.Count] = fs.m.AssemblyName;
sig_metadata_addends[str_tab.Count] = offset;
}
for (int i = 0; i < t.psize; i++)
str_tab.Add(0);
}
Dictionary<int, string> sig_metadata_addrs =
new Dictionary<int, string>(
new GenericEqualityComparer<int>());
Dictionary<int, long> sig_metadata_addends =
new Dictionary<int, long>(
new GenericEqualityComparer<int>());
List<byte> str_tab = new List<byte>();
private string Label;
public SignatureTable(string mod_name)
{
Label = mod_name + "_SignatureTable";
}
public void WriteToOutput(binary_library.IBinaryFile of,
metadata.MetadataStream ms, target.Target t,
binary_library.ISection rd = null)
{
if (str_tab.Count == 0)
return;
if(rd == null)
rd = of.GetRDataSection();
rd.Align(t.GetCTSize(ir.Opcode.ct_object));
var stab_lab = of.CreateSymbol();
stab_lab.Name = Label;
stab_lab.ObjectType = binary_library.SymbolObjectType.Object;
stab_lab.Offset = (ulong)rd.Data.Count;
stab_lab.Type = binary_library.SymbolType.Weak;
rd.AddSymbol(stab_lab);
int stab_base = rd.Data.Count;
foreach (byte b in str_tab)
rd.Data.Add(b);
foreach(var kvp in sig_metadata_addrs)
{
var reloc = of.CreateRelocation();
reloc.DefinedIn = rd;
reloc.Type = t.GetDataToDataReloc();
reloc.Addend = 0;
if (sig_metadata_addends.ContainsKey(kvp.Key))
reloc.Addend = sig_metadata_addends[kvp.Key];
var md_lab = of.CreateSymbol();
md_lab.Name = kvp.Value;
md_lab.ObjectType = binary_library.SymbolObjectType.Object;
reloc.References = md_lab;
reloc.Offset = (ulong)(kvp.Key + stab_base);
of.AddRelocation(reloc);
}
stab_lab.Size = rd.Data.Count - (int)stab_lab.Offset;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using ReadLine.Tests.Abstractions;
using Internal.ReadLine;
namespace ReadLine.Tests
{
public class KeyHandlerTests
{
private KeyHandler _keyHandler;
private ConsoleKeyInfo _keyInfo;
private List<string> _history;
private AutoCompleteHandler _autoCompleteHandler;
private string[] _completions;
private Internal.ReadLine.Abstractions.IConsole _console;
public KeyHandlerTests()
{
_autoCompleteHandler = new AutoCompleteHandler();
_completions = _autoCompleteHandler.GetSuggestions("", 0);
_history = new List<string>(new string[] { "dotnet run", "git init", "clear" });
_console = new Console2();
_keyHandler = new KeyHandler(_console, _history, null);
_keyInfo = new ConsoleKeyInfo('H', ConsoleKey.H, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('e', ConsoleKey.E, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('l', ConsoleKey.L, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('l', ConsoleKey.L, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('o', ConsoleKey.O, false, false, false);
_keyHandler.Handle(_keyInfo);
}
[Fact]
public void TestWriteChar()
{
Assert.Equal("Hello", _keyHandler.Text);
_keyInfo = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('W', ConsoleKey.W, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('o', ConsoleKey.O, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('r', ConsoleKey.R, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('l', ConsoleKey.L, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('d', ConsoleKey.D, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello World", _keyHandler.Text);
}
[Fact]
public void TestBackspace()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Backspace, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hell", _keyHandler.Text);
}
[Fact]
public void TestDelete()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Delete, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hell", _keyHandler.Text);
}
[Fact]
public void TestDelete_EndOfLine()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Delete, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello", _keyHandler.Text);
}
[Fact]
public void TestControlH()
{
_keyInfo = new ConsoleKeyInfo('H', ConsoleKey.H, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hell", _keyHandler.Text);
}
[Fact]
public void TestControlT()
{
var initialCursorCol = _console.CursorLeft;
var ctrlT = new ConsoleKeyInfo('\u0014', ConsoleKey.T, false, false, true);
_keyHandler.Handle(ctrlT);
Assert.Equal("Helol", _keyHandler.Text);
Assert.Equal(initialCursorCol, _console.CursorLeft);
}
[Fact]
public void TestControlT_LeftOnce_CursorMovesToEnd()
{
var initialCursorCol = _console.CursorLeft;
var leftArrow = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(leftArrow);
var ctrlT = new ConsoleKeyInfo('\u0014', ConsoleKey.T, false, false, true);
_keyHandler.Handle(ctrlT);
Assert.Equal("Helol", _keyHandler.Text);
Assert.Equal(initialCursorCol, _console.CursorLeft);
}
[Fact]
public void TestControlT_CursorInMiddleOfLine()
{
var leftArrow = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
Enumerable
.Repeat(leftArrow, 3)
.ToList()
.ForEach(_keyHandler.Handle);
var initialCursorCol = _console.CursorLeft;
var ctrlT = new ConsoleKeyInfo('\u0014', ConsoleKey.T, false, false, true);
_keyHandler.Handle(ctrlT);
Assert.Equal("Hlelo", _keyHandler.Text);
Assert.Equal(initialCursorCol + 1, _console.CursorLeft);
}
[Fact]
public void TestControlT_CursorAtBeginningOfLine_HasNoEffect()
{
var ctrlA = new ConsoleKeyInfo('\u0001', ConsoleKey.A, false, false, true);
_keyHandler.Handle(ctrlA);
var initialCursorCol = _console.CursorLeft;
var ctrlT = new ConsoleKeyInfo('\u0014', ConsoleKey.T, false, false, true);
_keyHandler.Handle(ctrlT);
Assert.Equal("Hello", _keyHandler.Text);
Assert.Equal(initialCursorCol, _console.CursorLeft);
}
[Fact]
public void TestHome()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Home, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('S', ConsoleKey.S, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("SHello", _keyHandler.Text);
}
[Fact]
public void TestControlA()
{
_keyInfo = new ConsoleKeyInfo('A', ConsoleKey.A, false, false, true);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('S', ConsoleKey.S, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("SHello", _keyHandler.Text);
}
[Fact]
public void TestEnd()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Home, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.End, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('!', ConsoleKey.D0, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello!", _keyHandler.Text);
}
[Fact]
public void TestControlE()
{
_keyInfo = new ConsoleKeyInfo('A', ConsoleKey.A, false, false, true);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('E', ConsoleKey.E, false, false, true);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('!', ConsoleKey.D0, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello!", _keyHandler.Text);
}
[Fact]
public void TestLeftArrow()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('N', ConsoleKey.N, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hell No", _keyHandler.Text);
}
[Fact]
public void TestControlB()
{
_keyInfo = new ConsoleKeyInfo('B', ConsoleKey.B, false, false, true);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('N', ConsoleKey.N, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hell No", _keyHandler.Text);
}
[Fact]
public void TestRightArrow()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.RightArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('!', ConsoleKey.D0, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello!", _keyHandler.Text);
}
[Fact]
public void TestControlD()
{
for (var i = 0; i < 4; i++)
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
}
_keyInfo = new ConsoleKeyInfo('\u0004', ConsoleKey.D, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hllo", _keyHandler.Text);
}
[Fact]
public void TestControlF()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('F', ConsoleKey.F, false, false, true);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('!', ConsoleKey.D0, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello!", _keyHandler.Text);
}
[Fact]
public void TestControlL()
{
_keyInfo = new ConsoleKeyInfo('L', ConsoleKey.L, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal(string.Empty, _keyHandler.Text);
}
[Fact]
public void TestUpArrow()
{
for (int i = _history.Count - 1; i >= 0 ; i--)
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.UpArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal(_history[i], _keyHandler.Text);
}
}
[Fact]
public void TestControlP()
{
for (int i = _history.Count - 1; i >= 0 ; i--)
{
_keyInfo = new ConsoleKeyInfo('P', ConsoleKey.P, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal(_history[i], _keyHandler.Text);
}
}
[Fact]
public void TestDownArrow()
{
for (int i = _history.Count - 1; i >= 0 ; i--)
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.UpArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
}
for (int i = 0; i < _history.Count; i++)
{
Assert.Equal(_history[i], _keyHandler.Text);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.DownArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
}
}
[Fact]
public void TestControlN()
{
for (int i = _history.Count - 1; i >= 0 ; i--)
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.UpArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
}
for (int i = 0; i < _history.Count; i++)
{
Assert.Equal(_history[i], _keyHandler.Text);
_keyInfo = new ConsoleKeyInfo('N', ConsoleKey.N, false, false, true);
_keyHandler.Handle(_keyInfo);
}
}
[Fact]
public void TestControlU()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('U', ConsoleKey.U, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal("o", _keyHandler.Text);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.End, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('U', ConsoleKey.U, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal(string.Empty, _keyHandler.Text);
}
[Fact]
public void TestControlK()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.LeftArrow, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('K', ConsoleKey.K, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hell", _keyHandler.Text);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Home, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('K', ConsoleKey.K, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal(string.Empty, _keyHandler.Text);
}
[Fact]
public void TestControlW()
{
_keyInfo = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('W', ConsoleKey.W, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('o', ConsoleKey.O, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('r', ConsoleKey.R, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('l', ConsoleKey.L, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('d', ConsoleKey.D, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('W', ConsoleKey.W, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal("Hello ", _keyHandler.Text);
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Backspace, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('W', ConsoleKey.W, false, false, true);
_keyHandler.Handle(_keyInfo);
Assert.Equal(string.Empty, _keyHandler.Text);
}
[Fact]
public void TestTab()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Tab, false, false, false);
_keyHandler.Handle(_keyInfo);
// Nothing happens when no auto complete handler is set
Assert.Equal("Hello", _keyHandler.Text);
_keyHandler = new KeyHandler(new Console2(), _history, _autoCompleteHandler);
_keyInfo = new ConsoleKeyInfo('H', ConsoleKey.H, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('i', ConsoleKey.I, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
_keyHandler.Handle(_keyInfo);
for (int i = 0; i < _completions.Length; i++)
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Tab, false, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal($"Hi {_completions[i]}", _keyHandler.Text);
}
}
[Fact]
public void TestBackwardsTab()
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Tab, false, false, false);
_keyHandler.Handle(_keyInfo);
// Nothing happens when no auto complete handler is set
Assert.Equal("Hello", _keyHandler.Text);
_keyHandler = new KeyHandler(new Console2(), _history, _autoCompleteHandler);
_keyInfo = new ConsoleKeyInfo('H', ConsoleKey.H, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo('i', ConsoleKey.I, false, false, false);
_keyHandler.Handle(_keyInfo);
_keyInfo = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
_keyHandler.Handle(_keyInfo);
// Bring up the first Autocomplete
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Tab, false, false, false);
_keyHandler.Handle(_keyInfo);
for (int i = _completions.Length - 1; i >= 0; i--)
{
_keyInfo = new ConsoleKeyInfo('\0', ConsoleKey.Tab, true, false, false);
_keyHandler.Handle(_keyInfo);
Assert.Equal($"Hi {_completions[i]}", _keyHandler.Text);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TableMap
{
internal abstract class Statement
{
public class SyntaxException : Exception
{
public SyntaxException(string msg) : base(msg) { }
}
public abstract Expression.EvalResult Execute(MakeState s);
public bool export = false;
public static bool FileDirExists(string name)
{
try
{
System.IO.FileInfo fi = new System.IO.FileInfo(name);
if (fi.Exists)
return true;
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(name);
return di.Exists;
}
catch (Exception)
{
return false;
}
}
internal static void ExportDef(string tag, MakeState s)
{
Expression.EvalResult e = s.GetDefine(tag);
MakeState cur_s = s.parent;
while (cur_s != null)
{
cur_s.SetDefine(tag, e);
cur_s = cur_s.parent;
}
}
}
internal abstract class DefineStatement : Statement
{
public Tokens assignop;
}
internal class DefineStringStatement : DefineStatement
{
public string tok_name;
public string val;
public override Expression.EvalResult Execute(MakeState s)
{
Expression.EvalResult e = new Expression.EvalResult(val);
s.SetDefine(tok_name, e, assignop);
if (export)
ExportDef(tok_name, s);
return new Expression.EvalResult(0);
}
}
internal class DefineLabelStatement : DefineStatement
{
public string tok_name;
public string val;
public override Expression.EvalResult Execute(MakeState s)
{
LabelExpression le = new LabelExpression { val = val };
Expression.EvalResult e = le.Evaluate(s);
s.SetDefine(tok_name, e, assignop);
if (export)
ExportDef(tok_name, s);
return new Expression.EvalResult(0);
}
}
internal class DefineExprStatement : DefineStatement
{
public Expression val;
public Expression tok_name;
public override Expression.EvalResult Execute(MakeState s)
{
Expression.EvalResult e = val.Evaluate(s);
if (tok_name is LabelExpression)
{
var tn = ((LabelExpression)tok_name).val;
s.SetLocalDefine(tn, e);
if (export)
ExportDef(tn, s);
}
else if(tok_name is LabelMemberExpression)
{
// left-most member must be a define
var lme = tok_name as LabelMemberExpression;
if (!(lme.label is LabelExpression))
throw new Exception("unable to assign to " + tok_name.ToString());
var o = s.GetDefine(((LabelExpression)lme.label).val);
// Now iterate through the various members, looking for
// what to set
Expression cur_member_lval = lme.member;
while(true)
{
if (cur_member_lval is LabelExpression)
{
// we've reached the end of the chain
break;
}
else if (cur_member_lval is LabelMemberExpression)
{
var new_lme = cur_member_lval as LabelMemberExpression;
if (!(new_lme.label is LabelExpression))
throw new Exception("unable to assign to " + tok_name.ToString());
lme = new_lme;
cur_member_lval = lme.member;
if (o.Type != Expression.EvalResult.ResultType.Object)
throw new Exception();
o = o.objval[((LabelExpression)lme.label).val];
}
else
throw new NotImplementedException();
}
string member_name = ((LabelExpression)cur_member_lval).val;
o.objval[member_name] = e;
}
else if (tok_name is LabelIndexedExpression)
{
var chain = get_chain(tok_name);
// left-most member must be a define
var lme = chain[0];
if (!(lme is LabelExpression))
throw new Exception("unable to assign to " + tok_name.ToString());
var o = s.GetDefine(((LabelExpression)lme).val);
// Now iterate through the various members, looking for
// what to set
o = follow_chain(o, chain, 1, chain.Count - 1, s);
if (o.Type != Expression.EvalResult.ResultType.Array)
throw new Exception("unable to assign to " + tok_name.ToString());
var idx = ((LabelIndexedExpression)tok_name).index.Evaluate(s).AsInt;
// increase the array size as appropriate
if(idx >= o.arrval.Count)
{
o.arrval.Capacity = (int)idx * 3 / 2;
while (idx >= o.arrval.Count)
o.arrval.Add(new Expression.EvalResult { Type = Expression.EvalResult.ResultType.Null });
}
o.arrval[(int)idx] = e;
}
else
throw new NotImplementedException();
return new Expression.EvalResult(0);
}
private Expression.EvalResult follow_chain(Expression.EvalResult o,
List<Expression> chain, int cur_idx, int max_idx,
MakeState s)
{
var next_member = chain[cur_idx];
Expression.EvalResult next_result = null;
if (next_member is LabelIndexedExpression)
{
var lie = next_member as LabelIndexedExpression;
if (o.Type != Expression.EvalResult.ResultType.Array)
throw new Exception();
next_result = o.arrval[(int)lie.index.Evaluate(s).AsInt];
}
else if (next_member is LabelMemberExpression)
{
var lme = next_member as LabelMemberExpression;
if (o.Type != Expression.EvalResult.ResultType.Object)
throw new Exception();
next_result = o.objval[((LabelExpression)lme.member).val];
}
else
throw new NotImplementedException();
cur_idx++;
if (cur_idx == max_idx)
return next_result;
return follow_chain(next_result, chain, cur_idx, max_idx, s);
}
private List<Expression> get_chain(Expression tok_name)
{
List<Expression> ret = new List<Expression>();
Expression cur_expr = tok_name;
while(true)
{
ret.Insert(0, cur_expr);
if (cur_expr is LabelIndexedExpression)
{
cur_expr = ((LabelIndexedExpression)cur_expr).label;
}
else if (cur_expr is LabelMemberExpression)
{
cur_expr = ((LabelMemberExpression)cur_expr).label;
}
else
break;
}
return ret;
}
}
internal class DefineIntStatement : DefineStatement
{
public string tok_name;
public int val;
public override Expression.EvalResult Execute(MakeState s)
{
Expression.EvalResult e = new Expression.EvalResult(val);
s.SetDefine(tok_name, e, assignop);
if (export)
ExportDef(tok_name, s);
return new Expression.EvalResult(0);
}
}
internal abstract class ControlStatement : Statement
{
public Statement code;
public Expression test;
}
internal class IfBlockStatement : ControlStatement
{
public Statement if_block;
public Statement else_block;
public override Expression.EvalResult Execute(MakeState s)
{
if (test.Evaluate(s).AsInt == 0)
{
if (else_block != null)
return else_block.Execute(s);
}
else
{
if (if_block != null)
return if_block.Execute(s);
}
return new Expression.EvalResult(0);
}
}
internal class DoBlock : ControlStatement
{
public override Expression.EvalResult Execute(MakeState s)
{
throw new NotImplementedException();
}
}
internal class ForBlockStatement : ControlStatement
{
public Statement incr, init;
public override Expression.EvalResult Execute(MakeState s)
{
// run initializer
Expression.EvalResult ret = init.Execute(s);
if (ret.AsInt != 0)
return ret;
while(true)
{
// check condition
if (test.Evaluate(s).AsInt == 0)
break;
// exec code
ret = code.Execute(s);
if (ret.AsInt != 0)
return ret;
if(s.returns != null)
{
return new Expression.EvalResult(0);
}
// run incrementer
incr.Execute(s);
}
return new Expression.EvalResult(0);
}
}
internal class ForEachBlock : ControlStatement
{
public Expression enumeration;
public string val;
public override Expression.EvalResult Execute(MakeState s)
{
Expression.EvalResult e = enumeration.Evaluate(s);
if (e.Type != Expression.EvalResult.ResultType.Array)
throw new Exception("does not evaluate to array");
foreach (Expression.EvalResult i in e.arrval)
{
//MakeState cur_s = s.Clone();
var cur_s = s;
cur_s.SetLocalDefine(val, i);
Expression.EvalResult ret = code.Execute(cur_s);
if (ret.AsInt != 0)
return ret;
if (cur_s.returns != null)
{
s.returns = cur_s.returns;
return new Expression.EvalResult(0);
}
}
return new Expression.EvalResult(0);
}
}
internal class WhileBlock : ControlStatement
{
public override Expression.EvalResult Execute(MakeState s)
{
throw new NotImplementedException();
}
}
internal class FunctionStatement : Statement
{
public string name;
public List<FunctionArg> args;
public Statement code;
public override Expression.EvalResult Execute(MakeState s)
{
string mangledname = Mangle();
s.funcs[mangledname] = this;
if (export)
{
MakeState cur_s = s.parent;
while (cur_s != null)
{
cur_s.funcs[mangledname] = this;
cur_s = cur_s.parent;
}
}
return new Expression.EvalResult(0);
}
public virtual Expression.EvalResult Run(MakeState s, List<Expression.EvalResult> passed_args)
{
MakeState new_s = s.Clone();
new_s.ClearLocalDefines();
for (int i = 0; i < args.Count; i++)
{
if (args[i].argtype == Expression.EvalResult.ResultType.Function)
{
FunctionStatement fs = new FunctionStatement();
var ofs = passed_args[i].funcval;
fs.name = args[i].name;
fs.args = ofs.args;
fs.code = ofs.code;
new_s.funcs[fs.Mangle()] = fs;
}
else
new_s.SetLocalDefine(args[i].name, passed_args[i]);
}
code.Execute(new_s);
if (new_s.returns != null)
return new_s.returns;
return new Expression.EvalResult();
}
public class FunctionArg
{
public string name;
public Expression.EvalResult.ResultType argtype;
}
public string Mangle()
{
StringBuilder sb = new StringBuilder();
sb.Append(name.Length.ToString());
sb.Append(name);
foreach (FunctionArg arg in args)
{
switch (arg.argtype)
{
case Expression.EvalResult.ResultType.Int:
sb.Append("i");
break;
case Expression.EvalResult.ResultType.String:
sb.Append("s");
break;
case Expression.EvalResult.ResultType.Array:
sb.Append("a");
break;
case Expression.EvalResult.ResultType.Object:
sb.Append("o");
break;
case Expression.EvalResult.ResultType.Void:
sb.Append("v");
break;
case Expression.EvalResult.ResultType.Function:
sb.Append("f");
break;
case Expression.EvalResult.ResultType.Any:
sb.Append("x");
break;
}
}
return sb.ToString();
}
}
internal class ExportStatement : Statement
{
public string v;
public override Expression.EvalResult Execute(MakeState s)
{
if (s.IsDefined(v) == false)
{
throw new Exception("export: variable " + v + " is not defined in this scope");
}
Expression.EvalResult e = s.GetDefine(v);
s.SetDefine(v, e);
MakeState cur_s = s.parent;
while (cur_s != null)
{
cur_s.SetDefine(v, e);
cur_s = cur_s.parent;
}
return new Expression.EvalResult(0);
}
}
internal class ReturnStatement : Statement
{
public Expression v;
public override Expression.EvalResult Execute(MakeState s)
{
s.returns = v.Evaluate(s);
return new Expression.EvalResult(0);
}
}
internal class StatementList : Statement
{
public List<Statement> list;
public override Expression.EvalResult Execute(MakeState s)
{
if (list != null)
{
foreach (Statement st in list)
{
Expression.EvalResult er = st.Execute(s);
if (!(st is ExpressionStatement) && er.AsInt != 0)
return er;
if (s.returns != null)
return new Expression.EvalResult(0);
}
}
return new Expression.EvalResult(0);
}
}
internal class StringStatement : Statement
{
public string val;
public override Expression.EvalResult Execute(MakeState s)
{
throw new NotImplementedException();
}
}
internal class ExpressionStatement : Statement
{
public Expression expr;
public override Expression.EvalResult Execute(MakeState s)
{
return expr.Evaluate(s);
}
}
internal class LabelStatement : Statement
{
public string val;
public override Expression.EvalResult Execute(MakeState s)
{
throw new NotImplementedException();
}
}
internal class IncludeStatement : Statement
{
public Expression include_file;
public override Expression.EvalResult Execute(MakeState s)
{
var f = include_file.Evaluate(s).strval;
MakeState new_s = s.Clone();
return Program.ExecuteFile(f, new_s);
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using metadata;
using libtysila5.target;
/* Exception headers are pushed by entry to protected blocks
* They are composed of:
* intptr EType
* intptr Handler (native code offset)
* intptr Catch Object (if applicable)
*/
namespace libtysila5.layout
{
public partial class Layout
{
public static int GetEhdrSize(Target t)
{
return 3 * t.GetPointerSize();
}
public static void OutputEHdr(MethodSpecWithEhdr ms,
Target t, binary_library.IBinaryFile of,
TysilaState s,
MetadataStream base_m = null,
binary_library.ISection os = null)
{
// Don't compile if not for this architecture
if (!t.IsMethodValid(ms.ms))
return;
if(os == null)
os = of.GetRDataSection();
os.Align(t.GetPointerSize());
var d = os.Data;
/* Symbol */
var sym = of.CreateSymbol();
sym.Name = ms.ms.MangleMethod() + "EH";
sym.ObjectType = binary_library.SymbolObjectType.Object;
sym.Offset = (ulong)d.Count;
sym.Type = binary_library.SymbolType.Global;
os.AddSymbol(sym);
if (base_m != null && ms.ms.m != base_m)
sym.Type = binary_library.SymbolType.Weak;
foreach(var ehdr in ms.c.ehdrs)
{
var v = t.IntPtrArray(BitConverter.GetBytes((int)ehdr.EType));
foreach (var b in v)
d.Add(b);
/* Handler */
var hand_sym = of.CreateSymbol();
hand_sym.Name = ms.ms.MangleMethod() + "EH" + ehdr.EhdrIdx.ToString();
var hand_reloc = of.CreateRelocation();
hand_reloc.Addend = 0;
hand_reloc.DefinedIn = os;
hand_reloc.Offset = (ulong)d.Count;
hand_reloc.References = hand_sym;
hand_reloc.Type = t.GetDataToCodeReloc();
of.AddRelocation(hand_reloc);
for (int i = 0; i < t.GetPointerSize(); i++)
d.Add(0);
/* Catch object */
if (ehdr.ClassToken != null)
{
var catch_sym = of.CreateSymbol();
catch_sym.Name = ehdr.ClassToken.MangleType();
var catch_reloc = of.CreateRelocation();
catch_reloc.Addend = 0;
catch_reloc.DefinedIn = os;
catch_reloc.Offset = (ulong)d.Count;
catch_reloc.References = catch_sym;
catch_reloc.Type = t.GetDataToDataReloc();
of.AddRelocation(catch_reloc);
s.r.VTableRequestor.Request(ehdr.ClassToken);
}
else if(ehdr.EType == ExceptionHeader.ExceptionHeaderType.Filter)
{
var filt_sym = of.CreateSymbol();
filt_sym.Name = ms.ms.MangleMethod() + "EHF" + ehdr.EhdrIdx.ToString();
var filt_reloc = of.CreateRelocation();
filt_reloc.Addend = 0;
filt_reloc.DefinedIn = os;
filt_reloc.Offset = (ulong)d.Count;
filt_reloc.References = filt_sym;
filt_reloc.Type = t.GetDataToCodeReloc();
of.AddRelocation(filt_reloc);
}
for (int i = 0; i < t.GetPointerSize(); i++)
d.Add(0);
}
sym.Size = (long)((ulong)d.Count - sym.Offset);
}
public class MethodSpecWithEhdr : Spec, IEquatable<MethodSpecWithEhdr>
{
public MethodSpec ms;
public Code c;
public override MetadataStream Metadata
{
get
{
return ms.Metadata;
}
}
public override bool IsInstantiatedGenericMethod
{
get
{
return ms.IsInstantiatedGenericMethod;
}
}
public override bool IsInstantiatedGenericType
{
get
{
return ms.IsInstantiatedGenericType;
}
}
public override bool IsArray
{
get
{
return ms.IsArray;
}
}
public override IEnumerable<int> CustomAttributes(string ctor = null)
{
return ms.CustomAttributes(ctor);
}
public bool Equals(MethodSpecWithEhdr other)
{
if (other == null)
return false;
return ms.Equals(other.ms);
}
public override int GetHashCode()
{
return ms.GetHashCode();
}
public override bool Equals(object obj)
{
return Equals(obj as MethodSpecWithEhdr);
}
public static implicit operator MethodSpecWithEhdr(Code c)
{
return new MethodSpecWithEhdr
{
c = c,
ms = c.ms
};
}
public static implicit operator MethodSpecWithEhdr(MethodSpec ms)
{
return new MethodSpecWithEhdr { ms = ms, c = null };
}
public override string Name
{
get
{
return ms.Name;
}
}
public override bool IsAlwaysInvoke
{
get
{
return ms.IsAlwaysInvoke;
}
}
public override bool HasCustomAttribute(string ctor)
{
return ms.HasCustomAttribute(ctor);
}
}
}
}
<file_sep>/* Copyright (C) 2018 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
namespace libsupcs
{
partial class TysosType : Type
{
/* represents a cache of all methods for this type - built on demand
*
* methods is a pure list of all methods
* first_name allows fast indexing by name
* in the instance two methods have the same name, next_name points to the
* next in the chain, or -1 if its the end of the chain.
*/
TysosMethod[] methods = null;
Dictionary<string, int> first_name = null;
int[] next_name = null;
protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
if (next_name == null)
build_method_list();
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: GetMethodImpl(" + name + ", " + ((types == null) ? "null" : types.Length.ToString()) + ")");
if (first_name.TryGetValue(name, out var fn) == false)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: GetMethodImpl: no methods by that name found");
return null;
}
while(fn != -1)
{
var cur_m = methods[fn];
// check binding flags
if (MatchBindingFlags(cur_m, bindingAttr))
{
// check parameters
bool match = true;
if (types != null)
{
var p = cur_m.GetParameters();
if (p.Length == types.Length)
{
for (int i = 0; i < p.Length; i++)
{
if (p[i].ParameterType != types[i])
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: GetMethodImpl: failing because " +
p[i].ParameterType.FullName + " != " + types[i].FullName);
match = false;
break;
}
}
}
else
{
match = false;
}
}
if (match)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: GetMethodImpl: match found");
return cur_m;
}
}
fn = next_name[fn];
}
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: GetMethodImpl: no match found on attributes/parameters");
return null;
}
private void build_method_list()
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: building method list for " + FullName);
var t = tspec;
var first_mdef = ts.m.GetIntEntry(metadata.MetadataStream.tid_TypeDef, t.tdrow, 5);
var last_mdef = ts.m.GetLastMethodDef(t.tdrow);
var _methods = new TysosMethod[last_mdef - first_mdef];
var _first_name = new Dictionary<string, int>(new metadata.GenericEqualityComparer<string>());
var _next_name = new int[last_mdef - first_mdef];
for(int i = 0; i < last_mdef - first_mdef; i++)
_next_name[i] = -1;
var cur_idx = 0;
for(var cur_mdef = first_mdef; cur_mdef < last_mdef; cur_mdef++, cur_idx++)
{
metadata.MethodSpec ms = new metadata.MethodSpec { type = t, mdrow = (int)cur_mdef, m = t.m, msig = (int)ts.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef, (int)cur_mdef, 4) };
var cur_m = new TysosMethod(ms, this);
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: adding method " + cur_m.Name);
_methods[cur_idx] = cur_m;
if (_first_name.TryGetValue(cur_m.Name, out var fn))
{
while (_next_name[fn] != -1)
fn = _next_name[fn];
_next_name[fn] = cur_idx;
}
else
_first_name[cur_m.Name] = cur_idx;
}
if(System.Threading.Interlocked.CompareExchange(ref methods, _methods, null) == null)
{
first_name = _first_name;
next_name = _next_name;
}
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType: done building method list");
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libsupcs
{
class Locale
{
[AlwaysCompile]
[WeakLinkage]
[libsupcs.MethodAlias("_ZW22System#2EGlobalization11CompareInfo_21construct_compareinfo_Rv_P2u1tu1S")]
static void CompareInfo_construct_compareinfo(System.Globalization.CompareInfo ci, string locale)
{
/* Mono's implementation of this (mono/metadata/locales.c) does nothing, so we do the same */
}
[AlwaysCompile]
[WeakLinkage]
[libsupcs.MethodAlias("_ZW22System#2EGlobalization11CompareInfo_22free_internal_collator_Rv_P1u1t")]
static void CompareInfo_free_internal_collator(System.Globalization.CompareInfo ci)
{
/* Mono's implementation of this (mono/metadata/locales.c) does nothing, so we do the same */
}
[AlwaysCompile]
[WeakLinkage]
[libsupcs.MethodAlias("_ZW22System#2EGlobalization11CompareInfo_16internal_compare_Ri_P8u1tu1Siiu1SiiV14CompareOptions")]
static int CompareInfo_internal_compare(System.Globalization.CompareInfo ci, string str1, int offset1,
int length1, string str2, int offset2, int length2, System.Globalization.CompareOptions options)
{
/* Based off the mono implementation */
int length = length1;
if(length2 > length)
length = length2;
if((offset1 + length) > str1.Length)
throw new Exception("Trying to compare more characters than exist in str1");
if((offset2 + length) > str2.Length)
throw new Exception("Trying to compare more characters than exist in str2");
for(int i = 0; i < length; i++)
{
int cc = compare_char(str1[offset1 + i], str2[offset2 + i], options);
if(cc != 0)
return cc;
}
return 0;
}
private static int compare_char(char a, char b, System.Globalization.CompareOptions options)
{
int result;
if ((options & System.Globalization.CompareOptions.Ordinal) == System.Globalization.CompareOptions.Ordinal)
return (int)a - (int)b;
if ((options & System.Globalization.CompareOptions.IgnoreCase) == System.Globalization.CompareOptions.IgnoreCase)
{
char al = char.ToLower(a);
char bl = char.ToLower(b);
result = (int)al - (int)bl;
}
else
result = (int)a - (int)b;
if (result < 0)
return -1;
if (result > 0)
return 1;
return 0;
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.target;
using libtysila5.util;
using metadata;
using libtysila5.ir;
namespace libtysila5.ir
{
public partial class ConvertToIR
{
static MethodSpec delegate_m_target;
static MethodSpec delegate_method_ptr;
public static bool CreateDelegate(metadata.TypeSpec ts,
target.Target t, TysilaState s)
{
if(delegate_m_target == null)
{
delegate_m_target = ts.m.GetFieldDefRow("m_target", ts.m.SystemDelegate);
if (delegate_m_target == null)
delegate_m_target = ts.m.GetFieldDefRow("_target", ts.m.SystemDelegate);
delegate_method_ptr = ts.m.GetFieldDefRow("method_ptr", ts.m.SystemDelegate);
if (delegate_method_ptr == null)
delegate_method_ptr = ts.m.GetFieldDefRow("_methodPtr", ts.m.SystemDelegate);
}
// Generate required delegate methods in IR
CreateDelegateCtor(ts, t, s);
CreateDelegateInvoke(ts, t, s);
CreateDelegateBeginInvoke(ts, t, s);
CreateDelegateEndInvoke(ts, t, s);
return true;
}
private static void CreateDelegateEndInvoke(TypeSpec ts, Target t, TysilaState s)
{
var ms = ts.m.GetMethodSpec(ts, "EndInvoke", 0, null);
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
List<cil.CilNode.IRNode> ret = new List<cil.CilNode.IRNode>();
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Error message
stack_before = ConvertToIR.ldstr(n, c, stack_before, "BeginInvoke is currently implemented");
// Create NotImplementedException
var ni_ts = c.ms.m.al.GetAssembly("mscorlib").GetTypeSpec("System", "NotImplementedException");
var ni_ctor_row = ni_ts.m.GetMethodDefRow(ni_ts, ".ctor",
c.special_meths.inst_Rv_s, c.special_meths);
var ni_ctor_ms = new MethodSpec
{
m = ni_ts.m,
type = ni_ts,
mdrow = ni_ctor_row,
msig = (int)ni_ts.m.GetIntEntry(MetadataStream.tid_MethodDef, ni_ctor_row, 4),
};
stack_before = ConvertToIR.newobj(n, c, stack_before, ni_ctor_ms);
stack_before = ConvertToIR.throw_(n, c, stack_before);
// Ret - not reached
//n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ((ret_ts == null) ? ir.Opcode.ct_unknown : Opcode.GetCTFromType(ret_ts)), stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
var msc = new layout.Layout.MethodSpecWithEhdr
{
ms = ms,
c = c
};
s.r.MethodRequestor.Remove(msc);
s.r.MethodRequestor.Request(msc);
}
private static void CreateDelegateBeginInvoke(TypeSpec ts, Target t, TysilaState s)
{
var ms = ts.m.GetMethodSpec(ts, "BeginInvoke", 0, null);
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
List<cil.CilNode.IRNode> ret = new List<cil.CilNode.IRNode>();
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Error message
stack_before = ConvertToIR.ldstr(n, c, stack_before, "BeginInvoke is currently implemented");
// Create NotImplementedException
var ni_ts = c.ms.m.al.GetAssembly("mscorlib").GetTypeSpec("System", "NotImplementedException");
var ni_ctor_row = ni_ts.m.GetMethodDefRow(ni_ts, ".ctor",
c.special_meths.inst_Rv_s, c.special_meths);
var ni_ctor_ms = new MethodSpec
{
m = ni_ts.m,
type = ni_ts,
mdrow = ni_ctor_row,
msig = (int)ni_ts.m.GetIntEntry(MetadataStream.tid_MethodDef, ni_ctor_row, 4),
};
stack_before = ConvertToIR.newobj(n, c, stack_before, ni_ctor_ms);
stack_before = ConvertToIR.throw_(n, c, stack_before);
// Ret - not reached
//n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ((ret_ts == null) ? ir.Opcode.ct_unknown : Opcode.GetCTFromType(ret_ts)), stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
var msc = new layout.Layout.MethodSpecWithEhdr
{
ms = ms,
c = c
};
s.r.MethodRequestor.Remove(msc);
s.r.MethodRequestor.Request(msc);
}
private static void CreateDelegateInvoke(TypeSpec ts, Target t, TysilaState s)
{
var ms = ts.m.GetMethodSpec(ts, "Invoke", 0, null);
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
List<cil.CilNode.IRNode> ret = new List<cil.CilNode.IRNode>();
util.Stack<StackItem> stack_before = new util.Stack<StackItem>();
TypeSpec fld_ts;
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Load m_target
stack_before = ConvertToIR.ldarg(n, c, stack_before, 0);
stack_before = ConvertToIR.ldflda(n, c, stack_before, false, out fld_ts, 0, delegate_m_target);
stack_before = ConvertToIR.binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ConvertToIR.ldind(n, c, stack_before, fld_ts);
// Duplicate and branch to the static implementation if null
stack_before = ConvertToIR.copy_to_front(n, c, stack_before);
stack_before = ConvertToIR.ldc(n, c, stack_before, 0, (int)CorElementType.Object);
var tstatic = c.next_mclabel--;
stack_before = ConvertToIR.brif(n, c, stack_before, Opcode.cc_eq, tstatic);
var tstatic_stack_in = new util.Stack<StackItem>(stack_before);
// Get number of params and push left to right
var sig_idx = ms.msig;
var pcount = ms.m.GetMethodDefSigParamCount(sig_idx);
for(int i = 0; i < pcount; i++)
stack_before = ConvertToIR.ldarg(n, c, stack_before, i + 1);
// Load method_ptr
stack_before = ConvertToIR.ldarg(n, c, stack_before, 0);
stack_before = ConvertToIR.ldflda(n, c, stack_before, false, out fld_ts, 0, delegate_method_ptr);
stack_before = ConvertToIR.binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ConvertToIR.ldind(n, c, stack_before, fld_ts);
// Build new method signature containing System.Object followed by the parameters of Invoke
sig_idx = ms.m.GetMethodDefSigRetTypeIndex(sig_idx);
var ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
List<TypeSpec> p = new List<TypeSpec>();
p.Add(ms.m.SystemObject);
for (int i = 0; i < pcount; i++)
p.Add(ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams));
var new_msig = c.special_meths.CreateMethodSignature(ret_ts, p.ToArray());
c.ret_ts = ret_ts;
// Calli
stack_before = ConvertToIR.call(n, c, stack_before, true, "noname", c.special_meths, new_msig);
// Ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ((ret_ts == null) ? ir.Opcode.ct_unknown : Opcode.GetCTFromType(ret_ts)), stack_before = stack_before, stack_after = stack_before });
// Static version of above
stack_before = mclabel(n, c, tstatic_stack_in, tstatic);
stack_before = ConvertToIR.pop(n, c, stack_before); // remove null m_target pointer
// Get number of params and push left to right
sig_idx = ms.msig;
pcount = ms.m.GetMethodDefSigParamCount(sig_idx);
for (int i = 0; i < pcount; i++)
stack_before = ConvertToIR.ldarg(n, c, stack_before, i + 1);
// Load method_ptr
stack_before = ConvertToIR.ldarg(n, c, stack_before, 0);
stack_before = ConvertToIR.ldflda(n, c, stack_before, false, out fld_ts, 0, delegate_method_ptr);
stack_before = ConvertToIR.binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_before = ConvertToIR.ldind(n, c, stack_before, fld_ts);
// Build new method signature containing the parameters of Invoke
sig_idx = ms.m.GetMethodDefSigRetTypeIndex(sig_idx);
ret_ts = ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams);
p = new List<TypeSpec>();
for (int i = 0; i < pcount; i++)
p.Add(ms.m.GetTypeSpec(ref sig_idx, ms.gtparams, ms.gmparams));
new_msig = c.special_meths.CreateMethodSignature(ret_ts, p.ToArray());
c.ret_ts = ret_ts;
// Calli
stack_before = ConvertToIR.call(n, c, stack_before, true, "noname", c.special_meths, new_msig);
// Ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, ct = ((ret_ts == null) ? ir.Opcode.ct_unknown : Opcode.GetCTFromType(ret_ts)), stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
var msc = new layout.Layout.MethodSpecWithEhdr
{
ms = ms,
c = c
};
s.r.MethodRequestor.Remove(msc);
s.r.MethodRequestor.Request(msc);
}
private static void CreateDelegateCtor(TypeSpec ts, Target t, TysilaState s)
{
var ms = ts.m.GetMethodSpec(ts, ".ctor", 0, null);
Code c = new Code { t = t, ms = ms, s = s };
t.AllocateLocalVarsArgs(c);
cil.CilNode n = new cil.CilNode(ms, 0);
List<cil.CilNode.IRNode> ret = new List<cil.CilNode.IRNode>();
util.Stack<StackItem> stack_before = new util.Stack<StackItem>(0);
TypeSpec fld_ts;
// Enter
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_enter, stack_before = stack_before, stack_after = stack_before });
// Store m_target
stack_before = ConvertToIR.ldarg(n, c, stack_before, 0);
stack_before = ConvertToIR.ldarg(n, c, stack_before, 1);
stack_before = ConvertToIR.ldflda(n, c, stack_before, false, out fld_ts, 1, delegate_m_target);
stack_before = ConvertToIR.binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr, 2);
stack_before = ConvertToIR.stind(n, c, stack_before, c.t.GetSize(fld_ts), 1, 0);
stack_before.Pop();
// Store method_ptr
stack_before = ConvertToIR.ldarg(n, c, stack_before, 0);
stack_before = ConvertToIR.ldarg(n, c, stack_before, 2);
stack_before = ConvertToIR.ldflda(n, c, stack_before, false, out fld_ts, 1, delegate_method_ptr);
stack_before = ConvertToIR.binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr, 2);
stack_before = ConvertToIR.stind(n, c, stack_before, c.t.GetSize(fld_ts), 1, 0);
stack_before.Pop();
// Ret
n.irnodes.Add(new cil.CilNode.IRNode { parent = n, opcode = Opcode.oc_ret, stack_before = stack_before, stack_after = stack_before });
c.cil = new List<cil.CilNode> { n };
c.ir = n.irnodes;
c.starts = new List<cil.CilNode> { n };
var msc = new layout.Layout.MethodSpecWithEhdr
{
ms = ms,
c = c
};
s.r.MethodRequestor.Remove(msc);
s.r.MethodRequestor.Request(msc);
}
}
}
<file_sep>/* Copyright (C) 2008 - 2019 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace tysos
{
unsafe class SymbolTable
{
internal abstract class SymbolProvider
{
internal protected abstract void* GetAddress(string s);
internal protected abstract string GetSymbol(void* address);
internal protected abstract string GetSymbolAndOffset(void* address, out UIntPtr offset);
}
internal Dictionary<string, UIntPtr> sym_to_offset;
internal metadata.Collections.SortedList<UIntPtr, string> offset_to_sym;
internal Dictionary<string, UIntPtr> sym_to_length;
internal List<ulong> static_fields_addresses = new List<ulong>();
internal List<ulong> static_fields_lengths = new List<ulong>();
internal List<SymbolProvider> symbol_providers = new List<SymbolProvider>();
public SymbolTable()
{
sym_to_offset = new Dictionary<string, UIntPtr>(0x20000, new libsupcs.GenericEqualityComparer<string>());
offset_to_sym = new metadata.Collections.SortedList<UIntPtr, string>(0x20000, new libsupcs.UIntPtrComparer());
sym_to_length = new Dictionary<string, UIntPtr>(0x20000, new libsupcs.GenericEqualityComparer<string>());
}
public void Add(string sym, void* address)
{
unsafe
{
ulong ots = libsupcs.CastOperations.ReinterpretAsUlong(offset_to_sym);
}
if (sym_to_offset.ContainsKey(sym))
{
System.Diagnostics.Debugger.Log(0, "libjit", "SymbolTable.Add: Warning: duplicate symbol: " +
sym);
}
else
sym_to_offset.Add(sym, (UIntPtr)address);
if(!offset_to_sym.ContainsKey((UIntPtr)address))
offset_to_sym.Add((UIntPtr)address, sym);
}
public void Add(string sym, void* address, UIntPtr length)
{
if (sym_to_offset.ContainsKey(sym))
{
System.Diagnostics.Debugger.Log(0, "libjit", "SymbolTable.Add: Warning: duplicate symbol: " +
sym);
}
else
{
sym_to_offset.Add(sym, (UIntPtr)address);
sym_to_length.Add(sym, length);
}
if (!offset_to_sym.ContainsKey((UIntPtr)address))
offset_to_sym.Add((UIntPtr)address, sym);
}
public void AddStaticField(ulong address, ulong length)
{
static_fields_addresses.Add(address);
static_fields_lengths.Add(length);
}
public void* GetAddress(string sym)
{
foreach (SymbolProvider sp in symbol_providers)
{
var ret = sp.GetAddress(sym);
if (ret != null)
return ret;
}
if (sym_to_offset.ContainsKey(sym))
return (void*)sym_to_offset[sym];
else
return (void*)0;
}
public UIntPtr GetLength(string sym)
{
/*foreach (SymbolProvider sp in symbol_providers)
{
ulong ret = sp.GetAddress(sym);
if (ret != 0)
return ret;
}*/
if (sym_to_length.ContainsKey(sym))
return sym_to_length[sym];
else
return (UIntPtr)0;
}
public string GetSymbol(void* address)
{
foreach (SymbolProvider sp in symbol_providers)
{
string ret = sp.GetSymbol(address);
if (ret != null)
return ret;
}
return (string)offset_to_sym[(UIntPtr)address];
}
public string GetSymbolAndOffset(void* address, out UIntPtr offset)
{
foreach (SymbolProvider sp in symbol_providers)
{
string ret = sp.GetSymbolAndOffset(address, out offset);
if (ret != null)
return ret;
}
if (offset_to_sym.ContainsKey((UIntPtr)address))
{
offset = (UIntPtr)0;
return offset_to_sym[(UIntPtr)address];
}
offset_to_sym.Add((UIntPtr)address, "probe");
int idx = offset_to_sym.IndexOfKey((UIntPtr)address);
offset_to_sym.RemoveAt(idx);
if (idx == 0)
{
offset = (UIntPtr)address;
return "offset_0";
}
var sym_addr = offset_to_sym.Keys[idx - 1];
offset = libsupcs.OtherOperations.Sub((UIntPtr)address, sym_addr);
return offset_to_sym[sym_addr];
}
}
}
<file_sep>using System;
using ConsoleUtils.ConsoleActions;
namespace ConsoleUtils
{
internal class ConsoleExtInstance : IConsole
{
internal int start_cursor = 0;
public PreviousLineBuffer PreviousLineBuffer { get { return ConsoleExt.PreviousLineBuffer; } }
public string CurrentLine { get { return ConsoleExt.CurrentLine; } set { ConsoleExt.CurrentLine = value; } }
public int CursorPosition { get { return Console.CursorLeft; } set { Console.CursorLeft = value; } }
public int StartCursorPosition { get { return start_cursor; } set { start_cursor = value; } }
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class MoveCursorLeftAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
console.CursorPosition = Math.Max(0, console.CursorPosition - 1);
}
}
}
<file_sep>/* Copyright (C) 2017-2018 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using binary_library.elf;
namespace genmissing
{
class Program
{
static List<string> input_files = new List<string>();
static string arch = "x86_64";
static string output_name = "missing.o";
static List<string> new_search_dirs = new List<string>();
static int Main(string[] args)
{
/* Parse args */
var argc = args.Length;
char c;
var go = new XGetoptCS.XGetopt();
var arg_str = "t:L:o:";
while ((c = go.Getopt(argc, args, arg_str)) != '\0')
{
switch (c)
{
case 't':
arch = go.Optarg;
break;
case 'L':
new_search_dirs.Add(go.Optarg);
break;
case 'o':
output_name = go.Optarg;
break;
case '?':
dump_opts();
return -1;
}
}
tysila4.Program.search_dirs.InsertRange(0, new_search_dirs);
var curopt = go.Optind;
while (curopt < argc)
input_files.Add(args[curopt++]);
if(input_files.Count == 0)
{
System.Console.WriteLine("No input files specified");
dump_opts();
return -1;
}
/* Load up each input file in turn */
var ifiles = new List<binary_library.IBinaryFile>();
foreach(var ifname in input_files)
{
var ifinfo = new System.IO.FileInfo(ifname);
if (!ifinfo.Exists)
throw new System.IO.FileNotFoundException("Cannot find: " + ifname);
/* Determine file type from extension */
binary_library.IBinaryFile ifobj = null;
if (ifinfo.Extension == ".o" || ifinfo.Extension == ".obj")
ifobj = new binary_library.elf.ElfFile();
if (ifobj == null)
ifobj = binary_library.BinaryFile.CreateBinaryFile(ifinfo.Extension);
if (ifobj == null)
throw new Exception("Unsupported file type: " + ifinfo.FullName);
/* Load up the particular file */
ifobj.Filename = ifinfo.FullName;
ifobj.Read();
ifiles.Add(ifobj);
}
/* Get a list of all defined symbols */
var def_syms = new Dictionary<string, binary_library.ISymbol>();
foreach(var file in ifiles)
{
var sym_count = file.GetSymbolCount();
for(int i = 0; i < sym_count; i++)
{
var sym = file.GetSymbol(i);
if (sym.DefinedIn != null && sym.Type != binary_library.SymbolType.Undefined)
def_syms[sym.Name] = sym;
}
}
/* Get a list of those relocations which are missing */
var missing = new Dictionary<string, binary_library.ISymbol>();
foreach(var file in ifiles)
{
var reloc_count = file.GetRelocationCount();
for(int i = 0; i < reloc_count; i++)
{
var reloc = file.GetRelocation(i);
if (reloc.References != null && !def_syms.ContainsKey(reloc.References.Name))
{
if (reloc.References.Name == "_Zu1O_7#2Ector_Rv_P1u1t")
System.Diagnostics.Debugger.Break();
missing[reloc.References.Name] = reloc.References;
}
}
}
/* Generate an output object */
var o = new binary_library.elf.ElfFile(ifiles[0].Bitness);
o.Init();
o.Architecture = arch;
o.Filename = output_name;
/* Generate dummy module */
var ofi = new System.IO.FileInfo(output_name);
var ms = new metadata.MetadataStream(ofi.Name.Substring(0, ofi.Name.Length - ofi.Extension.Length));
ms.al = new libtysila5.libtysila.AssemblyLoader(new tysila4.FileSystemFileLoader());
ms.LoadBuiltinTypes();
/* Load up assembler target */
var t = libtysila5.target.Target.targets[arch];
var fsi = new System.IO.FileInfo(output_name);
var s = new libtysila5.TysilaState();
s.st = new libtysila5.StringTable(fsi.Name.Substring(0, fsi.Name.Length - fsi.Extension.Length), ms.al, t);
/* Generate signature of missing_function(string) to call */
var special_c = new libtysila5.Code { ms = new metadata.MethodSpec { m = ms } };
var special = special_c.special_meths;
var missing_msig = special.CreateMethodSignature(null, new metadata.TypeSpec[] { ms.SystemString });
/* Generate stub functions for missing methods */
var m = missing.Keys;
var missing_types = new List<string>();
var other_missing = new List<string>();
foreach(var str in m)
{
try
{
if (ms.IsMangledMethod(str))
{
GenerateMissingMethod(str, ms, t, missing_msig, o, s);
}
else
{
ms.IsMangledMethod(str);
missing_types.Add(str);
}
}
catch(ArgumentException)
{
other_missing.Add(str);
}
}
/* Write out */
s.st.WriteToOutput(o, ms, t);
o.Write();
/* Dump missing types */
if (missing_types.Count > 0)
{
Console.WriteLine("Warning: the following missing types were also found:");
foreach (var mt in missing_types)
Console.WriteLine(" " + mt);
}
return 0;
}
private static void dump_opts()
{
Console.WriteLine("Usage: genmissing [-t architecture] [-o output_file] [-L library_path] <input_file_1> [extra_input_files]");
}
private static void GenerateMissingMethod(string str, metadata.MetadataStream m, libtysila5.target.Target t, int missing_msig, ElfFile o, libtysila5.TysilaState s)
{
/* Generate new method spec */
var ms = new metadata.MethodSpec { m = m, mangle_override = str };
/* Generate stub code */
libtysila5.Code c = new libtysila5.Code();
c.t = t;
c.ms = ms;
var ir = new List<libtysila5.cil.CilNode.IRNode>();
var stack = new libtysila5.util.Stack<libtysila5.ir.StackItem>();
var cilnode = new libtysila5.cil.CilNode(ms, 0);
cilnode.irnodes = ir;
c.ir = ir;
c.starts = new List<libtysila5.cil.CilNode> { cilnode };
c.s = s;
stack = libtysila5.ir.ConvertToIR.ldstr(cilnode, c, stack, str);
stack = libtysila5.ir.ConvertToIR.call(cilnode, c, stack, false, "missing_function",
c.special_meths, missing_msig);
/* Assemble */
libtysila5.libtysila.AssembleMethod(ms, o, t, s, null, null, c);
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class AutoCompleteRestOfLineAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (!console.PreviousLineBuffer.HasLines)
return;
var previous = console.PreviousLineBuffer.LineAtIndex;
if (previous.Length <= console.CursorPosition)
return;
var partToUse = previous.Remove(0, console.CursorPosition);
var newLine = console.CurrentLine.Remove(console.CursorPosition,
Math.Min(console.CurrentLine.Length - console.CursorPosition, partToUse.Length));
console.CurrentLine = newLine.Insert(console.CursorPosition, partToUse);
console.CursorPosition = console.CursorPosition + partToUse.Length;
}
}
}
<file_sep>/* Copyright (C) 2014 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
/* System.String internal calls */
namespace libsupcs
{
class String
{
[MethodReferenceAlias("strlen")]
[MethodImpl(MethodImplOptions.InternalCall)]
static unsafe extern int strlen(byte* s);
[MethodReferenceAlias("mbstowcs")]
[MethodImpl(MethodImplOptions.InternalCall)]
static unsafe extern int mbstowcs(char* dest, byte* src, int n);
[AlwaysCompile]
[MethodAlias("_Zu1S_15ReplaceInternal_Ru1S_P3u1tu1Su1S")]
static unsafe string InternalReplace(string str, string old_value, string new_value)
{
/* maximum size of new string is str if new_value <= old_value or
* if new_value is larger then assume str is made up of all old_value
* in which case it is this count * new_value + remainder (or count + 1 * new_value)
*/
int max_new_str;
if(new_value.Length > old_value.Length)
{
max_new_str = ((str.Length / old_value.Length) + 1) * new_value.Length;
}
else
{
max_new_str = str.Length;
}
//System.Diagnostics.Debugger.Log(0, "libsupcs", "InternalReplace: str: " + str + ", old_value: " + old_value +
// ", new_value: " + new_value + ", max_new_str: " + max_new_str.ToString());
/* limit stack alloc to 1024 chars to reduce risk of stack overflows. Implementations
* should have a stack guard page anyway to catch overflows of this size whilst larger
* stack allocs could be used to introduce code beyond the guard page.
*
* We do it this way because C# does not support conditional stack alloc assigns
*/
int max_stack_new_str = max_new_str > 1024 ? 1024 : max_new_str;
char* nstack = stackalloc char[max_stack_new_str];
char* ns;
if (max_new_str <= 1024)
ns = nstack;
else
ns = (char*)MemoryOperations.GcMalloc(max_new_str * sizeof(char));
char* ptr = ns;
for (int i = 0; i < str.Length; i++)
{
bool found = true;
for (int j = 0; j < old_value.Length; j++)
{
if (((i + j) >= str.Length) || (str[i + j] != old_value[j]))
{
found = false;
break;
}
}
if (found)
{
for (int j = 0; j < new_value.Length; j++)
*ptr++ = new_value[j];
i += old_value.Length;
i--; // the for loop adds a 1 for us
}
else
{
*ptr++ = str[i];
}
}
var str_len = ptr - ns;
//var ret = new string(ns, 0, (int)str_len);
//System.Diagnostics.Debugger.Log(0, "libsupcs", "InternalReplace: ret: " + ret);
//return ret;
return new string(ns, 0, (int)str_len);
}
[AlwaysCompile]
[MethodAlias("_Zu1S_20CompareOrdinalHelper_Ri_P6u1Siiu1Sii")]
static unsafe int CompareOrdinalHelper(byte *strA, int indexA, int countA, byte *strB, int indexB, int countB)
{
char* a = (char*)(strA + StringOperations.GetDataOffset()) + indexA;
char* b = (char*)(strB + StringOperations.GetDataOffset()) + indexB;
for(int i = 0; i < countA; i++, a++, b++)
{
if (*a < *b)
return -1;
else if (*a > *b)
return 1;
}
return 0;
}
[AlwaysCompile]
[MethodAlias("_Zu1S_7IsAscii_Rb_P1u1t")]
static bool IsAscii(string str)
{
foreach(var c in str)
{
if (c >= 0x80)
return false;
}
return true;
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_Zu1S_14InternalStrcpy_Rv_P5u1Siu1Sii")]
static unsafe bool InternalStrcpy(byte *dest, int destPos, byte *src, int srcPos, int count)
{
/* Get size of src and dest */
int srcLength = *(int*)(src + StringOperations.GetLengthOffset());
int destLength = *(int*)(dest + StringOperations.GetLengthOffset());
/* Ensure the source and destination are big enough */
if (destPos < 0)
return false;
if (srcPos < 0)
return false;
if (count < 0)
return false;
if (destPos + count > destLength)
return false;
if (srcPos + count > srcLength)
return false;
/* Do the copy */
MemoryOperations.MemCpy((void*)(dest + StringOperations.GetDataOffset() + destPos * 2),
(void*)(src + StringOperations.GetDataOffset() + srcPos * 2), count * 2);
return true;
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_Zu1S_14InternalStrcpy_Rv_P3u1Siu1S")]
static unsafe bool InternalStrcpy(byte* dest, int destPos, byte* src)
{
/* Get size of src and dest */
int srcLength = *(int*)(src + StringOperations.GetLengthOffset());
int destLength = *(int*)(dest + StringOperations.GetLengthOffset());
int srcPos = 0;
int count = srcLength;
/* Ensure the source and destination are big enough */
if (destPos < 0)
return false;
if (destPos + count > destLength)
return false;
/* Do the copy */
MemoryOperations.MemCpy((void*)(dest + StringOperations.GetDataOffset() + destPos * 2),
(void*)(src + StringOperations.GetDataOffset() + srcPos * 2), count * 2);
return true;
}
[MethodAlias("_Zu1S_7#2Ector_Rv_P2u1tu1Zc")]
[AlwaysCompile]
static unsafe void StringCtor(byte *str, char[] srcArr)
{
void* src = MemoryOperations.GetInternalArray(srcArr);
int len = srcArr.Length * sizeof(char);
void* dst = str + StringOperations.GetDataOffset();
MemoryOperations.MemCpy(dst, src, len);
}
[MethodAlias("_Zu1S_7#2Ector_Rv_P3u1tci")]
[AlwaysCompile]
static unsafe void StringCtor(byte *str, char c, int count)
{
char* dst = (char *)(str + StringOperations.GetDataOffset());
for (int i = 0; i < count; i++)
*dst++ = c;
}
[MethodAlias("_Zu1S_7#2Ector_Rv_P4u1tu1Zcii")]
[AlwaysCompile]
static unsafe void StringCtor(byte *str, char[] srcArr, int startIndex, int length)
{
void* src = (byte*)MemoryOperations.GetInternalArray(srcArr) + sizeof(char) * startIndex;
int len = length * sizeof(char);
void* dst = str + StringOperations.GetDataOffset();
MemoryOperations.MemCpy(dst, src, len);
}
[MethodAlias("_Zu1S_7#2Ector_Rv_P4u1tPcii")]
[AlwaysCompile]
static unsafe void StringCtor(byte* str, char* value, int startIndex, int length)
{
void* src = value + startIndex;
int len = length * sizeof(char);
void* dst = str + StringOperations.GetDataOffset();
MemoryOperations.MemCpy(dst, src, len);
}
[MethodAlias("_Zu1S_7#2Ector_Rv_P2u1tPa")]
[AlwaysCompile]
static unsafe void StringCtor(byte *str, sbyte *value)
{
int len = strlen((byte*)value);
void* dst = str + StringOperations.GetDataOffset();
mbstowcs((char*)dst, (byte*)value, len);
}
[MethodAlias("_Zu1S_28InternalUseRandomizedHashing_Rb_P0")]
[AlwaysCompile]
[WeakLinkage]
static bool InternalUseRandomizedHashing()
{
return false;
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class AutoCompleteSingleCharacterAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (!console.PreviousLineBuffer.HasLines ||
console.CurrentLine.Length >= console.PreviousLineBuffer.LastLine.Length)
return;
if (console.CursorPosition == console.CurrentLine.Length)
{
console.CurrentLine = console.CurrentLine + console.PreviousLineBuffer.LastLine[console.CurrentLine.Length];
}
console.CursorPosition++;
}
}
}
<file_sep>using System;
namespace ConsoleUtils
{
public class LineState
{
public LineState(string line, int cursorPosition)
{
Line = line;
if (line == null)
return;
CursorPosition = Math.Min(line.Length, Math.Max(0, cursorPosition));
LineBeforeCursor = line.Substring(0, CursorPosition);
LineAfterCursor = line.Substring(CursorPosition);
}
public string Line { get; private set; }
public int CursorPosition { get; private set; }
public string LineBeforeCursor { get; private set; }
public string LineAfterCursor { get; private set; }
}
}
<file_sep>namespace ConsoleUtils.ConsoleActions
{
public interface IConsole
{
PreviousLineBuffer PreviousLineBuffer { get; }
string CurrentLine { get; set; }
int CursorPosition { get; set; }
int StartCursorPosition { get; set; }
}
}<file_sep>TYBUILD=../tybuild/bin/Release/tybuild.exe
TYSILA=../tysila2/bin/Release/tysila2.exe
YASM=yasm
AR=x86_64-elf-ar
RANLIB=x86_64-elf-ranlib
ARM_AR=arm-none-eabi-ar
ARM_RANLIB=arm-none-eabi-ranlib
PELIBSUPCS=bin/Release/libsupcs.dll
LIBSUPCSOBJ=libsupcs.obj
LIBSUPCSA=libsupcs.a
ARM_LIBSUPCSOBJ = libsupcs.arm.obj
ARM_LIBSUPCSA = libsupcs.arm.a
X86_64_INVOKE=x86_64_Invoke.o
X86_64_ARITH=x86_64_arith.o
X86_64_CPU=x86_64_cpu.o
X86_64_ASM=$(X86_64_INVOKE) $(X86_64_ARITH) $(X86_64_CPU)
ARM_ASM=
MSCORLIBDLL=../mono/corlib/mscorlib.dll
TYSILAFLAGS += -q -c -g -L../mono/corlib
TYBUILDFLAGS += /p:Configuration=Release /v /unsafe /tools:3_5 /Wc,warn:0
.PHONY: clean
all: $(LIBSUPCSA)
$(TYBUILD):
cd ../tybuild && make
$(TYSILA2):
cd ../tysila2 && make
$(MSCORLIBDLL):
cd ../mono/corlib && make mscorlib.dll
$(PELIBSUPCS): $(TYBUILD)
$(TYBUILD) $(TYBUILDFLAGS)
$(LIBSUPCSOBJ): $(PELIBSUPCS) $(TYSILA) $(MSCORLIBDLL)
$(TYSILA) $(TYSILAFLAGS) -o $(LIBSUPCSOBJ) $(PELIBSUPCS)
$(ARM_LIBSUPCSOBJ): $(PELIBSUPCS) $(TYSILA) $(MSCORLIBDLL)
$(TYSILA) $(TYSILAFLAGS) --arch arm-elf-tysos -o $(ARM_LIBSUPCSOBJ) $(PELIBSUPCS)
$(X86_64_INVOKE): x86_64_Invoke.asm
$(YASM) -felf64 -o $@ $<
$(X86_64_ARITH): x86_64_arith.asm
$(YASM) -felf64 -o $@ $<
$(X86_64_CPU): x86_64_cpu.asm
$(YASM) -felf64 -o $@ $<
$(LIBSUPCSA): $(LIBSUPCSOBJ) $(X86_64_ASM)
$(AR) -cru $(LIBSUPCSA) $(LIBSUPCSOBJ) $(X86_64_ASM)
$(RANLIB) $(LIBSUPCSA)
$(ARM_LIBSUPCSA): $(ARM_LIBSUPCSOBJ) $(ARM_ASM)
$(ARM_AR) -cru $(ARM_LIBSUPCSA) $(ARM_LIBSUPCSOBJ) $(ARM_ASM)
$(ARM_RANLIB) $(ARM_LIBSUPCSA)
clean:
rm -rf obj bin $(PELIBSUPCS) $(LIBSUPCSOBJ) $(X86_64_ASM) $(LIBSUPCSA)
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using binary_library;
using libtysila5.ir;
using libtysila5.util;
using metadata;
namespace libtysila5.target.arm
{
partial class arm_Assembler : Target
{
static arm_Assembler()
{
init_instrs();
}
protected void init_options()
{
// cpu features
}
public override Reg AllocateStackLocation(Code c, int size, ref int cur_stack)
{
throw new NotImplementedException();
}
protected internal override bool IsCall(MCInst i)
{
throw new NotImplementedException();
}
protected internal override MCInst SaveRegister(Reg r)
{
throw new NotImplementedException();
}
protected internal override MCInst[] CreateMove(Reg src, Reg dest)
{
throw new NotImplementedException();
}
protected internal override bool NeedsBoxRetType(MethodSpec ms)
{
throw new NotImplementedException();
}
protected internal override void SetBranchDest(MCInst i, int d)
{
throw new NotImplementedException();
}
protected internal override int GetCondCode(MCInst i)
{
throw new NotImplementedException();
}
protected internal override Reg GetLALocation(int la_loc, int la_size, Code c)
{
if (Opcode.GetCTFromType(c.ret_ts) == Opcode.ct_vt)
la_loc += psize;
return new ContentsReg
{
basereg = r_fp,
disp = la_loc + 2 * psize,
size = la_size
};
}
protected internal override bool IsBranch(MCInst i)
{
throw new NotImplementedException();
}
protected internal override Reg GetMoveDest(MCInst i)
{
throw new NotImplementedException();
}
protected internal override int GetBranchDest(MCInst i)
{
throw new NotImplementedException();
}
protected internal override MCInst RestoreRegister(Reg r)
{
throw new NotImplementedException();
}
protected internal override Reg GetLVLocation(int lv_loc, int lv_size, Code c)
{
if (Opcode.GetCTFromType(c.ret_ts) == Opcode.ct_vt)
lv_loc += psize;
int disp = 0;
disp = -lv_size - lv_loc;
return new ContentsReg
{
basereg = r_fp,
disp = disp,
size = lv_size
};
}
protected internal override MCInst[] SetupStack(int lv_size)
{
throw new NotImplementedException();
}
protected internal override IRelocationType GetDataToDataReloc()
{
throw new NotImplementedException();
}
protected internal override IRelocationType GetDataToCodeReloc()
{
throw new NotImplementedException();
}
protected internal override Code AssembleBoxRetTypeMethod(MethodSpec ms, TysilaState s)
{
throw new NotImplementedException();
}
protected internal override Reg GetMoveSrc(MCInst i)
{
throw new NotImplementedException();
}
protected internal override Code AssembleBoxedMethod(MethodSpec ms, TysilaState s)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System.Collections.Generic;
namespace AutoCompleteUtils
{
public class CyclingAutoComplete
{
private List<string> _autoCompleteList;
private string _previousAutoComplete = string.Empty;
private int _autoCompleteIndex;
public string AutoComplete(string line, List<string> strings)
{
return AutoComplete(line, strings, CyclingDirections.Forward, true);
}
public string AutoComplete(string line, List<string> strings, CyclingDirections cyclingDirection)
{
return AutoComplete(line, strings, cyclingDirection, true);
}
public string AutoComplete(string line, List<string> strings, bool ignoreCase)
{
return AutoComplete(line, strings, CyclingDirections.Forward, ignoreCase);
}
public string AutoComplete(string line, List<string> strings, CyclingDirections cyclingDirection, bool ignoreCase)
{
if (IsPreviousCycle(line))
{
if (cyclingDirection == CyclingDirections.Forward)
return ContinueCycle();
return ContinueCycleReverse();
}
_autoCompleteList = AutoCompleteUtils.AutoComplete.GetAutoCompletePossibilities(line, strings, ignoreCase);
if (_autoCompleteList.Count == 0)
return line;
return StartNewCycle();
}
private string StartNewCycle()
{
_autoCompleteIndex = 0;
var autoCompleteLine = _autoCompleteList[_autoCompleteIndex];
_previousAutoComplete = autoCompleteLine;
return autoCompleteLine;
}
private string ContinueCycle()
{
_autoCompleteIndex++;
if (_autoCompleteIndex >= _autoCompleteList.Count)
_autoCompleteIndex = 0;
var autoCompleteLine = _autoCompleteList[_autoCompleteIndex];
_previousAutoComplete = autoCompleteLine;
return autoCompleteLine;
}
private string ContinueCycleReverse()
{
_autoCompleteIndex--;
if (_autoCompleteIndex < 0)
_autoCompleteIndex = _autoCompleteList.Count - 1;
var autoCompleteLine = _autoCompleteList[_autoCompleteIndex];
_previousAutoComplete = autoCompleteLine;
return autoCompleteLine;
}
private bool IsPreviousCycle(string line)
{
return _autoCompleteList != null && _autoCompleteList.Count != 0 && _previousAutoComplete == line;
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace libtysila5.target
{
public class HashTable
{
public int nbucket;
public int nchain;
public int[] bucket;
public int[] chain;
public int[] idx_map;
public byte[] data;
public int GetBlobIndex(IList<byte> key)
{
var hc = Hash(key);
var bucket_id = hc % (uint)nbucket;
var cur_idx = bucket[bucket_id];
while (cur_idx != -1)
{
if (CompareKey(cur_idx, key))
return idx_map[cur_idx];
cur_idx = chain[cur_idx];
}
return -1;
}
public uint ReadCompressedUInt(ref int idx)
{
byte b1 = data[idx++];
if ((b1 & 0x80) == 0)
return b1;
byte b2 = data[idx++];
if ((b1 & 0xc0) == 0x80)
return (b1 & 0x3fU) << 8 | b2;
byte b3 = data[idx++];
byte b4 = data[idx++];
return (b1 & 0x1fU) << 24 | ((uint)b2 << 16) |
((uint)b3 << 8) | b4;
}
public int GetValueIndex(int blob_index)
{
var key_len = data[blob_index];
return blob_index + 1 + key_len;
}
private bool CompareKey(int cur_idx, IList<byte> key)
{
// get key length
var blob_idx = idx_map[cur_idx];
var key_len = data[blob_idx];
if (key_len != key.Count)
return false;
blob_idx++;
for(int i = 0; i < key_len; i++)
{
if (data[blob_idx + i] != key[i])
return false;
}
return true;
}
public static uint Hash(IEnumerable<byte> v)
{
uint h = 0;
uint g = 0;
foreach (var b in v)
{
h = (h << 4) + b;
g = h & 0xf0000000U;
if (g != 0)
h ^= g >> 24;
h &= ~g;
}
return h;
}
public static void CompressInt(int val, List<byte> ret)
{
var u = BitConverter.ToUInt32(BitConverter.GetBytes(val), 0);
CompressUInt(u, ret);
}
public static void CompressUInt(uint u, List<byte> ret)
{
var b1 = u & 0xff;
var b2 = (u >> 8) & 0xff;
var b3 = (u >> 16) & 0xff;
var b4 = (u >> 24) & 0xff;
if (u <= 0x7fU)
{
ret.Add((byte)b1);
return;
}
else if (u <= 0x3fffU)
{
ret.Add((byte)(b2 | 0x80U));
ret.Add((byte)b1);
}
else if (u <= 0x1FFFFFFFU)
{
ret.Add((byte)(b4 | 0xc0U));
ret.Add((byte)b3);
ret.Add((byte)b2);
ret.Add((byte)b1);
}
else
throw new Exception("integer too large to compress");
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using metadata;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using libtysila5.target;
using binary_library.binary;
namespace tysila4
{
class COutput
{
internal static void WriteHeader(MetadataStream m, Target ass, string output_header,
string output_cinit)
{
FileStream fs = new FileStream(output_header, FileMode.Create, FileAccess.Write);
var sw = fs;
var hmsw = new MemoryStream();
var cmsw = new MemoryStream();
FileStream oci = null;
System.IO.FileInfo header_fi = new FileInfo(output_header);
if (output_cinit != null)
{
oci = new FileStream(output_cinit, FileMode.Create, FileAccess.Write);
HexFile.writeStr(oci, "#include \"" + header_fi.Name + "\"", true);
HexFile.writeStr(oci, "#include <string.h>", true);
HexFile.writeStr(oci, "#include <stdlib.h>", true);
HexFile.writeStr(oci, "#include <stdint.h>", true);
HexFile.writeStr(oci, "#include <stddef.h>", true);
HexFile.writeStr(oci, "", true);
HexFile.writeStr(oci, "INTPTR Get_Symbol_Addr(const char *name);", true);
HexFile.writeStr(oci, "", true);
}
List<string> advance_defines = new List<string>();
List<string> external_defines = new List<string>();
List<string> func_headers = new List<string>();
EmitType(m.GetSimpleTypeSpec(0x1c), hmsw, cmsw, advance_defines,
external_defines, func_headers, ass);
EmitType(m.GetSimpleTypeSpec(0xe), hmsw, cmsw, advance_defines,
external_defines, func_headers, ass);
EmitArrayInit(hmsw, cmsw, func_headers, ass, m);
for(int i = 1; i <= m.table_rows[MetadataStream.tid_CustomAttribute]; i++)
{
int type_tid, type_row;
m.GetCodedIndexEntry(MetadataStream.tid_CustomAttribute,
i, 1, m.CustomAttributeType, out type_tid,
out type_row);
MethodSpec ca_ms;
m.GetMethodDefRow(type_tid, type_row, out ca_ms);
var ca_ms_name = ca_ms.MangleMethod();
if (ca_ms_name == "_ZN14libsupcs#2Edll8libsupcs22OutputCHeaderAttribute_7#2Ector_Rv_P1u1t")
{
int parent_tid, parent_row;
m.GetCodedIndexEntry(MetadataStream.tid_CustomAttribute,
i, 0, m.HasCustomAttribute, out parent_tid,
out parent_row);
if(parent_tid == MetadataStream.tid_TypeDef)
{
var ts = m.GetTypeSpec(parent_tid, parent_row);
EmitType(ts, hmsw, cmsw, advance_defines,
external_defines, func_headers, ass);
}
}
}
HexFile.writeStr(sw, "");
HexFile.writeStr(sw, "#include <stdint.h>");
HexFile.writeStr(sw, "");
HexFile.writeStr(sw, "#ifdef INTPTR");
HexFile.writeStr(sw, "#undef INTPTR");
HexFile.writeStr(sw, "#endif");
HexFile.writeStr(sw, "#ifdef UINTPTR");
HexFile.writeStr(sw, "#undef UINTPTR");
HexFile.writeStr(sw, "#endif");
HexFile.writeStr(sw, "");
HexFile.writeStr(sw, "#define INTPTR " + ((ass.GetPointerSize() == 4) ? ass.GetCType(m.SystemInt32) : ass.GetCType(m.SystemInt64)));
HexFile.writeStr(sw, "#define UINTPTR " + ((ass.GetPointerSize() == 4) ? ass.GetCType(m.GetSimpleTypeSpec(0x09)) : ass.GetCType(m.GetSimpleTypeSpec(0x0b))));
HexFile.writeStr(sw, "");
EmitArrayType(sw, ass, m);
foreach (string s in advance_defines)
HexFile.writeStr(sw, s);
HexFile.writeStr(sw, "");
if (oci != null)
{
foreach (string s2 in func_headers)
HexFile.writeStr(sw, s2);
HexFile.writeStr(sw, "");
}
hmsw.Flush();
StreamReader hmsr = new StreamReader(hmsw);
hmsr.BaseStream.Seek(0, SeekOrigin.Begin);
string hs = hmsr.ReadLine();
while (hs != null)
{
HexFile.writeStr(sw, hs);
hs = hmsr.ReadLine();
}
sw.Close();
if (oci != null)
{
foreach (string s in external_defines)
HexFile.writeStr(oci, s);
HexFile.writeStr(oci, "");
cmsw.Flush();
StreamReader cmsr = new StreamReader(cmsw);
cmsr.BaseStream.Seek(0, SeekOrigin.Begin);
string cs = cmsr.ReadLine();
while (cs != null)
{
HexFile.writeStr(oci, cs);
cs = cmsr.ReadLine();
}
oci.Close();
}
}
private static void EmitType(TypeSpec tdr, Stream hmsw, Stream cmsw,
List<string> advance_defines, List<string> external_defines, List<string> header_funcs, Target ass)
{
//Layout l = Layout.GetTypeInfoLayout(new Assembler.TypeToCompile { _ass = ass, tsig = new Signature.Param(tdr, ass), type = tdr }, ass, false);
//Layout l = tdr.GetLayout(new Signature.Param(new Token(tdr), ass).Type, ass, null);
var tname = tdr.m.GetStringEntry(MetadataStream.tid_TypeDef,
tdr.tdrow, 1);
var tns = tdr.m.GetStringEntry(MetadataStream.tid_TypeDef,
tdr.tdrow, 2);
int next_rsvd = 0;
int align = libtysila5.layout.Layout.GetTypeAlignment(tdr, ass, false);
if (!tdr.IsEnum)
{
HexFile.writeStr(hmsw, "struct " + tns + "_" + tname + " {");
advance_defines.Add("struct " + tns + "_" + tname + ";");
List<TypeSpec> fields = new List<TypeSpec>();
List<string> fnames = new List<string>();
libtysila5.layout.Layout.GetFieldOffset(tdr, null, ass, out var is_tls, false,
fields, fnames);
for (int i = 0; i < fields.Count; i++)
{
int bytesize;
HexFile.writeStr(hmsw, " " + ass.GetCType(fields[i], out bytesize) + " " + fnames[i] + ";");
// Pad out to align size
bytesize = align - bytesize;
while ((bytesize % 2) != 0)
{
HexFile.writeStr(hmsw, " uint8_t __reserved" + (next_rsvd++).ToString() + ";");
bytesize--;
}
while ((bytesize % 4) != 0)
{
HexFile.writeStr(hmsw, " uint16_t __reserved" + (next_rsvd++).ToString() + ";");
bytesize -= 2;
}
while(bytesize != 0)
{
HexFile.writeStr(hmsw, " uint32_t __reserved" + (next_rsvd++).ToString() + ";");
bytesize -= 4;
}
}
//if (packed_structs)
// HexFile.writeStr(hmsw, "} __attribute__((__packed__));");
//else
HexFile.writeStr(hmsw, "};");
}
else
{
// Identify underlying type
var utype = tdr.UnderlyingType;
bool needs_comma = false;
HexFile.writeStr(hmsw, "enum " + tns + "_" + tname + " {");
var first_fdef = tdr.m.GetIntEntry(MetadataStream.tid_TypeDef,
tdr.tdrow, 4);
var last_fdef = tdr.m.GetLastFieldDef(tdr.tdrow);
for (uint fdef_row = first_fdef; fdef_row < last_fdef; fdef_row++)
{
// Ensure field is static
var flags = tdr.m.GetIntEntry(MetadataStream.tid_Field,
(int)fdef_row, 0);
if ((flags & 0x10) == 0x10)
{
for(int cridx = 1; cridx <= tdr.m.table_rows[MetadataStream.tid_Constant]; cridx++)
{
int crpar_tid, crpar_row;
tdr.m.GetCodedIndexEntry(MetadataStream.tid_Constant,
cridx, 1, tdr.m.HasConstant, out crpar_tid, out crpar_row);
if(crpar_tid == MetadataStream.tid_Field &&
crpar_row == fdef_row)
{
var value = (int)tdr.m.GetIntEntry(MetadataStream.tid_Constant,
cridx, 2);
if (tdr.m.SigReadUSCompressed(ref value) != 4)
throw new NotSupportedException("Constant value not int32");
var v = tdr.m.sh_blob.di.ReadInt(value);
var fname = tdr.m.GetStringEntry(MetadataStream.tid_Field,
(int)fdef_row, 1);
if (needs_comma)
HexFile.writeStr(hmsw, ",");
HexFile.writeStr(hmsw, " " + fname + " = " + v.ToString(), true);
needs_comma = true;
}
}
}
}
HexFile.writeStr(hmsw);
HexFile.writeStr(hmsw, "};");
}
HexFile.writeStr(hmsw);
//if (output_cinit != null)
//{
if (!tdr.IsValueType)
{
string init_func = "void Init_" + tns + "_" + tname + "(struct " +
tns + "_" + tname + " *obj)";
HexFile.writeStr(cmsw, init_func);
header_funcs.Add(init_func + ";");
HexFile.writeStr(cmsw, "{");
HexFile.writeStr(cmsw, " obj->__vtbl = Get_Symbol_Addr(\"" + tdr.MangleType() + "\");");
HexFile.writeStr(cmsw, " obj->__mutex_lock = 0;");
HexFile.writeStr(cmsw, "}");
HexFile.writeStr(cmsw);
if(tdr.Equals(tdr.m.SystemString))
EmitStringInit(tdr, hmsw, cmsw, advance_defines, external_defines, header_funcs, ass);
}
//}
}
private static void EmitArrayInit(Stream hmsw, Stream cmsw, List<string> header_funcs,
Target ass, MetadataStream m)
{
EmitArrayInit(m.SystemObject, "Ref", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.SystemChar, "Char", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.SystemIntPtr, "I", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.SystemInt8, "I1", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.SystemInt16, "I2", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.SystemInt32, "I4", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.SystemInt64, "I8", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.GetSimpleTypeSpec(0x19), "U", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.GetSimpleTypeSpec(0x05), "U1", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.GetSimpleTypeSpec(0x07), "U2", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.GetSimpleTypeSpec(0x09), "U4", hmsw, cmsw, header_funcs, ass);
EmitArrayInit(m.GetSimpleTypeSpec(0x0b), "U8", hmsw, cmsw, header_funcs, ass);
}
private static void EmitArrayType(Stream hmsw, Target ass, MetadataStream m)
{
HexFile.writeStr(hmsw, "struct __array");
HexFile.writeStr(hmsw, "{");
HexFile.writeStr(hmsw, " INTPTR __vtbl;");
HexFile.writeStr(hmsw, " int64_t __mutex_lock;");
HexFile.writeStr(hmsw, " INTPTR elemtype;");
HexFile.writeStr(hmsw, " INTPTR lobounds;");
HexFile.writeStr(hmsw, " INTPTR sizes;");
HexFile.writeStr(hmsw, " INTPTR inner_array;");
HexFile.writeStr(hmsw, " INTPTR rank;");
HexFile.writeStr(hmsw, " int32_t elem_size;");
//if (packed_structs)
// HexFile.writeStr(hmsw, "} __attribute__((__packed__));");
//else
HexFile.writeStr(hmsw, "};");
HexFile.writeStr(hmsw);
}
private static void EmitArrayInit(TypeSpec ts, string tname, Stream hmsw, Stream cmsw,
List<string> header_funcs, Target ass)
{
string typestr = ass.GetCType(ts);
string init_func_name = "void* Create_" + tname + "_Array(struct __array **arr_obj, int32_t length)";
/* Arrays have four pieces of memory allocated:
* - The array superblock
* - The lobounds array
* - The sizes array
* - The actual array data
*
* We do not allocate the last 3, as they may need to be placed at a different virtual address
* when relocated - let the implementation decide this
*
* Code is:
*
* struct __array
* {
* intptr __vtbl;
* int32_t __object_id;
* int64_t __mutex_lock;
* int32_t rank;
* int32_t elem_size;
* intptr lobounds;
* intptr sizes;
* intptr inner_array;
* } __attribute__((__packed__));
*
* void Create_X_Array(__array **arr_obj, int32_t num_elems)
* {
* *arr_obj = (__array *)malloc(sizeof(arr_obj));
* (*arr_obj)->rank = 1;
* }
*/
//int elem_size = ass.GetPackedSizeOf(new Signature.Param(baseType_Type));
header_funcs.Add(init_func_name + ";");
HexFile.writeStr(cmsw, init_func_name);
HexFile.writeStr(cmsw, "{");
HexFile.writeStr(cmsw, " *arr_obj = (struct __array *)malloc(sizeof(struct __array));");
HexFile.writeStr(cmsw, " (*arr_obj)->__vtbl = Get_Symbol_Addr(\"" + ts.SzArray.MangleType() + "\");");
HexFile.writeStr(cmsw, " (*arr_obj)->__mutex_lock = 0;");
HexFile.writeStr(cmsw, " (*arr_obj)->rank = 1;");
HexFile.writeStr(cmsw, " (*arr_obj)->elem_size = sizeof(" + typestr + ");");
HexFile.writeStr(cmsw, " (*arr_obj)->elemtype = Get_Symbol_Addr(\"" + ts.MangleType() + "\");");
HexFile.writeStr(cmsw, " (*arr_obj)->lobounds = (INTPTR)(intptr_t)malloc(sizeof(int32_t));");
HexFile.writeStr(cmsw, " (*arr_obj)->sizes = (INTPTR)(intptr_t)malloc(sizeof(int32_t));");
HexFile.writeStr(cmsw, " (*arr_obj)->inner_array = (INTPTR)(intptr_t)malloc(length * sizeof(" + typestr + "));");
HexFile.writeStr(cmsw, " *(int32_t *)(intptr_t)((*arr_obj)->lobounds) = 0;");
HexFile.writeStr(cmsw, " *(int32_t *)(intptr_t)((*arr_obj)->sizes) = length;");
HexFile.writeStr(cmsw, " return((void *)(intptr_t)((*arr_obj)->inner_array));");
HexFile.writeStr(cmsw, "}");
HexFile.writeStr(cmsw);
}
private static void EmitStringInit(TypeSpec tdr, Stream hmsw, Stream cmsw,
List<string> advance_defines, List<string> external_defines, List<string> header_funcs, Target ass)
{
// Emit a string creation instruction of the form:
// void CreateString(System_String **obj, const char *s)
string init_func = "void CreateString(struct System_String **obj, const char *s)";
header_funcs.Add(init_func + ";");
HexFile.writeStr(cmsw, init_func);
HexFile.writeStr(cmsw, "{");
HexFile.writeStr(cmsw, " int i;");
HexFile.writeStr(cmsw, " int l = s == NULL ? 0 : strlen(s);");
HexFile.writeStr(cmsw, " " + ass.GetCType(tdr.m.SystemChar) + " *p;");
HexFile.writeStr(cmsw, " *obj = (struct System_String *)malloc(sizeof(struct System_String) + l * sizeof(" +
ass.GetCType(tdr.m.SystemChar) + "));");
HexFile.writeStr(cmsw, " Init_System_String(*obj);");
HexFile.writeStr(cmsw, " (*obj)->m_stringLength = l;");
HexFile.writeStr(cmsw, " p = &((*obj)->m_firstChar);");
//HexFile.writeStr(cmsw, " p = (" + ass.GetCType(BaseType_Type.Char) +
// " *)(*obj + sizeof(struct System_String));");
HexFile.writeStr(cmsw, " for(i = 0; i < l; i++)");
HexFile.writeStr(cmsw, " p[i] = (" + ass.GetCType(tdr.m.SystemChar) + ")s[i];");
HexFile.writeStr(cmsw, "}");
HexFile.writeStr(cmsw);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using libtysila4.graph;
namespace tysila4
{
class dftest
{
MultiNode[] n;
Graph ret;
void AddEdge(int x, int y)
{
n[x - 1].AddNext(n[y - 1]);
n[y - 1].AddPrev(n[x - 1]);
ret.bbs_after[x - 1].Add(y - 1);
ret.bbs_before[y - 1].Add(x - 1);
}
public Graph gen_test()
{
ret = new Graph();
ret.bbs_after = new List<List<int>>(new List<int>[13]);
ret.bbs_before = new List<List<int>>(new List<int>[13]);
ret.bb_starts = new List<BaseNode>(new BaseNode[13]);
ret.bb_ends = new List<BaseNode>(new BaseNode[13]);
n = new MultiNode[13];
for (int i = 0; i < 13; i++)
{
n[i] = new MultiNode();
n[i].bb = i;
ret.bb_starts[i] = n[i];
ret.bb_ends[i] = n[i];
ret.bbs_after[i] = new List<int>();
ret.bbs_before[i] = new List<int>();
ret.blocks.Add(new List<BaseNode> { n[i] });
}
AddEdge(1, 2);
AddEdge(2, 3);
AddEdge(3, 3);
AddEdge(3, 4);
AddEdge(4, 13);
AddEdge(1, 5);
AddEdge(5, 6);
AddEdge(6, 4);
AddEdge(6, 8);
AddEdge(8, 13);
AddEdge(8, 5);
AddEdge(5, 7);
AddEdge(7, 8);
AddEdge(7, 12);
AddEdge(1, 9);
AddEdge(9, 10);
AddEdge(10, 12);
AddEdge(12, 13);
AddEdge(9, 11);
AddEdge(11, 12);
ret.Starts.Add(n[0]);
return ret;
}
public static void df_test()
{
var df = new dftest();
var g = df.gen_test();
var dg = libtysila4.graph.DominanceGraph.GenerateDominanceGraph(g, null);
}
}
}
<file_sep>// XGetopt.cs Version 1.0
//
// Author: <NAME>
// <EMAIL>
//
// Description:
// The Getopt() method parses command line arguments. It is modeled
// after the Unix function getopt(). Its parameters argc and argv are
// the argument count and array as passed into the application on program
// invocation. Getopt returns the next option letter in argv that
// matches a letter in optstring.
//
// optstring is a string of allowable option letters; if a letter is
// followed by a colon, the option is expected to have an argument that
// may or may not be separated from it by white space. optarg contains
// the option argument on return from Getopt (use the Optarg property).
//
// Option letters may be combined, e.g., "-ab" is equivalent to "-a -b".
// Option letters are case sensitive.
//
// Getopt places in the internal variable optind the argv index of the
// next argument to be processed. optind is initialized to 0 before the
// first call to Getopt. Use the Optind property to query the optind
// value.
//
// When all options have been processed (i.e., up to the first non-option
// argument), Getopt returns '\0', optarg will contain the argument,
// and optind will be set to the argv index of the argument. If there
// are no non-option arguments, optarg will be Empty.
//
// The special option "--" may be used to delimit the end of the options;
// '\0' will be returned, and "--" (and everything after it) will be
// skipped.
//
// Return Value:
// For option letters contained in the string optstring, Getopt will
// return the option letter. Getopt returns a question mark ('?') when
// it encounters an option letter not included in optstring. '\0' is
// returned when processing is finished.
//
// Limitations:
// 1) Long options are not supported.
// 2) The GNU double-colon extension is not supported.
// 3) The environment variable POSIXLY_CORRECT is not supported.
// 4) The + syntax is not supported.
// 5) The automatic permutation of arguments is not supported.
// 6) This implementation of Getopt() returns '\0' if an error is
// encountered, instead of -1 as the latest standard requires.
// 7) This implementation of Getopt() returns a char instead of an int.
//
// Example:
// static int Main(string[] args)
// {
// int argc = args.Length;
// char c;
// XGetopt go = new XGetopt();
// while ((c = go.Getopt(argc, args, "aBn:")) != '\0')
// {
// switch (c)
// {
// case 'a':
// Console.WriteLine("option -a");
// break;
//
// case 'B':
// Console.WriteLine("option -B");
// break;
//
// case 'n':
// Console.WriteLine("option -n with arg '{0}'", go.Optarg);
// break;
//
// case '?':
// Console.WriteLine("illegal option or missing arg");
// return 1;
// }
// }
//
// if (go.Optarg != string.Empty)
// Console.WriteLine("non-option arg '{0}'", go.Optarg);
//
// ...
//
// return 0;
// }
//
// History:
// Version 1.0 - 2007 June 5
// - Initial public release
//
// License:
// This software is released into the public domain. You are free to use
// it in any way you like, except that you may not sell this source code.
//
// This software is provided "as is" with no expressed or implied warranty.
// I accept no liability for any damage or loss of business that this
// software may cause.
//
///////////////////////////////////////////////////////////////////////////////
//#define XGETOPT_VERBOSE
using System;
using System.Collections.Generic;
using System.Text;
namespace XGetoptCS
{
public class XGetopt
{
#region Class data
private int optind;
private string nextarg;
private string optarg;
#endregion
#region Class properties
public string Optarg
{
get
{
return optarg;
}
}
public int Optind
{
get
{
return optind;
}
}
#endregion
#region Class public methods
public XGetopt()
{
Init();
}
public void Init()
{
optind = 0;
optarg = string.Empty;
nextarg = string.Empty;
}
public char Getopt(int argc, string[] argv, string optstring)
{
#if XGETOPT_VERBOSE
Console.WriteLine("Getopt: argc = {0}", argc);
#endif
optarg = string.Empty;
if (argc < 0)
return '?';
#if XGETOPT_VERBOSE
if (optind < argc)
Console.WriteLine("Getopt: argv[{0}] = {1}", optind, argv[optind]);
#endif
if (optind == 0)
nextarg = string.Empty;
if (nextarg.Length == 0)
{
if (optind >= argc || argv[optind][0] != '-' || argv[optind].Length < 2)
{
// no more options
optarg = string.Empty;
if (optind < argc)
optarg = argv[optind]; // return leftover arg
return '\0';
}
if (argv[optind] == "--")
{
// 'end of options' flag
optind++;
optarg = string.Empty;
if (optind < argc)
optarg = argv[optind];
return '\0';
}
nextarg = string.Empty;
if (optind < argc)
{
nextarg = argv[optind];
nextarg = nextarg.Substring(1); // skip past -
}
optind++;
}
char c = nextarg[0]; // get option char
nextarg = nextarg.Substring(1); // skip past option char
int index = optstring.IndexOf(c); // check if this is valid option char
if (index == -1 || c == ':')
return '?';
index++;
if ((index < optstring.Length) && (optstring[index] == ':'))
{
// option takes an arg
if (nextarg.Length > 0)
{
optarg = nextarg;
nextarg = string.Empty;
}
else if (optind < argc)
{
optarg = argv[optind];
optind++;
}
else
{
return '?';
}
}
return c;
}
#endregion
}
}
<file_sep>using System;
namespace ConsoleUtils
{
public static class ConsoleKeyConverter
{
public static bool TryParseChar(char keyChar, out ConsoleKey consoleKey)
{
if (!Enum.TryParse(keyChar.ToString().ToUpper(), out consoleKey))
return false;
return true;
}
public static char ConvertConsoleKey(ConsoleKey consoleKey)
{
return (char) consoleKey;
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Text;
using libtysila5.cil;
using metadata;
using libtysila5.util;
namespace libtysila5.ir
{
public partial class ConvertToIR
{
internal delegate Stack<StackItem> intcall_delegate(CilNode n, Code c, Stack<StackItem> stack_before);
internal static System.Collections.Generic.Dictionary<string, intcall_delegate> intcalls =
new System.Collections.Generic.Dictionary<string, intcall_delegate>(
new GenericEqualityComparer<string>());
static void init_intcalls()
{
intcalls["_Zu1S_9get_Chars_Rc_P2u1ti"] = string_getChars;
intcalls["_Zu1S_10get_Length_Ri_P1u1t"] = string_getLength;
intcalls["_Zu1S_19InternalAllocateStr_Ru1S_P1i"] = string_InternalAllocate;
intcalls["_Zu1S_18FastAllocateString_Ru1S_P1i"] = string_InternalAllocate;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_3Add_Ru1I_P2u1Iu1I"] = intptr_Add;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_3Mul_Ru1I_P2u1Iu1I"] = intptr_Mul;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_3Sub_Ru1I_P2u1Iu1I"] = intptr_Sub;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_3Add_Ru1U_P2u1Uu1U"] = uintptr_Add;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_3Mul_Ru1U_P2u1Uu1U"] = uintptr_Mul;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_3Sub_Ru1U_P2u1Uu1U"] = uintptr_Sub;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_5CallI_Rv_P1Pv"] = calli;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_5CallI_Rv_P2PvPv"] = calli_pvpv;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_5CallI_Ru1p0_P1Pv"] = calli_gen;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_18GetFunctionAddress_RPv_P1u1S"] = get_func_address;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_22GetStaticObjectAddress_RPv_P1u1S"] = get_static_obj_address;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_14GetPointerSize_Ri_P0"] = get_pointer_size;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_17GetArrayClassSize_Ri_P0"] = array_getArrayClassSize;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_17GetElemTypeOffset_Ri_P0"] = array_getElemTypeOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_19GetInnerArrayOffset_Ri_P0"] = array_getInnerArrayOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_17GetElemSizeOffset_Ri_P0"] = array_getElemSizeOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_13GetRankOffset_Ri_P0"] = array_getRankOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_14GetSizesOffset_Ri_P0"] = array_getSizesOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ArrayOperations_17GetLoboundsOffset_Ri_P0"] = array_getLoboundsOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_16GetInternalArray_RPv_P1W6System5Array"] = array_getInternalArray;
intcalls["_ZN14libsupcs#2Edll8libsupcs16StringOperations_13GetDataOffset_Ri_P0"] = string_getDataOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs16StringOperations_15GetLengthOffset_Ri_P0"] = string_getLengthOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_26GetVtblInterfacesPtrOffset_Ri_P0"] = class_getVtblInterfacesPtrOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_27GetVtblExtendsVtblPtrOffset_Ri_P0"] = class_getVtblExtendsPtrOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_22GetBoxedTypeDataOffset_Ri_P0"] = class_getBoxedTypeDataOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_18GetVtblFieldOffset_Ri_P0"] = class_getVtblFieldOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_21GetVtblTypeSizeOffset_Ri_P0"] = class_getVtblTypeSizeOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_18GetVtblFlagsOffset_Ri_P0"] = class_getVtblFlagsOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_25GetVtblBaseTypeVtblOffset_Ri_P0"] = class_getVtblBaseTypeVtblOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_25GetVtblTargetFieldsOffset_Ri_P0"] = class_getVtblTargetFieldsOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_18GetMutexLockOffset_Ri_P0"] = class_getMutexLockOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_23GetSystemTypeImplOffset_Ri_P0"] = class_getSystemTypeImplOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_14GetFieldOffset_Ri_P2u1Su1S"] = class_getFieldOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_20GetStaticFieldOffset_Ri_P2u1Su1S"] = class_getStaticFieldOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_21GetDelegateFPtrOffset_Ri_P0"] = class_getDelegateFPtrOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_6PeekU1_Rh_P1u1U"] = peek_Byte;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_6PeekU2_Rt_P1u1U"] = peek_Ushort;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_6PeekU4_Rj_P1u1U"] = peek_Uint;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_6PeekU8_Ry_P1u1U"] = peek_Ulong;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_4Poke_Rv_P2u1Uh"] = poke_Byte;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_4Poke_Rv_P2u1Ut"] = poke_Ushort;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_4Poke_Rv_P2u1Uj"] = poke_Uint;
intcalls["_ZN14libsupcs#2Edll8libsupcs16MemoryOperations_4Poke_Rv_P2u1Uy"] = poke_Ulong;
intcalls["_ZW20System#2EDiagnostics8Debugger_5Break_Rv_P0"] = debugger_Break;
intcalls["_ZW34System#2ERuntime#2EInteropServices7Marshal_37GetFunctionPointerForDelegateInternal_Ru1I_P1U6System8Delegate"] = getFunctionPointerForDelegate;
intcalls["_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_15InitializeArray_Rv_P2U6System5Arrayu1I"] = runtimeHelpers_initializeArray;
intcalls["_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_22get_OffsetToStringData_Ri_P0"] = runtimeHelpers_getOffsetToStringData;
intcalls["_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_31IsReferenceOrContainsReferences_Rb_P0"] = runtimeHelpers_isReferenceOrContainsReferences;
intcalls["_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_6Equals_Rb_P2u1Ou1O"] = runtimeHelpers_Equals;
intcalls["_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_11GetHashCode_Ri_P1u1O"] = runtimeHelpers_GetHashCode;
intcalls["_ZW35System#2ERuntime#2ECompilerServices10JitHelpers_10UnsafeCast_Ru1p0_P1u1O"] = jitHelpers_unsafeCast;
intcalls["_ZW35System#2ERuntime#2ECompilerServices10JitHelpers_24UnsafeCastToStackPointer_Ru1I_P1Ru1p0"] = jitHelpers_unsafeCastToStackPointer;
intcalls["_ZW20System#2EDiagnostics8Debugger_3Log_Rv_P3iu1Su1S"] = debugger_Log;
intcalls["_ZW19System#2EReflection8Assembly_20GetExecutingAssembly_RV8Assembly_P0"] = assembly_GetExecutingAssembly;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_21SyncValCompareAndSwap_Rh_P3Phhh"] = sync_cswap;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_12SpinlockHint_Rv_P0"] = spinlock_hint;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_28GetTypedReferenceValueOffset_Ri_P0"] = typedref_ValueOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15ClassOperations_27GetTypedReferenceTypeOffset_Ri_P0"] = typedref_TypeOffset;
intcalls["_ZN14libsupcs#2Edll8libsupcs15OtherOperations_15CompareExchange_RPv_P3PPvPvPv"] = threading_CompareExchange_IntPtr;
intcalls["_ZW18System#2EThreading11Interlocked_15CompareExchange_Ru1I_P3Ru1Iu1Iu1I"] = threading_CompareExchange_IntPtr;
intcalls["_ZW18System#2EThreading11Interlocked_15CompareExchange_Ru1O_P3Ru1Ou1Ou1O"] = threading_CompareExchange_Object;
intcalls["_ZW18System#2EThreading11Interlocked_15CompareExchange_Ri_P3Riii"] = threading_CompareExchange_int;
intcalls["_ZW18System#2EThreading11Interlocked_15CompareExchange_Rx_P3Rxxx"] = threading_CompareExchange_long;
intcalls["_ZW18System#2EThreading11Interlocked_16_CompareExchange_Rv_P3u1Tu1Tu1O"] = threading_CompareExchange_TypedRef;
intcalls["_ZW18System#2EThreading11Interlocked_15CompareExchange_Ru1p0_P3Ru1p0u1p0u1p0"] = threading_CompareExchange_Generic;
intcalls["_ZW18System#2EThreading11Interlocked_11ExchangeAdd_Rx_P2Rxx"] = threading_ExchangeAdd_long;
intcalls["_ZW34System#2ERuntime#2EInteropServices8GCHandle_23InternalCompareExchange_Ru1O_P4u1Iu1Ou1Ob"] = gcHandle_InternalCompareExchange;
intcalls["_ZW18System#2EThreading11Interlocked_8Exchange_Rx_P2Rxx"] = threading_Exchange_long;
intcalls["_ZW35System#2ERuntime#2ECompilerServices6Unsafe_2As_RRu1p1_P1Ru1p0"] = unsafe_as_generic;
intcalls["_ZW35System#2ERuntime#2ECompilerServices6Unsafe_13ReadUnaligned_Ru1p0_P1Rh"] = unsafe_readunaligned_generic;
intcalls["_ZW35System#2ERuntime#2ECompilerServices6Unsafe_13ReadUnaligned_Ru1p0_P1Pv"] = unsafe_readunaligned_generic;
}
private static Stack<StackItem> unsafe_as_generic(CilNode n, Code c, Stack<StackItem> stack_before)
{
// Handle similarly to ReinterpretAs...
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
var stack_after = new Stack<StackItem>(stack_before);
var popped_st = stack_after.Pop();
var new_st = popped_st.Clone();
new_st.ts = c_ms.ReturnType;
stack_after.Push(new_st);
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, arg_a = 0, res_a = 0, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> unsafe_readunaligned_generic(CilNode n, Code c, Stack<StackItem> stack_before)
{
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
var ts = c_ms.ReturnType;
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Push(new StackItem { ts = ts });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_ldind, ct = Opcode.GetCTFromType(ts), vt_size = c.t.GetSize(ts), imm_ul = 0, imm_l = ts.IsSigned ? 1 : 0, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> runtimeHelpers_GetHashCode(CilNode n, Code c, Stack<StackItem> stack_before)
{
// We are only required to return identical hashcodes for objects that have equal references
// First convert to an intptr to prevent conv_op_valid failing (this should encode to nop)
var stack_after = conv(n, c, stack_before, (int)CorElementType.I);
return conv(n, c, stack_after, (int)CorElementType.I4);
}
private static Stack<StackItem> runtimeHelpers_Equals(CilNode n, Code c, Stack<StackItem> stack_before)
{
return cmp(n, c, stack_before, Opcode.cc_eq);
}
private static Stack<StackItem> runtimeHelpers_isReferenceOrContainsReferences(CilNode n, Code c, Stack<StackItem> stack_before)
{
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
bool ret = isRefOrContainsRef(c_ms.gmparams[0], c);
if (ret)
return ldc(n, c, stack_before, -1, (int)CorElementType.I4);
else
return ldc(n, c, stack_before, 0, (int)CorElementType.I4);
}
private static bool isRefOrContainsRef(TypeSpec ts, Code c)
{
var ct = Opcode.GetCTFromType(ts);
if (ct == Opcode.ct_object)
return true;
else if (ct == Opcode.ct_vt)
{
System.Collections.Generic.List<TypeSpec> fld_types = new System.Collections.Generic.List<TypeSpec>();
layout.Layout.GetFieldOffset(ts, null, c.t, out var is_tls, false, fld_types);
foreach(var fld_type in fld_types)
{
if (isRefOrContainsRef(fld_type, c))
return true;
}
return false;
}
else
return false;
}
private static Stack<StackItem> gcHandle_InternalCompareExchange(CilNode n, Code c, Stack<StackItem> stack_before)
{
/* CompareExchange(IntPtr handle, Object value, Object old_value, bool isPinned)
*
* We ignore the isPinend value */
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
stack_after.Pop();
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemObject });
// Do synchronized instruction (arga = value, argb = comparand, argc = location, res = new)
n.irnodes.Add(new CilNode.IRNode
{
parent = n,
opcode = Opcode.oc_syncvalcompareandswap,
imm_l = c.t.GetPointerSize(),
imm_ul = 0,
stack_before = stack_before,
stack_after = stack_after,
arg_a = 2,
arg_b = 1,
arg_c = 3,
res_a = 0
});
return stack_after;
}
private static Stack<StackItem> threading_CompareExchange_int(CilNode n, Code c, Stack<StackItem> stack_before)
{
/* CompareExchange(ref int location1, int value, int comparand) */
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemInt32 });
// Do synchronized instruction (arga = value, argb = comparand, argc = location, res = new)
n.irnodes.Add(new CilNode.IRNode
{
parent = n,
opcode = Opcode.oc_syncvalcompareandswap,
imm_l = 4,
imm_ul = 0,
stack_before = stack_before,
stack_after = stack_after,
arg_a = 1,
arg_b = 0,
arg_c = 2,
res_a = 0
});
return stack_after;
}
private static Stack<StackItem> threading_Exchange_long(CilNode n, Code c, Stack<StackItem> stack_before)
{
/* Exchange(ref long location1, long value) */
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemInt64 });
// Do synchronized instruction (arga = location, argb = value, res = orig)
n.irnodes.Add(new CilNode.IRNode
{
parent = n,
opcode = Opcode.oc_syncvalswap,
imm_l = 8,
imm_ul = 0,
stack_before = stack_before,
stack_after = stack_after,
arg_a = 1,
arg_b = 0,
res_a = 0
});
return stack_after;
}
private static Stack<StackItem> threading_CompareExchange_long(CilNode n, Code c, Stack<StackItem> stack_before)
{
/* CompareExchange(ref int location1, int value, int comparand) */
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemInt64 });
// Do synchronized instruction (arga = value, argb = comparand, argc = location, res = new)
n.irnodes.Add(new CilNode.IRNode
{
parent = n,
opcode = Opcode.oc_syncvalcompareandswap,
imm_l = 8,
imm_ul = 0,
stack_before = stack_before,
stack_after = stack_after,
arg_a = 1,
arg_b = 0,
arg_c = 2,
res_a = 0
});
return stack_after;
}
private static Stack<StackItem> threading_ExchangeAdd_long(CilNode n, Code c, Stack<StackItem> stack_before)
{
/* ExchangeAdd(ref int location1, int value) */
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemInt64 });
// Do synchronized instruction (arga = value, argb = location, res = [location] (before add))
n.irnodes.Add(new CilNode.IRNode
{
parent = n,
opcode = Opcode.oc_syncvalexchangeandadd,
imm_l = 8,
imm_ul = 0,
stack_before = stack_before,
stack_after = stack_after,
arg_a = 0,
arg_b = 1,
res_a = 0
});
return stack_after;
}
private static Stack<StackItem> threading_CompareExchange_Generic(CilNode n, Code c, Stack<StackItem> stack_before)
{
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
/* Sanity check T is a reference type */
var T = c_ms.gmparams[0];
if(T.IsValueType)
throw new InvalidOperationException("CompareExchange<T> with value type (" + T.ToString()+ ")");
var ret = threading_CompareExchange_IntPtr(n, c, stack_before);
ret.Peek().ts = T;
return ret;
}
private static Stack<StackItem> threading_CompareExchange_Object(CilNode n, Code c, Stack<StackItem> stack_before)
{
var ret = threading_CompareExchange_IntPtr(n, c, stack_before);
ret.Peek().ts = c.ms.m.SystemObject;
return ret;
}
private static Stack<StackItem> threading_CompareExchange_IntPtr(CilNode n, Code c, Stack<StackItem> stack_before)
{
Stack<StackItem> ret;
if (c.t.GetPointerSize() == 4)
ret = threading_CompareExchange_int(n, c, stack_before);
else
ret = threading_CompareExchange_long(n, c, stack_before);
ret.Peek().ts = c.ms.m.SystemIntPtr;
return ret;
}
private static Stack<StackItem> threading_CompareExchange_TypedRef(CilNode n, Code c, Stack<StackItem> stack_before)
{
/* _CompareExchange(TypedReference location1, TypedReference Value, object comparand) */
// Convert in-place location1 to its ptr
stack_before = typedref_ValueOffset(n, c, stack_before);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, ir.Opcode.ct_intptr, 3, -1, 2);
stack_before = ldind(n, c, stack_before, c.ms.m.SystemIntPtr, 2, false, 2);
// Convert in-place Value to its ptr then dereference
stack_before = typedref_ValueOffset(n, c, stack_before);
stack_before = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add, ir.Opcode.ct_intptr, 2, -1, 1);
stack_before = ldind(n, c, stack_before, c.ms.m.SystemIntPtr, 1, false, 1);
stack_before = ldind(n, c, stack_before, c.ms.m.SystemObject, 1, false, 1);
// Do synchronized instruction (arga = value, argb = comparand, argc = location, res = new)
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
stack_after.Push(new StackItem { ts = c.ms.m.SystemObject });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_syncvalcompareandswap,
imm_l = c.t.GetPointerSize(), imm_ul = 0, stack_before = stack_before, stack_after = stack_after,
arg_a = 1, arg_b = 0, arg_c = 2, res_a = 0 });
// store res back to *location1
stack_after = stind(n, c, stack_after, c.t.GetPointerSize());
return stack_after;
}
private static Stack<StackItem> typedref_ValueOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var typedref = c.ms.m.al.GetAssembly("mscorlib").GetSimpleTypeSpec((int)CorElementType.TypedByRef);
return ldc(n, c, stack_before, layout.Layout.GetFieldOffset(typedref, "Value", c.t, out var is_tls), (int)CorElementType.I4);
}
private static Stack<StackItem> typedref_TypeOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var typedref = c.ms.m.al.GetAssembly("mscorlib").GetSimpleTypeSpec((int)CorElementType.TypedByRef);
return ldc(n, c, stack_before, layout.Layout.GetFieldOffset(typedref, "Type", c.t, out var is_tls), (int)CorElementType.I4);
}
private static Stack<StackItem> spinlock_hint(CilNode n, Code c, Stack<StackItem> stack_before)
{
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_spinlockhint, stack_before = stack_before, stack_after = stack_before });
return stack_before;
}
private static Stack<StackItem> sync_cswap(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
stack_after.Pop();
stack_after.Pop();
var ret_type_ptr = stack_after.Pop().ts;
var ret_type = ret_type_ptr.other;
var size = c.t.GetSize(ret_type);
stack_after.Push(new StackItem { ts = ret_type });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_syncvalcompareandswap, imm_l = size, imm_ul = ret_type.IsSigned ? 1UL : 0UL, stack_before = stack_before, stack_after = stack_after });
return stack_after;
}
private static Stack<StackItem> runtimeHelpers_getOffsetToStringData(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = ldc(n, c, stack_before, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Start_Char, c));
return stack_after;
}
private static Stack<StackItem> jitHelpers_unsafeCast(CilNode n, Code c, Stack<StackItem> stack_before)
{
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
/* TODO: limit usage to trusted code */
/* Ensure the stack contains a valid reference type */
var from_obj = stack_before.Peek();
if (from_obj.ts.IsValueType)
throw new Exception("Invalid type passed to JitHelpers.UnsafeCast: " + from_obj.ts);
/* Convert to the 'to' type */
var stack_after = new Stack<StackItem>(stack_before);
stack_after[stack_after.Count - 1] = new StackItem { ts = c_ms.gmparams[0] };
return stack_after;
}
private static Stack<StackItem> jitHelpers_unsafeCastToStackPointer(CilNode n, Code c, Stack<StackItem> stack_before)
{
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
/* TODO: limit usage to trusted code */
/* Ensure the stack contains a valid reference to T */
var from_obj = stack_before.Peek();
if (from_obj.ts.stype != TypeSpec.SpecialType.MPtr || !from_obj.ts.other.Equals(c_ms.gmparams[0]))
throw new Exception("Invalid type passed to JitHelpers.UnsafeCast: " + from_obj.ts);
/* Convert to the 'to' type */
var stack_after = new Stack<StackItem>(stack_before);
stack_after[stack_after.Count - 1] = new StackItem { ts = c.ms.m.SystemIntPtr };
return stack_after;
}
private static Stack<StackItem> string_InternalAllocate(CilNode n, Code c, Stack<StackItem> stack_before)
{
// save string length
var stack_after = copy_to_front(n, c, stack_before);
// Multiply number of characters by two, then add size of the string object and an extra pointer size to null-terminate for coreclr
stack_after = ldc(n, c, stack_after, 2);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_intptr);
stack_after = ldc(n, c, stack_after, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Start_Char, c) + c.t.GetPointerSize(), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
// Create object
stack_after = call(n, c, stack_after, false, "gcmalloc", c.special_meths,
c.special_meths.gcmalloc);
// vtbl
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldlab(n, c, stack_after, c.ms.m.SystemString.Type.MangleType());
stack_after = stind(n, c, stack_after, c.t.psize);
// mutex lock
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.MutexLock, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldc(n, c, stack_after, 0, 0x18);
stack_after = stind(n, c, stack_after, c.t.psize);
/* now the stack is ..., length, object.
*
* First save the length then move object up the stack */
stack_after = copy_to_front(n, c, stack_after);
stack_after = ldc(n, c, stack_after, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Length, c), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = copy_to_front(n, c, stack_after, 2);
stack_after = stind(n, c, stack_after, c.t.GetSize(c.ms.m.SystemIntPtr));
var stack_after2 = new Stack<StackItem>(stack_after);
stack_after2.Pop();
stack_after2.Pop();
stack_after2.Push(new StackItem { ts = c.ms.m.SystemString });
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_stackcopy, arg_a = 0, res_a = 0, stack_before = stack_after, stack_after = stack_after2 });
return stack_after2;
}
private static Stack<StackItem> assembly_GetExecutingAssembly(CilNode n, Code c, Stack<StackItem> stack_before)
{
// get the appropriate methods
var libsupcs = c.ms.m.al.GetAssembly("libsupcs");
if (libsupcs == null)
throw new Exception("Cannot load libsupcs");
var tmeth = libsupcs.GetTypeSpec("libsupcs", "TysosModule");
var get_mod = tmeth.m.GetMethodSpec(tmeth, "GetModule");
var get_ass = tmeth.m.GetMethodSpec(tmeth, "GetAssembly");
// push current assembly metadata and its name then call into libsupcs for the assembly itself
var stack_after = ldlab(n, c, stack_before, c.ms.m.AssemblyName);
stack_after = ldstr(n, c, stack_after, c.ms.m.AssemblyName);
stack_after = call(n, c, stack_after, false, null, null, 0, 0, get_mod);
stack_after = call(n, c, stack_after, false, null, null, 0, 0, get_ass);
return stack_after;
}
private static Stack<StackItem> debugger_Log(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = call(n, c, stack_before, false, "__log", c.special_meths,
c.special_meths.debugger_Log);
return stack_after;
}
private static Stack<StackItem> string_getDataOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = ldc(n, c, stack_before, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Start_Char, c));
return stack_after;
}
private static Stack<StackItem> string_getLengthOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = ldc(n, c, stack_before, layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Length, c));
return stack_after;
}
private static Stack<StackItem> runtimeHelpers_initializeArray(CilNode n, Code c, Stack<StackItem> stack_before)
{
// load dest pointer onto stack
var stack_after = copy_to_front(n, c, stack_before, 1);
stack_after = ldc(n, c, stack_after, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemIntPtr);
// load src pointer onto stack
stack_after = copy_to_front(n, c, stack_after, 1);
stack_after = ldc(n, c, stack_after, 2 * c.t.psize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemIntPtr);
// load byte count onto stack
stack_after = copy_to_front(n, c, stack_after, 2);
stack_after = ldc(n, c, stack_after, c.t.psize, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemInt32);
// call memcpy
stack_after = memcpy(n, c, stack_after);
// remove memcpy arguments
stack_after = new Stack<StackItem>(stack_after);
stack_after.Pop();
stack_after.Pop();
stack_after.Pop();
// remove function arguments
stack_after.Pop();
stack_after.Pop();
return stack_after;
}
private static Stack<StackItem> getFunctionPointerForDelegate(CilNode n, Code c, Stack<StackItem> stack_before)
{
var dgate = c.ms.m.SystemDelegate.Type;
var method_ptr = dgate.m.GetFieldDefRow("method_ptr", dgate);
if (method_ptr == null)
method_ptr = dgate.m.GetFieldDefRow("_methodPtr", dgate);
TypeSpec fld_ts;
var stack_after = ldflda(n, c, stack_before, false, out fld_ts, 0, method_ptr);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemIntPtr);
return stack_after;
}
private static Stack<StackItem> class_getDelegateFPtrOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var dgate = c.ms.m.SystemDelegate.Type;
var v = layout.Layout.GetFieldOffset(dgate, "_methodPtr", c.t, out var is_tls);
return ldc(n, c, stack_before, v);
}
private static Stack<StackItem> class_getSystemTypeImplOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var systype = c.ms.m.al.GetAssembly("libsupcs").GetTypeSpec("libsupcs", "TysosType");
var v = layout.Layout.GetFieldOffset(systype, "_impl", c.t, out var is_tls);
return ldc(n, c, stack_before, v);
}
private static Stack<StackItem> debugger_Break(CilNode n, Code c, Stack<StackItem> stack_before)
{
n.irnodes.Add(new CilNode.IRNode { parent = n, opcode = Opcode.oc_break, stack_before = stack_before, stack_after = stack_before });
return stack_before;
}
private static Stack<StackItem> calli(CilNode n, Code c, Stack<StackItem> stack_before)
{
return call(n, c, stack_before, true, "calli_target", c.special_meths, c.special_meths.static_Rv_P0);
}
private static Stack<StackItem> calli_pvpv(CilNode n, Code c, Stack<StackItem> stack_before)
{
return call(n, c, stack_before, true, "calli_target", c.special_meths, c.special_meths.static_Rv_P1Pv);
}
private static Stack<StackItem> calli_gen(CilNode n, Code c, Stack<StackItem> stack_before)
{
// get return type
var c_ms = c.ms.m.GetMethodSpec(n.inline_uint, c.ms.gtparams, c.ms.gmparams);
var rt = c_ms.ReturnType;
// build an appropriate signature
var sig = c.special_meths.CreateMethodSignature(rt, new TypeSpec[] { }, false);
return call(n, c, stack_before, true, "calli_target", c.special_meths, sig);
}
private static Stack<StackItem> poke_Ulong(CilNode n, Code c, Stack<StackItem> stack_before)
{
return stind(n, c, stack_before, 8);
}
private static Stack<StackItem> poke_Uint(CilNode n, Code c, Stack<StackItem> stack_before)
{
return stind(n, c, stack_before, 4);
}
private static Stack<StackItem> poke_Ushort(CilNode n, Code c, Stack<StackItem> stack_before)
{
return stind(n, c, stack_before, 2);
}
private static Stack<StackItem> poke_Byte(CilNode n, Code c, Stack<StackItem> stack_before)
{
return stind(n, c, stack_before, 1);
}
private static Stack<StackItem> peek_Ulong(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldind(n, c, stack_before, c.ms.m.SystemUInt64);
}
private static Stack<StackItem> peek_Uint(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldind(n, c, stack_before, c.ms.m.SystemUInt32);
}
private static Stack<StackItem> peek_Ushort(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldind(n, c, stack_before, c.ms.m.SystemUInt16);
}
private static Stack<StackItem> peek_Byte(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldind(n, c, stack_before, c.ms.m.SystemByte);
}
private static Stack<StackItem> array_getInternalArray(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t), 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemVoid.Type.Pointer);
return stack_after;
}
private static Stack<StackItem> class_getVtblFieldOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 0);
}
private static Stack<StackItem> class_getBoxedTypeDataOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetTypeSize(c.ms.m.SystemObject, c.t));
}
private static Stack<StackItem> class_getVtblExtendsPtrOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 2 * c.t.GetPointerSize());
}
private static Stack<StackItem> class_getVtblInterfacesPtrOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 1 * c.t.GetPointerSize());
}
private static Stack<StackItem> class_getVtblTypeSizeOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 3 * c.t.GetPointerSize());
}
private static Stack<StackItem> class_getVtblFlagsOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 4 * c.t.GetPointerSize());
}
private static Stack<StackItem> class_getVtblBaseTypeVtblOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 5 * c.t.GetPointerSize());
}
private static Stack<StackItem> class_getVtblTargetFieldsOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, 6 * c.t.GetPointerSize());
}
private static Stack<StackItem> class_getMutexLockOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.MutexLock, c.t));
}
private static Stack<StackItem> array_getLoboundsOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.LoboundsPointer, c.t));
}
private static Stack<StackItem> array_getSizesOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.SizesPointer, c.t));
}
private static Stack<StackItem> array_getRankOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.Rank, c.t));
}
private static Stack<StackItem> array_getElemSizeOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.ElemTypeSize, c.t));
}
private static Stack<StackItem> array_getInnerArrayOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.DataArrayPointer, c.t));
}
private static Stack<StackItem> array_getElemTypeOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayFieldOffset(layout.Layout.ArrayField.ElemTypeVtblPointer, c.t));
}
private static Stack<StackItem> array_getArrayClassSize(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, layout.Layout.GetArrayObjectSize(c.t));
}
private static Stack<StackItem> get_pointer_size(CilNode n, Code c, Stack<StackItem> stack_before)
{
return ldc(n, c, stack_before, c.t.GetPointerSize());
}
private static Stack<StackItem> class_getFieldOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
var field = stack_after.Pop().str_val;
var type = stack_after.Pop().str_val;
if(field == null || type == null)
{
throw new Exception("getFieldOffset with null arguments");
}
var ts = c.ms.m.DemangleType(type);
var offset = layout.Layout.GetFieldOffset(ts, field, c.t, out var is_tls);
stack_after = ldc(n, c, stack_after, offset);
return stack_after;
}
private static Stack<StackItem> class_getStaticFieldOffset(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
var field = stack_after.Pop().str_val;
var type = stack_after.Pop().str_val;
if (field == null || type == null)
{
throw new Exception("getStaticFieldOffset with null arguments");
}
var ts = c.ms.m.DemangleType(type);
var offset = layout.Layout.GetFieldOffset(ts, field, c.t, out var is_tls, true);
stack_after = ldc(n, c, stack_after, offset);
return stack_after;
}
private static Stack<StackItem> get_static_obj_address(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
var src = stack_after.Pop();
if (src.str_val == null)
return null;
stack_after = ldlab(n, c, stack_after, src.str_val);
return stack_after;
}
private static Stack<StackItem> get_func_address(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = new Stack<StackItem>(stack_before);
var src = stack_after.Pop();
if (src.str_val == null)
return null;
stack_after = ldlab(n, c, stack_after, src.str_val);
return stack_after;
}
private static Stack<StackItem> intptr_Mul(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.mul,
Opcode.ct_intptr);
return stack_after;
}
private static Stack<StackItem> intptr_Add(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add,
Opcode.ct_intptr);
return stack_after;
}
private static Stack<StackItem> intptr_Sub(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.sub,
Opcode.ct_intptr);
return stack_after;
}
private static Stack<StackItem> uintptr_Mul(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.mul,
Opcode.ct_intptr);
return stack_after;
}
private static Stack<StackItem> uintptr_Add(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.add,
Opcode.ct_intptr);
return stack_after;
}
private static Stack<StackItem> uintptr_Sub(CilNode n, Code c, Stack<StackItem> stack_before)
{
var stack_after = binnumop(n, c, stack_before, cil.Opcode.SingleOpcodes.sub,
Opcode.ct_intptr);
return stack_after;
}
static Stack<StackItem> string_getChars(CilNode n, Code c, Stack<StackItem> stack_before)
{
var char_offset = layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Start_Char, c);
var stack_after = ldc(n, c, stack_before, 2);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.mul, Opcode.ct_int32);
stack_after = conv(n, c, stack_after, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldc(n, c, stack_after, char_offset, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemChar);
return stack_after;
}
static Stack<StackItem> string_getLength(CilNode n, Code c, Stack<StackItem> stack_before)
{
var length_offset = layout.Layout.GetStringFieldOffset(layout.Layout.StringField.Length, c);
var stack_after = ldc(n, c, stack_before, length_offset, 0x18);
stack_after = binnumop(n, c, stack_after, cil.Opcode.SingleOpcodes.add, Opcode.ct_intptr);
stack_after = ldind(n, c, stack_after, c.ms.m.SystemInt32);
return stack_after;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.dwarf
{
public class DwarfTypeDIE : DwarfParentDIE
{
public metadata.TypeSpec ts { get; set; }
public string NameOverride { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
int abbrev;
// decide upon type
switch(ts.stype)
{
case metadata.TypeSpec.SpecialType.Ptr:
case metadata.TypeSpec.SpecialType.MPtr:
d.Add(16);
d.Add((byte)t.psize);
dcu.fmap[d.Count] = dcu.GetTypeDie(ts.other);
for (int i = 0; i < 4; i++) d.Add(0);
break;
case metadata.TypeSpec.SpecialType.Array:
throw new NotImplementedException();
case metadata.TypeSpec.SpecialType.SzArray:
throw new NotImplementedException();
case metadata.TypeSpec.SpecialType.None:
if(ts.SimpleType != 0)
{
// base_type
WriteBaseType(ts.SimpleType, ds, d, parent);
}
else if(ts.IsValueType && (ts.m == dcu.m))
{
if (ts.m == dcu.m)
{
// structure_type
var source_loc = GetSourceLoc();
if (source_loc == null)
d.Add(14);
else
d.Add(24);
w(d, ts.Name, ds.smap);
w(d, (uint)t.GetSize(ts));
if(source_loc != null)
{
d.Add((byte)source_loc.file);
d.Add((byte)source_loc.line);
d.Add((byte)source_loc.col);
}
base.WriteToOutput(ds, d, parent);
}
else
{
// structure_type external
throw new NotImplementedException();
}
}
else
{
if (ts.m == dcu.m)
{
// class_type
var source_loc = GetSourceLoc();
if (source_loc == null)
d.Add(13);
else
d.Add(23);
w(d, ts.Name, ds.smap);
w(d, (uint)t.GetSize(ts));
if (source_loc != null)
{
d.Add((byte)source_loc.file);
d.Add((byte)source_loc.line);
d.Add((byte)source_loc.col);
}
base.WriteToOutput(ds, d, parent);
}
else
{
// class_type external
throw new NotImplementedException();
}
}
break;
default:
throw new NotImplementedException();
}
}
class SourceLoc
{
public int file, line, col;
}
private SourceLoc GetSourceLoc()
{
DwarfMethodDIE first = null, ctor = null;
foreach(var die in Children)
{
if(die is DwarfMethodDIE)
{
var dmdie = die as DwarfMethodDIE;
if (first == null && dmdie.SourceFileId != 0)
first = dmdie;
if(ctor == null && dmdie.ms != null && dmdie.ms.Name == ".ctor" && dmdie.SourceFileId != 0)
{
ctor = dmdie;
break;
}
}
}
if (first == null)
return null;
var ret = new SourceLoc();
if(ctor != null)
{
ret.file = ctor.SourceFileId;
ret.line = ctor.StartLine;
ret.col = ctor.StartColumn;
}
else
{
ret.file = first.SourceFileId;
ret.line = first.StartLine;
ret.col = first.StartColumn;
}
return ret;
}
private void WriteBaseType(int st, DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
if (parent is DwarfNSDIE && ((DwarfNSDIE)parent).ns == "System" && dcu.basetype_dies.ContainsKey(st))
{
// These are typedefs to types in the global scope
d.Add(20);
w(d, ts.Name, ds.smap);
dcu.fmap[d.Count] = dcu.basetype_dies[st];
for (int i = 0; i < 4; i++) d.Add(0);
if (st == 0x1c)
System.Diagnostics.Debugger.Break();
}
else
{
/* There are a few CLI basetypes that do not have C# equivalents
* or this is a string/object in the main namespace */
switch (st)
{
case 0x11:
// ValueType
// class_type
d.Add(13);
w(d, "ValueType", ds.smap);
w(d, (uint)t.GetSize(ts));
base.WriteToOutput(ds, d, parent);
break;
case 0x18:
// IntPtr
d.Add(20);
w(d, "IntPtr", ds.smap);
dcu.fmap[d.Count] = dcu.basetype_dies[t.psize == 4 ? 0x08 : 0x0a];
for (int i = 0; i < 4; i++) d.Add(0);
break;
case 0x19:
// IntPtr
d.Add(20);
w(d, "UIntPtr", ds.smap);
dcu.fmap[d.Count] = dcu.basetype_dies[t.psize == 4 ? 0x09 : 0x0b];
for (int i = 0; i < 4; i++) d.Add(0);
break;
case 0x0e:
// String
// class_type
d.Add(13);
w(d, NameOverride ?? "String", ds.smap);
w(d, 0); // size - TODO
base.WriteToOutput(ds, d, parent);
break;
case 0x1c:
// Object
// class_type
d.Add(13);
w(d, NameOverride ?? "Object", ds.smap);
w(d, (uint)t.GetSize(ts));
base.WriteToOutput(ds, d, parent);
break;
default:
throw new NotImplementedException();
}
}
}
}
public class DwarfMemberDIE : DwarfDIE
{
public string Name { get; set; }
public int FieldOffset { get; set; }
public DwarfDIE FieldType { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
d.Add(18);
w(d, Name, ds.smap);
dcu.fmap[d.Count] = FieldType;
for (int i = 0; i < 4; i++)
d.Add(0);
w(d, (uint)FieldOffset);
}
}
public class DwarfBaseTypeDIE : DwarfParentDIE
{
public int stype { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
switch (stype)
{
case 0x02:
// bool
d.Add(15);
w(d, "bool", ds.smap);
d.Add((byte)t.GetSize(dcu.m.SystemBool));
d.Add(0x07); // unsigned
break;
case 0x03:
// Char
d.Add(15);
w(d, "char", ds.smap);
d.Add(2);
d.Add(0x06); // signed char
break;
case 0x04:
// I1
d.Add(15);
w(d, "sbyte", ds.smap);
d.Add(1);
d.Add(0x05); // signed
break;
case 0x05:
// U1
d.Add(15);
w(d, "byte", ds.smap);
d.Add(1);
d.Add(0x07); // unsigned
break;
case 0x06:
// I2
d.Add(15);
w(d, "short", ds.smap);
d.Add(2);
d.Add(0x05); // signed
break;
case 0x07:
// U2
d.Add(15);
w(d, "ushort", ds.smap);
d.Add(2);
d.Add(0x07); // unsigned
break;
case 0x08:
// I4
d.Add(15);
w(d, "int", ds.smap);
d.Add(4);
d.Add(0x05); // signed
break;
case 0x09:
// U4
d.Add(15);
w(d, "uint", ds.smap);
d.Add(4);
d.Add(0x07); // unsigned
break;
case 0x0a:
// I8
d.Add(15);
w(d, "long", ds.smap);
d.Add(8);
d.Add(0x05); // signed
break;
case 0x0b:
// U8
d.Add(15);
w(d, "ulong", ds.smap);
d.Add(8);
d.Add(0x07); // unsigned
break;
case 0x0c:
// R4
d.Add(15);
w(d, "float", ds.smap);
d.Add(4);
d.Add(0x04); // float
break;
case 0x0d:
// R8
d.Add(15);
w(d, "double", ds.smap);
d.Add(8);
d.Add(0x04); // float
break;
default:
throw new NotImplementedException();
}
}
}
}
<file_sep>using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace AutoCompleteUtils
{
public static class AutoComplete
{
public static List<string> GetAutoCompletePossibilities(string input, List<string> strings, bool ignoreCase = true)
{
if (string.IsNullOrEmpty(input) || strings == null || strings.Count == 0)
return new List<string>(0);
return strings.Where(s => s.StartsWith(input, ignoreCase, CultureInfo.InvariantCulture)).ToList();
}
public static string GetComplimentaryAutoComplete(string input, List<string> strings, bool ignoreCase = true)
{
if (string.IsNullOrEmpty(input))
return input;
var possibilities = GetAutoCompletePossibilities(input, strings, ignoreCase);
if (possibilities.Count == 0)
return input;
var leadingString = GetEqualLeadingString(possibilities, ignoreCase);
if (leadingString.Length == input.Length)
return input;
return leadingString;
}
public static string GetEqualLeadingString(List<string> strings, bool ignoreCase = true)
{
if (strings == null || strings.Count == 0)
return string.Empty;
if (strings.Count == 1)
return strings[0];
var baseString = strings[0];
var index = 0;
var result = string.Empty;
while (index < baseString.Length)
{
var currentChar = baseString[index];
for (var i = 1; i < strings.Count; i++)
{
var otherChar = strings[i][index];
if (ignoreCase)
{
if (char.ToUpperInvariant(otherChar) != char.ToUpperInvariant(currentChar))
return result;
}
else if(otherChar != currentChar)
return result;
}
result += currentChar;
index++;
}
return result;
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* This defines the TysosType which is a subtype of System.Type
*
* All TypeInfo structures produced by tysila2 follow this layout
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs
{
[ExtendsOverride("_ZW6System11RuntimeType")]
[VTableAlias("__tysos_type_vt")]
[SpecialType]
public unsafe partial class TysosType : Type
{
metadata.TypeSpec ts = null;
/** <summary>holds a pointer to the vtbl represented by this type</summary> */
internal void* _impl;
internal TysosType(void* vtbl)
{
_impl = vtbl;
// m_handle = this;
*(void**)((byte*)CastOperations.ReinterpretAsPointer(this) + ClassOperations.GetFieldOffset("_ZW6System11RuntimeType", "m_handle")) =
CastOperations.ReinterpretAsPointer(this);
}
internal TysosType(void* vtbl, metadata.TypeSpec typeSpec) : this(vtbl)
{
ts = typeSpec;
}
internal metadata.TypeSpec tspec
{
get
{
if (ts == null)
{
ts = Metadata.GetTypeSpec(this);
}
return ts;
}
}
public static implicit operator TysosType(metadata.TypeSpec ts)
{
var vtbl = JitOperations.GetAddressOfObject(ts.MangleType());
return new TysosType(vtbl, ts);
}
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosField ReinterpretAsFieldInfo(IntPtr addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosField ReinterpretAsFieldInfo(object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosMethod ReinterpretAsMethodInfo(IntPtr addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosType ReinterpretAsType(IntPtr addr);
[Bits32Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosType ReinterpretAsType(uint addr);
[Bits64Only]
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosType ReinterpretAsType(ulong addr);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static extern TysosType ReinterpretAsType(object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static unsafe extern TysosType ReinterpretAsType(void* obj);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static unsafe extern RuntimeTypeHandle ReinterpretAsTypeHandle(void* obj);
[MethodImpl(MethodImplOptions.InternalCall)]
[ReinterpretAsMethod]
public static unsafe extern TysosMethod ReinterpretAsMethodInfo(void* obj);
public unsafe virtual int GetClassSize() {
return *(int*)((byte*)_impl + ClassOperations.GetVtblTypeSizeOffset());
}
public unsafe override System.Reflection.Assembly Assembly
{
get {
var ret = RTH_GetModule(this).GetAssembly();
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosType.GetAssembly() returning " + ((ulong)CastOperations.ReinterpretAsPointer(ret)).ToString("X") +
" for " + ret.FullName);
return ret;
}
}
public override string AssemblyQualifiedName
{
get
{
return FullName + ", " + Assembly.FullName;
}
}
[AlwaysCompile]
[MethodAlias("_ZW6System17RuntimeTypeHandle_11GetBaseType_RV11RuntimeType_P1V11RuntimeType")]
internal static Type RTH_GetBaseType(TysosType t)
{
return t.BaseType;
}
public unsafe override Type BaseType
{
get {
void* extends_vtbl = *(void**)((byte*)_impl + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (extends_vtbl == null)
return null;
return internal_from_vtbl(extends_vtbl);
}
}
public override string FullName
{
get { return Namespace + "." + Name; }
}
public override Guid GUID
{
get { throw new NotImplementedException(); }
}
protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl()
{
throw new NotImplementedException();
}
protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
TysosMethod meth = GetMethodImpl(".ctor", bindingAttr, binder, callConvention, types, modifiers) as TysosMethod;
if (meth == null)
return null;
return new ConstructorInfo(meth, this);
}
public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr)
{
System.Reflection.MethodInfo[] mis = GetMethods(bindingAttr);
int count = 0;
foreach (System.Reflection.MethodInfo mi in mis)
{
if (mi.IsConstructor)
{
if (((bindingAttr & System.Reflection.BindingFlags.Static) == System.Reflection.BindingFlags.Static) && mi.IsStatic)
count++;
if (((bindingAttr & System.Reflection.BindingFlags.Instance) == System.Reflection.BindingFlags.Instance) && !mi.IsStatic)
count++;
}
}
System.Reflection.ConstructorInfo[] ret = new System.Reflection.ConstructorInfo[count];
int i = 0;
foreach (System.Reflection.MethodInfo mi in mis)
{
if (mi.IsConstructor)
{
bool add = false;
if (((bindingAttr & System.Reflection.BindingFlags.Static) == System.Reflection.BindingFlags.Static) && mi.IsStatic)
add = true;
if (((bindingAttr & System.Reflection.BindingFlags.Instance) == System.Reflection.BindingFlags.Instance) && !mi.IsStatic)
add = true;
if (add)
ret[i++] = new ConstructorInfo(mi as TysosMethod, this);
}
}
return ret;
}
public override Type GetElementType()
{
throw new NotImplementedException();
}
public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr)
{
System.Reflection.FieldInfo[] fields = GetFields(bindingAttr);
foreach (System.Reflection.FieldInfo f in fields)
{
if (f.Name == name)
return f;
}
return null;
}
public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override Type GetInterface(string name, bool ignoreCase)
{
throw new NotImplementedException();
}
public override Type[] GetInterfaces()
{
throw new NotImplementedException();
}
public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
[AlwaysCompile]
[MethodAlias("_ZW6System17RuntimeTypeHandle_40CreateInstanceForAnotherGenericParameter_Ru1O_P2V11RuntimeTypeV11RuntimeType")]
static unsafe internal object RTH_CreateInstanceForAnotherGenericParameter(TysosType template, TysosType newtype)
{
void* t_vtbl = template._impl;
void* n_vtbl = newtype._impl;
/* Special case a few generic types that are required before the JIT can start */
void* spec_vtbl = null;
void* spec_ctor = null;
if (t_vtbl == OtherOperations.GetStaticObjectAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1i"))
{
if (n_vtbl == OtherOperations.GetStaticObjectAddress("_Zu1S"))
{
spec_vtbl = OtherOperations.GetStaticObjectAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1u1S");
spec_ctor = OtherOperations.GetFunctionAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1u1S_7#2Ector_Rv_P1u1t");
}
else if (n_vtbl == OtherOperations.GetStaticObjectAddress("_Zj"))
{
spec_vtbl = OtherOperations.GetStaticObjectAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1j");
spec_ctor = OtherOperations.GetFunctionAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1j_7#2Ector_Rv_P1u1t");
}
else if (n_vtbl == OtherOperations.GetStaticObjectAddress("_Zi"))
{
spec_vtbl = OtherOperations.GetStaticObjectAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1i");
spec_ctor = OtherOperations.GetFunctionAddress("_ZW30System#2ECollections#2EGeneric25GenericEqualityComparer`1_G1i_7#2Ector_Rv_P1u1t");
}
}
if (spec_vtbl != null)
{
var ntype = internal_from_vtbl(spec_vtbl);
var obj = ntype.Create();
OtherOperations.CallI(CastOperations.ReinterpretAsPointer(obj), spec_ctor);
return obj;
}
// Else, generate from a call to MakeGenericType
var new_tspec = template.tspec.Clone();
new_tspec.gtparams[0] = newtype.tspec;
var tname = new_tspec.MangleType();
System.Diagnostics.Debugger.Log(0, "libsupcs", "CreateInstanceForAnotherGenericParameter: " + tname);
var vtbl = JitOperations.GetAddressOfObject(tname);
TysosType tt = null;
if (vtbl != null)
{
tt = internal_from_vtbl(vtbl);
}
else
{
vtbl = JitOperations.JitCompile(new_tspec);
tt = new TysosType(vtbl, new_tspec);
}
System.Diagnostics.Debugger.Log(0, "libsupcs", "CreateInstanceForAnotherGenericParameter: vtbl found");
var newobj = tt.Create();
var ctor = tt.GetConstructor(Type.EmptyTypes);
if (ctor != null)
ctor.Invoke(newobj, Type.EmptyTypes);
return newobj;
}
[AlwaysCompile]
[MethodAlias("_ZW6System17RuntimeTypeHandle_11Instantiate_Rv_P4V17RuntimeTypeHandlePu1IiU35System#2ERuntime#2ECompilerServices19ObjectHandleOnStack")]
static unsafe void RTH_Instantiate(RuntimeTypeHandle rth, IntPtr* gparam_rth, int gparam_count, HandleOnStack ret)
{
// Instantiate a generic type from a RTH (TysosType pointer)
var tt = Type_GetTypeFromHandle(rth);
if (tt == null)
throw new ArgumentNullException("RTH_Instantiate: rth is null");
if (gparam_count == 0)
{
// Non-generic version
*ret.ptr = CastOperations.ReinterpretAsPointer(tt);
return;
}
// Convert IntPtr * array to managed array
var gparr = new TysosType[gparam_count];
for (int i = 0; i < gparam_count; i++)
{
gparr[i] = ReinterpretAsType(gparam_rth[i]);
}
*ret.ptr = CastOperations.ReinterpretAsPointer(tt.MakeGenericType(gparr));
}
[MethodAlias("_ZW6System17RuntimeTypeHandle_8Allocate_Ru1O_P1V11RuntimeType")]
[AlwaysCompile]
static object RTH_Allocate(TysosType tt)
{
return tt.Create();
}
[MethodReferenceAlias("_ZW6System11RuntimeType_15MakeGenericType_RV4Type_P2u1tu1ZV4Type")]
[MethodImpl(MethodImplOptions.InternalCall)]
static extern Type RT_MakeGenericType(object _this, object _args);
public unsafe override Type MakeGenericType(params Type[] typeArguments)
{
/* We can provide fast implementations for some well-known types */
void* this_vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(this) + ClassOperations.GetSystemTypeImplOffset());
int arg_count = typeArguments.Length;
void* arg1 = null;
if (arg_count >= 1)
arg1 = *(void**)((byte*)CastOperations.ReinterpretAsPointer(typeArguments[0]) + ClassOperations.GetSystemTypeImplOffset());
// IEquatable<>
if (this_vtbl == OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1") && arg_count == 1)
{
if (arg1 == OtherOperations.GetStaticObjectAddress("_Zu1S"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1u1S"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Za"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1a"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zb"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1b"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zc"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1c"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zd"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1d"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zf"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1f"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zh"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1h"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zi"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1i"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zj"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1j"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zx"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1x"));
else if (arg1 == OtherOperations.GetStaticObjectAddress("_Zy"))
return internal_from_vtbl(OtherOperations.GetStaticObjectAddress("_ZW6System12IEquatable`1_G1y"));
}
System.Diagnostics.Debugger.Log(0, "libsupcs", "MakeGenericType: no fast implementation for");
System.Diagnostics.Debugger.Log((int)this_vtbl, "libsupcs", "this_vtbl");
System.Diagnostics.Debugger.Log(arg_count, "libsupcs", "arg_count");
System.Diagnostics.Debugger.Log((int)arg1, "libsupcs", "arg1");
/* Create a typespec for the new type */
var tmpl = this.tspec;
if(tmpl.GenericParamCount != typeArguments.Length)
{
throw new TypeLoadException("Incorrect number of generic parameters provided for " +
tmpl.MangleType() + ": got " + typeArguments.Length +
", expected " + tmpl.GenericParamCount);
}
var new_tspec = tmpl.Clone();
new_tspec.gtparams = new metadata.TypeSpec[typeArguments.Length];
for(int i = 0; i < typeArguments.Length; i++)
{
new_tspec.gtparams[i] = ((TysosType)typeArguments[i]).tspec;
}
var tname = new_tspec.MangleType();
System.Diagnostics.Debugger.Log(0, "libsupcs", "MakeGenericType: " + tname);
var new_addr = JitOperations.GetAddressOfObject(tname);
if(new_addr == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "MakeGenericType: not available - need to create");
var new_vtbl = JitOperations.JitCompile(new_tspec);
var new_tt = new TysosType(new_vtbl, new_tspec);
return new_tt;
}
else
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "MakeGenericType: is available - using already compiled version");
var existing_obj = internal_from_vtbl(new_addr);
return existing_obj;
}
//return RT_MakeGenericType(this, typeArguments);
}
private bool MatchBindingFlags(System.Reflection.MethodInfo mi, System.Reflection.BindingFlags bindingAttr)
{
bool match = false;
if (((bindingAttr & System.Reflection.BindingFlags.Static) == System.Reflection.BindingFlags.Static) && (mi.IsStatic))
match = true;
if (((bindingAttr & System.Reflection.BindingFlags.Instance) == System.Reflection.BindingFlags.Instance) && (!mi.IsStatic))
match = true;
return match;
}
public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr)
{
throw new NotImplementedException();
}
protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
protected override bool HasElementTypeImpl()
{
return (IsArray || IsZeroBasedArray || IsManagedPointer || IsUnmanagedPointer);
}
public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters)
{
if ((invokeAttr & System.Reflection.BindingFlags.CreateInstance) != 0)
{
// Invoke constructor
// build an array of the types to search for
Type[] param_types = null;
if (args != null)
{
param_types = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
param_types[i] = args[i].GetType();
}
// Find the constructor
System.Reflection.ConstructorInfo ci = GetConstructor(invokeAttr, binder, param_types, modifiers);
if (ci == null)
throw new MissingMethodException("Could not find a matching constructor");
// Execute it
return ci.Invoke(args);
}
else
{
throw new NotImplementedException("InvokeMember currently only defined for constructors");
}
}
protected override bool IsArrayImpl()
{
return IsZeroBasedArray;
}
protected override bool IsByRefImpl()
{
return IsManagedPointer;
}
protected override bool IsCOMObjectImpl()
{
throw new NotImplementedException();
}
protected override bool IsPointerImpl()
{
return IsUnmanagedPointer;
}
protected override bool IsPrimitiveImpl()
{
throw new NotImplementedException();
}
public override System.Reflection.Module Module
{
get { return TysosModule.ReinterpretAsModule(RTH_GetModule(this)); }
}
string nspace = null, name = null;
public override string Namespace
{
get {
if (nspace != null)
return nspace;
var ts = tspec;
if (ts == null)
nspace = "System";
else
{
nspace = ts.m.GetStringEntry(metadata.MetadataStream.tid_TypeDef,
ts.tdrow, 2);
}
return nspace;
}
}
public override Type UnderlyingSystemType
{
get { return this; }
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return false;
}
public override string Name
{
get
{
if (name != null)
return name;
var ts = tspec;
if (ts == null)
name = "Void";
else
{
name = ts.m.GetStringEntry(metadata.MetadataStream.tid_TypeDef,
ts.tdrow, 1);
}
return name;
}
}
public virtual TysosType UnboxedType { get { throw new NotImplementedException(); } }
public override bool IsGenericType
{
get
{
void* ti = **(void***)((byte*)CastOperations.ReinterpretAsPointer(this) + ClassOperations.GetSystemTypeImplOffset());
var gtid = *(int*)((void**)ti + 1);
// IsGenericType is true for instantiated and non-instantiated generic types
if (gtid == -1 || gtid == -2)
return true;
return false;
}
}
public unsafe override bool IsGenericTypeDefinition {
get {
void* ti = **(void***)((byte*)CastOperations.ReinterpretAsPointer(this) + ClassOperations.GetSystemTypeImplOffset());
return *(int*)((void**)ti + 1) == -1;
}
}
[MethodAlias("_ZW6System17RuntimeTypeHandle_17GetCorElementType_RU19System#2EReflection14CorElementType_P1U6System11RuntimeType")]
[AlwaysCompile]
unsafe static int RTH_GetCorElementType(void *type)
{
// We can interpret the first byte of the signature to get the cor type
void* ti = **(void***)((byte*)type + ClassOperations.GetSystemTypeImplOffset());
var mod_count = *(int*)((void**)ti + 5);
var stype = *(int*)((void**)ti + 6 + mod_count) & 0xff;
if (stype == 0x31)
return (int)metadata.CorElementType.ValueType;
else if (stype == 0x32)
return (int)metadata.CorElementType.Class;
return stype;
}
[MethodAlias("_ZW6System4Type_18type_is_subtype_of_Rb_P3V4TypeV4Typeb")]
[AlwaysCompile]
static unsafe bool IsSubtypeOf(void* subclass, void* superclass, bool check_interfaces)
{
var sub_vt = *(void**)((byte*)subclass + ClassOperations.GetSystemTypeImplOffset());
var super_vt = *(void**)((byte*)superclass + ClassOperations.GetSystemTypeImplOffset());
var cur_sub_vt = *(void**)((byte*)sub_vt + ClassOperations.GetVtblExtendsVtblPtrOffset());
while (cur_sub_vt != null)
{
if (cur_sub_vt == super_vt)
return true;
cur_sub_vt = *(void**)((byte*)cur_sub_vt + ClassOperations.GetVtblExtendsVtblPtrOffset());
}
if (check_interfaces)
throw new NotImplementedException();
return false;
}
[MethodAlias("_ZW6System4Type_23type_is_assignable_from_Rb_P2V4TypeV4Type")]
[AlwaysCompile]
static unsafe bool IsAssignableFrom(TysosType cur_type, TysosType from_type)
{
if (cur_type == from_type)
return true;
var cur_vtbl = *((void**)((byte*)CastOperations.ReinterpretAsPointer(cur_type) + ClassOperations.GetSystemTypeImplOffset()));
var from_vtbl = *((void**)((byte*)CastOperations.ReinterpretAsPointer(from_type) + ClassOperations.GetSystemTypeImplOffset()));
// check extends chain
var cur_from_vtbl = from_vtbl;
while (cur_from_vtbl != null)
{
if (cur_from_vtbl == cur_vtbl)
return true;
cur_from_vtbl = *((void**)((byte*)cur_from_vtbl + ClassOperations.GetVtblExtendsVtblPtrOffset()));
}
// check interfaces
var cur_from_iface_ptr = *(void***)((byte*)cur_vtbl + ClassOperations.GetVtblInterfacesPtrOffset());
while (*cur_from_iface_ptr != null)
{
if (*cur_from_iface_ptr == cur_vtbl)
return true;
cur_from_iface_ptr += 2;
}
// check whether they are arrays of the same type
var cur_ts = cur_type.tspec;
var from_ts = cur_type.tspec;
if (cur_ts.stype == metadata.TypeSpec.SpecialType.SzArray &&
from_ts.stype == metadata.TypeSpec.SpecialType.SzArray)
{
if (cur_ts.other.Equals(from_ts.other))
return true;
}
// TODO: complex array
return false;
}
public override Type GetGenericTypeDefinition()
{
var new_tspec = tspec.Clone();
new_tspec.gtparams = null;
var nts_name = new_tspec.MangleType();
var nts_addr = JitOperations.GetAddressOfObject(nts_name);
if (nts_addr != null)
return internal_from_vtbl(nts_addr);
else
return new TysosType(null, new_tspec);
}
public unsafe override RuntimeTypeHandle TypeHandle
{
get
{
var vtbl = *GetImplOffset();
return ReinterpretAsTypeHandle(vtbl);
}
}
public bool IsUnmanagedPointer { get { return tspec.stype == metadata.TypeSpec.SpecialType.Ptr; } }
public bool IsZeroBasedArray { get { return tspec.stype == metadata.TypeSpec.SpecialType.SzArray; } }
public bool IsManagedPointer { get { return tspec.stype == metadata.TypeSpec.SpecialType.MPtr; } }
public bool IsDynamic { get { throw new NotImplementedException(); } }
public uint TypeFlags { get { throw new NotImplementedException(); } }
public bool IsUninstantiatedGenericTypeParameter { get { throw new NotImplementedException(); } }
public bool IsUninstantiatedGenericMethodParameter { get { throw new NotImplementedException(); } }
public int UgtpIdx { get { throw new NotImplementedException(); } }
public int UgmpIdx { get { throw new NotImplementedException(); } }
internal unsafe static int GetValueTypeSize(void* boxed_vtbl)
{
/* Boxed value types (that aren't enums) store their size in the
* typeinfo. Enums store the underlying type there, so we have
* to call ourselves again if this is an enum. */
void* ti = *(void**)boxed_vtbl;
void* extends = *(void**)((byte*)boxed_vtbl + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (extends == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
void* underlying_type = *((void**)ti + 1);
return GetValueTypeSize(underlying_type);
}
/* All calling functions should guarantee this is a value type, so the following is valid */
return *(int*)((void**)ti + 1);
}
protected override bool IsValueTypeImpl()
{
unsafe
{
void* vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(this) + ClassOperations.GetSystemTypeImplOffset());
void* extends = *(void**)((byte*)vtbl + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (extends == OtherOperations.GetStaticObjectAddress("_Zu1L") ||
extends == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
return true;
return false;
}
}
[MethodAlias("_ZW6System4Type_15make_array_type_RV4Type_P2u1ti")]
[AlwaysCompile]
static TysosType make_array_type(TysosType cur_type, int rank)
{
throw new NotImplementedException();
}
internal unsafe object Create()
{
byte* ret = (byte*)MemoryOperations.GcMalloc(GetClassSize());
void* vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(this) + ClassOperations.GetSystemTypeImplOffset());
*(void**)(ret + ClassOperations.GetVtblFieldOffset()) = vtbl;
*(ulong*)(ret + ClassOperations.GetMutexLockOffset()) = 0;
return CastOperations.ReinterpretAsObject(ret);
}
static internal int obj_id = 0;
[MethodAlias("_Zu1O_7GetType_RW6System4Type_P1u1t")]
[AlwaysCompile]
static unsafe TysosType Object_GetType(void** obj)
{
void* vtbl = *obj;
return internal_from_vtbl(vtbl);
}
[MethodAlias("_ZW35System#2ERuntime#2ECompilerServices14RuntimeHelpers_20_RunClassConstructor_Rv_P1U6System11RuntimeType")]
[AlwaysCompile]
static unsafe void RuntimeHelpers__RunClassConstructor(void* vtbl)
{
// Ensure ptr is valid
if (vtbl == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "RuntimeHelpers._RunClassConstructor: called with null pointer");
throw new Exception("Invalid type handle");
}
// dereference vtbl pointer to get ti ptr
var ptr = *((void**)vtbl);
if (ptr == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "RuntimeHelpers._RunClassConstructor: called with null pointer");
throw new Exception("Invalid type handle");
}
if ((*((int*)ptr) & 0xf) != 0)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "RuntimeHelpers._RunClassConstructor: called with invalid runtimehandle: " +
(*((int*)ptr)).ToString() + " at " + ((ulong)ptr).ToString("X16"));
System.Diagnostics.Debugger.Break();
throw new Exception("Invalid type handle");
}
var ti_ptr = (void**)ptr;
var cctor_addr = ti_ptr[3];
if (cctor_addr != null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "RuntimeHelpers._RunClassConstructor: running static constructor at " +
((ulong)cctor_addr).ToString("X16"));
OtherOperations.CallI(cctor_addr);
System.Diagnostics.Debugger.Log(0, "libsupcs", "RuntimeHelpers._RunClassConstructor: finished running static constructor at " +
((ulong)cctor_addr).ToString("X16"));
}
}
internal unsafe void** GetImplOffset()
{
byte* tp = (byte*)CastOperations.ReinterpretAsPointer(this);
return (void**)(tp + ClassOperations.GetSystemTypeImplOffset());
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_ZW6System4Type_13op_Inequality_Rb_P2V4TypeV4Type")]
static internal unsafe bool NotEqualsInternal(TysosType a, TysosType b)
{
return !EqualsInternal(a, b);
}
[MethodAlias("_ZW6System4Type_11op_Equality_Rb_P2V4TypeV4Type")]
[MethodAlias("_ZW6System4Type_14EqualsInternal_Rb_P2u1tV4Type")]
[AlwaysCompile]
static internal unsafe bool EqualsInternal(TysosType a, TysosType b)
{
if (CastOperations.ReinterpretAsPointer(a) == CastOperations.ReinterpretAsPointer(b))
return true;
if (CastOperations.ReinterpretAsPointer(a) == null)
return false;
if (CastOperations.ReinterpretAsPointer(b) == null)
return false;
void* a_vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(a) + ClassOperations.GetSystemTypeImplOffset());
void* b_vtbl = *(void**)((byte*)CastOperations.ReinterpretAsPointer(b) + ClassOperations.GetSystemTypeImplOffset());
if ((a_vtbl != null) && (a_vtbl == b_vtbl))
return true;
if (a_vtbl == null || b_vtbl == null)
return false;
void* a_ti = *(void**)a_vtbl;
void* b_ti = *(void**)b_vtbl;
// if either is non-generic, then the equality is false at this point
if (*(int*)((void**)a_ti + 1) != 2 || *(int*)((void**)b_ti + 1) != 2)
return false;
return a.tspec.Equals(b.tspec);
}
[MethodAlias("_ZW6System17RuntimeTypeHandle_9CanCastTo_Rb_P2V11RuntimeTypeV11RuntimeType")]
[AlwaysCompile]
unsafe static bool CanCastTo(byte* from_type, byte* to_type)
{
return CanCast(*(void**)(from_type + ClassOperations.GetSystemTypeImplOffset()),
*(void**)(to_type + ClassOperations.GetSystemTypeImplOffset()));
}
internal static unsafe bool CanCast(void *from_vtbl, void *to_vtbl)
{
void* from_type;
void* to_type;
if (from_vtbl == null)
throw new InvalidCastException("CastClassEx: from_vtbl is null");
from_type = *(void**)from_vtbl;
to_type = *(void**)to_vtbl;
if (from_type == to_type)
return true;
/* If both are arrays with non-null elem types, do an array-element-compatible-with
* (CIL I:8.7.1) comparison */
var from_flags = *(uint*)((byte*)from_vtbl + ClassOperations.GetVtblFlagsOffset());
var to_flags = *(uint*)((byte*)to_vtbl + ClassOperations.GetVtblFlagsOffset());
var from_stype = from_flags & 0xf;
var to_stype = to_flags & 0xf;
if ((from_stype == 1 || from_stype == 2) && from_stype == to_stype)
{
/* Non-SZ array needs rank checking too */
if(from_stype == 2)
{
var from_rank = (from_flags >> 8) & 0xff;
var to_rank = (to_flags >> 8) & 0xff;
if (from_rank != to_rank)
return false;
}
void* from_et = *(void**)((byte*)from_vtbl + ClassOperations.GetVtblBaseTypeVtblOffset());
void* to_et = *(void**)((byte*)to_vtbl + ClassOperations.GetVtblBaseTypeVtblOffset());
if (from_et != null && to_et != null)
{
/* array-element-compatible-with is either:
* compatible-with
* or
* equality of reduced types */
if (CanCast(from_et, to_et))
return true;
from_et = get_reduced_type_vt(from_et);
to_et = get_reduced_type_vt(to_et);
if (from_et == to_et)
return true;
else
return false;
}
}
/* TODO: check from_type = V[] and to_type = IList<W> */
/* Check whether we extend the type */
void* cur_extends_vtbl = *(void**)((byte*)from_vtbl + ClassOperations.GetVtblExtendsVtblPtrOffset());
while (cur_extends_vtbl != null)
{
if (cur_extends_vtbl == to_vtbl)
return true;
cur_extends_vtbl = *(void**)((byte*)cur_extends_vtbl + ClassOperations.GetVtblExtendsVtblPtrOffset());
}
/* Check whether we implement the type as an interface */
void** cur_iface_ptr = *(void***)((byte*)from_vtbl + ClassOperations.GetVtblInterfacesPtrOffset());
if (cur_iface_ptr != null)
{
while (*cur_iface_ptr != null)
{
if (*cur_iface_ptr == to_vtbl)
return true;
cur_iface_ptr += 2;
}
}
return false;
}
[AlwaysCompile]
[MethodAlias("castclassex")]
internal static unsafe void *CastClassEx(void *from_obj, void *to_vtbl, int is_castclass)
{
if (from_obj == null)
{
return null;
}
if (to_vtbl == null)
throw new InvalidCastException("CastClassEx: to_vtbl is null");
var from_vtbl = *(void**)from_obj;
if (CanCast(from_vtbl, to_vtbl))
return from_obj;
else
{
// TODO: if is_castclass and fails, then throw System.InvalidCastException
System.Diagnostics.Debugger.Log(0, "libsupcs", "CastClassEx failing");
System.Diagnostics.Debugger.Log((int)from_obj, "libsupcs", "from_obj");
System.Diagnostics.Debugger.Log((int)to_vtbl, "libsupcs", "to_vtbl");
System.Diagnostics.Debugger.Log(0, "libsupcs", "from_vtbl: " + ((ulong)from_vtbl).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "to_vtbl: " + ((ulong)to_vtbl).ToString("X"));
System.Diagnostics.Debugger.Log(0, "libsupcs", "from_type: " + JitOperations.GetNameOfAddress(from_vtbl, out var unused) ?? "unknown");
System.Diagnostics.Debugger.Log(0, "libsupcs", "to_type: " + JitOperations.GetNameOfAddress(to_vtbl, out unused) ?? "unknown");
System.Diagnostics.Debugger.Log(0, "libsupcs", "calling_pc: " + ((ulong)OtherOperations.GetUnwinder().UnwindOne().GetInstructionPointer()).ToString("X"));
return null;
}
}
private static unsafe void* get_reduced_type_vt(void* et)
{
/* If this is an enum, get underlying type */
et = get_enum_underlying_type(et);
/* If this is a signed integer type, return the unsigned counterpart */
if (et == OtherOperations.GetStaticObjectAddress("_Za"))
return OtherOperations.GetStaticObjectAddress("_Zh");
else if (et == OtherOperations.GetStaticObjectAddress("_Zs"))
return OtherOperations.GetStaticObjectAddress("_Zt");
else if (et == OtherOperations.GetStaticObjectAddress("_Zc"))
return OtherOperations.GetStaticObjectAddress("_Zt");
else if (et == OtherOperations.GetStaticObjectAddress("_Zi"))
return OtherOperations.GetStaticObjectAddress("_Zj");
else if (et == OtherOperations.GetStaticObjectAddress("_Zx"))
return OtherOperations.GetStaticObjectAddress("_Zy");
else if (et == OtherOperations.GetStaticObjectAddress("_Zu1I"))
return OtherOperations.GetStaticObjectAddress("_Zu1U");
/* Else return the vtable unchanged */
return et;
}
/* If this is an enum vtable, return its underlying type, else
* return the vtable unchanged */
private static unsafe void* get_enum_underlying_type(void* vt)
{
void* extends = *(void**)((byte*)vt + ClassOperations.GetVtblExtendsVtblPtrOffset());
if (extends == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
void** ti = *(void***)vt;
return *(ti + 1);
}
return vt;
}
/** <summary>Get the size of the type when it is a field in a type. This will return the pointer size for
* reference types and boxed value types and the size of the type for unboxed value types</summary> */
internal virtual int GetSizeAsField()
{
if (IsValueType)
return GetClassSize();
else
return OtherOperations.GetPointerSize();
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_ZW34System#2ERuntime#2EInteropServices8GCHandle_11InternalGet_Ru1O_P1u1I")]
private static object InteropServices_GCHandle_InternalGet(IntPtr v)
{
return CastOperations.ReinterpretAsObject(CastOperations.ReinterpretAsPointer(v));
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_ZW6System17RuntimeTypeHandle_11GetGCHandle_Ru1I_P2V17RuntimeTypeHandleU34System#2ERuntime#2EInteropServices12GCHandleType")]
private static TysosType RTH_GetGCHandle(RuntimeTypeHandle rth, int gch_type)
{
return ReinterpretAsType(rth.Value);
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_Zu1L_14CanCompareBits_Rb_P1u1O")]
private static unsafe bool ValueType_CanCompareBits(void *o)
{
/* See InternalEquals for caveats */
return true;
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_Zu1L_15FastEqualsCheck_Rb_P2u1Ou1O")]
private static unsafe bool ValueType_FastEqualsCheck(void **o1, void **o2)
{
return ValueType_InternalEquals(o1, o2, out var fields);
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_Zu1L_14InternalEquals_Rb_P3u1Ou1ORu1Zu1O")]
private static unsafe bool ValueType_InternalEquals(void** o1, void** o2, out void* fields)
{
/* This doesn't yet perform the required behaviour. Currently, we just
* perform a byte-by-byte comparison, however if any of the fields are
* reference types we should instead run .Equals() on them.
*
* If we were to pass the references in the fields array i.e.
* [ obj1_field1, obj2_field1, obj1_field2, obj2_field2, ... ]
* then mono would do this for us.
*
* We need to check both type equality and byte-by-bye equality */
fields = null;
void* o1vt = *o1;
void* o2vt = *o2;
/* Rationalise vtables to enums to their underlying type counterparts */
void* o1ext = *(void**)((byte*)o1vt + ClassOperations.GetVtblExtendsVtblPtrOffset());
void* o2ext = *(void**)((byte*)o2vt + ClassOperations.GetVtblExtendsVtblPtrOffset());
if(o1ext == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
void** enum_ti = *(void***)o1vt;
o1vt = *(enum_ti + 1);
}
if (o2ext == OtherOperations.GetStaticObjectAddress("_ZW6System4Enum"))
{
void** enum_ti = *(void***)o2vt;
o2vt = *(enum_ti + 1);
}
// This needs fixing for dynamic types
if (o1vt != o2vt)
{
while (true) ;
return false;
}
// Get type sizes
int o1tsize = *(int*)((byte*)o1vt + ClassOperations.GetVtblTypeSizeOffset());
int o2tsize = *(int*)((byte*)o2vt + ClassOperations.GetVtblTypeSizeOffset());
if (o1tsize != o2tsize)
return false;
int header_size = ClassOperations.GetBoxedTypeDataOffset();
byte* o1_ptr = (byte*)o1 + header_size;
byte* o2_ptr = (byte*)o2 + header_size;
if (MemoryOperations.MemCmp(o1_ptr, o2_ptr, o1tsize - header_size) == 0)
return true;
else
return false;
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_Zu1L_11GetHashCode_Ri_P1u1t")]
private static unsafe int ValueType_GetHashCode(void **o)
{
void* f;
return ValueType_InternalGetHashCode(o, out f);
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_Zu1L_19InternalGetHashCode_Ri_P2u1ORu1Zu1O")]
private static unsafe int ValueType_InternalGetHashCode(void** o, out void* fields)
{
/* This doesn't yet perform the required behaviour. Currently, we just
* perform a byte-by-byte hash, however if any of the fields are
* reference types we should instead run .GetHashCode() on them.
*
* If we were to pass the references in the fields array i.e.
* [ field1, field2, ... ]
* then mono would do this for us. */
fields = null;
void* ovt = *o;
// Get type size
int otsize = *(int*)((byte*)ovt + ClassOperations.GetVtblTypeSizeOffset());
// Get pointer to data
int header_size = ClassOperations.GetBoxedTypeDataOffset();
byte* o_ptr = (byte*)o + header_size;
// ELF hash
uint h = 0, g;
for(int i = 0; i < (otsize-header_size); i++)
{
h = (h << 4) + *o_ptr++;
g = h & 0xf0000000;
if(g != 0)
{
h ^= g >> 24;
}
h &= ~g;
}
unchecked
{
return (int)h;
}
}
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("_Zu1O_15MemberwiseClone_Ru1O_P1u1t")]
static unsafe void* MemberwiseClone(void *obj)
{
void* vtbl = *((void**)obj);
int class_size = *(int*)((byte*)vtbl + ClassOperations.GetVtblTypeSizeOffset());
void* ret = MemoryOperations.GcMalloc(class_size);
MemoryOperations.MemCpy(ret, obj, class_size);
// Set the mutex lock on the new object to 0
*(void**)((byte*)ret + ClassOperations.GetMutexLockOffset()) = null;
return ret;
}
// all instatiated types will return false. Later we will subclass TysosType to return true
// for generic parameters types which we construct on the fly for generic type definitions
public override bool IsGenericParameter { get { return false; } }
[AlwaysCompile]
[MethodAlias("_ZW6System17RuntimeTypeHandle_17IsGenericVariable_Rb_P1V11RuntimeType")]
static internal unsafe bool RTH_IsGenericVariable(TysosType t)
{
return t.IsGenericParameter;
}
[AlwaysCompile]
[MethodAlias("_ZW6System17RuntimeTypeHandle_11IsInterface_Rb_P1V11RuntimeType")]
static internal unsafe bool RTH_IsInterface(void *vtbl)
{
void** ti = *(void***)vtbl;
var flags = *(int*)(ti + 4); // 4th special field is flags
return ((flags & 0x20) == 0x20);
}
[AlwaysCompile]
[MethodAlias("_ZW6System17RuntimeTypeHandle_9GetModule_RU19System#2EReflection13RuntimeModule_P1U6System11RuntimeType")]
static internal unsafe TysosModule RTH_GetModule(TysosType t)
{
var aptr = (t.tspec.m.file as Metadata.BinaryInterface).b;
return TysosModule.GetModule(aptr, t.tspec.m.AssemblyName);
}
[MethodAlias("_ZW6System4Type_17GetTypeFromHandle_RV4Type_P1V17RuntimeTypeHandle")]
[AlwaysCompile]
static internal unsafe TysosType Type_GetTypeFromHandle(void* val)
{
return internal_from_vtbl(val);
}
[MethodReferenceAlias("_ZW6System4Type_17GetTypeFromHandle_RV4Type_P1V17RuntimeTypeHandle")]
static extern internal unsafe TysosType Type_GetTypeFromHandle(RuntimeTypeHandle rth);
[AlwaysCompile]
[MethodAlias("__type_from_vtbl")]
static internal unsafe TysosType internal_from_vtbl(void *vtbl)
{
/* The default value for a type info is:
*
* intptr type (= 0)
* intptr enum_underlying_type_vtbl_ptr
* intptr tysostype pointer
* intptr metadata reference count
* metadata references
* signature
*
*/
void* ti = *(void**)vtbl;
void** ttptr = (void**)ti + 2;
if(*ttptr == null)
{
var tt = CastOperations.ReinterpretAsPointer(new TysosType(vtbl));
OtherOperations.CompareExchange(ttptr, tt);
}
return ReinterpretAsType(*ttptr);
}
// From CoreCLR
internal enum TypeNameFormatFlags
{
FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible
FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names
FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings)
FormatAssembly = 0x00000004, // Include assembly display name in type names
FormatSignature = 0x00000008, // Include signature in method names
FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names
#if _DEBUG
FormatDebug = 0x00000020, // For debug printing of types only
#endif
FormatAngleBrackets = 0x00000040, // Whether generic types are C<T> or C[T]
FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub}
FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters
// If we want to be able to distinguish between overloads whose parameter types have the same name but come from different assemblies,
// we can add FormatAssembly | FormatNoVersion to FormatSerialization. But we are omitting it because it is not a useful scenario
// and including the assembly name will normally increase the size of the serialized data and also decrease the performance.
FormatSerialization = FormatNamespace |
FormatGenericParam |
FormatFullInst
}
[MethodAlias("_ZW6System17RuntimeTypeHandle_13ConstructName_Rv_P3V17RuntimeTypeHandleV19TypeNameFormatFlagsU35System#2ERuntime#2ECompilerServices19StringHandleOnStack")]
[AlwaysCompile]
static void ConstructName(RuntimeTypeHandle rth, TypeNameFormatFlags formatFlags, ref string ret)
{
var tt = ReinterpretAsType(rth.Value);
ret = tt.ConstructName(formatFlags);
}
string ConstructName(TypeNameFormatFlags formatFlags)
{
// Very basic implementation - does not handle most flags
StringBuilder sb = new StringBuilder();
if((formatFlags & TypeNameFormatFlags.FormatNamespace) == TypeNameFormatFlags.FormatNamespace)
{
sb.Append(Namespace);
sb.Append(".");
}
sb.Append(Name);
return sb.ToString();
}
[MethodAlias("_ZW34System#2ERuntime#2EInteropServices7Marshal_37GetDelegateForFunctionPointerInternal_RU6System8Delegate_P2u1IV4Type")]
[AlwaysCompile]
static void* Marshal_GetDelegateForFunctionPointer(void *ptr, TysosType t)
{
// build new object of the appropriate size
var ret = MemoryOperations.GcMalloc(t.GetClassSize());
// extract vtbl and write it to the appropriate field
*(void**)ret = t._impl;
// mutex lock
*(int*)((byte*)ret + ClassOperations.GetMutexLockOffset()) = 0;
// insert the function pointer
*(void**)((byte*)ret + ClassOperations.GetDelegateFPtrOffset()) = ptr;
return ret;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.dwarf
{
public class DwarfNSDIE : DwarfParentDIE
{
public string ns { get; set; }
public override void WriteToOutput(DwarfSections ds, IList<byte> d, DwarfDIE parent)
{
d.Add((byte)12);
w(d, ns, ds.smap);
base.WriteToOutput(ds, d, parent);
}
}
}
<file_sep>using System;
namespace ConsoleUtils.ConsoleActions
{
public interface IConsoleAction
{
void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo);
}
}<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.cil;
using metadata;
namespace libtysila5.ir
{
public class SpecialMethods : metadata.MetadataStream
{
public int gcmalloc;
public int castclassex;
public int throw_;
public int try_enter;
public int catch_enter;
public int leave;
public int rethrow;
public int strlen;
public int wcslen;
public int inst_Rv_s;
public int inst_Rv_P0;
public int static_Rv_P0;
public int static_Rv_P1Pv;
public int memcpy;
public int memset;
public int debugger_Log;
public int invoke;
public int string_ci;
public int string_Zc;
public int string_Pcii;
public int string_Pa;
public int string_Zcii;
public int string_Pc;
public int string_PaiiEncoding;
public int string_Paii;
public int type_from_vtbl;
public int array_copyToManaged;
public int rint;
MetadataStream corlib;
List<byte> b = new List<byte>();
public override uint GetIntEntry(int table_id, int row, int col)
{
return corlib.GetIntEntry(table_id, row, col);
}
public SpecialMethods(metadata.MetadataStream m)
{
corlib = m.al.GetAssembly("mscorlib");
var i = corlib.GetTypeSpec("System", "Int32");
var u = corlib.GetTypeSpec("System", "UInt32");
var I = corlib.GetTypeSpec("System", "IntPtr");
var o = corlib.GetSimpleTypeSpec(0x1c);
var s = corlib.GetSimpleTypeSpec(0x0e);
var a = corlib.GetSimpleTypeSpec(0x04);
var Pa = a.Pointer;
var c = corlib.GetSimpleTypeSpec(0x03);
var Pc = c.Pointer;
var Zc = c.SzArray;
var Zo = o.SzArray;
var Pv = m.SystemVoid.Type.Pointer;
var d = corlib.GetSimpleTypeSpec(0xd);
gcmalloc = CreateMethodSignature(b, I,
new metadata.TypeSpec[] { i });
castclassex = CreateMethodSignature(b, o,
new TypeSpec[] { I, I, i });
throw_ = CreateMethodSignature(b, null,
new TypeSpec[] { o });
try_enter = CreateMethodSignature(b, null,
new TypeSpec[] { I, I });
catch_enter = CreateMethodSignature(b, null,
new TypeSpec[] { I, I });
leave = CreateMethodSignature(b, null,
new TypeSpec[] { I });
rethrow = CreateMethodSignature(b, null,
new TypeSpec[] { });
strlen = CreateMethodSignature(b, I,
new TypeSpec[] { Pa });
wcslen = CreateMethodSignature(b, I,
new TypeSpec[] { Pc });
memcpy = CreateMethodSignature(I,
new TypeSpec[] { I, I, i });
memset = CreateMethodSignature(I,
new TypeSpec[] { I, i, i });
invoke = CreateMethodSignature(o,
new TypeSpec[] { Pv, Zo, Pv, u });
inst_Rv_s = CreateMethodSignature(b, null,
new TypeSpec[] { s }, true);
inst_Rv_P0 = CreateMethodSignature(b, null,
new TypeSpec[] { }, true);
static_Rv_P0 = CreateMethodSignature(b, null,
new TypeSpec[] { }, false);
static_Rv_P1Pv = CreateMethodSignature(b, null,
new TypeSpec[] { Pv }, false);
string_ci = CreateMethodSignature(null,
new TypeSpec[] { c, i }, true);
string_Zc = CreateMethodSignature(null,
new TypeSpec[] { Zc }, true);
string_Pcii = CreateMethodSignature(null,
new TypeSpec[] { Pc, i, i }, true);
string_Pa = CreateMethodSignature(null,
new TypeSpec[] { Pa }, true);
string_Zcii = CreateMethodSignature(null,
new TypeSpec[] { Zc, i, i }, true);
string_Pc = CreateMethodSignature(null,
new TypeSpec[] { Pc }, true);
string_PaiiEncoding = CreateMethodSignature(null,
new TypeSpec[] { Pa, i, i, corlib.GetTypeSpec("System.Text", "Encoding") }, true);
string_Paii = CreateMethodSignature(null,
new TypeSpec[] { Pa, i, i }, true);
type_from_vtbl = CreateMethodSignature(o, new TypeSpec[] { I });
array_copyToManaged = CreateMethodSignature(null,
new TypeSpec[] { Pv, Pv, i, i }, false);
debugger_Log = CreateMethodSignature(null,
new TypeSpec[] { i, s, s });
rint = CreateMethodSignature(d, new TypeSpec[] { d });
sh_blob = new BlobStream(b);
al = m.al;
SystemArray = m.SystemArray;
SystemByte = m.SystemByte;
SystemChar = m.SystemChar;
SystemDelegate = m.SystemDelegate;
SystemEnum = m.SystemEnum;
SystemInt16 = m.SystemInt16;
SystemInt32 = m.SystemInt32;
SystemInt64 = m.SystemInt64;
SystemInt8 = m.SystemInt8;
SystemIntPtr = m.SystemIntPtr;
SystemObject = m.SystemObject;
SystemRuntimeFieldHandle = m.SystemRuntimeFieldHandle;
SystemRuntimeMethodHandle = m.SystemRuntimeMethodHandle;
SystemRuntimeTypeHandle = m.SystemRuntimeTypeHandle;
SystemString = m.SystemString;
SystemUInt16 = m.SystemUInt16;
SystemUInt32 = m.SystemUInt32;
SystemUInt64 = m.SystemUInt64;
SystemValueType = m.SystemValueType;
SystemVoid = m.SystemVoid;
}
public MethodSpec GetMethodSpec(int msig)
{
return new MethodSpec
{
m = this,
msig = msig
};
}
public int CreateMethodSignature(TypeSpec rettype, TypeSpec[] ps, bool has_this = false, TypeSpec[] gmparams = null)
{
return CreateMethodSignature(b, rettype, ps, has_this, gmparams);
}
public int CreateMethodSignature(List<byte> b, TypeSpec rettype, TypeSpec[] ps, bool has_this = false, TypeSpec[] gmparams = null)
{
List<byte> tmp = new List<byte>();
byte cc = 0;
if (has_this)
cc |= 0x20;
if (gmparams != null)
cc |= 0x10;
tmp.Add(cc);
if(gmparams != null)
{
CompressInt(tmp, gmparams.Length);
foreach (var gmp in gmparams)
CreateTypeSignature(tmp, gmp);
}
CompressInt(tmp, ps.Length);
CreateTypeSignature(tmp, rettype);
foreach (var p in ps)
CreateTypeSignature(tmp, p);
int ret = b.Count;
CompressInt(b, tmp.Count);
b.AddRange(tmp);
return ret;
}
private void CreateTypeSignature(List<byte> tmp, TypeSpec ts)
{
if(ts == null)
{
tmp.Add(0x01);
return;
}
switch(ts.stype)
{
case TypeSpec.SpecialType.None:
int stype = -1;
if(ts.m.simple_type_idx != null)
stype = ts.m.simple_type_idx[ts.tdrow];
if (stype == -1)
{
if (ts.gtparams != null)
{
tmp.Add(0x15);
}
int val = 0;
if (ts.IsValueType)
val = 0x11;
else
val = 0x12;
val |= 0x80;
tmp.Add((byte)val);
CompressInt(tmp, ts.m.AssemblyName.Length);
foreach (var ch in ts.m.AssemblyName)
tmp.Add((byte)ch);
// create typedef pointer
var tok = corlib.MakeCodedIndexEntry(
tid_TypeDef,
ts.tdrow,
TypeDefOrRef);
CompressInt(tmp, tok);
if(ts.gtparams != null)
{
CompressInt(tmp, ts.gtparams.Length);
foreach (var gtp in ts.gtparams)
CreateTypeSignature(tmp, gtp);
}
}
else
tmp.Add((byte)stype);
break;
case TypeSpec.SpecialType.Ptr:
tmp.Add(0x0f);
CreateTypeSignature(tmp, ts.other);
break;
case TypeSpec.SpecialType.MPtr:
tmp.Add(0x10);
CreateTypeSignature(tmp, ts.other);
break;
case TypeSpec.SpecialType.SzArray:
tmp.Add(0x1d);
CreateTypeSignature(tmp, ts.other);
break;
default:
throw new NotImplementedException();
}
}
private void CompressInt(List<byte> b, int v)
{
unchecked
{
if (v >= -64 && v <= 63)
{
b.Add((byte)v);
}
else if (v >= -8192 && v <= 8191)
{
b.Add((byte)(((v >> 8) & 0xff) | 0x80));
b.Add((byte)(v & 0xff));
}
else
{
b.Add((byte)(((v >> 24) & 0xff) | 0xc0));
b.Add((byte)((v >> 16) & 0xff));
b.Add((byte)((v >> 8) & 0xff));
b.Add((byte)(v & 0xff));
}
}
}
private void CompressInt(List<byte> b, uint v)
{
unchecked
{
if (v <= 127)
{
b.Add((byte)v);
}
else if (v <= 0x3fff)
{
b.Add((byte)(((v >> 8) & 0xff) | 0x80));
b.Add((byte)(v & 0xff));
}
else
{
b.Add((byte)(((v >> 24) & 0xff) | 0xc0));
b.Add((byte)((v >> 16) & 0xff));
b.Add((byte)((v >> 8) & 0xff));
b.Add((byte)(v & 0xff));
}
}
}
class BlobStream : metadata.PEFile.StreamHeader
{
public BlobStream(IList<byte> arr)
{
di = new metadata.ArrayInterface(arr);
}
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.cil
{
class CilParser
{
static internal Code ParseCIL(metadata.DataInterface di,
metadata.MethodSpec ms, int boffset, int length,
long lvar_sig_tok, bool has_exceptions = false,
List<metadata.ExceptionHeader> ehdrs = null)
{
Code ret = new Code();
ret.cil = new List<CilNode>();
ret.ms = ms;
int table_id;
int row;
ms.m.InterpretToken((uint)lvar_sig_tok,
out table_id, out row);
int idx = (int)ms.m.GetIntEntry(table_id, row, 0);
var rtsig = ms.m.GetMethodDefSigRetTypeIndex(ms.msig);
ret.ret_ts = ms.m.GetTypeSpec(ref rtsig, ms.gtparams, ms.gmparams);
ret.lvar_sig_tok = idx;
Dictionary<int, List<int>> offsets_before =
new Dictionary<int, List<int>>(new GenericEqualityComparer<int>());
// First, generate CilNodes for each instruction
int offset = 0;
while (offset < length)
{
CilNode n = new CilNode(ms, offset);
/* Determine try block starts */
if (ehdrs != null)
{
foreach (var ehdr in ehdrs)
{
if (ehdr.TryILOffset == offset)
{
n.try_starts.Insert(0, ehdr);
}
if (ehdr.HandlerILOffset == offset ||
(ehdr.EType == metadata.ExceptionHeader.ExceptionHeaderType.Filter && ehdr.FilterOffset == offset))
{
n.handler_starts.Add(ehdr);
}
if(offset >= ehdr.HandlerILOffset &&
offset < ehdr.HandlerILOffset + ehdr.HandlerLength)
{
n.is_in_excpt_handler = true;
}
}
}
/* Parse prefixes */
bool cont = true;
while (cont)
{
if (di.ReadByte(offset + boffset) == 0xfe)
{
switch (di.ReadByte(offset + boffset + 1))
{
case 0x16:
n.constrained = true;
offset += 2;
n.constrained_tok = di.ReadUInt(offset + boffset);
offset += 4;
break;
case 0x19:
if ((di.ReadByte(offset + boffset + 2) & 0x01) == 0x01)
n.no_typecheck = true;
if ((di.ReadByte(offset + boffset + 2) & 0x02) == 0x02)
n.no_rangecheck = true;
if ((di.ReadByte(offset + boffset + 2) & 0x04) == 0x04)
n.no_nullcheck = true;
offset += 3;
break;
case 0x1e:
n.read_only = true;
offset += 2;
break;
case 0x14:
n.tail = true;
offset += 2;
break;
case 0x12:
n.unaligned = true;
n.unaligned_alignment = di.ReadByte(offset + boffset + 2);
offset += 3;
break;
case 0x13:
n.volatile_ = true;
offset += 2;
break;
default:
cont = false;
break;
}
}
else
cont = false;
}
/* Parse opcode */
if (di.ReadByte(offset + boffset) == (int)Opcode.SingleOpcodes.double_)
{
offset++;
n.opcode = OpcodeList.Opcodes[0xfe00 + di.ReadByte(offset + boffset)];
}
else if (di.ReadByte(offset + boffset) == (int)Opcode.SingleOpcodes.tysila)
{
//if (opts.AllowTysilaOpcodes)
//{
offset++;
n.opcode = OpcodeList.Opcodes[0xfd00 + di.ReadByte(offset + boffset)];
//}
//else
// throw new UnauthorizedAccessException("Opcodes in the range 0xfd00 - 0xfdff are not allowed in user code");
}
else
n.opcode = OpcodeList.Opcodes[di.ReadByte(offset + boffset)];
offset++;
/* Parse immediate operands */
switch (n.opcode.inline)
{
case Opcode.InlineVar.InlineBrTarget:
case Opcode.InlineVar.InlineI:
case Opcode.InlineVar.InlineField:
case Opcode.InlineVar.InlineMethod:
case Opcode.InlineVar.InlineSig:
case Opcode.InlineVar.InlineString:
case Opcode.InlineVar.InlineTok:
case Opcode.InlineVar.InlineType:
case Opcode.InlineVar.ShortInlineR:
n.inline_int = di.ReadInt(offset + boffset);
n.inline_uint = di.ReadUInt(offset + boffset);
n.inline_long = n.inline_int;
n.inline_val = new byte[4];
for (int i = 0; i < 4; i++)
n.inline_val[i] = di.ReadByte(offset + boffset + i);
offset += 4;
if (n.opcode.inline == Opcode.InlineVar.ShortInlineR)
{
unsafe
{
fixed (int* ii = &n.inline_int)
{
fixed (float* ifl = &n.inline_float)
{
*(int*)ifl = *ii;
}
}
}
n.inline_double = n.inline_float;
}
break;
case Opcode.InlineVar.InlineI8:
case Opcode.InlineVar.InlineR:
n.inline_int = di.ReadInt(offset + boffset);
n.inline_uint = di.ReadUInt(offset + boffset);
n.inline_long = di.ReadLong(offset + boffset);
n.inline_val = new byte[8];
for (int i = 0; i < 8; i++)
n.inline_val[i] = di.ReadByte(offset + boffset + i);
offset += 8;
if (n.opcode.inline == Opcode.InlineVar.InlineR)
{
unsafe
{
fixed (long* ii = &n.inline_long)
{
fixed (double* ifl = &n.inline_double)
{
*(long*)ifl = *ii;
}
}
}
n.inline_float = (float)n.inline_double;
}
break;
case Opcode.InlineVar.InlineVar:
//line.inline_int = LSB_Assembler.FromByteArrayI2S(code, offset);
//line.inline_uint = LSB_Assembler.FromByteArrayU2S(code, offset);
//line.inline_val = new byte[2];
//LSB_Assembler.SetByteArrayS(line.inline_val, 0, code, offset, 2);
throw new NotImplementedException();
offset += 2;
break;
case Opcode.InlineVar.ShortInlineBrTarget:
case Opcode.InlineVar.ShortInlineI:
case Opcode.InlineVar.ShortInlineVar:
n.inline_int = di.ReadSByte(offset + boffset);
n.inline_uint = di.ReadByte(offset + boffset);
n.inline_long = n.inline_int;
n.inline_val = new byte[1];
n.inline_val[0] = di.ReadByte(offset + boffset);
offset += 1;
break;
case Opcode.InlineVar.InlineSwitch:
uint switch_len = di.ReadUInt(offset + boffset);
n.inline_int = (int)switch_len;
n.inline_long = n.inline_int;
offset += 4;
n.inline_array = new List<int>();
for (uint switch_it = 0; switch_it < switch_len; switch_it++)
{
n.inline_array.Add(di.ReadInt(offset + boffset));
offset += 4;
}
break;
}
/* Determine the next instruction in the stream */
switch (n.opcode.ctrl)
{
case Opcode.ControlFlow.BRANCH:
n.il_offsets_after.Add(offset + n.inline_int);
break;
case Opcode.ControlFlow.COND_BRANCH:
if (n.opcode.opcode1 == Opcode.SingleOpcodes.switch_)
{
foreach (int jmp_target in n.inline_array)
n.il_offsets_after.Add(offset + jmp_target);
n.il_offsets_after.Add(offset);
}
else
{
n.il_offsets_after.Add(offset);
n.il_offsets_after.Add(offset + n.inline_int);
}
break;
case Opcode.ControlFlow.NEXT:
case Opcode.ControlFlow.CALL:
case Opcode.ControlFlow.BREAK:
n.il_offsets_after.Add(offset);
break;
}
n.il_offset_after = offset;
ret.offset_map[n.il_offset] = n;
ret.offset_order.Add(n.il_offset);
// Store this node as the offset_before whatever it
// references
foreach (var offset_after in n.il_offsets_after)
{
List<int> after_list;
if (!offsets_before.TryGetValue(offset_after,
out after_list))
{
after_list = new List<int>();
offsets_before[offset_after] = after_list;
}
if (!after_list.Contains(n.il_offset))
after_list.Add(n.il_offset);
}
ret.cil.Add(n);
}
/* Now determine which instructions are branch targets
* so we don't coalesce a block containing
* a branch into a single instruction */
foreach(var n in ret.cil)
{
if (n.opcode.ctrl == Opcode.ControlFlow.BRANCH)
ret.offset_map[n.il_offsets_after[0]].is_block_start = true;
else if(n.opcode.ctrl == Opcode.ControlFlow.COND_BRANCH)
ret.offset_map[n.il_offsets_after[1]].is_block_start = true;
}
ret.starts = new List<CilNode>();
if (ret.cil.Count > 0)
ret.starts.Add(ret.cil[0]);
if (ehdrs != null)
{
foreach (var e in ehdrs)
{
ret.starts.Add(ret.offset_map[e.HandlerILOffset]);
if (e.EType == metadata.ExceptionHeader.ExceptionHeaderType.Filter)
{
var filter_start = ret.offset_map[e.FilterOffset];
ret.starts.Add(filter_start);
filter_start.is_filter_start = true;
}
}
}
ret.ehdrs = ehdrs;
foreach(var n in ret.cil)
{
foreach(var next in n.il_offsets_after)
{
var next_n = ret.offset_map[next];
next_n.prev.Add(n);
}
}
return ret;
}
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using binary_library;
using libtysila5.ir;
using libtysila5.util;
using metadata;
using libtysila5.cil;
namespace libtysila5.target.arm
{
partial class arm_Assembler : Target
{
static MCInst inst(CilNode.IRNode parent,
int inst,
Param Rn = null,
Param Rd = null,
Param Rm = null,
Param Rt = null,
int imm = 0,
int W = 0,
int S = 0,
Param[] register_list = null,
string str_target = null,
bool is_tls = false)
{
string str = null;
insts.TryGetValue(inst, out str);
MCInst ret = new MCInst
{
parent = parent,
p = new Param[]
{
new Param { t = ir.Opcode.vl_str, v = inst, str = str, v2 = is_tls ? 1 : 0 },
Rn,
Rd,
Rm,
Rt,
imm,
W,
S,
RegListToInt(register_list),
str_target
}
};
return ret;
}
static private Param RegListToInt(Param[] register_list)
{
if (register_list == null)
return 0;
ulong val = 0;
foreach(var r in register_list)
{
val |= r.mreg.mask;
}
return (int)val;
}
internal static List<MCInst> handle_add(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var a = n.stack_before.Peek(n.arg_a).reg;
var b = n.stack_before.Peek(n.arg_b).reg;
var res = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
if(a.type == rt_gpr && b.type == rt_gpr && res.type == rt_gpr)
{
r.Add(inst(n, arm_add_reg, Rd: res, Rn: a, Rm: b));
return r;
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_and(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_br(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_break(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_brif(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_call(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return handle_call(n, c, false, t);
}
internal static List<MCInst> handle_calli(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return handle_call(n, c, true, t);
}
private static List<MCInst> handle_call(CilNode.IRNode n,
Code c, metadata.MethodSpec call_ms, ir.Param[] p,
Reg dest, string target = null, Reg temp_reg = null)
{
/* used for handling calls to utility functions
* (e.g. memcpy/memset etc) whilst ensuring that
* all required registers are saved around the
* call */
return handle_call(n, c, false, c.t, target, call_ms, p, dest, dest != null);
}
static List<Reg> get_push_list(CilNode.IRNode n, Code c,
metadata.MethodSpec call_ms, out metadata.TypeSpec rt,
ref Reg dest, out int rct, bool want_return = true)
{
/* Determine which registers we need to save */
var caller_preserves = c.t.cc_caller_preserves_map[call_ms.CallingConvention];
ulong defined = 0;
foreach (var si in n.stack_after)
defined |= si.reg.mask;
foreach (var si in n.stack_before)
defined |= si.reg.mask;
var rt_idx = call_ms.m.GetMethodDefSigRetTypeIndex(call_ms.msig);
rt = call_ms.m.GetTypeSpec(ref rt_idx, call_ms.gtparams, call_ms.gmparams);
rct = ir.Opcode.ct_unknown;
if (rt != null && want_return)
{
defined &= ~n.stack_after.Peek().reg.mask;
if (dest == null)
dest = n.stack_after.Peek().reg;
rct = ir.Opcode.GetCTFromType(rt);
}
var to_push = new util.Set();
to_push.Union(defined);
to_push.Intersect(caller_preserves);
List<Reg> push_list = new List<Reg>();
while (!to_push.Empty)
{
var first_set = to_push.get_first_set();
push_list.Add(c.t.regs[first_set]);
to_push.unset(first_set);
}
return push_list;
}
private static List<MCInst> handle_call(CilNode.IRNode n, Code c, bool is_calli, Target t,
string target = null, metadata.MethodSpec call_ms = null,
ir.Param[] p = null, Reg dest = null, bool want_return = true)
{
List<MCInst> r = new List<MCInst>();
if (call_ms == null)
call_ms = n.imm_ms;
if (target == null && is_calli == false)
target = call_ms.m.MangleMethod(call_ms);
Reg act_dest = null;
metadata.TypeSpec rt;
int rct;
var push_list = get_push_list(n, c, call_ms,
out rt, ref dest, out rct, want_return);
// Store the current index, we will insert instructions
// to save clobbered registers here
int push_list_index = r.Count;
/* Push arguments */
int push_length = 0;
int vt_push_length = 0;
bool vt_dest_adjust = false;
if (rct == ir.Opcode.ct_vt)
{
if (dest is ContentsReg)
{
act_dest = dest;
}
else
{
throw new NotImplementedException();
}
}
var sig_idx = call_ms.msig;
var pcount = call_ms.m.GetMethodDefSigParamCountIncludeThis(sig_idx);
sig_idx = call_ms.m.GetMethodDefSigRetTypeIndex(sig_idx);
var rt2 = call_ms.m.GetTypeSpec(ref sig_idx, call_ms.gtparams == null ? c.ms.gtparams : call_ms.gtparams, c.ms.gmparams);
int calli_adjust = is_calli ? 1 : 0;
metadata.TypeSpec[] push_tss = new metadata.TypeSpec[pcount];
for (int i = 0; i < pcount; i++)
{
if (i == 0 && call_ms.m.GetMethodDefSigHasNonExplicitThis(call_ms.msig))
push_tss[i] = call_ms.type;
else
push_tss[i] = call_ms.m.GetTypeSpec(ref sig_idx, call_ms.gtparams, call_ms.gmparams);
}
/* Push value type address if required */
metadata.TypeSpec hidden_loc_type = null;
if (rct == ir.Opcode.ct_vt)
{
var act_dest_cr = act_dest as ContentsReg;
if (act_dest_cr == null)
throw new NotImplementedException();
if (vt_dest_adjust)
{
throw new NotImplementedException();
}
//r.Add(inst(x86_lea_r32, r_eax, act_dest, n));
//r.Add(inst(x86_push_r32, r_eax, n));
hidden_loc_type = call_ms.m.SystemIntPtr;
}
// Build list of source and destination registers for parameters
int cstack_loc = 0;
var cc = t.cc_map[call_ms.CallingConvention];
var cc_class = t.cc_classmap[call_ms.CallingConvention];
int[] la_sizes;
metadata.TypeSpec[] la_types;
var to_locs = t.GetRegLocs(new ir.Param
{
m = call_ms.m,
v2 = call_ms.msig,
ms = call_ms
},
ref cstack_loc, cc, cc_class, call_ms.CallingConvention,
out la_sizes, out la_types,
hidden_loc_type
);
Reg calli_reg = null;
if (is_calli)
{
calli_reg = r_r10;
// Add the target register to those we want to pass
Reg[] new_to_locs = new Reg[to_locs.Length + calli_adjust];
for (int i = 0; i < to_locs.Length; i++)
new_to_locs[i] = to_locs[i];
new_to_locs[to_locs.Length] = calli_reg;
to_locs = new_to_locs;
}
// Append the register arguments to the push list
foreach (var arg in to_locs)
{
if (arg.type == rt_gpr || arg.type == rt_float)
{
if (!push_list.Contains(arg))
push_list.Add(arg);
}
}
List<MCInst> r2 = new List<MCInst>();
// Insert the push instructions at the start of the stream
int x = 0;
foreach (var push_reg in push_list)
handle_push(push_reg, ref x, r2, n, c);
foreach (var r2inst in r2)
r.Insert(push_list_index++, r2inst);
// Get from locs
ir.Param[] from_locs;
int hidden_adjust = hidden_loc_type == null ? 0 : 1;
if (p == null)
{
from_locs = new ir.Param[pcount + hidden_adjust + calli_adjust];
for (int i = 0; i < pcount; i++)
{
var stack_loc = pcount - i - 1;
if (n.arg_list != null)
stack_loc = n.arg_list[i];
from_locs[i + hidden_adjust] = n.stack_before.Peek(stack_loc + calli_adjust).reg;
}
if (is_calli)
from_locs[pcount + hidden_adjust] = n.stack_before.Peek(0).reg;
}
else
{
from_locs = p;
// adjust any rsp relative registers dependent on how many registers we have saved
foreach (var l in from_locs)
{
if (l != null &&
l.t == ir.Opcode.vl_mreg &&
l.mreg is ContentsReg)
{
var l2 = l.mreg as ContentsReg;
if (l2.basereg.Equals(r_sp))
{
l2.disp += x;
}
}
}
}
// Reserve any required stack space
if (cstack_loc != 0)
{
push_length += cstack_loc;
r.Add(inst(n, arm_sub_sp_imm, imm: cstack_loc));
}
// Move from the from list to the to list such that
// we never overwrite a from loc that hasn't been
// transfered yet
pcount += hidden_adjust;
pcount += calli_adjust;
var to_do = pcount;
bool[] done = new bool[pcount];
if (hidden_adjust != 0)
{
// load up the address of the return value
throw new NotImplementedException();
/*
var ret_to = to_locs[0];
if (!(ret_to is ContentsReg))
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, ret_to, act_dest, n));
else
{
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64, r_eax, act_dest, n));
handle_move(ret_to, r_eax, r, n, c);
}
to_do--;
done[0] = true;*/
}
while (to_do > 0)
{
int done_this_iter = 0;
for (int to_i = 0; to_i < pcount; to_i++)
{
if (!done[to_i])
{
var to_reg = to_locs[to_i];
if (to_reg.type == rt_stack)
{
to_reg = new ContentsReg
{
basereg = r_sp,
disp = to_reg.stack_loc,
size = to_reg.size
};
}
bool possible = true;
// determine if this to register is the source of a from
for (int from_i = 0; from_i < pcount; from_i++)
{
if (to_i == from_i)
continue;
if (!done[from_i] && from_locs[from_i].mreg != null &&
from_locs[from_i].mreg.Equals(to_reg))
{
possible = false;
break;
}
}
if (possible)
{
var from_reg = from_locs[to_i];
switch (from_reg.t)
{
case ir.Opcode.vl_mreg:
if (from_reg.want_address)
{
throw new NotImplementedException();
/*
Reg lea_to = to_reg;
if (to_reg is ContentsReg)
lea_to = r_eax;
r.Add(inst(t.psize == 4 ? x86_lea_r32 : x86_lea_r64,
lea_to, from_reg.mreg, n));
handle_move(to_reg, lea_to, r, n, c);
*/
}
else
handle_move(to_reg, from_reg.mreg, r, n, c);
break;
case ir.Opcode.vl_c:
case ir.Opcode.vl_c32:
case ir.Opcode.vl_c64:
if (from_reg.v > int.MaxValue ||
from_reg.v < int.MinValue)
{
throw new NotImplementedException();
}
else
{
handle_const(to_reg, from_reg.v, r, n, c);
}
break;
default:
throw new NotSupportedException();
}
to_do--;
done_this_iter++;
done[to_i] = true;
}
}
}
if (done_this_iter == 0)
{
// find two gprs/xmms we can swap to put them both
// in the correct locations
for (int i = 0; i < pcount; i++)
{
if (done[i])
continue;
var from_i = from_locs[i].mreg;
var to_i = to_locs[i];
if (from_i == null)
continue;
if (from_i.type != rt_gpr &&
from_i.type != rt_float)
continue;
if (to_i.type != rt_gpr &&
to_i.type != rt_float)
continue;
for (int j = 0; j < pcount; j++)
{
if (j == i)
continue;
if (done[j])
continue;
var from_j = from_locs[j].mreg;
if (from_j == null)
continue;
var to_j = to_locs[j];
if (from_i.Equals(to_j) &&
from_j.Equals(to_i))
{
// we can swap these
if (from_i.type == rt_gpr || from_i.type == rt_float)
{
handle_swap(to_i, to_j, r, n, c);
}
else if(from_i.type == rt_float)
{
throw new NotImplementedException();
}
done_this_iter += 2;
to_do -= 2;
done[i] = true;
done[j] = true;
break;
}
}
}
}
if (done_this_iter == 0)
{
// find two unassigned gprs/xmms we can swap, which
// may not necessarily put them in the correct place
bool shift_found = false;
// try with gprs first
int a = -1;
int b = -1;
for (int i = 0; i < pcount; i++)
{
if (done[i] == false && from_locs[i].mreg != null &&
from_locs[i].mreg.type == rt_gpr)
{
if (a == -1)
a = i;
else
{
b = i;
shift_found = true;
}
}
}
if (shift_found)
{
handle_swap(from_locs[a].mreg, from_locs[b].mreg, r, n, c);
var tmp = from_locs[a];
from_locs[a] = from_locs[b];
from_locs[b] = from_locs[a];
}
else
{
a = -1;
b = -1;
for (int i = 0; i < pcount; i++)
{
if (done[i] == false && from_locs[i].mreg != null &&
from_locs[i].mreg.type == rt_float)
{
if (a == -1)
a = i;
else
{
b = i;
shift_found = true;
}
}
}
if (shift_found)
{
handle_swap(from_locs[a].mreg, from_locs[b].mreg, r, n, c);
var tmp = from_locs[a];
from_locs[a] = from_locs[b];
from_locs[b] = from_locs[a];
}
}
if (!shift_found)
throw new NotImplementedException();
}
}
// Do the call
if (is_calli)
{
// Thumb mode requires LSB set to 1
r.Add(inst(n, arm_orr_imm, Rd: calli_reg, Rn: calli_reg, imm: 1));
r.Add(inst(n, arm_blx, Rm: calli_reg));
}
else
{
r.Add(inst(n, arm_bl, Rm: new ir.Param { t = ir.Opcode.vl_call_target, str = target }));
}
// Restore stack
if (push_length != 0)
{
r.Add(inst(n, arm_add_sp_imm, imm: push_length));
}
// Get vt return value
if (rct == ir.Opcode.ct_vt && !act_dest.Equals(dest))
{
handle_move(dest, act_dest, r, n, c);
}
// Restore saved registers
for (int i = push_list.Count - 1; i >= 0; i--)
handle_pop(push_list[i], ref x, r, n, c);
// Get other return value
if (rt != null && rct != ir.Opcode.ct_vt && rct != ir.Opcode.ct_unknown)
{
var rt_size = c.t.GetSize(rt);
if (rct == ir.Opcode.ct_float)
{
handle_move(dest, r_s0, r, n, c);
}
else if (rt_size <= 4)
{
handle_move(dest, r_r0, r, n, c);
}
else if (rt_size == 8)
{
throw new NotImplementedException();
/*
if (t.psize == 4)
{
var drd = dest as DoubleReg;
r.Add(inst(x86_mov_rm32_r32, drd.a, r_eax, n));
r.Add(inst(x86_mov_rm32_r32, drd.b, r_edx, n));
}
else
{
r.Add(inst(x86_mov_rm64_r64, dest, r_eax, n));
} */
}
else
throw new NotImplementedException();
}
return r;
}
private static void handle_pop(Reg reg, ref int push_length, List<MCInst> r, CilNode.IRNode n, Code c)
{
switch (reg.type)
{
case rt_gpr:
r.Add(inst(n, arm_pop, register_list: new Param[] { reg }));
push_length += c.t.psize;
break;
default:
throw new NotImplementedException();
}
}
private static void handle_swap(Reg to_i, Reg to_j, List<MCInst> r, CilNode.IRNode n, Code c)
{
throw new NotImplementedException();
}
private static void handle_const(Reg to_reg, long v, List<MCInst> r, CilNode.IRNode n, Code c)
{
if (to_reg.type != rt_gpr)
throw new NotImplementedException();
r.Add(inst(n, arm_mov_imm, Rd: to_reg, imm: (int)(v & 0xffff)));
if(v < 0 || v > UInt16.MaxValue)
{
r.Add(inst(n, arm_movt_imm, Rd: to_reg, imm: (int)((v >> 16) & 0xffff)));
}
}
internal static List<MCInst> handle_cctor_runonce(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_cmp(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_conv(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_div(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_enter(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
List<MCInst> r = new List<MCInst>();
var n = nodes[start];
var lv_size = c.lv_total_size + c.stack_total_size;
if (ir.Opcode.GetCTFromType(c.ret_ts) == ir.Opcode.ct_vt)
{
throw new NotImplementedException();
}
/* standard ARM prologue is:
*
* mov ip, sp
* stmdb sp!, {fp, ip, lr, pc} (push fp, ip, lr and pc)
* sub fp, ip, #4
*/
r.Add(inst(n, arm_mov_reg, Rd: r_ip, Rm: r_sp));
r.Add(inst(n, arm_stmdb, Rn: r_sp, W: 1, register_list: new Param[] { r_fp, r_ip, r_lr, r_pc }));
r.Add(inst(n, arm_sub_imm, Rd: r_fp, Rn: r_ip, imm: 4));
/* Move incoming arguments to the appropriate locations */
for (int i = 0; i < c.la_needs_assign.Length; i++)
{
if (c.la_needs_assign[i])
{
var from = c.incoming_args[i];
var to = c.la_locs[i];
handle_move(to, from, r, n, c);
}
}
/* Save clobbered registers */
var regs_to_save = c.regs_used & c.t.cc_callee_preserves_map[c.ms.CallingConvention];
var regs_set = new util.Set();
regs_set.Union(regs_to_save);
int y = 0;
while (regs_set.Empty == false)
{
var reg = regs_set.get_first_set();
regs_set.unset(reg);
var cur_reg = t.regs[reg];
handle_push(cur_reg, ref y, r, n, c);
c.regs_saved.Add(cur_reg);
}
if (ir.Opcode.GetCTFromType(c.ret_ts) == ir.Opcode.ct_vt)
{
throw new NotImplementedException();
//handle_move(new ContentsReg { basereg = r_ebp, disp = -t.psize, size = t.psize },
// t.psize == 4 ? r_eax : r_edi, r, n, c);
}
return r;
}
private static void handle_push(Reg reg, ref int push_length, List<MCInst> r, CilNode.IRNode n, Code c)
{
switch(reg.type)
{
case rt_gpr:
r.Add(inst(n, arm_push, register_list: new Param[] { reg }));
push_length += c.t.psize;
break;
default:
throw new NotImplementedException();
}
}
private static void handle_move(Reg to, Reg from, List<MCInst> r, CilNode.IRNode n, Code c)
{
if (to.type == rt_contents && from.type == rt_contents)
{
throw new NotImplementedException();
}
else if (to.type == rt_contents && from.type == rt_gpr)
{
var cto = to as ContentsReg;
if (cto.size != c.t.psize)
{
throw new NotImplementedException();
}
r.Add(inst(n, arm_str_imm, Rt: from, Rn: cto.basereg, imm: (int)cto.disp));
}
else if (to.type == rt_gpr && from.type == rt_contents)
{
var cfrom = from as ContentsReg;
if (cfrom.size != c.t.psize)
{
throw new NotImplementedException();
}
r.Add(inst(n, arm_ldr_imm, Rt: to, Rn: cfrom.basereg, imm: (int)cfrom.disp));
}
else if(to.type == rt_gpr && from.type == rt_gpr)
{
r.Add(inst(n, arm_mov_reg, Rd: to, Rm: from));
}
else
{
throw new NotImplementedException();
}
}
internal static List<MCInst> handle_enter_handler(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldarg(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ctret;
var src = c.la_locs[(int)n.imm_l];
var dest = n.stack_after.Peek(n.res_a).reg;
var r = new List<MCInst>();
if (n_ct == ir.Opcode.ct_int32 ||
n_ct == ir.Opcode.ct_float ||
n_ct == ir.Opcode.ct_vt ||
n_ct == ir.Opcode.ct_int64)
{
handle_move(dest, src, r, n, c);
return r;
}
return null;
}
internal static List<MCInst> handle_ldarga(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
List<MCInst> r = new List<MCInst>();
var dest = n.stack_after.Peek(n.res_a);
handle_const(dest.reg, n.imm_l, r, n, c);
return r;
}
internal static List<MCInst> handle_ldfp(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldlabaddr(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
List<MCInst> r = new List<MCInst>();
var dest = n.stack_after.Peek(n.res_a);
r.Add(inst(n, arm_mov_imm, Rd: dest.reg, imm: 0, str_target: n.imm_lab));
r.Add(inst(n, arm_movt_imm, Rd: dest.reg, imm: 0, str_target: n.imm_lab));
return r;
}
internal static List<MCInst> handle_ldloc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var src = c.lv_locs[(int)n.imm_l];
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
if (dest.type == rt_gpr)
{
handle_move(dest, src, r, n, c);
return r;
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldloca(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_ldobja(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_localloc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_memcpy(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_memset(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_mul(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_neg(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_not(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_nop(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_or(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_rem(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_ret(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
return handle_ret(n, c, t);
}
private static List<MCInst> handle_ret(CilNode.IRNode n, Code c, Target t)
{
List<MCInst> r = new List<MCInst>();
/* Put a local label here so we can jmp here at will */
int ret_lab = c.cctor_ret_tag;
if (ret_lab == -1)
{
ret_lab = c.next_mclabel--;
c.cctor_ret_tag = ret_lab;
}
r.Add(inst(n, Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = ret_lab }));
if (n.stack_before.Count == 1)
{
var reg = n.stack_before.Peek().reg;
switch (n.ct)
{
case ir.Opcode.ct_int32:
case ir.Opcode.ct_intptr:
case ir.Opcode.ct_object:
case ir.Opcode.ct_ref:
handle_move(r_r0, reg, r, n, c);
break;
case ir.Opcode.ct_int64:
throw new NotImplementedException();
break;
case ir.Opcode.ct_vt:
throw new NotImplementedException();
/*
// move address to save to to eax
handle_move(r_eax, new ContentsReg { basereg = r_ebp, disp = -t.psize, size = t.psize },
r, n, c);
// move struct to [eax]
var vt_size = c.t.GetSize(c.ret_ts);
handle_move(new ContentsReg { basereg = r_eax, size = vt_size },
reg, r, n, c); */
break;
case ir.Opcode.ct_float:
handle_move(r_s0, reg, r, n, c);
break;
default:
throw new NotImplementedException(ir.Opcode.ct_names[n.ct]);
}
}
// Restore used regs
if (!n.parent.is_in_excpt_handler)
{
// we use values relative to rbp here in case the function
// did a localloc which has changed the stack pointer
for (int i = 0; i < c.regs_saved.Count; i++)
{
ContentsReg cr = new ContentsReg { basereg = r_fp, disp = -c.lv_total_size - c.stack_total_size - t.psize * (i + 1), size = t.psize };
handle_move(c.regs_saved[i], cr, r, n, c);
}
}
else
{
// in exception handler we have to pop the values off the stack
// because rsp is not by default restored so we may return to the
// wrong place
// this works because we do not allow localloc in exception handlers
int x = 0;
for (int i = c.regs_saved.Count - 1; i >= 0; i--)
handle_pop(c.regs_saved[i], ref x, r, n, c);
}
if (n.parent.is_in_excpt_handler)
{
// in exception handler - don't restore sp
r.Add(inst(n, arm_pop, register_list: new Param[] { r_fp, r_lr }));
}
else
{
// standard function
r.Add(inst(n, arm_ldm, Rn: r_sp, register_list: new Param[] { r_fp, r_sp, r_lr }));
}
// Insert a code sequence here if this is a static constructor
if (c.is_cctor)
{
/* Sequence is:
*
* Load static field pointer
* mov rcx, lab_addr
*
* Set done flag
* mov_rm8_imm8 [rcx], 2
*
* Get return eip
* mov_r32_rm32/64 rcx, [rsp]
*
* Is this cctor was called by a direct call (i.e. [rcx-6] == 0xe8) then:
*
* Overwrite the preceeding 5 bytes with nops
* mov_rm32_imm32 [rcx - 5], 0x00401f0f ; 4 byte nop
* mov_rm8_imm8 [rcx - 1], 0x90 ; 1 byte nop
*
* Else skip to here (this is the case where we were called indirectly from
* System.Runtime.CompilerServices._RunClassConstructor())
*/
throw new NotImplementedException();
/*
r.Add(inst(x86_mov_rm32_imm32, r_ecx, new ir.Param { t = ir.Opcode.vl_str, str = c.ms.type.MangleType() + "S" }, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, 0, 2, n));
r.Add(inst(t.psize == 4 ? x86_mov_r32_rm32 : x86_mov_r64_rm64, r_ecx, new ContentsReg { basereg = r_esp }, n));
r.Add(inst(x86_cmp_rm8_imm8, new ContentsReg { basereg = r_ecx, disp = -6, size = 1 }, 0xe8, n));
int end_lab = c.next_mclabel--;
r.Add(inst_jmp(x86_jcc_rel32, end_lab, ir.Opcode.cc_ne, n));
//r.Add(inst(x86_mov_rm32disp_imm32, r_ecx, -5, 0x00401f0f, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -1, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -2, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -3, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -4, 0x90, n));
r.Add(inst(x86_mov_rm8disp_imm32, r_ecx, -5, 0x90, n));
r.Add(inst(Generic.g_mclabel, new ir.Param { t = ir.Opcode.vl_br_target, v = end_lab }, n)); */
}
if (c.ms.CallingConvention == "isrec")
{
throw new NotImplementedException();
// pop error code from stack
//r.Add(inst(t.psize == 4 ? x86_add_rm32_imm8 : x86_add_rm64_imm8,
// r_esp, 8, n));
}
if (c.ms.CallingConvention == "isr" || c.ms.CallingConvention == "isrec")
{
throw new NotImplementedException();
//r.Add(inst(t.psize == 4 ? x86_iret : x86_iretq, n));
}
else
{
r.Add(inst(n, arm_bx, Rm: r_lr));
}
return r;
}
internal static List<MCInst> handle_shl(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_shr(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_shr_un(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_spinlockhint(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_stackcopy(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var src = n.stack_before.Peek(n.arg_a).reg;
var dest = n.stack_after.Peek(n.res_a).reg;
List<MCInst> r = new List<MCInst>();
handle_move(dest, src, r, n, c);
return r;
}
internal static List<MCInst> handle_starg(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_stind(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct2 = n.ct2;
var addr = n.stack_before.Peek(n.arg_a).reg;
var val = n.stack_before.Peek(n.arg_b).reg;
bool is_tls = n.imm_ul == 1UL;
List<MCInst> r = new List<MCInst>();
if (addr.type == rt_gpr && val.type == rt_gpr)
{
handle_move(new ContentsReg { basereg = addr, size = c.t.psize }, val, r, n, c);
return r;
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_stloc(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
var n = nodes[start];
var n_ct = n.ct;
var src = n.stack_before.Peek(n.arg_a).reg;
var dest = c.lv_locs[(int)n.imm_l];
List<MCInst> r = new List<MCInst>();
if(src.type == rt_gpr)
{
handle_move(dest, src, r, n, c);
return r;
}
throw new NotImplementedException();
}
internal static List<MCInst> handle_sub(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_switch(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_syncvalcompareandswap(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_syncvalswap(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_syncvalexchangeandadd(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_target_specific(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_xor(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
internal static List<MCInst> handle_zeromem(
Target t,
List<CilNode.IRNode> nodes,
int start, int count, Code c)
{
throw new NotImplementedException();
}
}
}
<file_sep>/* Copyright (C) 2017 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.target
{
public class ChooseInstructions
{
public static void DoChoosing(Code c)
{
c.mc = new List<MCInst>();
var md = c.t.instrs.MaxDepth;
/* Rationalise CT types depending on platform */
foreach(var ir in c.ir)
{
ir.ct = c.t.RationaliseCT(ir.ct);
ir.ct2 = c.t.RationaliseCT(ir.ct2);
ir.ctret = c.t.RationaliseCT(ir.ctret);
}
for (int i = 0; i < c.ir.Count;)
{
int end_node = i + 1;
while (end_node < c.ir.Count && c.ir[end_node].parent.is_block_start == false &&
end_node <= (i + md))
end_node++;
int count = end_node - i;
while(count > 0)
{
var encoder = c.t.instrs.GetValue(c.ir, i, count);
if(encoder != null)
{
var instrs = encoder(c.t, c.ir, i, count, c);
if(instrs != null)
{
c.ir[i].mc = instrs;
c.mc.AddRange(instrs);
break;
}
}
count--;
}
if (count == 0)
{
var irnode = c.ir[i];
throw new Exception("Cannot encode " + irnode.ToString());
}
i += count;
}
}
}
public partial class Target
{
internal List<MCInst> handle_external(Target t,
List<cil.CilNode.IRNode> nodes,
int start, int count, Code c, string func_name)
{
var n = nodes[start];
var lastn = nodes[start + count - 1];
metadata.TypeSpec[] p;
if (n.ct != ir.Opcode.ct_unknown)
{
var ats = ir.Opcode.GetTypeFromCT(n.ct, c.ms.m);
if (n.ct2 != ir.Opcode.ct_unknown)
{
var bts = ir.Opcode.GetTypeFromCT(n.ct, c.ms.m);
p = new metadata.TypeSpec[] { ats, bts };
}
else
p = new metadata.TypeSpec[] { ats };
}
else
p = new metadata.TypeSpec[] { };
var rts = ir.Opcode.GetTypeFromCT(lastn.ctret, c.ms.m);
/* If we are compressing lots of ir into a single call,
* make sure the call instuction is aware of the end stack
* state */
if (n != lastn)
n.stack_after = lastn.stack_after;
var msig = c.special_meths.CreateMethodSignature(rts, p);
n.imm_ms = new metadata.MethodSpec { mangle_override = func_name, m = c.special_meths, msig = msig };
n.opcode = ir.Opcode.oc_call;
/* Now locate the call instruction */
var call_handler = instrs.GetValue(nodes, start, 1);
if (call_handler == null)
throw new Exception("Unable to locate call handler");
var r = call_handler(t, nodes, start, 1, c);
if (r == null)
throw new Exception("Unable to invoke call handler to handle external call");
return r;
}
}
public delegate List<MCInst> InstructionHandler(
Target t,
List<cil.CilNode.IRNode> node,
int start, int count, Code c);
}
<file_sep>/* Copyright (C) 2008 - 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// Utility functions
using System;
using System.Collections.Generic;
using System.Text;
namespace libtysila5.util
{
public class util
{
/** <summary>Simple implementation of Except from C# 3.0</summary>
* <param name="first">Elements of this set are returned as a new set, unless they occur in second</param>
* <param name="second">If an element is in this set, it prevents that value being returned should it occur in first</param>
*/
public static IEnumerable<T> Except<T>(IEnumerable<T> first, IEnumerable<T> second)
{
List<T> ret = new List<T>();
IList<T> s = second as IList<T>;
if (s == null)
s = new List<T>(second);
foreach (T t in first)
{
if (!(s.Contains(t)))
ret.Add(t);
}
return ret;
}
/** <summary>Returns a dictionary containing elements within first but not second</summary> */
public static IEnumerable<KeyValuePair<K, V>> Except<K, V>(IDictionary<K, V> first, IDictionary<K, V> second)
{
foreach (KeyValuePair<K, V> kvp in first)
{
if (!second.ContainsKey(kvp.Key))
yield return kvp;
}
yield break;
}
/** <summary>Simple implementation of Intersect from C# 3.0</summary>
* <param name="first">First set</param>
* <param name="second">Second set</param>
*/
public static IEnumerable<T> Intersect<T>(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == null)
yield break;
if (second == null)
yield break;
if (!(first is ICollection<T>))
first = new List<T>(first);
foreach (T t in second)
{
if (((ICollection<T>)first).Contains(t))
yield return t;
}
yield break;
}
/** <summary>Returns a Dictionary of items from first whose keys are in second</summary>
* <param name="first">Source dictionary</param>
* <param name="second">Keys to look for</param>
*/
public static IDictionary<K, V> Intersect<K, V>(IDictionary<K, V> first, ICollection<K> second)
{
Dictionary<K, V> ret = new Dictionary<K, V>();
foreach (K k in second)
{
if (first.ContainsKey(k))
ret.Add(k, first[k]);
}
return ret;
}
/** <summary>Simple implementation of Union from C# 3.0</summary>
* <param name="first">First set</param>
* <param name="second">Second set</param>
*/
public static IEnumerable<T> Union<T>(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == null)
yield break;
if (second == null)
yield break;
if (!(first is ICollection<T>))
first = new List<T>(first);
foreach (T t in first)
yield return t;
foreach (T t in second)
{
if (!(((ICollection<T>)first).Contains(t)))
yield return t;
}
yield break;
}
/** <summary>Returns a dictionary containing those members of the initial dictionary whose keys are contained in match</summary>
*/
public static IEnumerable<KeyValuePair<K, V>> Union<K, V>(IDictionary<K, V> initial, IEnumerable<K> match)
{
if (!(match is ICollection<K>))
match = new List<K>(match);
foreach (KeyValuePair<K, V> kvp in initial)
{
if (((ICollection<K>)match).Contains(kvp.Key))
yield return kvp;
}
yield break;
}
/** <summary>Aligns a value to a multiple of a particular value</summary>
*/
public static int align(int input, int factor)
{
int i_rem_f = input % factor;
if (i_rem_f == 0)
return input;
return input - i_rem_f + factor;
}
/** <summary>Return the largest of two numbers</summary>
*/
public static int max(int a, int b)
{
if (a >= b)
return a;
else
return b;
}
/** <summary>A generic high-performance set implementation</summary>
*/
public class Set<T> : IEnumerable<T>, IEquatable<Set<T>>, ICollection<T>
{
Dictionary<T, bool> d = new Dictionary<T, bool>();
public Set() { }
public Set(ICollection<T> ts) { AddRange(ts); }
public void Add(T t)
{
if (!d.ContainsKey(t))
d.Add(t, true);
}
public void AddRange(IEnumerable<T> ts)
{
foreach (T t in ts)
Add(t);
}
public bool Remove(T t)
{
if (d.ContainsKey(t))
return d.Remove(t);
return false;
}
public bool Contains(T t)
{
return d.ContainsKey(t);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
int i = 0;
foreach (KeyValuePair<T, bool> kvp in d)
{
if (i != 0)
sb.Append(", ");
sb.Append(kvp.Key.ToString());
i++;
}
sb.Append("}");
return sb.ToString();
}
public IEnumerator<T> GetEnumerator()
{
return (IEnumerator<T>)d.Keys.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return d.Keys.GetEnumerator();
}
public bool Equals(Set<T> other)
{
if (d.Count != other.d.Count)
return false;
foreach (KeyValuePair<T, bool> kvp in d)
{
if (!other.Contains(kvp.Key))
return false;
}
return true;
}
public Set<T> Intersect(IEnumerable<T> other)
{
Set<T> ret = new Set<T>();
foreach (T t in other)
{
if (Contains(t))
ret.Add(t);
}
return ret;
}
public Set<T> Except(IEnumerable<T> other)
{
Set<T> ret = new Set<T>(this);
foreach (T t in other)
ret.Remove(t);
return ret;
}
public Set<T> Union(IEnumerable<T> other)
{
Set<T> ret = new Set<T>(this);
foreach (T t in other)
ret.Add(t);
return ret;
}
public int Count { get { return d.Count; } }
public void Clear()
{
d.Clear();
}
public void CopyTo(T[] array, int arrayIndex)
{
d.Keys.CopyTo(array, arrayIndex);
}
public bool IsReadOnly
{
get { return false; }
}
public T ItemAtIndex(int idx)
{
IEnumerator<T> e = d.Keys.GetEnumerator();
e.MoveNext();
while(idx-- > 0)
e.MoveNext();
return e.Current;
}
}
/** <summary>A class mapping A to B and B to A</summary> */
public class ABMap<T, U>
{
Dictionary<T, U> ab_map = new Dictionary<T, U>();
Dictionary<U, T> ba_map = new Dictionary<U, T>();
public void Add(T a, U b)
{
ab_map.Add(a, b);
ba_map.Add(b, a);
}
public void RemoveA(T a)
{
U b = ab_map[a];
ab_map.Remove(a);
ba_map.Remove(b);
}
public void RemoveB(U b)
{
T a = ba_map[b];
ba_map.Remove(b);
ab_map.Remove(a);
}
public void ReplaceAtA(T a, U b)
{
ba_map.Remove(ab_map[a]);
ab_map[a] = b;
ba_map[b] = a;
}
public void ReplaceAtB(U b, T a)
{
ab_map.Remove(ba_map[b]);
ba_map[b] = a;
ab_map[a] = b;
}
public U GetAtA(T a)
{
return ab_map[a];
}
public T GetAtB(U b)
{
return ba_map[b];
}
public ICollection<T> GetAs()
{
return (ICollection<T>)ab_map.Keys;
}
public ICollection<U> GetBs()
{
return (ICollection<U>)ba_map.Keys;
}
public void Clear()
{
ab_map.Clear();
ba_map.Clear();
}
public int Count
{
get { return ab_map.Count; }
}
public bool ContainsA(T a)
{
return ab_map.ContainsKey(a);
}
public bool ContainsB(U b)
{
return ba_map.ContainsKey(b);
}
}
/** <summary>A stack of items</summary> */
public class Stack<T> : IList<T>
{
List<T> l;
public Stack()
{
l = new List<T>();
}
public Stack(IEnumerable<T> collection)
{
l = new List<T>(collection);
}
public int IndexOf(T item)
{
return l.IndexOf(item);
}
public void Insert(int index, T item)
{
l.Insert(index, item);
}
public void RemoveAt(int index)
{
l.RemoveAt(index);
}
public T this[int index]
{
get
{
return l[index];
}
set
{
l[index] = value;
}
}
public void Add(T item)
{
l.Add(item);
}
public void Clear()
{
l.Clear();
}
public bool Contains(T item)
{
return l.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
l.CopyTo(array, arrayIndex);
}
public int Count
{
get { return l.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
return l.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
return l.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return l.GetEnumerator();
}
public void Push(T item)
{
l.Add(item);
}
public T Pop()
{
if (l.Count == 0)
return default(T);
T ret = l[l.Count - 1];
l.RemoveAt(l.Count - 1);
return ret;
}
public T Peek()
{
return l[l.Count - 1];
}
public T Peek(int n)
{
return l[l.Count - 1 - n];
}
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class InsertCharacterAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (consoleKeyInfo.KeyChar == 0 || console.CurrentLine.Length >= byte.MaxValue - 1)
return;
console.CurrentLine = console.CurrentLine.Insert(console.CursorPosition - console.StartCursorPosition, consoleKeyInfo.KeyChar.ToString());
console.CursorPosition++;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace TableMap
{
internal class Expression
{
public Expression a, b;
public Tokens op;
public virtual EvalResult Evaluate(MakeState s)
{
EvalResult ea, eb;
switch (op)
{
case Tokens.NOT:
ea = a.Evaluate(s);
check_null(ea);
if (ea.AsInt == 0)
return new EvalResult(1);
else
return new EvalResult(0);
case Tokens.LAND:
ea = a.Evaluate(s);
if (ea.AsInt == 0)
return new EvalResult(0);
eb = b.Evaluate(s);
if (eb.AsInt == 0)
return new EvalResult(0);
return new EvalResult(1);
case Tokens.LOR:
ea = a.Evaluate(s);
if (ea.AsInt != 0)
return new EvalResult(1);
eb = b.Evaluate(s);
if (eb.AsInt != 0)
return new EvalResult(1);
return new EvalResult(0);
case Tokens.PLUS:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
if (ea.Type == EvalResult.ResultType.Int && eb.Type == EvalResult.ResultType.Int)
return new EvalResult(ea.intval + eb.intval);
else if (ea.Type == EvalResult.ResultType.String && eb.Type == EvalResult.ResultType.String)
return new EvalResult(ea.strval + eb.strval);
else if (ea.Type == EvalResult.ResultType.Int && eb.Type == EvalResult.ResultType.String)
return new EvalResult(ea.intval.ToString() + eb.strval);
else if (ea.Type == EvalResult.ResultType.String && eb.Type == EvalResult.ResultType.Int)
return new EvalResult(ea.strval + eb.intval.ToString());
else if (ea.Type == EvalResult.ResultType.Void && eb.Type == EvalResult.ResultType.Void)
return new EvalResult();
else
throw new Statement.SyntaxException("Mismatched arguments to PLUS: " + ea.Type.ToString() + " and " + eb.Type.ToString());
case Tokens.MUL:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
return new EvalResult(ea.AsInt * eb.AsInt);
case Tokens.MINUS:
ea = a.Evaluate(s);
check_null(ea);
if (b == null)
{
// unary minus
if (ea.Type == EvalResult.ResultType.Void)
return ea;
if (ea.Type == EvalResult.ResultType.String)
throw new Statement.SyntaxException("Cannot apply unary minus to type string");
return new EvalResult(0 - ea.intval);
}
else
{
eb = b.Evaluate(s);
check_null(eb);
if (ea.Type == EvalResult.ResultType.String && (eb.Type == EvalResult.ResultType.Int || eb.Type == EvalResult.ResultType.Void))
{
long rem_amount = eb.AsInt;
if (rem_amount > ea.strval.Length)
rem_amount = ea.strval.Length;
return new EvalResult(ea.strval.Substring(0, ea.strval.Length - (int)rem_amount));
}
else if (ea.Type == EvalResult.ResultType.String && eb.Type == EvalResult.ResultType.String)
{
if (ea.strval.EndsWith(eb.strval))
return new EvalResult(ea.strval.Substring(0, ea.strval.Length - eb.strval.Length));
else
throw new Statement.SyntaxException(ea.strval + " does not end with " + eb.strval);
}
else if (ea.Type == EvalResult.ResultType.Void && eb.Type == EvalResult.ResultType.Void)
{
return new EvalResult();
}
else
{
return new EvalResult(ea.AsInt - eb.AsInt);
}
}
case Tokens.DEFINED:
ea = a.Evaluate(s);
if (ea.Type != EvalResult.ResultType.String)
throw new Statement.SyntaxException("defined requires a string/label argument");
if (s.IsDefined(ea.strval))
return new EvalResult(1);
else
return new EvalResult(0);
case Tokens.EQUALS:
case Tokens.NOTEQUAL:
{
int _true = 1;
int _false = 0;
if (op == Tokens.NOTEQUAL)
{
_true = 0;
_false = 1;
}
ea = a.Evaluate(s);
eb = b.Evaluate(s);
if (ea.Type == EvalResult.ResultType.String && eb.Type == EvalResult.ResultType.String)
{
if (ea.strval == null)
{
if (eb.strval == null)
return new EvalResult(_true);
else
return new EvalResult(_false);
}
if (ea.strval.Equals(eb.strval))
return new EvalResult(_true);
else
return new EvalResult(_false);
}
else if (ea.Type == EvalResult.ResultType.Null && eb.Type != EvalResult.ResultType.Null)
return new EvalResult(_false);
else if(ea.Type != EvalResult.ResultType.Null && eb.Type == EvalResult.ResultType.Null)
return new EvalResult(_false);
else if(ea.Type == EvalResult.ResultType.Null && eb.Type == EvalResult.ResultType.Null)
return new EvalResult(_true);
{
if (ea.AsInt == eb.AsInt)
return new EvalResult(_true);
else
return new EvalResult(_false);
}
}
case Tokens.LT:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
if (ea.AsInt < eb.AsInt)
return new EvalResult(1);
else
return new EvalResult(0);
case Tokens.GT:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
if (ea.AsInt > eb.AsInt)
return new EvalResult(1);
else
return new EvalResult(0);
case Tokens.LSHIFT:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
return new EvalResult(ea.AsInt << (int)eb.AsInt);
case Tokens.RSHIFT:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
return new EvalResult(ea.AsInt >> (int)eb.AsInt);
case Tokens.OR:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
return new EvalResult(ea.AsInt | eb.AsInt);
case Tokens.AND:
ea = a.Evaluate(s);
eb = b.Evaluate(s);
check_null(ea);
check_null(eb);
return new EvalResult(ea.AsInt & eb.AsInt);
}
throw new NotImplementedException(op.ToString());
}
private void check_null(EvalResult ea)
{
if (ea.Type == EvalResult.ResultType.Null)
throw new Exception("null not allowed in expression");
}
public class EvalResult
{
public enum ResultType { Int, String, Void, Function, MakeRule, Object, Array, Any, Null };
public ResultType Type;
public string strval;
public long intval;
public Dictionary<string, EvalResult> objval;
public FunctionStatement funcval;
public List<EvalResult> arrval;
public EvalResult()
{
Type = ResultType.Void;
}
public EvalResult(long i)
{
Type = ResultType.Int;
intval = i;
}
public EvalResult(string s)
{
Type = ResultType.String;
strval = s;
}
public EvalResult(FunctionStatement f)
{
Type = ResultType.Function;
funcval = f;
}
public EvalResult(Dictionary<string, EvalResult> o)
{
Type = ResultType.Object;
objval = o;
}
public EvalResult(IEnumerable<string> sarr)
{
Type = ResultType.Array;
arrval = new List<EvalResult>();
foreach (string src in sarr)
arrval.Add(new EvalResult(src));
}
public EvalResult(IEnumerable<int> iarr)
{
Type = ResultType.Array;
arrval = new List<EvalResult>();
foreach (int src in iarr)
arrval.Add(new EvalResult(src));
}
public EvalResult(IEnumerable<EvalResult> earr)
{
Type = ResultType.Array;
arrval = new List<EvalResult>(earr);
}
public long AsInt
{
get
{
switch (Type)
{
case ResultType.Int:
return intval;
case ResultType.String:
if (strval == null || strval == "")
return 0;
return 1;
case ResultType.Void:
return 0;
case ResultType.Null:
return 0;
default:
throw new NotSupportedException();
}
}
}
public static implicit operator Expression(EvalResult er)
{
return new ResultExpression { e = er };
}
public override string ToString()
{
switch (Type)
{
case ResultType.Int:
return intval.ToString();
case ResultType.String:
return "\"" + strval + "\"";
case ResultType.Void:
return "{void}";
case ResultType.Array:
{
StringBuilder sb = new StringBuilder();
sb.Append("[ ");
for(int i = 0; i < arrval.Count; i++)
{
if (i != 0)
sb.Append(", ");
sb.Append(arrval[i].ToString());
}
sb.Append(" ]");
return sb.ToString();
}
case ResultType.Null:
return "null";
case ResultType.Object:
{
StringBuilder sb = new StringBuilder();
sb.Append("[ ");
int i = 0;
foreach(var kvp in objval)
{
if (i != 0)
sb.Append(", ");
sb.Append(kvp.Key);
sb.Append(" = ");
sb.Append(kvp.Value.ToString());
i++;
}
sb.Append(" ]");
return sb.ToString();
}
default:
throw new NotSupportedException();
}
}
}
}
internal class ResultExpression : Expression
{
public EvalResult e;
public override EvalResult Evaluate(MakeState s)
{
return e;
}
}
internal class StringExpression : Expression
{
public string val;
public override EvalResult Evaluate(MakeState s)
{
/* First, parse variables in the shell command */
StringBuilder sb = new StringBuilder();
int i = 0;
while (i < val.Length)
{
if (val[i] == '\\' && i < (val.Length - 1))
{
sb.Append(val[i++]);
sb.Append(val[i++]);
}
else if (val[i] == '$')
{
/* Now try and match the largest possible variable we can */
int j = i + 1;
string match = null;
while (j < (val.Length) && val[j] != '$')
{
string test = val.Substring(i + 1, j - i);
if (s.IsDefined(test))
match = test;
j++;
}
if (match != null)
{
sb.Append(s.GetDefine(match).strval);
i++;
i += match.Length;
}
else
sb.Append(val[i++]);
}
else
sb.Append(val[i++]);
}
return new EvalResult(sb.ToString());
}
}
internal class LabelExpression : Expression
{
public string val;
public override EvalResult Evaluate(MakeState s)
{
if (s.IsDefined(val))
return s.GetDefine(val);
else if (s.funcs.ContainsKey(val))
return new EvalResult
{
Type = EvalResult.ResultType.Function,
funcval = new FunctionStatement
{
name = val
}
};
else
return new EvalResult();
}
public override string ToString()
{
return val;
}
}
internal class FunctionRefExpression : Expression
{
public string name;
public List<EvalResult.ResultType> args;
public override EvalResult Evaluate(MakeState s)
{
FunctionStatement fs = new FunctionStatement();
fs.name = name;
fs.args = new List<FunctionStatement.FunctionArg>();
foreach (var arg in args)
fs.args.Add(new FunctionStatement.FunctionArg { argtype = arg });
var mangled = fs.Mangle();
if (s.funcs.ContainsKey(mangled))
{
fs.args = s.funcs[mangled].args;
fs.code = s.funcs[mangled].code;
return new EvalResult(fs);
}
else
return new EvalResult();
}
}
internal class LabelIndexedExpression : Expression
{
public Expression label;
public Expression index;
public override EvalResult Evaluate(MakeState s)
{
EvalResult elabel = label.Evaluate(s);
EvalResult eindex = index.Evaluate(s);
switch(elabel.Type)
{
case EvalResult.ResultType.String:
return new EvalResult(new string(elabel.strval[(int)eindex.AsInt], 1));
case EvalResult.ResultType.Array:
{
var idx = eindex.AsInt;
if (idx < 0 || idx >= elabel.arrval.Count)
return new EvalResult { Type = EvalResult.ResultType.Null };
else
return elabel.arrval[(int)idx];
}
case EvalResult.ResultType.Object:
return elabel.objval[eindex.strval];
default:
throw new Statement.SyntaxException("indexing cannot be applied to object of type: " + elabel.Type.ToString());
}
}
}
internal class LabelMemberExpression : Expression
{
public Expression label;
public Expression member;
public override EvalResult Evaluate(MakeState s)
{
EvalResult elabel = label.Evaluate(s);
if (member is LabelExpression)
{
string m = ((LabelExpression)member).val;
switch (elabel.Type)
{
case EvalResult.ResultType.String:
if (m == "length")
return new EvalResult(elabel.strval.Length);
break;
case EvalResult.ResultType.Object:
if (elabel.objval.ContainsKey(m))
return elabel.objval[m];
break;
case EvalResult.ResultType.Array:
if (m == "length")
return new EvalResult(elabel.arrval.Count);
break;
}
if (m == "type")
return new EvalResult(elabel.Type.ToString());
throw new Statement.SyntaxException("object: " + label.ToString() + " does not contain member " + m.ToString());
}
else if (member is FuncCall)
{
FuncCall f = member as FuncCall;
FuncCall fsite = new FuncCall { target = f.target };
fsite.args = new List<Expression>(f.args);
fsite.args.Insert(0, label);
string m = fsite.Mangle(s);
switch (elabel.Type)
{
case EvalResult.ResultType.String:
if(m == "5splitss")
{
string[] split = elabel.strval.Split(new string[] { f.args[0].Evaluate(s).strval }, StringSplitOptions.None);
EvalResult[] ret = new EvalResult[split.Length];
for (int i = 0; i < split.Length; i++)
ret[i] = new EvalResult(split[i]);
return new EvalResult(ret);
}
else if(m == "9substringsi")
{
return new EvalResult(elabel.strval.Substring((int)f.args[0].Evaluate(s).AsInt));
}
else if(m == "9substringsii")
{
return new EvalResult(elabel.strval.Substring((int)f.args[0].Evaluate(s).AsInt, (int)f.args[1].Evaluate(s).AsInt));
}
break;
case EvalResult.ResultType.Array:
if (m == "3addai")
{
elabel.arrval.Add(new EvalResult(f.args[0].Evaluate(s).intval));
return new EvalResult();
}
else if (m == "3addas")
{
elabel.arrval.Add(new EvalResult(f.args[0].Evaluate(s).strval));
return new EvalResult();
}
else if (m == "3addao")
{
elabel.arrval.Add(new EvalResult(f.args[0].Evaluate(s).objval));
return new EvalResult();
}
else if (m == "3addaa")
{
elabel.arrval.Add(new EvalResult(f.args[0].Evaluate(s).arrval));
return new EvalResult();
}
else if (m == "3addav")
{
elabel.arrval.Add(new EvalResult());
return new EvalResult();
}
else if (m == "3addan")
{
elabel.arrval.Add(new EvalResult { Type = EvalResult.ResultType.Null });
return new EvalResult();
}
else if (m == "8addrangeaa")
{
elabel.arrval.AddRange(f.args[0].Evaluate(s).arrval);
return new EvalResult();
}
else if (m == "6insertaii")
{
elabel.arrval.Insert((int)f.args[1].Evaluate(s).intval, new EvalResult(f.args[0].Evaluate(s).intval));
return new EvalResult();
}
else if (m == "6insertais")
{
elabel.arrval.Insert((int)f.args[1].Evaluate(s).intval, new EvalResult(f.args[0].Evaluate(s).strval));
return new EvalResult();
}
else if (m == "6insertaio")
{
elabel.arrval.Insert((int)f.args[1].Evaluate(s).intval, new EvalResult(f.args[0].Evaluate(s).objval));
return new EvalResult();
}
else if (m == "6insertaia")
{
elabel.arrval.Insert((int)f.args[1].Evaluate(s).intval, new EvalResult(f.args[0].Evaluate(s).arrval));
return new EvalResult();
}
else if (m == "6removeai")
{
elabel.arrval.RemoveAt((int)f.args[0].Evaluate(s).intval);
return new EvalResult();
}
break;
case EvalResult.ResultType.Object:
if (elabel.objval.ContainsKey(m))
{
EvalResult feval = elabel.objval[m];
if (feval.Type == EvalResult.ResultType.Function)
{
List<EvalResult> fargs = new List<EvalResult>();
foreach (Expression e in fsite.args)
fargs.Add(e.Evaluate(s));
return feval.funcval.Run(s, fargs);
}
}
break;
}
throw new Statement.SyntaxException("object: " + label.ToString() + " does not contain member " + m.ToString());
}
else
throw new NotSupportedException();
}
}
internal class IntExpression : Expression
{
public int val;
public override EvalResult Evaluate(MakeState s)
{
return new EvalResult(val);
}
}
internal class NullExpression : Expression
{
public override EvalResult Evaluate(MakeState s)
{
return new EvalResult { Type = EvalResult.ResultType.Null };
}
}
internal class ObjectExpression : Expression
{
public Dictionary<string, Expression.EvalResult> val =
new Dictionary<string, EvalResult>();
public override EvalResult Evaluate(MakeState s)
{
return new EvalResult(val);
}
}
internal class ProjectDepends : Expression
{
public Expression project;
}
internal class ShellCmdDepends : Expression
{
public Expression shellcmd;
}
internal class FuncCall : Expression
{
public string target;
public List<Expression> args;
public string Mangle(MakeState s)
{
List<Expression.EvalResult> ers = new List<EvalResult>();
foreach (var arg in args)
ers.Add(arg.Evaluate(s));
return Mangle(target, ers);
}
public static string Mangle(string target, List<Expression.EvalResult> args)
{
StringBuilder sb = new StringBuilder();
sb.Append(target.Length.ToString());
sb.Append(target);
foreach (var e in args)
{
switch (e.Type)
{
case EvalResult.ResultType.Int:
sb.Append("i");
break;
case EvalResult.ResultType.String:
sb.Append("s");
break;
case EvalResult.ResultType.Array:
sb.Append("a");
break;
case EvalResult.ResultType.Object:
sb.Append("o");
break;
case EvalResult.ResultType.Void:
sb.Append("v");
break;
case EvalResult.ResultType.Null:
sb.Append("n");
break;
case EvalResult.ResultType.Function:
sb.Append("f");
break;
case EvalResult.ResultType.Any:
sb.Append("x");
break;
}
}
return sb.ToString();
}
public override EvalResult Evaluate(MakeState s)
{
List<string> mangle_all = MangleAll(s);
foreach (var mangled_name in mangle_all)
{
if (s.funcs.ContainsKey(mangled_name))
{
List<EvalResult> args_to_pass = new List<EvalResult>();
foreach (Expression arg in args)
args_to_pass.Add(arg.Evaluate(s));
return s.funcs[mangled_name].Run(s, args_to_pass);
}
}
throw new Statement.SyntaxException("unable to find function " + Mangle(s));
}
static Dictionary<string, List<string>> mangle_all_cache = new Dictionary<string, List<string>>();
private List<string> MangleAll(MakeState s)
{
var cache_key = Mangle(s);
List<string> ret;
if (mangle_all_cache.TryGetValue(cache_key, out ret))
return ret;
List<Expression.EvalResult> ers = new List<EvalResult>();
foreach (var arg in args)
ers.Add(arg.Evaluate(s));
ret = new List<string>();
for(int i = 0; i <= args.Count; i++)
{
MangleAllLine(i, 0, ret, ers);
}
mangle_all_cache[cache_key] = ret;
return ret;
}
private void MangleAllLine(int total_anys,
int cur_anys, List<string> ret,
List<Expression.EvalResult> args_in)
{
if (cur_anys == total_anys)
{
var m = Mangle(target, args_in);
if (!ret.Contains(m))
ret.Add(m);
}
else
{
for(int i = 0; i < args_in.Count; i++)
{
if (args_in[i].Type == EvalResult.ResultType.Any)
continue;
List<EvalResult> new_args_in = new List<EvalResult>(args_in);
new_args_in[i] = new EvalResult { Type = EvalResult.ResultType.Any };
MangleAllLine(total_anys, cur_anys + 1, ret, new_args_in);
}
}
}
}
class ArrayExpression : Expression
{
public List<Expression> val;
public override EvalResult Evaluate(MakeState s)
{
List<EvalResult> ret = new List<EvalResult>();
foreach (Expression e in val)
ret.Add(e.Evaluate(s));
return new EvalResult(ret);
}
}
class ObjExpression : Expression
{
public List<ObjDef> val;
public override EvalResult Evaluate(MakeState s)
{
Dictionary<string, EvalResult> ret = new Dictionary<string, EvalResult>();
foreach (ObjDef o in val)
ret[o.name] = o.val.Evaluate(s);
return new EvalResult(ret);
}
}
class ObjDef
{
public string name;
public Expression val;
}
}
<file_sep>/* Copyright (C) 2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using libtysila5.util;
namespace libtysila5.target.x86
{
partial class x86_Assembler
{
protected internal override void AssemblePass(Code c)
{
var Code = c.s.text_section.Data as List<byte>;
var code_start = Code.Count;
Dictionary<int, int> il_starts = new Dictionary<int, int>(
new GenericEqualityComparer<int>());
/* Get maximum il offset of method */
int max_il = 0;
if (c.cil != null)
{
foreach (var cil in c.cil)
{
if (cil.il_offset > max_il)
max_il = cil.il_offset;
}
}
max_il++;
for (int i = 0; i < max_il; i++)
il_starts[i] = -1;
List<int> rel_srcs = new List<int>();
List<int> rel_dests = new List<int>();
foreach(var I in c.mc)
{
var mc_offset = Code.Count - code_start;
I.offset = mc_offset;
I.addr = Code.Count;
I.end_addr = Code.Count;
if (I.parent != null)
{
var cil = I.parent.parent;
if (il_starts[cil.il_offset] == -1)
{
var ir = I.parent;
/* We don't want the il offset for the first node to point
* to the enter/enter_handler opcode as this potentially breaks
* small methods like:
*
* IL_0000: br.s IL_0000
*
* where we want the jmp to be to the br irnode, rather than the enter irnode */
if (ir.opcode != libtysila5.ir.Opcode.oc_enter &&
ir.opcode != libtysila5.ir.Opcode.oc_enter_handler &&
ir.ignore_for_mcoffset == false)
{
il_starts[cil.il_offset] = mc_offset;
cil.mc_offset = mc_offset;
}
}
}
if (I.p.Length == 0)
continue;
int tls_flag = (int)I.p[0].v2;
switch (I.p[0].v)
{
case Generic.g_mclabel:
il_starts[(int)I.p[1].v] = mc_offset;
break;
case Generic.g_label:
c.extra_labels.Add(new Code.Label
{
Offset = mc_offset + code_start,
Name = I.p[1].str
});
break;
case x86_push_rm32:
AddRex(Code, Rex(0, null, I.p[1].mreg));
Code.Add(0xff);
Code.AddRange(ModRMSIB(6, I.p[1].mreg));
break;
case x86_push_r32:
AddRex(Code, Rex(0, null, I.p[1].mreg));
Code.Add(PlusRD(0x50, I.p[1].mreg));
break;
case x86_push_imm32:
Code.Add(0x68);
AddImm32(Code, I.p[1].v);
break;
case x86_pop_rm32:
AddRex(Code, Rex(0, null, I.p[1].mreg));
Code.Add(0x8f);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
break;
case x86_pop_r32:
AddRex(Code, Rex(0, null, I.p[1].mreg));
Code.Add(PlusRD(0x58, I.p[1].mreg));
break;
case x86_mov_r32_rm32:
case x86_mov_r8_rm8:
case x86_mov_r16_rm16:
case x86_mov_r64_rm64:
if (I.p[0].v == x86_mov_r8_rm8)
{
Code.AddRange(TLSOverride(ref tls_flag));
Code.Add(0x8a);
}
else if (I.p[0].v == x86_mov_r16_rm16)
{
Code.AddRange(TLSOverride(ref tls_flag));
Code.Add(0x67);
Code.Add(0x8b);
}
else
{
Code.AddRange(TLSOverride(ref tls_flag));
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x8b);
}
switch(I.p[2].t)
{
case ir.Opcode.vl_mreg:
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case ir.Opcode.vl_str:
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), 5, 0, -1, 0, 0, false));
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_386_32();
reloc.Addend = I.p[2].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[2].str;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
break;
default:
throw new NotSupportedException();
}
break;
case x86_mov_rm32_r32:
case x86_mov_rm64_r64:
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x89);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_mov_rm64_imm32:
case x86_mov_rm32_imm32:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xc7);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
switch (I.p[2].t)
{
case ir.Opcode.vl_c:
case ir.Opcode.vl_c32:
AddImm32(Code, I.p[2].v);
break;
case ir.Opcode.vl_str:
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
if (I.p[2].v2 == 1)
{
if (psize == 4)
reloc.Type = new binary_library.elf.ElfFile.Rel_386_TLS_DTPOFF32();
else
reloc.Type = new binary_library.elf.ElfFile.Rel_x86_64_TLS_TPOFF32();
}
else if (psize == 4)
reloc.Type = new binary_library.elf.ElfFile.Rel_386_32();
else
reloc.Type = new binary_library.elf.ElfFile.Rel_x86_64_32();
reloc.Addend = I.p[2].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[2].str;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
break;
default:
throw new NotSupportedException();
}
break;
case x86_add_rm32_imm32:
case x86_add_rm64_imm32:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0x81);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
AddImm32(Code, I.p[2].v);
if (I.p.Length == 4)
throw new Exception();
break;
case x86_add_rm32_imm8:
case x86_add_rm64_imm8:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0x83);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
AddImm8(Code, I.p[2].v);
if (I.p.Length == 4)
throw new Exception();
break;
case x86_adc_r32_rm32:
Code.Add(0x13);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_sub_rm32_imm32:
case x86_sub_rm64_imm32:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0x81);
Code.AddRange(ModRMSIB(5, I.p[1].mreg));
AddImm32(Code, I.p[2].v);
if (I.p.Length == 4)
throw new Exception();
break;
case x86_sub_rm32_imm8:
case x86_sub_rm64_imm8:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0x83);
Code.AddRange(ModRMSIB(5, I.p[1].mreg));
AddImm8(Code, I.p[2].v);
if (I.p.Length == 4)
throw new Exception();
break;
case x86_sub_r32_rm32:
case x86_sub_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x2b);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_and_r32_rm32:
case x86_and_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x23);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_and_rm32_r32:
case x86_and_rm64_r64:
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x21);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_or_r32_rm32:
case x86_or_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0b);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_or_rm32_r32:
case x86_or_rm64_r64:
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x09);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_xor_r32_rm32:
case x86_xor_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x33);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_xor_rm32_r32:
case x86_xor_rm64_r64:
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x31);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_sbb_r32_rm32:
case x86_sbb_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x1b);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_add_r64_rm64:
case x86_add_r32_rm32:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x03);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_add_rm32_r32:
case x86_add_rm64_r64:
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x01);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
if (I.p.Length == 4)
throw new Exception();
break;
case x86_call_rel32:
{
Code.Add(0xe8);
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_386_PC32();
reloc.Addend = -4;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[1].str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Function;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
}
break;
case x86_call_rm32:
{
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xff);
var obj = I.p[1];
Code.AddRange(ModRMSIB(2, obj.mreg));
break;
}
case x86_cmp_rm32_r32:
case x86_cmp_rm64_r64:
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x39);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_cmp_r32_rm32:
case x86_cmp_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x3b);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cmp_rm32_imm32:
if (I.p[1].mreg == r_eax)
Code.Add(0x3d);
else
{
Code.Add(0x81);
Code.AddRange(ModRMSIB(7, I.p[1].mreg));
}
AddImm32(Code, I.p[2].v);
break;
case x86_cmp_rm8_imm8:
if (I.p[1].mreg == r_eax)
Code.Add(0x3c);
else
{
AddRex(Code, Rex(0, null, I.p[1].mreg));
Code.Add(0x80);
Code.AddRange(ModRMSIB(7, I.p[1].mreg));
}
AddImm8(Code, I.p[2].v);
break;
case x86_cmp_rm32_imm8:
Code.Add(0x83);
Code.AddRange(ModRMSIB(7, I.p[1].mreg));
AddImm8(Code, I.p[2].v);
break;
case x86_lock_cmpxchg_rm8_r8:
Code.Add(0xf0); // lock before rex
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg, null, true, true));
Code.Add(0x0f);
Code.Add(0xb0);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_lock_cmpxchg_rm32_r32:
case x86_lock_cmpxchg_rm64_r64:
Code.Add(0xf0); // lock before rex
Code.AddRange(TLSOverride(ref tls_flag));
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x0f);
Code.Add(0xb1);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_lock_xadd_rm64_r64:
Code.Add(0xf0); // lock before rex
Code.AddRange(TLSOverride(ref tls_flag));
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x0f);
Code.Add(0xc1);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_lock_cmpxchg8b_m64:
Code.Add(0xf0);
Code.AddRange(TLSOverride(ref tls_flag));
Code.Add(0x0f);
Code.Add(0xc7);
Code.AddRange(ModRMSIB(1, I.p[1].mreg));
break;
case x86_lock_xchg_rm32ptr_r32:
case x86_lock_xchg_rm64ptr_r64:
Code.Add(0xf0);
Code.AddRange(TLSOverride(ref tls_flag));
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x87);
Code.AddRange(ModRMSIB(I.p[2].mreg, new ContentsReg { basereg = I.p[1].mreg }));
break;
case x86_pause:
Code.Add(0xf3);
Code.Add(0x90);
break;
case x86_set_rm32:
if (I.p[1].v != ir.Opcode.cc_never)
{
Code.Add(0x0f);
switch (I.p[1].v)
{
case ir.Opcode.cc_a:
Code.Add(0x97);
break;
case ir.Opcode.cc_ae:
Code.Add(0x93);
break;
case ir.Opcode.cc_b:
Code.Add(0x92);
break;
case ir.Opcode.cc_be:
Code.Add(0x96);
break;
case ir.Opcode.cc_eq:
Code.Add(0x94);
break;
case ir.Opcode.cc_ge:
Code.Add(0x9d);
break;
case ir.Opcode.cc_gt:
Code.Add(0x9f);
break;
case ir.Opcode.cc_le:
Code.Add(0x9e);
break;
case ir.Opcode.cc_lt:
Code.Add(0x9c);
break;
case ir.Opcode.cc_ne:
Code.Add(0x95);
break;
case ir.Opcode.cc_always:
throw new NotImplementedException();
}
Code.AddRange(ModRMSIB(2, I.p[2].mreg));
}
break;
case x86_movsxbd:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, null, true));
Code.Add(0x0f);
Code.Add(0xbe);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movsxwd:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0xbf);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movsxdq_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x63);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movzxbd:
case x86_movzxbq:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, null, true));
Code.Add(0x0f);
Code.Add(0xb6);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movzxwd:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0xb7);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movsxbd_r32_rm8disp:
case x86_movsxbq_r64_rm8disp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, null, true));
Code.Add(0x0f);
Code.Add(0xbe);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_movsxwd_r32_rm16disp:
case x86_movsxwq_r64_rm16disp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0xbf);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_movzxbd_r32_rm8disp:
case x86_movzxbq_r64_rm8disp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, null, true));
Code.Add(0x0f);
Code.Add(0xb6);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_movzxwd_r32_rm16disp:
case x86_movzxwq_r64_rm16disp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0xb7);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_jcc_rel32:
if (I.p[1].v != ir.Opcode.cc_never)
{
Code.Add(0x0f);
switch (I.p[1].v)
{
case ir.Opcode.cc_a:
Code.Add(0x87);
break;
case ir.Opcode.cc_ae:
Code.Add(0x83);
break;
case ir.Opcode.cc_b:
Code.Add(0x82);
break;
case ir.Opcode.cc_be:
Code.Add(0x86);
break;
case ir.Opcode.cc_eq:
Code.Add(0x84);
break;
case ir.Opcode.cc_ge:
Code.Add(0x8d);
break;
case ir.Opcode.cc_gt:
Code.Add(0x8f);
break;
case ir.Opcode.cc_le:
Code.Add(0x8e);
break;
case ir.Opcode.cc_lt:
Code.Add(0x8c);
break;
case ir.Opcode.cc_ne:
Code.Add(0x85);
break;
case ir.Opcode.cc_always:
throw new NotImplementedException();
}
rel_srcs.Add(Code.Count);
rel_dests.Add((int)I.p[2].v);
AddImm32(Code, 0);
}
break;
case x86_jmp_rel32:
Code.Add(0xe9);
if (I.p[1].t == ir.Opcode.vl_br_target)
{
rel_srcs.Add(Code.Count);
rel_dests.Add((int)I.p[1].v);
AddImm32(Code, 0);
}
else if (I.p[1].t == ir.Opcode.vl_str)
{
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
if (psize == 4)
reloc.Type = new binary_library.elf.ElfFile.Rel_386_PC32();
else
reloc.Type = new binary_library.elf.ElfFile.Rel_x86_64_pc32();
reloc.Addend = -4;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[1].str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Function;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
}
else
throw new NotSupportedException();
break;
case x86_ret:
Code.Add(0xc3);
break;
case Generic.g_loadaddress:
{
Code.Add(0xc7);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_386_32();
reloc.Addend = I.p[2].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[2].str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Function;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
}
break;
case x86_mov_rm32_lab:
{
Code.Add(0xc7);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_386_32();
reloc.Addend = I.p[2].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[2].str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Object;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
}
break;
case x86_mov_r32_lab:
{
Code.Add(0x8b);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), 5, 0, -1, 0, 0, false));
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_386_32();
reloc.Addend = I.p[2].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[2].str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Object;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
}
break;
case x86_mov_lab_r32:
{
Code.Add(0x89);
Code.AddRange(ModRMSIB(GetR(I.p[2].mreg), 5, 0, -1, 0, 0, false));
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
reloc.Type = new binary_library.elf.ElfFile.Rel_386_32();
reloc.Addend = I.p[1].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[1].str;
reloc.References.ObjectType = binary_library.SymbolObjectType.Object;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm32(Code, 0);
}
break;
case x86_idiv_rm32:
case x86_idiv_rm64:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xf7);
Code.AddRange(ModRMSIB(7, I.p[1].mreg));
break;
case x86_imul_r32_rm32_imm32:
Code.Add(0x69);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
AddImm32(Code, I.p[3].v);
break;
case x86_imul_r32_rm32:
case x86_imul_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0xaf);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_mov_r32_rm32sib:
Code.Add(0x8b);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[3].mreg), 0, GetR(I.p[2].mreg)));
break;
case x86_mov_r32_rm32disp:
case x86_mov_r64_rm64disp:
Code.AddRange(TLSOverride(ref tls_flag));
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x8b);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v, I.p[2].mreg.Equals(x86_64.x86_64_Assembler.r_r13)));
break;
case x86_mov_r32_rm16disp:
Code.Add(0x66);
Code.Add(0x8b);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_mov_r32_rm8disp:
Code.Add(0x8a);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_mov_rm32disp_imm32:
case x86_mov_rm64disp_imm32:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xc7);
Code.AddRange(ModRMSIB(0, GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
AddImm32(Code, I.p[3].v);
break;
case x86_mov_rm16disp_imm32:
Code.Add(0x66);
Code.Add(0xc7);
Code.AddRange(ModRMSIB(0, GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
AddImm16(Code, I.p[3].v);
break;
case x86_mov_rm8disp_imm32:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg, null, true));
Code.Add(0xc6);
Code.AddRange(ModRMSIB(0, GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
AddImm8(Code, I.p[3].v);
break;
case x86_mov_rm8disp_r8:
AddRex(Code, Rex(I.p[0].v, I.p[3].mreg, I.p[1].mreg, null, true, true));
Code.Add(0x88);
Code.AddRange(ModRMSIB(GetR(I.p[3].mreg), GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
break;
case x86_mov_rm16disp_r16:
Code.Add(0x66);
AddRex(Code, Rex(I.p[0].v, I.p[3].mreg, I.p[1].mreg));
Code.Add(0x89);
Code.AddRange(ModRMSIB(GetR(I.p[3].mreg), GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
break;
case x86_mov_rm32disp_r32:
case x86_mov_rm64disp_r64:
Code.AddRange(TLSOverride(ref tls_flag));
AddRex(Code, Rex(I.p[0].v, I.p[3].mreg, I.p[1].mreg));
Code.Add(0x89);
Code.AddRange(ModRMSIB(GetR(I.p[3].mreg), GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
break;
case x86_mov_r32_rm32sibscaledisp:
case x86_mov_r64_rm64sibscaledisp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, I.p[3].mreg));
Code.Add(0x8b);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, GetRM(I.p[3].mreg), -1, (int)I.p[5].v, false, (int)I.p[4].v));
break;
case x86_movzxbd_r32_rm8sibscaledisp:
case x86_movzxbq_r64_rm8sibscaledisp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, I.p[3].mreg, true));
Code.Add(0x0f);
Code.Add(0xb6);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, GetRM(I.p[3].mreg), -1, (int)I.p[5].v, false, (int)I.p[4].v));
break;
case x86_movzxwd_r32_rm16sibscaledisp:
case x86_movzxwq_r64_rm16sibscaledisp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, I.p[3].mreg));
Code.Add(0x0f);
Code.Add(0xb7);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, GetRM(I.p[3].mreg), -1, (int)I.p[5].v, false, (int)I.p[4].v));
break;
case x86_movsxbd_r32_rm8sibscaledisp:
case x86_movsxbq_r64_rm8sibscaledisp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, I.p[3].mreg, true));
Code.Add(0x0f);
Code.Add(0xbe);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, GetRM(I.p[3].mreg), -1, (int)I.p[5].v, false, (int)I.p[4].v));
break;
case x86_movsxwd_r32_rm16sibscaledisp:
case x86_movsxwq_r64_rm16sibscaledisp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, I.p[3].mreg));
Code.Add(0x0f);
Code.Add(0xbf);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, GetRM(I.p[3].mreg), -1, (int)I.p[5].v, false, (int)I.p[4].v));
break;
case x86_movsxdq_r64_rm32sibscaledisp:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg, I.p[3].mreg));
Code.Add(0x63);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, GetRM(I.p[3].mreg), -1, (int)I.p[5].v, false, (int)I.p[4].v));
break;
case x86_neg_rm32:
case x86_neg_rm64:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xf7);
Code.AddRange(ModRMSIB(3, I.p[1].mreg));
break;
case x86_not_rm32:
case x86_not_rm64:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xf7);
Code.AddRange(ModRMSIB(2, I.p[1].mreg));
break;
case x86_lea_r32:
case x86_lea_r64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x8d);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_sar_rm32_imm8:
Code.Add(0xc1);
Code.AddRange(ModRMSIB(7, I.p[1].mreg));
AddImm8(Code, I.p[2].v);
break;
case x86_and_rm32_imm8:
case x86_and_rm64_imm8:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0x83);
Code.AddRange(ModRMSIB(4, I.p[1].mreg));
AddImm8(Code, I.p[2].v);
if (I.p.Length == 4)
throw new Exception();
break;
case x86_and_rm32_imm32:
Code.Add(0x81);
Code.AddRange(ModRMSIB(4, I.p[1].mreg));
AddImm8(Code, I.p[2].v);
if (I.p.Length == 4)
throw new Exception();
break;
case x86_sal_rm32_cl:
case x86_sal_rm64_cl:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xd3);
Code.AddRange(ModRMSIB(4, I.p[1].mreg));
break;
case x86_sar_rm32_cl:
case x86_sar_rm64_cl:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xd3);
Code.AddRange(ModRMSIB(7, I.p[1].mreg));
break;
case x86_shr_rm32_cl:
case x86_shr_rm64_cl:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(0xd3);
Code.AddRange(ModRMSIB(5, I.p[1].mreg));
break;
case x86_xchg_r32_rm32:
case x86_xchg_r64_rm64:
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x87);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_xchg_rm32_r32:
Code.Add(0x87);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_mov_r64_imm64:
AddRex(Code, Rex(I.p[0].v, null, I.p[1].mreg));
Code.Add(PlusRD(0xb8, I.p[1].mreg));
switch (I.p[2].t)
{
case ir.Opcode.vl_c:
case ir.Opcode.vl_c32:
case ir.Opcode.vl_c64:
AddImm64(Code, I.p[2].v);
break;
case ir.Opcode.vl_str:
var reloc = c.s.bf.CreateRelocation();
reloc.DefinedIn = c.s.text_section;
if (I.p[2].v2 == 1)
{
throw new NotImplementedException("TLS label with mcmodel large");
}
reloc.Type = new binary_library.elf.ElfFile.Rel_x86_64_64();
reloc.Addend = I.p[2].v;
reloc.References = c.s.bf.CreateSymbol();
reloc.References.Name = I.p[2].str;
reloc.Offset = (ulong)Code.Count;
c.s.bf.AddRelocation(reloc);
AddImm64(Code, 0);
break;
default:
throw new NotSupportedException();
}
break;
case x86_nop:
Code.Add(0x90);
break;
case x86_out_dx_al:
Code.Add(0xee);
break;
case x86_out_dx_ax:
Code.Add(0x66);
Code.Add(0xef);
break;
case x86_out_dx_eax:
Code.Add(0xef);
break;
case x86_in_al_dx:
Code.Add(0xec);
break;
case x86_in_ax_dx:
Code.Add(0x66);
Code.Add(0xed);
break;
case x86_in_eax_dx:
Code.Add(0xed);
break;
case x86_int3:
Code.Add(0xcc);
break;
case x86_xorpd_xmm_xmmm128:
Code.Add(0x66);
Code.Add(0x0f);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x57);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movsd_xmmm64_xmm:
Code.Add(0xf2);
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x0f);
Code.Add(0x11);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_movsd_xmmm64disp_xmm:
Code.Add(0xf2);
AddRex(Code, Rex(I.p[0].v, I.p[3].mreg, I.p[1].mreg));
Code.Add(0x0f);
Code.Add(0x11);
Code.AddRange(ModRMSIB(GetR(I.p[3].mreg), GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
break;
case x86_movsd_xmm_xmmm64:
Code.Add(0xf2);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0x10);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_movsd_xmm_xmmm64disp:
Code.Add(0xf2);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0x10);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_movss_xmmm32_xmm:
Code.Add(0xf3);
AddRex(Code, Rex(I.p[0].v, I.p[2].mreg, I.p[1].mreg));
Code.Add(0x0f);
Code.Add(0x11);
Code.AddRange(ModRMSIB(I.p[2].mreg, I.p[1].mreg));
break;
case x86_movss_xmmm32disp_xmm:
Code.Add(0xf3);
AddRex(Code, Rex(I.p[0].v, I.p[3].mreg, I.p[1].mreg));
Code.Add(0x0f);
Code.Add(0x11);
Code.AddRange(ModRMSIB(GetR(I.p[3].mreg), GetRM(I.p[1].mreg), 2, -1, -1, (int)I.p[2].v));
break;
case x86_movss_xmm_xmmm32:
Code.Add(0xf3);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0x10);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cvtsd2si_r32_xmmm64:
case x86_cvtsd2si_r64_xmmm64:
Code.Add(0xf2);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0x2d);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cvtsi2sd_xmm_rm32:
case x86_cvtsi2sd_xmm_rm64:
Code.Add(0xf2);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0x2a);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cvtsd2ss_xmm_xmmm64:
Code.Add(0xf2);
Code.Add(0x0f);
Code.Add(0x5a);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cvtss2sd_xmm_xmmm32:
Code.Add(0xf3);
Code.Add(0x0f);
Code.Add(0x5a);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cvtss2sd_xmm_xmmm32disp:
Code.Add(0xf3);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x0f);
Code.Add(0x5a);
Code.AddRange(ModRMSIB(GetR(I.p[1].mreg), GetRM(I.p[2].mreg), 2, -1, -1, (int)I.p[3].v));
break;
case x86_addsd_xmm_xmmm64:
Code.Add(0xf2);
Code.Add(0x0f);
Code.Add(0x58);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_subsd_xmm_xmmm64:
Code.Add(0xf2);
Code.Add(0x0f);
Code.Add(0x5c);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_mulsd_xmm_xmmm64:
Code.Add(0xf2);
Code.Add(0x0f);
Code.Add(0x59);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_divsd_xmm_xmmm64:
Code.Add(0xf2);
Code.Add(0x0f);
Code.Add(0x5e);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_comisd_xmm_xmmm64:
Code.Add(0x66);
Code.Add(0x0f);
Code.Add(0x2f);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_ucomisd_xmm_xmmm64:
Code.Add(0x66);
Code.Add(0x0f);
Code.Add(0x2e);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
break;
case x86_cmpsd_xmm_xmmm64_imm8:
Code.Add(0xf2);
Code.Add(0x0f);
Code.Add(0xc2);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
AddImm8(Code, I.p[3].v);
break;
case x86_roundsd_xmm_xmmm64_imm8:
Code.Add(0x66);
Code.Add(0x0f);
AddRex(Code, Rex(I.p[0].v, I.p[1].mreg, I.p[2].mreg));
Code.Add(0x3a);
Code.Add(0x0b);
Code.AddRange(ModRMSIB(I.p[1].mreg, I.p[2].mreg));
AddImm8(Code, I.p[3].v);
break;
case x86_iret:
case x86_iretq:
AddRex(Code, Rex(I.p[0].v, null, null));
Code.Add(0xcf);
break;
case x86_pushf:
Code.Add(0x9c);
break;
case x86_popf:
case x86_popfq:
AddRex(Code, Rex(I.p[0].v, null, null));
Code.Add(0x9d);
break;
case x86_cli:
Code.Add(0xfa);
break;
case x86_fstp_m64:
Code.Add(0xdd);
Code.AddRange(ModRMSIB(3, I.p[1].mreg));
break;
case x86_fld_m64:
Code.Add(0xdd);
Code.AddRange(ModRMSIB(0, I.p[1].mreg));
break;
default:
throw new NotImplementedException(insts[(int)I.p[0].v]);
}
if (tls_flag == 1)
throw new NotImplementedException("TLS not supported for " + insts[(int)I.p[0].v]);
I.end_addr = Code.Count;
}
// Handle cil instructions which encode to nothing (e.g. nop) but may still be branch targets - point them to the next instruction
int cur_il_start = -1;
for (int i = 0; i < max_il; i++)
{
if (il_starts[i] == -1)
il_starts[i] = cur_il_start;
else
cur_il_start = il_starts[i];
}
// Patch up references
for (int i = 0; i < rel_srcs.Count; i++)
{
var src = rel_srcs[i];
var dest = rel_dests[i];
var dest_offset = il_starts[dest] + code_start;
var offset = dest_offset - src - 4;
InsertImm32(Code, offset, src);
}
}
private IEnumerable<byte> TLSOverride(ref int tls_flag)
{
if (tls_flag == 0)
return new byte[0];
if(psize == 8)
{
// use %fs for TLS
tls_flag = 0;
return new byte[] { 0x64 };
}
else
{
// use %gs for TLS
tls_flag = 0;
return new byte[] { 0x65 };
}
throw new NotImplementedException();
}
private void AddRex(List<byte> code, byte v)
{
if (v != 0)
code.Add(v);
}
private byte Rex(long oc, Reg r, Reg rm_ocreg, Reg sib_index = null, bool is_rm8 = false, bool is_r8 = false)
{
int rex = 0;
if (oc >= x86_mov_r64_imm64)
rex |= 0x8;
if (r != null && r.id >= x86_64.x86_64_Assembler.r_r8.id)
rex |= 0x4;
if (rm_ocreg != null && rm_ocreg.id >= x86_64.x86_64_Assembler.r_r8.id)
rex |= 0x1;
if ((rm_ocreg is ContentsReg) && (((ContentsReg)rm_ocreg).basereg.id >= x86_64.x86_64_Assembler.r_r8.id))
rex |= 0x1;
if(sib_index != null && sib_index.id >= x86_64.x86_64_Assembler.r_r8.id)
rex |= 0x2;
if (is_rm8 && rm_ocreg != null && !(rm_ocreg is ContentsReg))
{
if (rm_ocreg.Equals(r_esp) ||
rm_ocreg.Equals(r_ebp) ||
rm_ocreg.Equals(r_edi) ||
rm_ocreg.Equals(r_esi))
{
rex |= 0x40;
}
}
if (is_r8 && r != null && !(r is ContentsReg))
{
if (r.Equals(r_esp) ||
r.Equals(r_ebp) ||
r.Equals(r_edi) ||
r.Equals(r_esi))
{
rex |= 0x40;
}
}
if (rex != 0)
{
if (psize == 4)
throw new Exception("Cannot encode rex prefix in ia32 mode");
return (byte)(0x40 | rex);
}
return 0;
}
private void InsertImm32(List<byte> c, int v, int offset)
{
c[offset] = (byte)(v & 0xff);
c[offset + 1] = (byte)((v >> 8) & 0xff);
c[offset + 2] = (byte)((v >> 16) & 0xff);
c[offset + 3] = (byte)((v >> 24) & 0xff);
}
private void AddImm64(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
c.Add((byte)((v >> 8) & 0xff));
c.Add((byte)((v >> 16) & 0xff));
c.Add((byte)((v >> 24) & 0xff));
c.Add((byte)((v >> 32) & 0xff));
c.Add((byte)((v >> 40) & 0xff));
c.Add((byte)((v >> 48) & 0xff));
c.Add((byte)((v >> 56) & 0xff));
}
private void AddImm32(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
c.Add((byte)((v >> 8) & 0xff));
c.Add((byte)((v >> 16) & 0xff));
c.Add((byte)((v >> 24) & 0xff));
}
private void AddImm16(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
c.Add((byte)((v >> 8) & 0xff));
}
private void AddImm8(List<byte> c, long v)
{
c.Add((byte)(v & 0xff));
}
private IEnumerable<byte> ModRMSIB(Reg r, Reg rm, bool is_rm8 = false)
{
int r_val = GetR(r);
int rm_val, mod_val, disp_len, disp_val;
bool rm_is_ebp;
GetModRM(rm, out rm_val, out mod_val, out disp_len, out disp_val, out rm_is_ebp);
return ModRMSIB(r_val, rm_val, mod_val, -1, disp_len, disp_val, rm_is_ebp);
}
private IEnumerable<byte> ModRMSIB(int r, Target.Reg rm, bool is_rm8 = false)
{
int rm_val, mod_val, disp_len, disp_val;
bool rm_is_ebp;
GetModRM(rm, out rm_val, out mod_val, out disp_len, out disp_val, out rm_is_ebp);
return ModRMSIB(r, rm_val, mod_val, -1, disp_len, disp_val, rm_is_ebp);
}
/* private IEnumerable<byte> ModRM(Reg r, Reg rm)
{
int r_val = GetR(r);
int rm_val, mod_val, disp_len, disp_val;
GetModRM(rm, out rm_val, out mod_val, out disp_len, out disp_val);
return ModRM(r_val, rm_val, mod_val, disp_len, disp_val);
} */
private int GetR(Reg r)
{
if (r.Equals(r_eax))
return 0;
else if (r.Equals(r_ecx))
return 1;
else if (r.Equals(r_edx))
return 2;
else if (r.Equals(r_ebx))
return 3;
else if (r.Equals(r_esp))
return 4;
else if (r.Equals(r_ebp))
return 5;
else if (r.Equals(r_esi))
return 6;
else if (r.Equals(r_edi))
return 7;
else if (r.Equals(r_xmm0))
return 0;
else if (r.Equals(r_xmm1))
return 1;
else if (r.Equals(r_xmm2))
return 2;
else if (r.Equals(r_xmm3))
return 3;
else if (r.Equals(r_xmm4))
return 4;
else if (r.Equals(r_xmm5))
return 5;
else if (r.Equals(r_xmm6))
return 6;
else if (r.Equals(r_xmm7))
return 7;
else if (r.Equals(x86_64.x86_64_Assembler.r_r8))
return 0;
else if (r.Equals(x86_64.x86_64_Assembler.r_r9))
return 1;
else if (r.Equals(x86_64.x86_64_Assembler.r_r10))
return 2;
else if (r.Equals(x86_64.x86_64_Assembler.r_r11))
return 3;
else if (r.Equals(x86_64.x86_64_Assembler.r_r12))
return 4;
else if (r.Equals(x86_64.x86_64_Assembler.r_r13))
return 5;
else if (r.Equals(x86_64.x86_64_Assembler.r_r14))
return 6;
else if (r.Equals(x86_64.x86_64_Assembler.r_r15))
return 7;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm8))
return 0;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm9))
return 1;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm10))
return 2;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm11))
return 3;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm12))
return 4;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm13))
return 5;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm14))
return 6;
else if (r.Equals(x86_64.x86_64_Assembler.r_xmm15))
return 7;
throw new NotSupportedException();
}
private byte PlusRD(int v, Reg mreg)
{
if (mreg.Equals(r_eax))
return (byte)(v + 0);
else if (mreg.Equals(r_ecx))
return (byte)(v + 1);
else if (mreg.Equals(r_edx))
return (byte)(v + 2);
else if (mreg.Equals(r_ebx))
return (byte)(v + 3);
else if (mreg.Equals(r_esp))
return (byte)(v + 4);
else if (mreg.Equals(r_ebp))
return (byte)(v + 5);
else if (mreg.Equals(r_esi))
return (byte)(v + 6);
else if (mreg.Equals(r_edi))
return (byte)(v + 7);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r8))
return (byte)(v + 0);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r9))
return (byte)(v + 1);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r10))
return (byte)(v + 2);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r11))
return (byte)(v + 3);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r12))
return (byte)(v + 4);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r13))
return (byte)(v + 5);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r14))
return (byte)(v + 6);
else if (mreg.Equals(x86_64.x86_64_Assembler.r_r15))
return (byte)(v + 7);
throw new NotSupportedException();
}
/* private IEnumerable<byte> ModRM(int r, Target.Reg rm)
{
int rm_val, mod_val, disp_len, disp_val;
GetModRM(rm, out rm_val, out mod_val, out disp_len, out disp_val);
return ModRM(r, rm_val, mod_val, disp_len, disp_val);
} */
private void GetModRM(Reg rm, out int rm_val, out int mod_val, out int disp_len, out int disp_val, out bool rm_is_ebp)
{
if (rm is Target.ContentsReg)
{
var cr = rm as Target.ContentsReg;
if (cr.disp == 0 && !cr.basereg.Equals(r_ebp))
{
mod_val = 0;
disp_len = 0;
}
else if (cr.disp >= -128 && cr.disp < 127)
{
mod_val = 1;
disp_len = 1;
}
else
{
mod_val = 2;
disp_len = 4;
}
disp_val = (int)cr.disp;
rm_val = GetRM(cr.basereg);
rm_is_ebp = cr.basereg.Equals(r_ebp) || cr.basereg.Equals(x86_64.x86_64_Assembler.r_r13);
}
else
{
mod_val = 3;
disp_len = 0;
disp_val = 0;
rm_val = GetRM(rm);
rm_is_ebp = false;
}
}
private int GetMod(Target.Reg rm)
{
if(rm is Target.ContentsReg)
{
var cr = rm as Target.ContentsReg;
if (cr.disp == 0)
return 0;
else if (cr.disp >= -128 && cr.disp < 127)
return 1;
else
return 2;
}
return 3;
}
private int GetRM(Target.Reg rm)
{
if(rm is Target.ContentsReg)
{
var cr = rm as Target.ContentsReg;
rm = cr.basereg;
}
if (rm.Equals(r_eax))
return 0;
else if (rm.Equals(r_ecx))
return 1;
else if (rm.Equals(r_edx))
return 2;
else if (rm.Equals(r_ebx))
return 3;
else if (rm.Equals(r_esp))
return 4;
else if (rm.Equals(r_ebp))
return 5;
else if (rm.Equals(r_esi))
return 6;
else if (rm.Equals(r_edi))
return 7;
else if (rm.Equals(r_xmm0))
return 0;
else if (rm.Equals(r_xmm1))
return 1;
else if (rm.Equals(r_xmm2))
return 2;
else if (rm.Equals(r_xmm3))
return 3;
else if (rm.Equals(r_xmm4))
return 4;
else if (rm.Equals(r_xmm5))
return 5;
else if (rm.Equals(r_xmm6))
return 6;
else if (rm.Equals(r_xmm7))
return 7;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r8))
return 0;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r9))
return 1;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r10))
return 2;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r11))
return 3;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r12))
return 4;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r13))
return 5;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r14))
return 6;
else if (rm.Equals(x86_64.x86_64_Assembler.r_r15))
return 7;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm8))
return 0;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm9))
return 1;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm10))
return 2;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm11))
return 3;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm12))
return 4;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm13))
return 5;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm14))
return 6;
else if (rm.Equals(x86_64.x86_64_Assembler.r_xmm15))
return 7;
if(rm.type == rt_stack)
{
var rm_reg = new ContentsReg
{
basereg = r_esp,
disp = rm.stack_loc,
size = rm.size
};
return GetRM(rm_reg);
}
throw new NotSupportedException();
}
/* private IEnumerable<byte> ModRM(int r, int rm, int mod, int disp_len = 0, int disp = 0)
{
yield return (byte)(mod << 6 | r << 3 | rm);
for (int i = 0; i < disp_len; i++)
yield return (byte)(disp >> (8 * i));
} */
private IEnumerable<byte> ModRMSIB(int r, int rm, int mod,
int index = -1, int disp_len = 0,
int disp = 0, bool rm_is_ebp = true, int scale = -1)
{
/* catch the case where we're trying to do something to esp
or ebp without an sib byte */
int _base = -1;
int ss = -1;
bool has_sib = false;
if (index >= 0)
{
_base = rm;
has_sib = true;
rm = 4;
if (mod == 3)
throw new NotSupportedException("SIB addressing with mod == 3");
if (scale == -1)
scale = 1;
}
else if (rm == 4 && mod != 3)
{
_base = 4;
index = 4;
has_sib = true;
}
else if(rm == 5 && mod == 0 && rm_is_ebp)
{
_base = 5;
index = 4;
ss = 0;
if (disp_len == 0)
{
disp = 0;
disp_len = 1;
}
has_sib = true;
}
if(disp_len == -1 && mod == 2)
{
if (disp == 0 && !rm_is_ebp)
{
mod = 0;
disp_len = 0;
}
else if (disp >= sbyte.MinValue && disp <= sbyte.MaxValue)
disp_len = 1;
else
disp_len = 4;
}
if (disp_len == 1)
mod = 1;
else if (disp_len == 4)
mod = 2;
if(rm == 5 && mod == 0)
{
//
}
yield return (byte)(mod << 6 | r << 3 | rm);
if(has_sib)
{
if(ss == -1)
{
switch(scale)
{
case -1:
case 1:
ss = 0;
break;
case 2:
ss = 1;
break;
case 4:
ss = 2;
break;
case 8:
ss = 3;
break;
default:
throw new NotSupportedException("Invalid SIB scale: " + scale.ToString());
}
}
yield return (byte)(ss << 6 | index << 3 | _base);
}
for (int i = 0; i < disp_len; i++)
yield return (byte)(disp >> (8 * i));
}
}
}
<file_sep>/* Copyright (C) 2011 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* This defines the TysosMethod which is a subtype of System.Reflection.MethodInfo
*
* All MethodInfo structures produced by tysila2 follow this layout
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;
namespace libsupcs
{
[ExtendsOverride("_ZW19System#2EReflection17RuntimeMethodInfo")]
[VTableAlias("__tysos_method_vt")]
public unsafe class TysosMethod : System.Reflection.MethodInfo
{
public TysosType OwningType;
public TysosType _ReturnType;
public bool returns_void;
[NullTerminatedListOf(typeof(TysosType))]
public TysosType[] _ParamTypes;
public TysosParameterInfo[] _Params;
public string _Name;
public string _MangledName;
public IntPtr Signature;
public IntPtr Sig_references;
public Int32 Flags;
public Int32 ImplFlags;
public UInt32 TysosFlags;
public void* MethodAddress;
[NullTerminatedListOf(typeof(EHClause))]
public IntPtr EHClauses;
public IntPtr Instructions;
public const string PureVirtualName = "__cxa_pure_virtual";
public metadata.MethodSpec mspec;
public TysosMethod(metadata.MethodSpec ms, TysosType owning_type)
{
mspec = ms;
OwningType = owning_type;
}
public const UInt32 TF_X86_ISR = 0x10000001;
public const UInt32 TF_X86_ISREC = 0x10000002;
public const UInt32 TF_CC_STANDARD = 1;
public const UInt32 TF_CC_VARARGS = 2;
public const UInt32 TF_CC_HASTHIS = 32;
public const UInt32 TF_CC_EXPLICITTHIS = 64;
public const UInt32 TF_CC_MASK = 0x7f;
[VTableAlias("__tysos_ehclause_vt")]
public class EHClause
{
public IntPtr TryStart;
public IntPtr TryEnd;
public IntPtr Handler;
public TysosType CatchObject;
public Int32 Flags;
public bool IsFinally { get { if ((Flags & 0x2) == 0x2) return true; return false; } }
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)]
[MethodReferenceAlias("__invoke")]
static extern void* InternalInvoke(void* maddr, int pcnt, void** parameters, void** types, void* ret_vtbl, uint flags);
internal const uint invoke_flag_instance = 1U;
internal const uint invoke_flag_vt = 2U;
internal const uint invoke_flag_vt_ret = 4U;
public override System.Reflection.CallingConventions CallingConvention
{
get
{
return (System.Reflection.CallingConventions)(int)(TysosFlags & TF_CC_MASK);
}
}
public override System.Reflection.MethodInfo GetBaseDefinition()
{
throw new NotImplementedException();
}
public override System.Reflection.ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { throw new NotImplementedException(); }
}
public override System.Reflection.MethodAttributes Attributes
{
get
{
return (System.Reflection.MethodAttributes)mspec.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef, mspec.mdrow, 2);
}
}
public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags()
{
return (System.Reflection.MethodImplAttributes)mspec.m.GetIntEntry(metadata.MetadataStream.tid_MethodDef, mspec.mdrow, 1);
}
public unsafe override System.Reflection.ParameterInfo[] GetParameters()
{
if (_Params == null)
{
var pc = mspec.m.GetMethodDefSigParamCount(mspec.msig);
var rt_idx = mspec.m.GetMethodDefSigRetTypeIndex(mspec.msig);
mspec.m.GetTypeSpec(ref rt_idx, mspec.gtparams, mspec.gmparams);
var _params = new TysosParameterInfo[pc];
var _ptypes = new TysosType[pc];
for (int i = 0; i < pc; i++)
{
var tspec = mspec.m.GetTypeSpec(ref rt_idx, mspec.gtparams, mspec.gmparams);
TysosType tt = tspec;
_ptypes[i] = tt;
TysosParameterInfo tpi = new TysosParameterInfo(tt, i, this);
_params[i] = tpi;
}
if (System.Threading.Interlocked.CompareExchange(ref _Params, _params, null) == null)
{
_ParamTypes = _ptypes;
}
}
return _Params;
}
public override Type ReturnType
{
get
{
if (_ReturnType == null && !returns_void)
{
var rtspec = mspec.ReturnType;
TysosType _rt;
if (rtspec == null)
{
_rt = null;
returns_void = true;
}
else
_rt = rtspec;
System.Threading.Interlocked.CompareExchange(ref _ReturnType, _rt, null);
}
return _ReturnType;
}
}
public override object Invoke(object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture)
{
uint flags = 0;
if (MethodAddress == null)
{
var mangled_name = mspec.MangleMethod();
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosMethod.Invoke: requesting run-time address for " + mangled_name);
MethodAddress = JitOperations.GetAddressOfObject(mspec.MangleMethod());
if (MethodAddress == null)
{
System.Diagnostics.Debugger.Log(0, "libsupcs", "TysosMethod.Invoke: jit compiling method");
MethodAddress = JitOperations.JitCompile(this.mspec);
}
}
if (MethodAddress == null)
throw new System.Reflection.TargetException("Method does not have a defined implementation (" + OwningType.FullName + "." + Name + "())");
if (!IsStatic && (obj == null))
throw new System.Reflection.TargetException("Instance method and obj is null (" + OwningType.FullName + "." + Name + "())");
// TODO: check number and type of parameters is what the method expects
// Get total number of parameters
int p_length = 0;
if (parameters != null)
p_length = parameters.Length;
if (!IsStatic)
p_length++;
// See InternalStrCpy for the rationale here
int max_stack_alloc = p_length > 512 ? 512 : p_length;
IntPtr* pstack = stackalloc IntPtr[max_stack_alloc];
IntPtr* tstack = stackalloc IntPtr[max_stack_alloc];
void** ps, ts;
if (max_stack_alloc <= 512)
{
ps = (void**)pstack;
ts = (void**)tstack;
}
else
{
ps = (void**)MemoryOperations.GcMalloc(p_length * sizeof(void*));
ts = (void**)MemoryOperations.GcMalloc(p_length * sizeof(void*));
}
// Build a new params array to include obj if necessary, and a tysos type array
int curptr = 0;
if (!IsStatic)
{
ps[0] = CastOperations.ReinterpretAsPointer(obj);
ts[0] = OtherOperations.GetStaticObjectAddress("_Zu1O");
curptr++;
}
if (parameters != null)
{
for (int i = 0; i < parameters.Length; i++, curptr++)
{
var cp = CastOperations.ReinterpretAsPointer(parameters[i]);
ps[curptr] = cp;
ts[curptr] = *(void**)cp;
}
}
if (!IsStatic)
flags |= invoke_flag_instance;
if (OwningType.IsValueType)
flags |= invoke_flag_vt;
if (ReturnType != null && ReturnType.IsValueType)
flags |= invoke_flag_vt_ret;
return CastOperations.ReinterpretAsObject(InternalInvoke(MethodAddress, p_length, ps, ts,
(ReturnType != null) ? TysosType.ReinterpretAsType(ReturnType)._impl : null, flags));
}
/** <summary>Override this in you application to pass Invokes across thread boundaries</summary> */
[AlwaysCompile]
[WeakLinkage]
[MethodAlias("invoke")]
public static void* Invoke(void* mptr, object[] args, void* rtype, uint flags)
{
return InternalInvoke(mptr, args, rtype, flags);
}
public static void* InternalInvoke(void* mptr, object[] args, void* rtype, uint flags)
{
int p_length = (args == null) ? 0 : args.Length;
// See InternalStrCpy for the rationale here
int max_stack_alloc = p_length > 512 ? 512 : p_length;
IntPtr* pstack = stackalloc IntPtr[max_stack_alloc];
IntPtr* tstack = stackalloc IntPtr[max_stack_alloc];
void** ps, ts;
if (max_stack_alloc <= 512)
{
ps = (void**)pstack;
ts = (void**)tstack;
}
else
{
ps = (void**)MemoryOperations.GcMalloc(p_length * sizeof(void*));
ts = (void**)MemoryOperations.GcMalloc(p_length * sizeof(void*));
}
// Build a new params array and a tysos type array
if (args != null)
{
for (int i = 0; i < args.Length; i++)
{
var cp = CastOperations.ReinterpretAsPointer(args[i]);
ps[i] = cp;
ts[i] = *(void**)cp;
}
}
return InternalInvoke(mptr, args.Length, ps, ts, rtype, flags);
}
public override RuntimeMethodHandle MethodHandle
{
get { throw new NotImplementedException(); }
}
public override Type DeclaringType
{
get { return OwningType; }
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override string Name
{
get
{
if(_Name == null)
{
string name = mspec.m.GetStringEntry(metadata.MetadataStream.tid_MethodDef, mspec.mdrow, 3);
System.Threading.Interlocked.CompareExchange(ref _Name, name, null);
}
return _Name;
}
}
public override Type ReflectedType
{
get { throw new NotImplementedException(); }
}
}
public class TysosParameterInfo : System.Reflection.ParameterInfo
{
internal TysosParameterInfo(Type param_type, int param_no, TysosMethod decl_method)
{
/* This is a basic implementation: tysila does not currently provide either the
* parameter name or its attributes in the _Params list */
this.ClassImpl = param_type;
this.PositionImpl = param_no;
this.NameImpl = param_no.ToString();
this.MemberImpl = decl_method;
this.DefaultValueImpl = null;
this.AttrsImpl = System.Reflection.ParameterAttributes.None;
}
}
}
<file_sep>/* Copyright (C) 2014-2016 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace libsupcs
{
/* The following class is taken from Mono. mono/corlib/System.Collections.Generic/EqualityComparer.cs
* Authors: <NAME> (<EMAIL>), Copyright (C) 2004 Novell, Inc under the same license as this file
*
* We need to use our own version of this as EqualityComparer<T> has a static constructor which instantiates
* a generic type, and if the jit is not functioning this cannot yet be done */
public class GenericEqualityComparer<T> : EqualityComparer<T> where T : System.IEquatable<T>
{
public override int GetHashCode(T obj)
{
return obj.GetHashCode();
}
public override bool Equals(T x, T y)
{
if (x == null)
return y == null;
return x.Equals(y);
}
}
public class GenericEqualityComparerRef<T> : EqualityComparer<T> where T : class
{
public override int GetHashCode(T obj)
{
return obj.GetHashCode();
}
public override bool Equals(T x, T y)
{
if (x == null)
return y == null;
return x.Equals(y);
}
}
public class GenericComparer<T> : IComparer<T> where T : System.IComparable<T>
{
public int Compare(T x, T y)
{
return x.CompareTo(y);
}
}
public class IntPtrComparer : IComparer<IntPtr>
{
[MethodReferenceAlias("intptr_compare")]
[MethodImpl(MethodImplOptions.InternalCall)]
extern public int Compare(IntPtr x, IntPtr y);
[MethodAlias("intptr_compare")]
[AlwaysCompile]
[Bits32Only]
int Compare32(int x, int y)
{
if (x > y)
return 1;
if (x == y)
return 0;
return -1;
}
[MethodAlias("intptr_compare")]
[AlwaysCompile]
[Bits64Only]
int Compare64(long x, long y)
{
if (x > y)
return 1;
if (x == y)
return 0;
return -1;
}
}
public class UIntPtrComparer : IComparer<UIntPtr>
{
[MethodReferenceAlias("uintptr_compare")]
[MethodImpl(MethodImplOptions.InternalCall)]
extern public int Compare(UIntPtr x, UIntPtr y);
[MethodAlias("uintptr_compare")]
[AlwaysCompile]
[Bits32Only]
int Compare32(uint x, uint y)
{
if (x > y)
return 1;
if (x == y)
return 0;
return -1;
}
[MethodAlias("uintptr_compare")]
[AlwaysCompile]
[Bits64Only]
int Compare64(ulong x, ulong y)
{
if (x > y)
return 1;
if (x == y)
return 0;
return -1;
}
}
}
<file_sep>
using System;
namespace ConsoleUtils.ConsoleActions
{
public class CycleUpAction : IConsoleAction
{
public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo)
{
if (!console.PreviousLineBuffer.CycleUp())
return;
console.CurrentLine = console.PreviousLineBuffer.LineAtIndex;
console.CursorPosition = console.CurrentLine.Length;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace libsupcs
{
unsafe struct HandleOnStack
{
public void** ptr;
}
}
<file_sep>namespace AutoCompleteUtils
{
public enum CyclingDirections
{
Forward,
Backward
}
}<file_sep>/* Copyright (C) 2018 by <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/* Managed implementation of number formatting for coreclr */
using System;
using System.Globalization;
namespace libsupcs
{
unsafe class NumberFormat
{
static string uppercaseDigits = "0123456789ABCDEF";
static string lowercaseDigits = "0123456789abcdef";
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_ZW6System6Number_12FormatUInt32_Ru1S_P3ju1SU22System#2EGlobalization16NumberFormatInfo")]
static string FormatUInt32(uint v, string fmt, NumberFormatInfo nfi)
{
byte* v2 = stackalloc byte[8];
*(ulong*)v2 = v;
return FormatInteger(v2, false, 4, fmt, nfi);
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_ZW6System6Number_11FormatInt32_Ru1S_P3iu1SU22System#2EGlobalization16NumberFormatInfo")]
static string FormatInt32(int v, string fmt, NumberFormatInfo nfi)
{
byte* v2 = stackalloc byte[8];
*(long*)v2 = v;
return FormatInteger(v2, true, 4, fmt, nfi);
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_ZW6System6Number_12FormatUInt64_Ru1S_P3yu1SU22System#2EGlobalization16NumberFormatInfo")]
static string FormatUInt64(ulong v, string fmt, NumberFormatInfo nfi)
{
byte* v2 = stackalloc byte[8];
*(ulong*)v2 = v;
return FormatInteger(v2, false, 8, fmt, nfi);
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_ZW6System6Number_11FormatInt64_Ru1S_P3xu1SU22System#2EGlobalization16NumberFormatInfo")]
static string FormatInt64(long v, string fmt, NumberFormatInfo nfi)
{
byte* v2 = stackalloc byte[8];
*(long*)v2 = v;
return FormatInteger(v2, true, 8, fmt, nfi);
}
[WeakLinkage]
[AlwaysCompile]
[MethodAlias("_ZW6System6Number_12FormatDouble_Ru1S_P3du1SU22System#2EGlobalization16NumberFormatInfo")]
static string FormatDouble(double v, string fmt, NumberFormatInfo nfi)
{
// we do not currently support doubles longer than int64 or other than fixed point
// no more than 9 decimal places
if (double.IsNegativeInfinity(v))
{
return nfi != null ? (nfi.NegativeInfinitySymbol ?? ((nfi.NegativeSign ?? "-") + "Inf")) : "-Inf";
}
if (double.IsPositiveInfinity(v))
{
return nfi != null ? (nfi.PositiveInfinitySymbol ?? "Inf") : "Inf";
}
if (double.IsNaN(v))
{
return nfi != null ? (nfi.NaNSymbol ?? "NaN") : "NaN";
}
// get integral portion
if (v < long.MinValue || v > long.MaxValue)
return "<too large>";
var integral = (long)v;
var istr = FormatInt64(integral, null, nfi);
// get decimal portion
const int MAX_DEC = 9;
const int MAX_DEC_P10 = 10 ^ MAX_DEC;
var d = (long)((v - integral) * MAX_DEC_P10);
var dstr = FormatInt64(d, null, nfi);
// append them together
const int MAX_STR = 256;
char* ret = stackalloc char[MAX_STR];
int cur_ret = 0;
foreach (var c in istr)
ret[cur_ret++] = c;
if (dstr.Length != 1 || dstr[0] != '0')
{
// There is a fractional part of the number
var dec_pt = nfi != null ? (nfi.NumberDecimalSeparator ?? ".") : ".";
foreach (var c in dec_pt)
ret[cur_ret++] = c;
// pad with zeros until significant part is reached
for (int i = 0; i < (dstr.Length - MAX_DEC); i++)
ret[cur_ret++] = '0';
// determine how much of the actual value to print e.g. if it is 0.123456 we only print 6
// digits, but dstr is "123456000"
int to_trim = 0;
for(int i = dstr.Length - 1; i >= 0; i--)
{
if (dstr[i] == '0')
to_trim++;
else
break;
}
for (int i = 0; i < dstr.Length - to_trim; i++)
ret[cur_ret++] = dstr[i];
}
return new string(ret, 0, cur_ret);
}
/* The main format function */
static string FormatInteger(byte *v, bool is_signed, int blen, string fmt, NumberFormatInfo nfi)
{
long s = *(long*)v;
ulong us = *(ulong*)v;
bool is_negative = false;
if(is_signed)
{
if (s < 0)
{
is_negative = true;
us = (ulong)(-s);
}
else
us = (ulong)s;
}
const int MAX_STR = 256;
char* ret = stackalloc char[MAX_STR];
int cur_ret = 0;
if (fmt == null || fmt.Equals(string.Empty))
fmt = "G";
char* f = StringOperations.GetChars(fmt);
int cur_fmt = 0;
int l_fmt = fmt.Length;
char c_f = *f; // Current formatting character
int p = -1; // Current precision (used if 'G' is converted to 'F')
while(cur_fmt < l_fmt)
{
switch(c_f)
{
case 'G':
case 'g':
{
/* Generic format strings are either fixed point or exponential, depending on
* the exponent of the number */
int sig_digits = get_number_from_fmt_string(f, cur_fmt, l_fmt, out int new_cur_fmt);
if(sig_digits == -1)
{
switch(blen)
{
case 4:
sig_digits = 10;
break;
case 8:
sig_digits = 19;
break;
default:
sig_digits = 29;
break;
}
}
int exp = get_exponent_u(us);
if(exp < sig_digits && exp >= -4)
{
c_f = 'F';
p = 0;
}
else
{
if (c_f == 'G')
c_f = 'E';
else
c_f = 'e';
}
}
continue;
case 'F':
case 'f':
case 'N':
case 'n':
{
if (p == -1)
p = get_number_from_fmt_string(f, cur_fmt + 1, l_fmt, out cur_fmt);
else
get_number_from_fmt_string(f, cur_fmt + 1, l_fmt, out cur_fmt); // ignore p in the string (this is a 'G' converted to 'F')
if(p == -1)
{
if (nfi != null)
p = nfi.NumberDecimalDigits;
else
p = 2;
}
if(is_negative)
{
if (nfi != null && nfi.NegativeSign != null)
append_string(ret, nfi.NegativeSign, ref cur_ret, MAX_STR);
else
append_string(ret, "-", ref cur_ret, MAX_STR);
}
/* build a string before the decimal point */
char* rev_str = stackalloc char[MAX_STR];
int cur_rev_str = 0;
ulong c_us = us;
string[] digits = null;
if (nfi != null && nfi.NativeDigits != null)
digits = nfi.NativeDigits;
while(c_us != 0)
{
if (digits == null)
rev_str[cur_rev_str++] = (char)('0' + (c_us % 10));
else
append_string(rev_str, digits[(int)(c_us % 10)], ref cur_rev_str, MAX_STR);
c_us /= 10;
}
/* append back onto the original string in reverse order */
if (cur_rev_str == 0)
append_string(ret, "0", ref cur_ret, MAX_STR);
else
{
while(cur_rev_str > 0)
{
char c = rev_str[--cur_rev_str];
if(((c_f == 'n') || (c_f == 'N')) && cur_rev_str != 0 && ((cur_rev_str % 3) == 0))
{
if (nfi != null && nfi.NumberGroupSeparator != null)
append_string(ret, nfi.NumberGroupSeparator, ref cur_ret, MAX_STR);
else
append_string(ret, ",", ref cur_ret, MAX_STR);
}
if (cur_ret < MAX_STR)
ret[cur_ret++] = c;
}
}
if(p > 0)
{
/* Add .0000... after string */
if (nfi != null && nfi.NumberDecimalSeparator != null)
append_string(ret, nfi.NumberDecimalSeparator, ref cur_ret, MAX_STR);
else
append_string(ret, ".", ref cur_ret, MAX_STR);
var cur_p = p;
while (p-- > 0)
append_string(ret, "0", ref cur_ret, MAX_STR);
}
p = -1; // reset precision so that we look for it again in the next formatting operation - if 'G' then it will be set to zero again
}
break;
case 'X':
case 'x':
{
int dcount = get_number_from_fmt_string(f, cur_fmt + 1, l_fmt, out cur_fmt);
if (dcount == -1)
dcount = blen * 2;
string digits;
if (c_f == 'X')
digits = uppercaseDigits;
else
digits = lowercaseDigits;
for(int i = dcount - 1; i >= 0; i--)
{
if(i > (blen * 2))
{
if (cur_ret < MAX_STR)
ret[cur_ret++] = '0';
}
else
{
byte b = v[i / 2];
if ((i % 2) == 1)
b >>= 4;
else
b &= 0xf;
if (cur_ret < MAX_STR)
ret[cur_ret++] = digits[b];
}
}
}
break;
default:
/* Add verbatim */
if (cur_ret < MAX_STR)
ret[cur_ret++] = c_f;
cur_fmt++;
break;
}
c_f = f[cur_fmt];
}
return new string(ret, 0, cur_ret);
}
private static void append_string(char* ret, string s, ref int cur_ret, int mAX_STR)
{
int s_idx = 0;
while(cur_ret < mAX_STR && s_idx < s.Length)
{
ret[cur_ret++] = s[s_idx++];
}
}
private static int get_exponent_u(ulong us)
{
int ret = 0;
while(us >= 10)
{
us /= 10;
ret++;
}
return ret;
}
private static int get_number_from_fmt_string(char* f, int cur_fmt, int l_fmt, out int new_cur_fmt)
{
if (cur_fmt >= l_fmt || !char.IsDigit(f[cur_fmt]))
{
new_cur_fmt = cur_fmt;
return -1;
}
int ret = 0;
while(cur_fmt < l_fmt && char.IsDigit(f[cur_fmt]))
{
int d = f[cur_fmt] - '0';
ret *= 10;
ret += d;
cur_fmt++;
}
new_cur_fmt = cur_fmt;
return ret;
}
}
}
<file_sep>#!/bin/bash
set -e
# Based on https://wiki.osdev.org/GCC_Cross-Compiler
# install prerequisites
DEBIAN_FRONTEND='noninteractive' apt-get update
DEBIAN_FRONTEND='noninteractive' apt-get install -y \
curl nasm build-essential bison flex libgmp3-dev \
libmpc-dev libmpfr-dev texinfo yasm libunwind8 libunwind-dev \
unzip mono-mcs
# download and extract sources
rm -rf ~/src
mkdir ~/src && cd ~/src
curl -s https://ftp.gnu.org/gnu/binutils/binutils-2.30.tar.gz \
--output binutils-2.30.tar.gz > /dev/null
curl -s https://ftp.gnu.org/gnu/gcc/gcc-8.1.0/gcc-8.1.0.tar.gz \
--output gcc-8.1.0.tar.gz > /dev/null
tar -xf binutils-2.30.tar.gz
tar -xf gcc-8.1.0.tar.gz
# export variables
export PREFIX="/usr/local/cross"
export TARGET=i686-elf
export PATH="$PREFIX/bin:$PATH"
# build binutils
cd ~/src
mkdir build-binutils
cd build-binutils
../binutils-2.30/configure --target=$TARGET --prefix="$PREFIX" \
--with-sysroot --disable-nls --disable-werror
make
make install
# build gcc
cd ~/src
# The $PREFIX/bin dir _must_ be in the PATH.
which -- $TARGET-as || echo $TARGET-as is not in the PATH
mkdir build-gcc
cd build-gcc
../gcc-8.1.0/configure --target=$TARGET --prefix="$PREFIX" --disable-nls \
--enable-languages=c,c++ --without-headers
make -j$((`nproc`+1)) all-gcc
make -j$((`nproc`+1)) all-target-libgcc
make install-gcc
make install-target-libgcc
cd ..
# and again for 64 bit versions
export TARGET=x86_64-elf
mkdir build-binutils64
cd build-binutils64
../binutils-2.30/configure --target=$TARGET --prefix="$PREFIX" \
--with-sysroot --disable-nls --disable-werror
make
make install
# build gcc
cd ~/src
# The $PREFIX/bin dir _must_ be in the PATH.
which -- $TARGET-as || echo $TARGET-as is not in the PATH
mkdir build-gcc64
cd build-gcc64
../gcc-8.1.0/configure --target=$TARGET --prefix="$PREFIX" --disable-nls \
--enable-languages=c,c++ --without-headers
make -j$((`nproc`+1)) all-gcc
make -j$((`nproc`+1)) all-target-libgcc
make install-gcc
make install-target-libgcc
cd ..
# get tymake and tysila
cd ~/src
git clone https://github.com/jncronin/tymake.git
git clone --recurse https://github.com/jncronin/tysila.git
# build them
cd ~/src/tymake
dotnet publish -c Release -p:TargetLatestRuntimePatch=true -p:PublishDir=/usr/local/tymake -r linux-x64
export PATH="/usr/local/tymake:$PATH"
cd ~/src/tysila
dotnet publish -c Release -p:TargetLatestRuntimePatch=true -p:PublishDir=/usr/local/tysila -r linux-x64
export PATH="/usr/local/tysila:$PATH"
# get coreclr 2.0 prebuilt
cd ~/src
wget --no-check-certificate https://172.16.31.10/files/tools/coreclr-2.0.0.zip
unzip coreclr-2.0.0.zip
cp -dpR coreclr /usr/local
export PATH="/usr/local/coreclr:$PATH"
# build libsupcs
cd ~/src/tysila
mkdir -p tysila4/bin/Release
mkdir -p /usr/local/libsupcs
dotnet build -c Release libsupcs
cp tysila4/bin/Release/netcoreapp2.0/libsupcs.dll tysila4/bin/Release/netcoreapp2.0/metadata.dll tysila4/bin/Release
tymake "TYSILA=\"/usr/local/tysila/tysila4\";GENMISSING=\"/usr/local/tysila/genmissing\";MSCORLIB=\"/usr/local/coreclr/mscorlib.dll\";INSTALL_DIR=\"/usr/local/libsupcs\";" libsupcs.tmk
export PATH="/usr/local/libsupcs:$PATH"
# compile mscorlib
tysila4 -o /app/mscorlib.x86_64.o -t x86_64 /usr/local/coreclr/mscorlib.dll
# bring all together into /app
cp /usr/local/libsupcs/libsupcs.x86_64.a /app
<file_sep>using Internal.ReadLine;
using Internal.ReadLine.Abstractions;
using System.Collections.Generic;
namespace System
{
public static class ReadLine
{
private static List<string> _history;
static ReadLine()
{
_history = new List<string>();
}
public static void AddHistory(params string[] text) => _history.AddRange(text);
public static List<string> GetHistory() => _history;
public static void ClearHistory() => _history = new List<string>();
public static bool HistoryEnabled { get; set; }
public static IAutoCompleteHandler AutoCompletionHandler { private get; set; }
public static string Read(string prompt = "", string @default = "")
{
Console.Write(prompt);
KeyHandler keyHandler = new KeyHandler(new Console2(), _history, AutoCompletionHandler);
string text = null;
try
{
text = GetText(keyHandler);
}
catch(InvalidOperationException)
{
// this occurs if the console does not support System.Console.ReadKey
text = System.Console.ReadLine();
}
if (String.IsNullOrWhiteSpace(text) && !String.IsNullOrWhiteSpace(@default))
{
text = @default;
}
else
{
if (HistoryEnabled)
_history.Add(text);
}
return text;
}
public static string ReadPassword(string prompt = "")
{
Console.Write(prompt);
KeyHandler keyHandler = new KeyHandler(new Console2() { PasswordMode = true }, null, null);
return GetText(keyHandler);
}
private static string GetText(KeyHandler keyHandler)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
Console.WriteLine();
return keyHandler.Text;
}
}
}
<file_sep>all: barebones.iso
loader.o: loader.asm
nasm -felf -o loader.o loader.asm
netstandard2.0/barebones.dll: kernel.cs
dotnet build
kernel.o: netstandard2.0/barebones.dll
dotnet run --project ../../tysila4 -t x86 -e _start -o kernel.o -L /mnt/d/coreclr netstandard2.0/barebones.dll
iso/kernel.bin: kernel.o
i686-elf-ld -T linker.ld --gc-sections --undefined=gcmalloc --unresolved-symbols=ignore-all -o iso/kernel.bin loader.o kernel.o
barebones.iso: iso/kernel.bin iso/boot/grub/grub.cfg
grub-mkrescue -o barebones.iso iso
| 9db7be44ce8748c8d50b4a13e9e2979448848a93 | [
"Makefile",
"C#",
"Text",
"C",
"Dockerfile",
"Shell"
] | 106 | C# | jncronin/tysila | 3c4c3589cad4277956d58cc8e2b5eb32b50deb53 | 88c76a09287375b73598e018391eb984e31ac471 |
refs/heads/master | <file_sep># alchohol project psit
โปรเจคนี้เป็นส่วนหนึ่งของวิชาPsit
โดยเป็นการนำปริมาณการดื่มแอลกอฮอล์ตั้งแต่ปี2550-2558
มาวิเคราะห์ดูว่ามีการเพิ่มมากขึ้นหรือลดน้อยลงเพียงใด
โดยแบ่งเป็น2ประเภท ตามเพศ และ อายุ
<file_sep>import pygal
line_chart = pygal.Line()
line_chart.title = 'Consumption rate by genders (in %)'
line_chart.x_labels = map(str, range(2550, 2558))
line_chart.add('Overall',[30.02, None, None, None, 31.53, None, 32.22, 32.29])
line_chart.add('Male',[52.26, None, None, None, 53.37, None, 53.99, 52.96])
line_chart.add('Female',[9.09, None, None, None, 10.87, None, 11.79, 12.92])
line_chart.render_to_file('gender.svg')
| 6bb5408e325571dfdba42dceb4938c7fdf7d6fa1 | [
"Markdown",
"Python"
] | 2 | Markdown | jamesmhee/psit-project | 5a9383f41b15b650ef3ed5ab8d2e356c5b65613d | ff736f027e12905bf072a9cc7ba498573ac25a71 |
refs/heads/master | <file_sep>/*
* File: wildfire.h
*
* Author: <NAME>
*
* Date: 8 July 2017
*
* Description:
* Implements the simulation of spreading fire. The program implements
* a combination of [Shiflet] Assignents with variations. The state of
* the system is repeatedly computed and displayed to show the progression
* of a forest fire. Each state represents the start of a new cycle. The simulation
* is represented by a grid of cells. Cursor-control functions are used to show changes
* to the grid as the fire spreads. The optional print mode prints another grid for
* each simulation cycle.
*
*/
#ifndef wildfire
#define wildfire
/// Help function gives instructions. Prints usage information to stderr.
/// Terminates program when finished.
///
static void help();
/// Modifies the grid in place. Applies spread function to
/// each cell.
/// Changes any burning tree to a 0,1,2 or 3 to represent
/// its current cycle. These numbers are ignored when the grid
/// is printed. The function handles the 2-cycle burn for trees that burn.
///
/// @param g: grid to be updated
///
static void update( char g[size][size] );
/// Implements the spread algorithm. Function handles 8-way connectivity of neighbors.
/// The 2-cycle burn for burning trees is handled in update.
///
/// @param row: the destination row
/// @param col: the destination column
/// @param copy: copy of grid that doesn't change
///
static int applySpread(int row, int col, char copy[size][size]);
/// Shuffles grid data to initialize cycle 0. Taken from lecture.
///
/// @param size: size of data
/// @param data: 1d array of empty, tree, and burning characters
///
static void shuffle( long size, char data[]);
/// Uses getopt() function to process command line options. Runs the simulation until
/// all fires are out or max number of cycles is reached.
///
/// @param size: size of data
/// @param data: 1d array of empty, tree, and burning characters
///
int main( int argc, char * argv[] );
#endif
<file_sep>// file: wildfire.c
// Implements the simulation of spreading fire. The program implements
// a combination of [Shiflet] Assignents with variations. The state of
// the system is repeatedly computed and displayed to show the progression
// of a forest fire. Each state represents the start of a new cycle. The simulation
// is represented by a grid of cells. Cursor-control functions are used to show changes
// to the grid as the fire spreads. The optional print mode prints another grid for
// each simulation cycle.
// author: wor3835 | <EMAIL>
//
#define _BSD_SOURCE // must be set before headers
#include <unistd.h> // usleep
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memcpy, strcpy
#include <getopt.h> // processes command line arguments that begin with (-)
#include "display.h" // display cursor
//#include "wildfire.h"
#include <limits.h>
// default values for simulation
#define DEFAULT_BURN 0.10 // default pBurning
#define DEFAULT_PROB_CATCH 0.30 // default pCatch
#define DEFAULT_DENSITY 0.50 // default density
#define DEFAULT_PROP_NEIGHBOR 0.25 // default pNeighbor
#define DEFAULT_PRINT_COUNT 0 // print mode is turned off and overlay display mode is on
#define DEFAULT_SIZE 10 // default size
#define DEFAULT_TREES 0 // default totalTrees
#define DEFAULT_FIRE 0 // default fireTrees
#define DEFAULT_LIVING 0 // default livingTrees
#define DEFAULT_SPACES 0 // default spaces
//
static size_t size = DEFAULT_SIZE; // size of the grid
static float pCatch = DEFAULT_PROB_CATCH; // probability of a tree catching fire
static float density = DEFAULT_DENSITY; // density
static float pBurning = DEFAULT_BURN; // proportion of the tree population initially on fire
static float pNeighbor = DEFAULT_PROP_NEIGHBOR; // proportion of neighbors that will influence a tree catching fire
static int print = DEFAULT_PRINT_COUNT; // print mode; 1 if on, 0 if off
static int cycle = INT_MAX; // cycle of simulation
static int changes = 0; // number of changes in most recent cycle
static int cChanges = 0; // cumulative number of changes of all cycles
static int totalTrees = DEFAULT_TREES; // total number of trees
static int fireTrees = DEFAULT_FIRE; // total number of trees on fire
static int livingTrees = DEFAULT_LIVING; // total number of living trees
static int spaces = DEFAULT_SPACES; // total number of spaces in grid
// function declarations //
static int applySpread(int row, int col, char copy[size][size]);
static void help();
static void update( char g[size][size] );
static void shuffle( long size, char data[]);
int main( int argc, char * argv[] );
/// help function gives instructions. Prints usage information to stderr.
static void help() {
fprintf( stderr, "usage: wildfire [options]\n" );
fprintf( stderr, "By default, the simulation runs in overlay display mode.\n" );
fprintf( stderr, "The -pN option makes the simulation run in print mode for up to N cycles.\n" );
printf("\n");
fprintf( stderr, "Simulation Configuration Options:\n" );
fprintf( stderr, " -H # View simulation options and quit.\n" );
fprintf( stderr, " -bN # proportion of trees that are already burning. 0 < N < 101.\n" );
fprintf( stderr, " -cN # probability that a tree will catch fire. 0 < N < 101.\n" );
fprintf( stderr, " -dN # density/proportion of trees in the grid. 0 < N < 101.\n" );
fprintf( stderr, " -nN # proportion of neighbors that influence a tree catching fire. -1 < N < 101.\n" );
fprintf( stderr, " -pN # number of cycles to print before quitting. -1 < N < ...\n" );
fprintf( stderr, " -sN # simulation grid size. 4 < N < 41.\n" );
printf("\n");
printf("\n");
exit(0);
}
/// Modifies the grid in place. Applies spread function to
/// each cell.
/// Changes any burning tree to a 0,1,2 or 3 to represent
/// its current cycle. These numbers are ignored when the grid
/// is printed. The function handles the 2-cycle burn for trees that burn.
static void update( char g[size][size] ) {
int s = size;
char cpy[s][s];
memcpy(cpy, g, sizeof (char) * s * s); // makes copy of 2D array
int r;
int c;
int ret; // return value of spread (1 if tree starts burning)
for (r = 0; r < s; r++) {
for (c = 0; c < s; c++) {
if ( cpy[r][c] == 'Y' ) {
ret = applySpread(r, c, cpy);
if ( ret == 1 ) {
g[r][c] = '0'; // becomes burning in actual grid
changes++;
fireTrees++;
livingTrees--;
}
}
else if ( cpy[r][c] == '*' ) {
g[r][c] = '0';
}
else if ( cpy[r][c] == '0' ) {
g[r][c] = '1'; // first cycle
}
else if ( cpy[r][c] == '1' ) {
g[r][c] = '2'; // second cycle
}
else if ( cpy[r][c] == '2' ) {
g[r][c] = '.'; // third cycle
changes++;
totalTrees--;
fireTrees--;
}
}
}
}
/// Implements the spread algorithm. Function handles 8-way connectivity of neighbors. The 2-cycle
/// burn for burning trees is handled in update.
static int applySpread(int row, int col, char copy[size][size]) {
int totalNeighbors = 0; // total neighbors of tree
int burningNeighbors = 0; // total tree neighbors of tree
int tmpsize = size;
if ( ( row - 1 >= 0 ) ) { // north neighbor
if ( ( copy[row - 1][col] == 'Y' || copy[row - 1][col] == '*'
|| copy[row - 1][col] == '0' || copy[row - 1][col] == '1' || copy[row - 1][col] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row - 1][col] == '*' || copy[row - 1][col] == '0' || copy[row - 1][col] == '1'
|| copy[row - 1][col] == '2') ) {
burningNeighbors++;
}
}
if ( ( col + 1 < tmpsize ) ) { // east neighbor
if ( ( copy[row][col + 1] == 'Y' || copy[row][col + 1] == '*'
|| copy[row][col + 1] == '0' || copy[row][col + 1] == '1' || copy[row][col + 1] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row][col + 1] == '*' || copy[row][col + 1] == '0' || copy[row][col + 1] == '1'
|| copy[row][col + 1] == '2') ) {
burningNeighbors++;
}
}
if ( ( row + 1 < tmpsize) ) { // south neighbor
if ( ( copy[row + 1][col] == 'Y' || copy[row + 1][col] == '*'
|| copy[row + 1][col] == '0' || copy[row + 1][col] == '1' || copy[row + 1][col] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row + 1][col] == '*' || copy[row + 1][col] == '0' || copy[row + 1][col] == '1'
|| copy[row + 1][col] == '2') ) {
burningNeighbors++;
}
}
if ( ( col - 1 >= 0 ) ) { // west neighbor
if ( ( copy[row][col - 1] == 'Y' || copy[row][col - 1] == '*'
|| copy[row][col - 1] == '0' || copy[row][col - 1] == '1' || copy[row][col - 1] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row][col - 1] == '*' || copy[row][col - 1] == '0' || copy[row][col - 1] == '1'
|| copy[row][col - 1] == '2') ) {
burningNeighbors++;
}
}
if ( ( row - 1 >= 0 && col + 1 < tmpsize ) ) { // northeast neighbor
if ( ( copy[row - 1][col + 1] == 'Y' || copy[row - 1][col + 1] == '*'
|| copy[row - 1][col + 1] == '0' || copy[row - 1][col + 1] == '1' || copy[row - 1][col + 1] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row - 1][col + 1] == '*' || copy[row - 1][col + 1] == '0' || copy[row - 1][col + 1] == '1'
|| copy[row - 1][col + 1] == '2') ) {
burningNeighbors++;
}
}
if ( ( row + 1 < tmpsize && col + 1 < tmpsize ) ) { // southeast neighbor
if ( ( copy[row + 1][col + 1] == 'Y' || copy[row + 1][col + 1] == '*'
|| copy[row + 1][col + 1] == '0' || copy[row + 1][col + 1] == '1' || copy[row + 1][col + 1] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row + 1][col + 1] == '*' || copy[row + 1][col + 1] == '0' || copy[row + 1][col + 1] == '1'
|| copy[row + 1][col + 1] == '2') ) {
burningNeighbors++;
}
}
if ( ( row + 1 < tmpsize && col - 1 >= 0 ) ) { // southwest neighbor
if ( ( copy[row + 1][col - 1] == 'Y' || copy[row + 1][col - 1] == '*'
|| copy[row + 1][col - 1] == '0' || copy[row + 1][col - 1] == '1' || copy[row + 1][col - 1] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row + 1][col - 1] == '*' || copy[row + 1][col + 1] == '0' || copy[row + 1][col - 1] == '1'
|| copy[row + 1][col - 1] == '2') ) {
burningNeighbors++;
}
}
if ( ( row - 1 >= 0 && col - 1 >= 0 ) ) { // northwest neighbor
if ( ( copy[row - 1][col - 1] == 'Y' || copy[row - 1][col - 1] == '*'
|| copy[row - 1][col - 1] == '0' || copy[row - 1][col - 1] == '1' || copy[row - 1][col - 1] == '2') ) {
totalNeighbors++;
}
if ( ( copy[row - 1][col - 1] == '*' || copy[row - 1][col - 1] == '0' || copy[row - 1][col - 1] == '1'
|| copy[row - 1][col - 1] == '2') ) {
burningNeighbors++;
}
}
if ( ( (float) burningNeighbors/totalNeighbors ) > pNeighbor ) { // proportion of neighbors is higher
float rand = random() / (float) RAND_MAX;
if ( rand < pCatch) {
return 1;
}
}
return 0;
}
/// Shuffles grid data to initialize cycle 0
/// @param size size of grid
/// @param data array of cells in grid
///
static void shuffle( long size, char data[]) {
for( int i = 0; i < size - 1; ++i) {
unsigned long j = (i + random()) % size;
char tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
/// Uses getopt() function to process command line options.
/// @param argc length of argv
/// @param argv array of command strings
///
int main( int argc, char * argv[] ) {
int seed = 41;
srandom(seed); // seeds random number generator
int c;
int opterr = 0;
// // // // // // // // // // // // // // // // // // // // // // // //
//
// If -H, -b, -c, -d, -n, -p or -s are on the command line, getopt will
// process those arguments. All options except the -H option expect an
// argument.
//
// // // // // // // // // // // // // // // // // // // // // // // //
while ( (c = getopt( argc, argv, "Hb:c:d:n:p:s:") ) != -1 ) {
switch ( c ) {
case 'H':
help();
break;
case 'b':
opterr = (int)strtol( optarg, NULL, 10);
if ( 0 < opterr && opterr < 101) {
pBurning = (float)opterr/100;
} else {
fprintf( stderr, "(-bN) proportion already burning. must be an integer in [1...100].\n");
help();
}
break;
case 'c':
opterr = (int)strtol( optarg, NULL, 10);
if (0 < opterr && opterr < 101) {
pCatch = (float)opterr/100;
} else {
fprintf( stderr, "(-cN) probability a tree will catch fire. must be an integer in [1...100].\n");
help();
}
break;
case 'd':
opterr = (int)strtol( optarg, NULL, 10);
if (0 < opterr && opterr < 101) {
density = (float)opterr/100;
} else {
fprintf( stderr, "(-dN) density of trees in the grid must be an integer in [1...100].\n");
help();
}
break;
case 'n':
opterr = (int)strtol( optarg, NULL, 10);
if (-1 < opterr && opterr < 101) {
pNeighbor = (float)opterr/100;
} else {
fprintf( stderr, "(-nN) neighbors influence catching fire must be an integer in [0...100].\n");
help();
}
break;
case 'p':
opterr = (int)strtol( optarg, NULL, 10);
if (-1 < opterr) {
print = 1;
cycle = (int)opterr;
} else {
fprintf( stderr, "(-pN) number of cycles to print. must be an integer in [0...10000].\n");
help();
}
break;
case 's':
opterr = (int)strtol( optarg, NULL, 10);
if (4 < opterr && opterr < 41) {
size = (size_t)opterr;
} else {
fprintf( stderr, "(-sN) simulation grid size must be an integer in [5...40].\n");
help();
}
break;
default:
fprintf( stderr, "Bad option causes failure. \n");
break;
}
}
// gets cells
float x = (size * size) * density;
totalTrees = (int)(x + 0.5); // rounds float to integer
float y = totalTrees * pBurning; // represented by (*)
fireTrees = (int)(y + 0.5);
float z = (totalTrees - fireTrees); // represented by (Y)
livingTrees = (int)(z + 0.5);
float s = (size * size) - totalTrees; // represented by space character
spaces = (int)(s + 0.5);
size_t spots = spaces + livingTrees + fireTrees;
char start[spots];
memset(start, 0, spots);
int d;
int e;
int f;
size_t len;
for (d = 0; d < spaces; d++) {
len = strlen(start);
start[len] = ' ';
start[len + 1] = '\0';
}
for (e = 0; e < livingTrees; e++) {
len = strlen(start);
start[len] = 'Y';
start[len + 1] = '\0';
}
for (f = 0; f < fireTrees; f++) {
len = strlen(start);
start[len] = '*';
start[len + 1] = '\0';
}
shuffle(spots, start);
//
char grid [size][size]; // grid is represented as a 2D array
int i;
int j;
int k = 0;
if (print == 0) {
clear();
}
if (print == 1) {
printf("%s\n", "============================");
printf("%s\n", "======== Wildfire ==========");
printf("%s\n", "============================");
printf("==== Print <= %d Cycles ====\n", cycle);
printf("%s\n", "============================");
}
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
grid[i][j] = start[k];
if (print == 0) {
set_cur_pos(i, j);
put(grid[i][j]);
} else {
printf("%c", grid[i][j]);
}
k++;
}
printf("\n");
}
printf("\rsize %zu, pCatch %.2f, density %.2f, pBurning %.2f, pNeighbor %.2f", size, pCatch, density, pBurning, pNeighbor);
printf("\ncycle %d, changes %d, cumulative changes %d\n ", 0, 0, 0);
usleep(750000);
// // // // // // // // // // // // // // // // // // // // // // // //
//
// The Simulation Loop:
// The loop continually applies the update algorithm and checks if
// all fires are out or the number of cycles has been reached.
//
// // // // // // // // // // // // // // // // // // // // // // // //
int currCycle = 1; // current cycle of simulation
while(fireTrees > 0 && cycle > 0) {
update(grid);
cChanges += changes;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if ( grid[i][j] == '0' || grid[i][j] == '1' || grid[i][j] == '2' ) {
if ( print == 0) {
set_cur_pos(i, j);
put('*');
} else {
printf("%c", '*');
}
} else {
if ( print == 0) {
set_cur_pos(i, j);
put(grid[i][j]);
} else {
printf("%c", grid[i][j]);
}
}
}
if( print == 1 && i != (size - 1)) {
printf("\n");
}
}
puts(" ");
printf("\rsize %zu, pCatch %.2f, density %.2f, pBurning %.2f, pNeighbor %.2f", size, pCatch, density, pBurning, pNeighbor);
printf("\ncycle %d, changes %d, cumulative changes %d \n", currCycle, changes, cChanges);
changes = 0;
currCycle++;
cycle--;
usleep(750000);
}
if ( fireTrees == 0) {
printf("%s\n", "Fires are out.");
}
return(EXIT_SUCCESS);
}
<file_sep>// file: use_getopt.c
// use_getopt.c demonstrates use of the getopt command line processing tool.
// author: bksteele
//
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h> // processing for "-fN" command line args
#define DEFAULT_SIZE 10 ///< used if no override on command line
static size_t the_size = DEFAULT_SIZE; ///< a program setting.
static size_t the_count = 0; ///< another program setting. default is 0.
/// usage function gives instructions.
static void usage() {
fprintf( stderr, "\nusage: use_getopt [-H -pNUM -s pos_num]\n" );
fprintf( stderr, "\t-H is for getting help\n" );
fprintf( stderr, "\t-pN overrides the default count\n" );
fprintf( stderr, "\t-sN overrides the default size\n" );
fprintf( stderr, "\nAn argument pair of \"-p 5\" is same as \"-p5\"\n" );
}
/// This demonstrates the use of the getopt() function.
/// main : [-H] [-p num] [-s pos_num] [-- ... ] -> int
/// To terminate option flag processing enter the "--" as an argument.
/// @param argc the length of the command line arguments array
/// @param argv the array of command line argument strings
///
/// @see man -s 3 getopt
/// @see man getopt
///
int main( int argc, char * argv[] ) {
int opt;
int tmpsize = 0;
fprintf( stderr, "command line:\t >>> " );
for ( int j = 0; j < argc; ++j ) {
fprintf( stderr, "%s ", argv[j] );
}
fprintf( stderr, "\n" );
usage(); // print usage to guide the demonstration
// // // // // // // // // // // // // // // // // // // // // // // //
// string "Hs:p:" means that, if -H -s or -p are on the command line,
// then getopt code will process those arguments, ignoring others.
// The -H option (case sensitive) has no argument.
// The -s and -p options each expect an argument.
// // // // // // // // // // // // // // // // // // // // // // // //
while ( (opt = getopt( argc, argv, "Hs:p:") ) != -1 ) {
switch ( opt ) {
case 'H':
fprintf( stderr, "\nPlease read the usage message above.\n" );
break;
case 'p':
tmpsize = (int)strtol( optarg, NULL, 10 );
if ( tmpsize > 0 ) {
the_count = (size_t)tmpsize;
printf( "Option %c got the value %d\n", opt, tmpsize );
} else {
fprintf( stderr, "The -p got no value; should be an error.\n" );
}
break;
case 's':
tmpsize = (int)strtol( optarg, NULL, 10 );
if ( tmpsize > 0 ) {
the_size = (size_t)tmpsize;
printf( "Option %c got the value %d\n", opt, tmpsize );
break;
} else {
fprintf( stderr, "The -s option requires positive value\n" );
return EXIT_FAILURE;
}
default:
// some unknown, possibly unacceptable option flag
fprintf( stderr, "Bad option causes failure; ignored.\n" );
break;
}
}
printf( "\nsettings: " );
printf( "the_size == %zu;\n", the_size );
printf( "the_count == %zu;\n", the_count );
printf( "\n" );
// // // // // // // // // // // // // // // // // // // // // // // //
// this example shows the remaining command line arguments.
// At this point, optind should equal index of next argument.
// if there are additional arguments, optind is index of the first one.
// // // // // // // // // // // // // // // // // // // // // // // //
printf( "\n\tREMAINING COMMAND LINE ARGUMENTS: (index: argv[index])\n" );
for ( int j = optind; j < argc; ++j ) {
printf( "\t(%d: %s)\n", j, argv[j] );
}
printf( "\n" );
return EXIT_SUCCESS;
}
<file_sep># wild-fire
Implements the simulation of spreading fire. The program implements
a combination of [Shiflet] Assignents with variations. The state of
the system is repeatedly computed and displayed to show the progression
of a forest fire. Each state represents the start of a new cycle. The simulation
is represented by a grid of cells. Cursor-control functions are used to show changes
to the grid as the fire spreads. The optional print mode prints another grid for
each simulation cycle.
# compile
gcc -std=c99 -o wildfire wildfire.c display.c
# run
./wildfire
usage: wildfire [options]
By default, the simulation runs in overlay display mode
The -pN option makes the simulation run in print mode for up to N cycles
Simulation Configuration Options:
-H # View simulation options and quit.
-bN # proportion of trees that are already burning. 0 < N < 101.
-cN # probability that a tree will catch fire. 0 < N < 101.
-dN # density/proportion of trees in the grid. 0 < N < 101.
-nN # proportion of neighbors that influence a tree catching fire. -1 < N < 101.
-pN # number of cycles to print before quitting. -1 < N < ...
-sN # simulation grid size. 4 < N < 41.
| 34b71ad76636b31718b65ca8d760526aa69454fd | [
"Markdown",
"C"
] | 4 | C | wor3835/wild-fire | 45e8ea8f00a774f3cea407c20864bb52f8414685 | 46539570eb1dc593f23bd24320b0ac337f503c1a |
refs/heads/master | <repo_name>Jontronics/occubot<file_sep>/app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const twilio = require('twilio');
const accountSid = '<KEY>';
const authToken = '<PASSWORD>';
const client = new twilio(accountSid, authToken);
let MessageSchema = new mongoose.Schema({
phoneNumber: String
//eventually capture the address...addressName: String
})
let Message = mongoose.model('Message', MessageSchema);
app.use(bodyParser.urlencoded({extended: false}))
mongoose.connect('mongodb://isaac:<EMAIL>.<EMAIL>:35540/occupi-chat-db', {useMongoClient:true})
.then(() => {
console.log('db connected brrrrrrrrap');
})
app.get('/', (req, res) => {
res.end();
})
app.post('/inbound', (req, res) => {
let from = req.body.From;
let to = req.body.To;
let body = req.body.Body;
Message.find({phoneNumber: req.body.From}, (err, message) => {
if(message.length !== 0) {
// we need to continue the convo
if(body === "290 Harman st" || "290 Harman St" || "290 harman st" || "290 Harman Street" || "290 harman street") {
Message.findByIdAndUpdate(message[0]._id, {"$set": {"addressName": body}}, {"new":true, "upsert": true}, () => {
client.messages.create({
to: `${from}`,
from: `${to}`,
body: 'Ok great!!!!!! that apartment is still available. Click on this link and buy jon a beer. '
})
res.end()
})
} else if(body !== "290 Harman st" || "290 Harman St" || "290 harman st" || "290 Harman Street" || "290 harman street") {
Message.findByIdAndUpdate(message[0]._id, {"$set": {"addressRented": body}}, {"new":true, "upsert": true}, () => {
client.messages.create({
to: `${from}`,
from: `${to}`,
body: 'Oh man, that apartment got rented bud. But since im occubot master fresh, ill still help you out. Check out this link.and do stuff. '
})
res.end()
})
}
} else {
if(body === "Showing" || "SHOWING" || "showing") {
let newMessage = new Message();
newMessage.phoneNumber = from;
newMessage.save(() => {
client.messages.create({
to: `${from}`,
from: `${to}`,
body: 'Hey this is occub0tMasterFreshYo. Please text me the address of the apartment that you would like to see. '
})
res.end();
})
}
}
res.end();
})
})
app.listen(3000, () => {
console.log('server connected yaaaaaaay');
}) | 42f44e07760d6dabb7a719a904cc2a2f3af7addc | [
"JavaScript"
] | 1 | JavaScript | Jontronics/occubot | 819a3babfcdd68770e29a54365a980c940270a6e | 9ca86c7e85eba8938da6dfe690e47a389e632215 |
refs/heads/master | <file_sep>export interface APIPhoto {
id: string;
url: string;
width: number;
height: number;
}
export enum ProfileImageFAB {
'DELETE' = 'X',
'ADD' = '+',
}
// export type ProfileImageFAB = {}
<file_sep>export const IMAGES = [
{
id: '11111111',
url: 'https://collectionimages.npg.org.uk/large/mw82857/Bill-Gates.jpg',
width: 796,
height: 800,
centerX: 366,
centerY: 408,
},
{
id: '11111112',
url:
'https://i.pinimg.com/564x/87/64/76/876476178e8cd6bcaab1269f7283d97b.jpg',
width: 480,
height: 768,
centerX: 259,
centerY: 361,
},
{
id: '11111113',
url:
'https://media.king5.com/assets/KING/images/156daac9-f162-4c82-bb78-6edc4225d9ae/156daac9-f162-4c82-bb78-6edc4225d9ae_750x422.jpg',
width: 750,
height: 422,
centerX: 349,
centerY: 203,
},
];
<file_sep>import React, {useState, useEffect} from 'react';
import {StyleSheet, View, Modal, TouchableHighlight} from 'react-native';
import {RNCamera} from 'react-native-camera';
import {ConfirmationPageOne} from './confirmation/ConfirmationPageOne';
import {TextButton} from 'tht-buttons';
export const Camera = (props) => {
const [camera, setCamera] = useState('');
const [showConfirmation, setShowConfirmation] = useState(false);
const [uri, setUri] = useState('');
const [isVideo, setIsVideo] = useState(false);
const takePicture = async () => {
setIsVideo(false);
if (camera) {
const options = {quality: 0.5, base64: true};
const data = await camera.takePictureAsync(options);
console.log(data.uri);
setUri(data.uri);
}
};
useEffect(() => {
if (uri) {
setShowConfirmation(true);
}
}, [uri]);
const mediaConfirmed = (media) => {
console.log('media confirmed');
// setShowConfirmation(false);
props.onFinish(media);
};
return (
<View style={styles.container}>
<RNCamera
ref={(ref) => setCamera(ref)}
style={styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.on}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
onGoogleVisionBarcodesDetected={({barcodes}) => {
console.log(barcodes);
}}>
<View style={styles.container}>
<View style={styles.topButtons}>
<TextButton
text="X"
onPress={() => props.onCancel()}
style={styles.topText}
buttonStyle={styles.topButton}
/>
<TextButton
text="Flip"
onPress={() => props.onCancel()}
style={styles.topText}
buttonStyle={[styles.topButton, styles.flipButton]}
/>
</View>
<SnapButton onPress={() => takePicture()} />
</View>
</RNCamera>
<Modal animationType="slide" visible={showConfirmation}>
<ConfirmationPageOne
uri={uri}
isVideo={isVideo}
onConfirm={(confirmedUri) => mediaConfirmed(confirmedUri)}
onCancel={() => setShowConfirmation(!showConfirmation)}
/>
</Modal>
</View>
);
};
const SnapButton = ({onPress, onLongPress}) => {
return (
<View>
<TouchableHighlight
onPress={() => onPress()}
onLongPress={() => onLongPress()}>
<View style={styles.capture} />
</TouchableHighlight>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-between',
},
preview: {
flex: 1,
},
topButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
},
topText: {
fontSize: 25,
// margin: 20,
},
topButton: {
margin: 20,
},
flipButton: {
borderColor: 'black',
borderWidth: 1,
padding: 5,
},
capture: {
height: 50,
width: 50,
borderRadius: 25,
backgroundColor: 'red',
alignSelf: 'center',
marginBottom: 20,
},
});
<file_sep># together-demo
video: https://youtu.be/97wnXjhfVt8
| 2bdf65b69c4b442ac147b3166cee9ad5cfe73055 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 4 | TypeScript | mzruiz/together-demo | cd64ca2391fd100b24764ff6814b77fce1406cf6 | 02fd36fabb6b00959ad404e0cee48c89ee69caa3 |
refs/heads/master | <file_sep>do not remove this file, please
<file_sep>var gulp = require( 'gulp' ),
browserify = require( 'browserify' ),
browsersync = require( 'browser-sync' ).create(),
source = require( 'vinyl-source-stream' );
$ = require( 'gulp-load-plugins' )();
var assets = './assets';
var config = {
sassDir: assets + '/sass',
jsDir: assets + '/js',
imgDir: assets + '/images',
fontDir: assets + '/fonts',
distDir: assets + '/dist',
bowerDir: './bower_components'
};
gulp.task('sync', function() {
browsersync.init({
server: {
baseDir: "../pokehex"
}
});
// browsersync.init({
// });
// browsersync.init( config, function ( err, browsersync ) {
// if( !err ) {
//console.log("BrowserSync is ready!");
//}
//});
});
gulp.task('icons', function() {
return gulp.src( config.bowerDir + '/fontawesome/fonts/**.*' )
.pipe( gulp.dest( config.fontDir ));
});
gulp.task('browserify', function() {
return browserify( config.jsDir + '/main.js' )
.bundle()
.on( 'error', function( err )
{
console.log( err.toString() );
this.emit( 'end' );
})
.pipe( source( 'main.bundle.js' ))
.pipe( gulp.dest( config.distDir ));
});
gulp.task('scripts', ['browserify'], function() {
return gulp.src( config.distDir + '/main.bundle.js' )
// .pipe( jshint() )
// .pipe( jshint.reporter( 'jshint-stylish' ))
.pipe( $.rename( 'main.min.js' ))
.pipe( $.uglify() )
.pipe( gulp.dest( config.distDir ))
.pipe( browsersync.reload({ stream: true, once: true }));
});
gulp.task('styles', function() {
return gulp.src( config.sassDir + '/**/*.scss' )
.pipe( $.sass() )
.pipe( $.autoprefixer( 'last 3 version', 'ie 8', 'ie 9' ))
.pipe( $.rename({ suffix: '.min' }))
.pipe( $.minifyCss() )
.pipe( gulp.dest( config.distDir ))
.pipe( browsersync.reload({ stream: true }));
});
gulp.task('watch', ['sync'], function() {
gulp.watch( config.sassDir + '/**/*.scss', [ 'styles' ]);
gulp.watch( config.jsDir + '/**/*.js', [ 'scripts' ]);
gulp.watch( "./**/*.html" ).on( 'change', browsersync.reload );
gulp.watch( "./**/*.php" ).on( 'change', browsersync.reload );
});
gulp.task( 'default', [ 'scripts', 'styles' ]);
| f07bd022db80eb891af7ddd351f7d9d19ca0490d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | zachfedor/pokehex | c20878c9e19c638b2a7444b9e2c1c91118cb6cb3 | e6e1884fdd32fbbdeb66b2a8c716b81e7f8aae0a |
refs/heads/master | <repo_name>ClearVoice/multigzip<file_sep>/setup.py
from setuptools import setup
from multigzip import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='multigzip',
version=__version__,
provides=['multigzip'],
author='<NAME>',
url='https://github.com/ClearVoice/multigzip',
setup_requires='setuptools',
license='MIT',
author_email='<EMAIL>',
description='Multi Member GZip Support for Python 3',
long_description=long_description,
long_description_content_type="text/markdown",
packages=['multigzip'],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent"
],
)
<file_sep>/multigzip/__init__.py
__version__ = '0.0.2'
from .gzip2 import GzipFile
__all__ = ["GzipFile"]
<file_sep>/README.md
# Multi GZip
This package is a port of the Python2 gzip implementation with the goal of
providing multi-member gzip support. Currently Python3's gzip implementation
supports reading multi-member gzip files as a single stream, but does not
provide the ability to read or write one member at a time. This is useful
for iterating over the members of a gzip file in e.g. WARC files.
## Usage Example
```python
from multigzip import GzipFile
with GzipFile(filename='tests.txt.gz', mode='wb') as f:
f.write_member(b'Hello world 1')
f.write_member(b'Hello world 2')
f.write_member(b'Hello world 3')
with GzipFile(filename='tests.txt.gz', mode='r') as f:
# Note that read() returns a file-like object
# this is unchanged vs the `gzip2` module ported
# from warc
print(f.read_member().read())
print(f.read_member().read())
print(f.read_member().read())
```
### Supports Python3 Only
<file_sep>/tests/test_multigzip.py
import pytest
from io import BytesIO
from multigzip import GzipFile
@pytest.fixture
def file_obj():
fo = BytesIO()
yield fo
fo.close()
del fo
def test_multigzip(file_obj):
with GzipFile(fileobj=file_obj, mode='wb') as wf:
wf.write_member(b'Hello World 1')
wf.write_member(b'Hello World 2')
wf.write_member(b'Hello World 3')
file_obj.seek(0)
with GzipFile(fileobj=file_obj, mode='rb') as rf:
assert rf.read_member().read() == b'Hello World 1'
assert rf.read_member().read() == b'Hello World 2'
assert rf.read_member().read() == b'Hello World 3'
<file_sep>/requirements-dev.txt
-e .
pytest
coverage
flake8
tox
<file_sep>/multigzip/gzip2.py
"""Enhanced gzip library to support multiple member gzip files.
GZIP has an interesting property that contatination of mutliple gzip files is a valid gzip file.
In other words, a gzip file can have multiple members, each individually gzip
compressed. The members simply appear one after another in the file, with no
additional information before, between, or after them.
See GZIP RFC for more information.
http://www.gzip.org/zlib/rfc-gzip.html
This library provides support for creating and reading multi-member gzip files.
"""
from .gzip import WRITE, READ, write32u, GzipFile as BaseGzipFile
import zlib
def open(filename, mode="rb", compresslevel=9):
"""Shorthand for GzipFile(filename, mode, compresslevel).
"""
return GzipFile(filename, mode, compresslevel)
class GzipFile(BaseGzipFile):
"""GzipFile with support for multi-member gzip files.
"""
def __init__(self, filename=None, mode=None,
compresslevel=9, fileobj=None):
BaseGzipFile.__init__(self,
filename=filename,
mode=mode,
compresslevel=compresslevel,
fileobj=fileobj)
if self.mode == WRITE:
# Indicates the start of a new member if value is True.
# The BaseGzipFile constructor already wrote the header for new
# member, so marking as False.
self._new_member = False
# When _member_lock is True, only one member in gzip file is read
self._member_lock = False
def close_member(self):
"""Closes the current member being written.
"""
# The new member is not yet started, no need to close
if self._new_member:
return
self.fileobj.write(self.compress.flush())
write32u(self.fileobj, self.crc)
# self.size may exceed 2GB, or even 4GB
write32u(self.fileobj, self.size & 0xffffffff)
self.size = 0
self.compress = zlib.compressobj(9,
zlib.DEFLATED,
-zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL,
0)
self._new_member = True
def _start_member(self):
"""Starts writing a new member if required.
"""
if self._new_member:
self._init_write(self.name)
self._write_gzip_header()
self._new_member = False
def write(self, data):
self._start_member()
BaseGzipFile.write(self, data)
def close(self):
"""Closes the gzip with care to handle multiple members.
"""
if self.fileobj is None:
return
if self.mode == WRITE:
self.close_member()
self.fileobj = None
elif self.mode == READ:
self.fileobj = None
if self.myfileobj:
self.myfileobj.close()
self.myfileobj = None
def _read(self, size):
# Treat end of member as end of file when _member_lock flag is set
if self._member_lock and self._new_member:
raise EOFError()
else:
return BaseGzipFile._read(self, size)
def read_member(self):
"""Returns a file-like object to read one member from the gzip file.
"""
if self._member_lock is False:
self._member_lock = True
if self._new_member:
try:
# Read one byte to move to the next member
BaseGzipFile._read(self, 1)
assert self._new_member is False
except EOFError:
return None
return self
def write_member(self, data):
"""Writes the given data as one gzip member.
The data can be a string, an iterator that gives strings or a file-like object.
"""
if isinstance(data, bytes):
self.write(data)
else:
for text in data:
self.write(text)
self.close_member()
| 16372f220f141955e147dad081250113f6d08c56 | [
"Markdown",
"Python",
"Text"
] | 6 | Python | ClearVoice/multigzip | ce821ef2a81e634eadfbc5b19fd55fcf0e30d4ce | 04ca5bbb62a38314b7923c8dc29e4cc87203e71c |
refs/heads/master | <file_sep>8-Bit-Rhino
===========
A repository for ATLS 4519: Computer Game Devlopment for the XBOX.
Members
---------
<NAME>
<NAME>
<NAME>
<NAME>
Projects
--------
###Pong
Our game implements a basic pong game where the player is against the opponent. Our emeblishments include an electronica type feel to the game, as well as some goofy sounds.
###Banana Bombers
Our final project. Please view the README within the directory for a complete description.
<file_sep>/* File: clsSprite.cs Feb 2013
* Author: JKB University of Colorado Boulder
* Student: <NAME> <EMAIL>
* Description:
* Class to provide sprite.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics; // for Texture2D
using Microsoft.Xna.Framework; // for Vector2
namespace ATLS_4519_Lab3
{
class clsSprite
{
public Texture2D texture { get; set; } // sprite texture, read-only property
public Vector2 position { get; set; } // sprite position on screen
public Vector2 size { get; set; } // sprite size in pixels
public Vector2 velocity { get; set; } // sprite velocity
private Vector2 screenSize { get; set; } // screen size
public Vector2 center { get { return position + (size / 2); } } // sprite center
public float radius { get { return size.X / 2; } } // sprite radius
public int[] score;
public clsSprite(Texture2D newTexture, Vector2 newPosition, Vector2 newSize, int ScreenWidth, int ScreenHeight)
{
texture = newTexture;
position = newPosition;
size = newSize;
screenSize = new Vector2(ScreenWidth, ScreenHeight);
score = new int[] { 0, 0 }; // Player = 0, Opponent = 1
}
public bool CircleCollides(clsSprite otherSprite)
{
// Check if two circle sprites collided
return (Vector2.Distance(this.center, otherSprite.center) < this.radius +
otherSprite.radius);
}
public int Collides(clsSprite otherSprite)
{
int hit = 0;
// check if two sprites intersect
if (this.position.X + this.size.X > otherSprite.position.X &&
this.position.X < otherSprite.position.X + otherSprite.size.X &&
this.position.Y + this.size.Y > otherSprite.position.Y &&
this.position.Y < otherSprite.position.Y + otherSprite.size.Y) {
if (this.position.Y < otherSprite.position.Y + 6 ||
this.position.Y > otherSprite.position.Y + otherSprite.size.Y - 6)
hit = 2;
else
hit = 1;
}
return hit;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
public Vector2 Midpoint(clsSprite other) {
return new Vector2((this.position.X + other.position.X) / 2,
(this.position.Y + other.position.Y) / 2);
}
public int Move()
{
int hitWall = 0;
// if we move out of the screen, invert velocity
// checking right boundary (player)
if (position.X + size.X + velocity.X > screenSize.X) {
velocity = new Vector2(-velocity.X, velocity.Y);
hitWall = 2;
++score[1];
}
// checking bottom boundary
if (position.Y + size.Y + velocity.Y > screenSize.Y) {
velocity = new Vector2(velocity.X, -velocity.Y);
hitWall = 1;
}
// checking left boundary (opponent)
if (position.X + velocity.X < 0) {
velocity = new Vector2(-velocity.X, velocity.Y);
hitWall = 3;
++score[0];
}
// checking top boundary
if (position.Y + velocity.Y < 0) {
velocity = new Vector2(velocity.X, -velocity.Y);
hitWall = 1;
}
// since we adjusted the velocity, just add it to the current position
position += velocity;
return hitWall;
}
}
}<file_sep>/* File: Game1.cs Feb 2013
* Author: JKB University of Colorado Boulder
* Students: 8-Bit Rhino (<NAME>, <NAME>, <NAME>, <NAME>)
* Description:
* The main program.
* Needed to follow this to get XACT to work: http://stackoverflow.com/questions/10307898/xna-4-0-cannot-create-an-audioengine
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Diagnostics;
using System.Threading;
namespace ATLS_4519_Lab3
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
// Sprite Objects
clsSprite ball;
clsSprite opponent;
clsSprite player;
// SpriteBatch which will draw (render) the sprite
SpriteBatch spriteBatch;
// Create a SoundEffect resource
SoundEffect walls, start, miss, win, lose, killshot;
// Audio Objects
AudioEngine audioEngine;
SoundBank soundBank;
WaveBank waveBank;
WaveBank streamingWaveBank;
Cue musicCue;
// Font Objects
SpriteFont Font1;
Vector2 FontPos;
bool isDone;
int finalScore;
public string victory; // used to hold the congratulations/blnt message
// Set window deimensions for ease.
int winX, winY;
// Define threshold for oppenent's ai complexity
int threshold;
// Define enum for ease of programming
enum Who { Player, Opponent };
public Game1()
{
graphics = new GraphicsDeviceManager(this);
// changing the back buffer size changes the window size (in windowed mode)
graphics.PreferredBackBufferWidth = 1200;
graphics.PreferredBackBufferHeight = 600;
threshold = graphics.PreferredBackBufferWidth / 2;
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// Set window size
winX = graphics.PreferredBackBufferWidth;
winY = graphics.PreferredBackBufferHeight;
// Initialize isDone boolean
isDone = false;
finalScore = 7;
// Start first sound bite
start = Content.Load<SoundEffect>("herewego");
start.Play();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Set Some Variables
float padX = 24; // Paddle Width
float padY = 64; // Paddle Height
float ballD = 32; // Ball Diameter
Random rnd = new Random();
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Load the SoundEffect resource
walls = Content.Load<SoundEffect>("VOLTAGE");
miss = Content.Load<SoundEffect>("neat");
win = Content.Load<SoundEffect>("score");
lose = Content.Load<SoundEffect>("miss");
killshot = Content.Load<SoundEffect>("killshot");
// Load files built from XACT project
audioEngine = new AudioEngine("Content\\Lab3Sounds.xgs");
waveBank = new WaveBank(audioEngine, "Content\\Wave Bank.xwb");
soundBank = new SoundBank(audioEngine, "Content\\Sound Bank.xsb");
// Load streaming wave bank
streamingWaveBank = new WaveBank(audioEngine, "Content\\Music.xwb", 0, 4);
// The audio engine must be updated before the streaming cue is ready
audioEngine.Update();
// Get cue for streaming music
musicCue = soundBank.GetCue("EricJordan_2012_30sec");
// Start the background music
musicCue.Play();
// Load Font
Font1 = Content.Load<SpriteFont>("Courier New");
// Load a 2D texture sprite
ball = new clsSprite(Content.Load<Texture2D>("volt-ball-final"),
new Vector2(winX/2, winY/2), new Vector2(ballD, ballD),
winX, winY);
opponent = new clsSprite(Content.Load<Texture2D>("vt_left_paddle"),
new Vector2(10, winY/2 - padY), new Vector2(padX, padY),
winX, winY);
player = new clsSprite(Content.Load<Texture2D>("vt_right_paddle"),
new Vector2(winX - (10+padX), winY / 2 - padY), new Vector2(padX, padY),
winX, winY);
// Create a SpriteBatch to render the sprite
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
// Set the velocity of the ball sprites will move
ball.velocity = new Vector2(rnd.Next(3,6), rnd.Next(-5, 6));
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// Free the previously allocated resources
ball.texture.Dispose();
opponent.texture.Dispose();
player.texture.Dispose();
spriteBatch.Dispose();
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Get User input
KeyboardState keyboardState = Keyboard.GetState();
// Add chance to the mix
Random rnd = new Random();
// Move ball and get information
int wall = ball.Move();
// Check for kill shot
int[] kill = new int [] { 0, 0 };
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// Check if isDoneed
if (ball.score[(int)Who.Player] >= finalScore) {
victory = "That's pretty neat! You won!";
isDone = true;
}
else if (ball.score[(int)Who.Opponent] >= finalScore) {
victory = "G Dangit! You lost!";
isDone = true;
}
// Move the sprite
if (wall > 0) { // Check if hit wall
switch (wall) {
case 2: // Player Miss
threshold -= 10;
ball.position = new Vector2(winX / 2, winY / 2);
ball.velocity = new Vector2(-rnd.Next(3, 6), rnd.Next(-5, 6));
miss.Play(1f, 1f, 0f);
break;
case 3: // Opponent Miss
threshold += 10;
ball.position = new Vector2(winX / 2, winY / 2);
ball.velocity = new Vector2(rnd.Next(3, 6), rnd.Next(-5, 6));
miss.Play(1f, 1f, 0f);
break;
default:
walls.Play(.50f, .75f, 0f);
break;
}
}
if (!isDone) {
// Change the sprite 2 position using the left thumbstick of the Xbox 360 controller
// Vector2 LeftThumb = GamePad.GetState(PlayerIndex.One).ThumbSticks.Left;
// opponent.position += new Vector2(LeftThumb.X, -LeftThumb.Y) * 5;
// Change the sprite 2 position using the keyboard
if (keyboardState.IsKeyDown(Keys.Up) && player.position.Y > 0) { player.position += new Vector2(0, -5); }
if (keyboardState.IsKeyDown(Keys.Down) && player.position.Y < (winY-player.size.Y)) { player.position += new Vector2(0, 5); }
// Opponent Algorithm
if (ball.position.X < threshold) {
if (opponent.position.Y > ball.position.Y) { opponent.position += new Vector2(0, -5); }
if (opponent.position.Y < ball.position.Y) { opponent.position += new Vector2(0, 5); }
}
// Collision Detection and Handeling
if ((kill[(int)Who.Player] = ball.Collides(player)) > 0 ||
(kill[(int)Who.Opponent] = ball.Collides(opponent)) > 0) {
if (kill[(int)Who.Player] == 2 || kill[(int)Who.Opponent] == 2) { //Kill Shot!
ball.velocity = new Vector2(-ball.velocity.X + (rnd.Next(-10, 10)), ball.velocity.Y + (rnd.Next(-10, 10)));
killshot.Play(1f, 1f, 0f);
}
else
ball.velocity = new Vector2(-ball.velocity.X + (rnd.Next(-2, 2)), ball.velocity.Y + (rnd.Next(-2, 2)));
GamePad.SetVibration(PlayerIndex.One, 1.0f, 1.0f);
walls.Play(1f, 1f, 0f);
}
else
GamePad.SetVibration(PlayerIndex.One, 0f, 0f);
// Update the audio engine
audioEngine.Update();
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// Draw the sprite using Alpha Blend, which uses transparency information if available
// In 4.0, this behavior is the default; in XNA 3.1, it is not
spriteBatch.Begin();
if (!isDone) {
// Write Scores
spriteBatch.DrawString(Font1, "Opponent: " + ball.score[(int)Who.Opponent], new Vector2(5, 10), Color.Green);
spriteBatch.DrawString(Font1, "Player: " + ball.score[(int)Who.Player], new Vector2(winX - Font1.MeasureString("Player: " + ball.score[0]).X - 5, 10), Color.Green);
spriteBatch.DrawString(Font1, "Vel: ( " + ball.velocity.X + ", " + ball.velocity.Y + " ) Threshold: " + threshold, new Vector2(5, winY - Font1.LineSpacing), Color.Green);
// Draw physical objects
ball.Draw(spriteBatch);
opponent.Draw(spriteBatch);
player.Draw(spriteBatch);
}
else {
FontPos = new Vector2((winX / 2) - 400, (winY / 2) - 50);
spriteBatch.DrawString(Font1, victory, FontPos, Color.Green);
ball.score[0] = ball.score[1] = 0;
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| 0a71bd2ffe0c6cda29eaecd8cf8f7fdb349c979b | [
"Markdown",
"C#"
] | 3 | Markdown | pevargas/8-Bit-Rhino | 5307eaa74795f26e2ee976782d77f61b734e0ec0 | 479b7446c9b71f33a855168ed5b127055ef7a43c |
refs/heads/master | <file_sep>package B1_NgonNguLapTrinhJava.BaiTap;
import java.util.Scanner;
public class HienThiCacLoaiHinh {
public static void main(String[] args) {
Menu();
}
private static void Menu(){
int choise=-1;
Scanner scanner= new Scanner(System.in);
while (choise!=0){
System.out.println("Menu" +
"\n1.Print the rectangle" +
"\n2.Print the square triangle (The corner is square at 4 different angles: top-left, top-right, botton-left, botton-right)" +
"\n3.Print isosceles triangle" +
"\n4.Exit");
choise=scanner.nextInt();
switch (choise){
case 1:
PrinTheRectangle();
break;
case 2:
PrintTheSquareTriangle();
break;
case 3:
PrintIsoscelesTriangle();
break;
case 4:
System.exit(4);
break;
default:
System.out.println("choose again !!!");
}
}
}
private static void PrinTheRectangle(){
int height, width;
String PrinTheRectangle;
Scanner input = new Scanner(System.in);
System.out.println("Enter the height of the rectangle: ");
height= input.nextInt();
System.out.println("Enter the width of the rectangle: ");
width=input.nextInt();
for(int i=1;i<=height;i++){
for (int j=0;j<=width;j++){
System.out.print("* ");
}
System.out.println();
}
input.nextLine();
input.nextLine();
}
private static void PrintTheSquareTriangle(){
Scanner scanner=new Scanner(System.in);
int choise=-1;
while (choise!=5){
System.out.println("Print the square triangle" +
"\nThe corner is square at 4 different angles:" +
"\n1.top-left" +
"\n2.top-right" +
"\n3.botton-left" +
"\n4.botton-right" +
"\n5.Bach to menu");
choise=scanner.nextInt();
switch (choise){
case 1:
PrintTheSquareTriangleTopLeft();
break;
case 2:
PrintTheSquareTriangleTopRight();
break;
case 3:
PrintTheSquareTriangleBottonLeft();
break;
case 4:
PrintTheSquareTriangleBottonRight();
break;
case 5:
Menu();
default:
System.out.println("choose again !!!");
}
}
}
private static void PrintTheSquareTriangleTopLeft(){
Scanner input=new Scanner(System.in);
int height,width;
System.out.println("Enter height of square triangle");
height=input.nextInt();
int run=height;
for (int i=0;i<height;i++){
for (int j=0;j<run;j++){
System.out.print("* ");
}
run--;
System.out.println();
}
input.nextLine();
input.nextLine();
}
private static void PrintTheSquareTriangleBottonLeft(){
Scanner input=new Scanner(System.in);
int height,width;
System.out.println("Enter height of square triangle");
height=input.nextInt();
int run =1;
for (int i=0;i<height;i++){
for (int j=0;j<run;j++){
System.out.print("* ");
}
run++;
System.out.println();
}
input.nextLine();
input.nextLine();
}
private static void PrintTheSquareTriangleTopRight(){
Scanner input=new Scanner(System.in);
int height,width;
System.out.println("Enter height of square triangle");
height=input.nextInt();
int run=height;
int space=0;
for (int i=0;i<height;i++){
for (int a=0;a<space;a++){
System.out.print(" ");
}
for (int j=0;j<run;j++){
System.out.print("* ");
}
run--;
space++;
System.out.println();
}
input.nextLine();
input.nextLine();
}
private static void PrintTheSquareTriangleBottonRight() {
Scanner input = new Scanner(System.in);
int height, width;
System.out.println("Enter height of square triangle");
height = input.nextInt();
int run = 1;
int space = height-run;
for (int i = 0; i < height; i++) {
for (int a = 0; a < space; a++) {
System.out.print(" ");
}
for (int j = 0; j < run; j++) {
System.out.print("* ");
}
run++;
space--;
System.out.println();
}
input.nextLine();
input.nextLine();
}
private static void PrintIsoscelesTriangle(){
Scanner input = new Scanner(System.in);
int height, width;
System.out.println("Enter height of square triangle");
height = input.nextInt();
width=height*2;
int run = 1;
int space = height-1;
for (int i = 0; i < height; i++) {
for (int a = 0; a < space; a++) {
System.out.print(" ");
}
for (int j = 0; j < run; j++) {
System.out.print("* ");
}
run=run+2;
space--;
System.out.println();
}
input.nextLine();
input.nextLine();
}
}
<file_sep>package B2_MangVaPhuongThucTrongJava.BaiTap;
import java.util.Random;
import java.util.Scanner;
public class TimPhanTuLonNhatTrongMangHaiChieu {
public static void main(String[] args) {
int[][] array= createTwoDimensionalArray();
displayTwoDimensionalArray(array);
System.out.println("Max of the Two Dimensional Array :"+searchElementOfTwoDimensionalArray(array));
}
public static int[][] createTwoDimensionalArray(){
int column;
int row;
Scanner scanner= new Scanner(System.in);
Random rd = new Random();
System.out.print("Enter the number column of array : ");
column=scanner.nextInt();
System.out.print("Enter the number row of array: ");
row= scanner.nextInt();
int[][] array = new int[row][column];
for (int i=0;i<array.length;i++){
for (int j=0; j< array[0].length;j++){
array[i][j]=rd.nextInt(1000);
}
}
return array;
}
public static int searchElementOfTwoDimensionalArray(int[][] array){
int max=0;
for (int[] ints : array) {
for (int j = 0; j < array[0].length; j++) {
if (ints[j] > max) {
max = ints[j];
}
}
}
return max;
}
public static void displayTwoDimensionalArray(int[][] array){
for (int i=0;i<array.length;i++){
for (int j=0; j< array[0].length;j++){
System.out.print(array[i][j]+"\t");
}
System.out.println();
}
}
}
<file_sep>package B1_NgonNguLapTrinhJava.BaiTap;
import java.util.Scanner;
public class DocSoThanhChu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number: ");
int a =scanner.nextInt();
String read;
if(a<=9){
read=OneToNine(a);
System.out.println(read);
}if(9<a && 20>a){
TenToNineteen(a);
}if(20<a && 100>a){
read=TwentyToNinetynine(a);
System.out.println(read);
}if(100<=a && 1000>a){
read=OneHundredToNineHundredNinetyNine(a);
System.out.println(read);
}
}
private static String OneToNine(int a){
String one_digit="";
switch (a){
case 0:
one_digit="zero";
break;
case 1:
one_digit="one";
break;
case 2:
one_digit="two";
break;
case 3:
one_digit="three";
break;
case 4:
one_digit="four";
break;
case 5:
one_digit="five";
break;
case 6:
one_digit="six";
break;
case 7:
one_digit="seven";
break;
case 8:
one_digit="eight";
break;
case 9:
one_digit="nine";
break;
}
return one_digit;
}
private static String TenToNineteen(int a){
String ReadTenToNineteen="";
switch (a){
case 10:
ReadTenToNineteen="ten";
break;
case 11:
ReadTenToNineteen="eleven";
break;
case 12:
ReadTenToNineteen="twelve";
break;
case 13:
ReadTenToNineteen="thirteen";
break;
case 14:
ReadTenToNineteen="fourteen";
break;
case 15:
ReadTenToNineteen="fifteen";
break;
case 16:
ReadTenToNineteen="sixteen";
break;
case 17:
ReadTenToNineteen="seventeen";
break;
case 18:
ReadTenToNineteen="eighteen";
break;
case 19:
ReadTenToNineteen="nineteen";
break;
}
return ReadTenToNineteen;
}
private static String TwentyToNinetynine(int a){
int b=a%10;
int c=a-b;
String ReadTwentyToninetynine="";
String dozens="";
String row_unit="";
switch (c){
case 20:
dozens="twenty";
break;
case 30:
dozens="thirty";
break;
case 40:
dozens="forty";
break;
case 50:
dozens="fifty";
break;
case 60:
dozens="sixty";
break;
case 70:
dozens="seventy";
break;
case 80:
dozens="eighty";
break;
case 90:
dozens="ninety";
break;
}
row_unit=OneToNine(b);
if(b==0){
ReadTwentyToninetynine=dozens;
}else {
ReadTwentyToninetynine=dozens+" "+row_unit;
}
return ReadTwentyToninetynine;
}
private static String OneHundredToNineHundredNinetyNine(int a){
String ReadOneHundredToNineHundredNinetyNine="";
String hundred="";
String dozens="";
int b=a%100;
int c=a-b;
switch (c){
case 100:
hundred="one hundred";
break;
case 200:
hundred="two hundred";
break;
case 300:
hundred="three hundred";
break;
case 400:
hundred="four hundred";
break;
case 500:
hundred="five hundred";
break;
case 600:
hundred="six hundred";
break;
case 700:
hundred="seven hundred";
break;
case 800:
hundred="eight hundred";
break;
case 900:
hundred="nine hundred";
break;
}
dozens=TwentyToNinetynine(b);
ReadOneHundredToNineHundredNinetyNine=hundred+" "+dozens;
return ReadOneHundredToNineHundredNinetyNine;
}
}
<file_sep>package B2_MangVaPhuongThucTrongJava.BaiTap;
import java.util.Scanner;
public class GopMang {
public static void main(String[] args) {
int[] array1;
int[] array2;
System.out.println("Create");
}
public int[] creatArray(){
Scanner scanner= new Scanner(System.in);
int side=-1;
while (!(side>0 && side<20)){
System.out.print("Enter the side of array: ");
side=scanner.nextInt();
if(!(side>0 && side<20)){
System.out.println("the side fail!!!.Please enter the side");
}
}
int[] array=new int[side];
for (int element:array) {
element=scanner.nextInt();
}
return array;
}
}
<file_sep>package B4_KeThua.BaiTap.LopPointVaLopMoveablePoint;
public class MoveablePoint extends Point {
private float xSpeed=0.0f;
private float ySpeed=0.0f;
public MoveablePoint() {
}
public MoveablePoint(float xSpeed, float ySpeed) {
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}
public MoveablePoint(float x, float y, float xSpeed, float ySpeed) {
super(x, y);
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}
public float getxSpeed() {
return xSpeed;
}
public void setxSpeed(float xSpeed) {
this.xSpeed = xSpeed;
}
public float getySpeed() {
return ySpeed;
}
public void setySpeed(float ySpeed) {
this.ySpeed = ySpeed;
}
public void setSpeed(float xSpeed,float ySpeed){
setxSpeed(xSpeed);
setySpeed(ySpeed);
}
public float[] getSpeed(){
float[] array=new float[2];
array[0]=xSpeed;
array[1]=ySpeed;
return array;
}
@Override
public String toString() {
return "Speed: "+getSpeed()[0]+" "+getSpeed()[1];
}
public MoveablePoint move(MoveablePoint moveablePoint) {
moveablePoint.setX(super.getX()+this.getxSpeed());
moveablePoint.setY(super.getY() + this.getySpeed());
return moveablePoint;
}
}
<file_sep>package B1_NgonNguLapTrinhJava.BaiTap;
import static B1_NgonNguLapTrinhJava.BaiTap.HienThiCacSoNguyenToNhoHon100.IsThePrime;
public class HienThi20SoNguyenToDauTien {
public static void main(String[] args) {
int count=0;
int number=2;
while (count!=20){
if(IsThePrime(number)){
count++;
System.out.println(count+"."+number);
}
number++;
}
}
}
<file_sep>package B4_KeThua.BaiTap.LopCircleVaLopCylinder;
public class Cylinder extends Circle{
private double height;
public Cylinder() {
}
public Cylinder(double height) {
this.height = height;
}
public Cylinder(String color, double radius, double height) {
super(color, radius);
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
@Override
public double getArea() {
return getRadius()*2*3.14*height;
}
public double getVolume(){
return getRadius()*getRadius()*3.14*height;
}
@Override
public String toString() {
return "Cylinder{" +
"height=" + height +
"radius"+getRadius()+
"color"+getColor()+
'}';
}
}
<file_sep>package B1_NgonNguLapTrinhJava.BaiTap;
public class HienThiCacSoNguyenToNhoHon100 {
public static void main(String[] args) {
for (int number=2;number<100;number++){
if (IsThePrime(number)){
System.out.println(number);
}
}
}
public static boolean IsThePrime(int a){
boolean is_the_prime=false;
if(a<=2){
if(a<2){
is_the_prime=false;
}
if(a==2){
is_the_prime=true;
}
}else {
for (int i=2;i<a;i++){
if(a%i==0){
is_the_prime=false;
break;
}else {
is_the_prime=true;
}
}
}
return is_the_prime;
}
}
<file_sep>package B3_LopVaDoiTuongTrongJava.ThucHanh;
import java.util.Scanner;
public class Rectangle {
double width,height;
public Rectangle() {
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea(){
return this.width*this.height;
}
public double getPerimeter(){
return (this.width+this.height)*2;
}
public String display(){
return "Rectangle have :" +
"\nwidth: " + this.width+
"\nheight: " + this.height+
"\narea: "+ this.getArea()+
"\nperimeter: "+ this.getPerimeter();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the width:");
double width = scanner.nextDouble();
System.out.print("Enter the height:");
double height = scanner.nextDouble();
Rectangle rectangle=new Rectangle(width,height);
System.out.println(rectangle.display());
}
}
<file_sep>package B4_KeThua.BaiTap.LopPoint2dVaPoint3d;
public class Test {
public static void main(String[] args) {
Point2D point2D=new Point2D((float) 4.7,(float) 3.8);
System.out.println(point2D);
Point3D point3D=new Point3D(3.2f,4.6f,5.5f);
System.out.println(point3D);
}
}
| ef285ceea827937d0ab84bee3b6c835215a83503 | [
"Java"
] | 10 | Java | naki2204/Module2_javaCore | 4b8535b784495836a1140db42060f4da165f9edc | f88b87710f127d56d74a5cc8b7fdde3fab061c8d |
refs/heads/master | <file_sep># from selenium import webdriver
# import unittest
# class TestDr(unittest.TestCase):
# def SetUp(self):
# self.driver=webdriver.Firefox()
#
# self.driver.get('http://192.168.72.48/iwebshop/')
# self.driver.maximize_window()
# self.driver.implicitly_wait(30)
# def test_login(self):
# self.driver.find_element_by_link_text('登录').click()
# self.driver.find_element_by_css_selector('[type="text"]').send_keys('admin')
# self.driver.find_element_by_css_selector('[type="password"]').send_keys('<PASSWORD>')
# self.driver.find_element_by_link_text('登录').click()
# self.driver.find_element_by_link_text('安全退出').click()
# def tearDown(self):
# self.driver.quit()
# if __name__ == '__main__':
# unittest.main()
<file_sep>[pytest]
addopts = -s --alluredir report
python_files = test*.py
python_classes = Test*
python_functions = test_* | 317cb38704da4318adc4ea2035b5f095b287aafc | [
"Python",
"INI"
] | 2 | Python | whoDawn/test_03 | 6d5ef218803e00a00e9c1a835a3582f89b021373 | 9ccf102f85682a28c946f4f0c40387971961475d |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Configuration;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace lab1
{
public static class Shingles
{
private const int HashCount = 84;
private const int HashGroupCount = 14;
private static List<char> _stop_symbols = new List<char>()
{ '.', ',', '!', '?', ':', ';', '-', '\n', '\r', '(', ')', '\'' };
private static List<string> _stop_words = new List<string>(){"это", "как", "так",
"и", "в", "над",
"к", "до", "не",
"на", "но", "за",
"то", "с", "ли",
"а", "во", "от",
"со", "для", "о",
"же", "ну", "вы",
"бы", "что", "кто",
"он", "она"};
private static List<Func<string, uint>> _84AvasomeFunctions;
static Shingles()
{
GenerateFunctions();
}
private static void GenerateFunctions()
{
_84AvasomeFunctions = new List<Func<string, uint>>();
var r = new Random();
for (int i = 0; i < 84; i++)
{
int b = r.Next(5, 20);
int simple = r.Next(b+1, b*2);
var function = new Func<string, uint>(s => (uint) s.Select((t, j) =>
{
return (t*((uint) Math.Pow(b, j)%simple)%simple);
}).Sum());
_84AvasomeFunctions.Add(function);
}
}
public static List<string> Canonize(string text)
{
List<string> list = text.ToLower().Split(' ').ToList();
list.ForEach(x => x.Trim(_stop_symbols.ToArray()));
list.RemoveAll(x => _stop_words.Contains(x));
return list;
}
public static List<string> GetShingle(List<string> text, uint length)
{
var ret = new List<string>();
for (int i = 0; i < text.Count-length; i++)
{
string mid = "";
for (int j = i; j < i+length; j++)
mid += text[j];
ret.Add(mid);
}
return ret;
}
public static List<uint> GetHash(List<string> text)
{
var result = new List<uint>();
for (var i = 0; i < HashCount; i++)
{
result.Add(uint.MaxValue);
}
foreach (var shingle in text)
{
for (int i = 0; i < _84AvasomeFunctions.Count; i++)
{
var hash = _84AvasomeFunctions[i](shingle);
if (result[i] > hash)
result[i] = hash;
}
}
//result.Sort((x, y) =>
//{
// if (x > y) return 1;
// if (x < y) return -1;
// return 0;
//});
return result;
}
public static float Compare(List<uint> shingles1, List<uint> shingles2)
{
uint count = 0;
var realcount = Math.Max(shingles1.FindIndex(x => x == uint.MaxValue),
shingles2.FindIndex(x => x == uint.MaxValue));
for (int i = 0; i < HashCount; i++)
{
//if (shingles1.Contains(shingles2[i]))
if(shingles1[i]==shingles2[i])
count++;
}
if (realcount == -1)
realcount = HashCount;
return (float)count/realcount;
}
public static List<KeyValuePair<int, int>> SuperMap()
{
var map = new List<KeyValuePair<int, int>>();
for (int i = 0; i < HashCount; i++)
{
map.Add(new KeyValuePair<int, int>());
}
var list = new List<int>();
var r = new Random();
for (int i = 0; i < HashGroupCount; i++)
{
for (int j = 0; j < HashCount/HashGroupCount; j++)
{
int k = r.Next(0, (HashCount - 1));
while (list.Contains(k))
k = r.Next(0, HashCount);
list.Add(k);
map[k] = new KeyValuePair<int, int>(i,j);
}
}
return map;
}
public static List<List<uint>> GetSuperHash(List<KeyValuePair<int, int>> map, List<uint> hash )
{
var ret = new List<List<uint>>();
for (int i = 0; i < HashGroupCount; i++)
{
ret.Add(new List<uint>());
for (int j = 0; j < HashCount/HashGroupCount; j++)
{
ret[i].Add(0);
}
}
for (int i = 0; i < HashCount; i++)
{
ret[map[i].Key][map[i].Value] = hash[i];
}
return ret;
}
public static float CompareSuper(List<List<uint>> shingles1, List<List<uint>> shingles2)
{
uint count = 0;
for (int i = 0; i < HashGroupCount; i++)
{
bool res = true;
for (int j = 0; j < HashCount/HashGroupCount; j++)
{
var r1 = shingles1[i][j];
var r2 = shingles2[i][j];
if (shingles1[i][j] != shingles2[i][j])
//if (shingles1[i].Contains(shingles2[i][j]))
{
res = false;
break;
}
}
if (res)
count++;
}
return (float) count/HashGroupCount;
}
public static List<KeyValuePair<int, int>> GetMegaHash()
{
var map = new List<KeyValuePair<int, int>>();
for (int i = 0; i < HashGroupCount; i++)
{
for (int j = i+1; j < HashGroupCount; j++)
{
map.Add(new KeyValuePair<int, int>(i,j));
}
}
return map;
}
public static List<List<uint>> GetMegaHash(List<KeyValuePair<int, int>> map, List<List<uint>> super)
{
var ret = new List<List<uint>>();
foreach (var pair in map)
{
var list = new List<uint>(super[pair.Key]);
list.AddRange(super[pair.Value]);
ret.Add(list);
}
return ret;
}
public static float CompareMega(List<List<uint>> shingles1, List<List<uint>> shingles2)
{
uint count = 0;
for (int i = 0; i < HashGroupCount; i++)
{
bool res = true;
for (int j = 0; j < shingles1[i].Count; j++)
{
if (shingles1[i][j] != shingles2[i][j])
//if (shingles1[i].Contains(shingles2[i][j]))
res = false;
}
if (res)
count++;
}
return (float)count / shingles1.Count;
}
}
}
<file_sep>#!/usr/bin/env python
#-*- coding: utf-8 -*-
from __future__ import division
from collections import defaultdict
from math import log
import os
def prepare(filename):
stop_symbols = '.,!?:;-\n\r()0123456789'
with open(filename) as f:
tokens = f.read().split()
c = filename[6]
results = [t.strip(stop_symbols) for t in tokens if t.decode('utf8')[0].isupper()]
results = [t for t in results if len(t.decode('utf8'))>2]
return results, c
def tokens(filename):
stop_symbols = '.,!?:;-\n\r()0123456789'
with open(filename) as f:
tokens = f.read().split()
results = [t.strip(stop_symbols) for t in tokens if t.decode('utf8')[0].isupper()]
results = [t for t in results if len(t.decode('utf8'))>2]
return results
def tmpfile(filename, data, c):
f = open(filename, 'a')
for d in data:
f.write('{0} {1}\n'.format(d, c))
def train(samples):
classes, freq = defaultdict(lambda:0), defaultdict(lambda:0)
for feats, label in samples:
classes[label] += 1
freq[label, feats] += 1
for label, feat in freq:
freq[label, feat] /= classes[label]
for c in classes:
classes[c] /= len(samples)
return classes, freq
def process(f1, f2):
r, c = prepare(f1)
tmpfile(f2, r,c)
def classify_b(classifier, feats):
classes, prob = classifier
rescl = 0;
ressum = 1000;
for cl in classes:
s = 0
count1=0
count3=0
for l, f in prob:
if l is cl:
count3+=1
if f.encode('utf8') in feats:
s += log(prob[cl,f])
count1 +=1
else:
s += log(1-prob[cl,f])
print cl, s, count1
if s < ressum:
ressum = s
rescl = cl
print rescl
def classify_m(classifier, feats):
classes, prob = classifier
rescl = 0;
ressum = 1000;
for cl in classes:
s = 0
count1=0
count3=0
for f in feats:
if not prob[cl , f.decode('utf8')] is 0:
s += log(prob[cl,f.decode('utf8')])
count1 +=1
print cl, s, count1
if s < ressum:
ressum = s
rescl = cl
print rescl
def get_features(sample): return (sample[-1],) # get last letter
process('train/p1.txt', 'tmp.txt')
process('train/p2.txt', 'tmp.txt')
process('train/p3.txt', 'tmp.txt')
process('train/r1.txt', 'tmp.txt')
process('train/r2.txt', 'tmp.txt')
process('train/r3.txt', 'tmp.txt')
process('train/r4.txt', 'tmp.txt')
samples = (line.decode('utf-8').split() for line in open('tmp.txt'))
features = [(feat, label) for feat, label in samples]
classifier = train(features)
t = tokens('test1.txt')
#t = tokens('train/p1.txt')
classify_b(classifier, t)
classify_m(classifier, t)
os.remove('tmp.txt')
#print 'gender: ', classify(classifier, get_features(u'ыва'))
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lab1
{
class Program
{
static void Main(string[] args)
{
var file1 = new StreamReader("../../Data/1.txt",Encoding.Default);
var file2 = new StreamReader("../../Data/3.txt", Encoding.Default);
string text1 = file1.ReadToEnd();
string text2 = file2.ReadToEnd();
uint lenght = 10;
var shin1 = Shingles.GetShingle(Shingles.Canonize(text1), lenght);
var shin2 = Shingles.GetShingle(Shingles.Canonize(text2), lenght);
var hash1 = Shingles.GetHash(shin1);
var hash2 = Shingles.GetHash(shin2);
var result = Shingles.Compare(hash1, hash2);
Console.WriteLine("common = {0}%\n", result * 100);
var map = Shingles.SuperMap();
var shash1 = Shingles.GetSuperHash(map, hash1);
var shash2 = Shingles.GetSuperHash(map, hash2);
var result2 = Shingles.CompareSuper(shash1, shash2);
Console.WriteLine("super = {0}%\n", result2 * 100);
var map2 = Shingles.GetMegaHash();
var mhash1 = Shingles.GetMegaHash(map2, shash1);
var mhash2 = Shingles.GetMegaHash(map2, shash2);
var result3 = Shingles.CompareMega(mhash1, mhash2);
Console.WriteLine("mega = {0}%\n", result2 * 100);
Console.ReadLine();
}
}
}
| fa734b0fc7ea6ba5643cd63d03a178deb4825a01 | [
"C#",
"Python"
] | 3 | C# | nmenshov/shingles | f2d65c8f48da2e4427e507bf189dae9849965480 | b41dc22f341e29023a576e083bb9e1ef54474d9f |
refs/heads/main | <repo_name>ducvuongg61/Demo_CodeGym<file_sep>/demosecurity/src/main/java/codegym/vn/demosecurity/service/UserServiceImpl.java
package codegym.vn.demosecurity.service;
import codegym.vn.demosecurity.entities.Account;
import codegym.vn.demosecurity.repository.AccountRepository;
import codegym.vn.demosecurity.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
AccountRepository accountRepository;
@Autowired
RoleRepository roleRepository;
@Override
public UserDetails loadUserByUsername(String accountName) throws UsernameNotFoundException {
// get user trong database ra
Account account = accountRepository.getAccountsByAccountName(accountName);
if (account == null) {
throw new UsernameNotFoundException("User " + accountName + " was not found");
}
// Lấy các quyền của user trong database
List<String> roles = roleRepository.getRolesName(accountName);
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
if (roles != null) {
// Chuyển các quyền từ kiểu String sang kiểu GrantedAuthority của Spring Security
for (String role: roles) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role);
grantedAuthorities.add(grantedAuthority);
}
}
// Tạo User theo cách của Spring Security
UserDetails userDetails = new User(account.getAccountName(), account.getPassword(),
grantedAuthorities);
return userDetails;
}
}
<file_sep>/springboot/src/main/java/codegym/restcontroller/UserRestController.java
package codegym.restcontroller;
import codegym.entity.User;
import codegym.service.iml.UserServiceImpl2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/user")
public class UserRestController {
@Autowired
UserServiceImpl2 service;
@RequestMapping(value = "/list",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> getList() {
return service.getListUser();
}
@RequestMapping(value = "/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Object getUserById(@PathVariable int id) {
User user = service.getUser(id);
if (user == null) {
return "Not found";
}
return user;
}
@RequestMapping(value = "/create",
method = RequestMethod.POST)
@ResponseBody
public String createUser(@RequestBody User user) {
service.saveUser(user);
return "Save user success";
}
@RequestMapping(value = "/update",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String updateUser(@RequestBody User user) {
service.editUser(user);
return "Edit user success";
}
@RequestMapping(value = "/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String deleteUser(@PathVariable int id) {
User user = service.getUser(id);
service.deleteUser(user);
return "Delete user success";
}
@RequestMapping(value = "/searchByName",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<User> deleteUser(@RequestParam String name) {
List<User> users = service.getListUserByName(name);
return users;
}
}
<file_sep>/springboot/src/main/java/codegym/entity/User.java
package codegym.entity;
import javax.persistence.*;
import javax.validation.constraints.*;
@Entity
@NamedQueries({
@NamedQuery(name="findCustomerByAge", query = "select u from User u where u.age = ?1"),
@NamedQuery(name="findCustomerByName", query = "select u from User u where u.name like :name"),
})
public class User {
@Id
@GeneratedValue
private int id;
@NotEmpty(message = "{name.empty}")
@Size(min = 4, max = 20, message = "{name.length}")
private String name;
// @Min(value = 18, message = "Tuổi phải lớn hơn hoặc bằng 18")
// @Max(value = 65, message = "Tuổi phải nhỏ hơn hoặc bằng 65")
private int age;
@NotBlank(message = "{address.empty}")
private String address;
public User() {
}
public User(int id, String name, int age, String address) {
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
<file_sep>/springboot/src/main/java/codegym/service/iml/UserServiceImpl2.java
package codegym.service.iml;
import codegym.entity.User;
import codegym.repository.UserRepository2;
import codegym.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl2 implements UserService {
private UserRepository2 userRepository2;
@Autowired
public UserServiceImpl2(UserRepository2 userRepository2) {
this.userRepository2 = userRepository2;
}
@Override
public User getUser(int id) {
return userRepository2.findById(id).orElse(null);
}
@Override
public List<User> getListUser() {
System.out.println("Get list user");
List<User> users = new ArrayList<>();
userRepository2.findAll().forEach(users::add);
return users;
}
@Override
public void saveUser(User user) {
userRepository2.save(user);
}
@Override
public void editUser(User user) {
userRepository2.save(user);
}
@Override
public void deleteUser(User user) {
userRepository2.delete(user);
}
@Override
public void saveOrEdit(User user) {
userRepository2.save(user);
}
@Override
public List<User> getListUserByName(String name) {
return userRepository2.findUsersByNameContaining(name);
}
@Override
public List<User> getListUserByAge(int age) {
return userRepository2.findUsersByAge(age);
}
}
<file_sep>/application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/orm?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username=linhtran
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update<file_sep>/springboot/src/main/java/codegym/aspect/LoggingAspect.java
package codegym.aspect;
import codegym.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.logging.Logger;
@Component
@Aspect
public class LoggingAspect {
private Logger logger = Logger.getLogger(LoggingAspect.class.getName());
@Pointcut("execution(* codegym.service.iml.UserServiceImpl2.*(..))")
public void serviceMethods() {};
@Around("serviceMethods()")
public Object logMethodCall(ProceedingJoinPoint jp) throws Throwable {
String methodName = jp.getSignature().getName();
logger.info("Start: " + jp.getSignature().toShortString() + "-" + methodName);
Object o = jp.proceed();
logger.info("End: " + jp.getSignature().toShortString());
return o;
}
}
<file_sep>/demosecurity/src/main/java/codegym/vn/demosecurity/entities/Account.java
package codegym.vn.demosecurity.entities;
import javax.persistence.*;
@Entity
@Table (name = "account")
public class Account {
@Id
@GeneratedValue
@Column(name = "account_id")
private Long id;
@Column(name = "account_name", nullable = false, unique = true)
private String accountName;
@Column(name = "password", length = 128, nullable = false)
private String password;
public Account() {
}
public Account(Long id, String accountName, String password) {
this.id = id;
this.accountName = accountName;
this.password = <PASSWORD>;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<file_sep>/springboot/src/main/java/codegym/validator/AgeCustomValidation.java
package codegym.validator;
import codegym.entity.User;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class AgeCustomValidation implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
User user = (User) target;
if (user.getAge() < 18 || user.getAge() > 65) {
// ValidationUtils.rejectIfEmpty(errors, "age", "age.numberLessThan18");
errors.rejectValue("age", "age.numberLessThan18", new Object[]{18, 65}, "Tuổi lớn hơn 18");
}
}
}
<file_sep>/springboot/src/main/resources/static/js/create.js
function saveUser() {
const user = {
id : $("#id").val(),
name: $("#name").val(),
age: $("#age").val(),
address: $("#address").val()
};
$.ajax({
url: "/api/user/create",
type: "post",
contentType: "application/json",
data: JSON.stringify(user),
success: function(data) {
alert(data);
}
});
}<file_sep>/springboot/src/main/java/codegym/service/iml/UserServiceImpl.java
package codegym.service.iml;
import codegym.entity.User;
import codegym.repository.UserRepository;
import codegym.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserRepository userRepository;
@Override
public User getUser(int id) {
return userRepository.getUser(id);
}
@Override
public List<User> getListUser() {
return userRepository.getListUser();
}
@Override
public void saveUser(User user) {
userRepository.saveUser(user);
}
@Override
public void editUser(User user) {
userRepository.editUser(user);
}
@Override
public void deleteUser(User user) {
userRepository.deleteUser(user);
}
@Override
public void saveOrEdit(User user) {
userRepository.saveOrEdit(user);
}
@Override
public List<User> getListUserByName(String name) {
return userRepository.getListUserByName(name);
}
@Override
public List<User> getListUserByAge(int age) {
return userRepository.getListUserByAge(age);
}
}
<file_sep>/springboot/src/main/resources/static/js/list.js
function searchByName() {
const name = $("#name").val();
$.ajax({
url: "/api/user/searchByName",
type: "get",
data: {
name : name
},
success: function(data) {
// alert(JSON.stringify(data));
var result =
`<tr>
<th>No</th>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Detail</th>
<th>Edit</th>
<th>Delete</th>
</tr>`;
for (var i = 0; i < data.length; i++) {
result +=
`<tr>
<td>${i + 1}</td>
<td>${data[i].id}</td>
<td>${data[i].name}</td>
<td>${data[i].age}</td>
<td>${data[i].address}</td>
<td><a href="/user/detail/${data[i].id}">Detail</a></td>
<td><a href="/user/edit/${data[i].id}">Edit</a></td>
<td><a href="/user/delete/${data[i].id}">Delete</a></td>
</tr>`
}
$("#result").html(result);
}
});
}<file_sep>/demosecurity/src/main/resources/application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/demosecurity?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username=linhtran
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
| c9979bea5fbc769aa5441dc667d5378bdfbd4a52 | [
"JavaScript",
"Java",
"INI"
] | 12 | Java | ducvuongg61/Demo_CodeGym | 6eddf369d3886356e298921ab16c93d0088b94e2 | ba3fdc40d4453d362565b77d295f3909c496b820 |
refs/heads/master | <repo_name>Michai329/OOP3200-F2020-ICE7<file_sep>/src/ca/durhamcollege/Main.java
package ca.durhamcollege;
public class Main {
public static void main(String[] args)
{
Person person = new Person("Michai", 21);
person.saysHello();
}
}
| 575a5b6bb427a0bbd4b157b82a8cb405e6f807a1 | [
"Java"
] | 1 | Java | Michai329/OOP3200-F2020-ICE7 | b7b18e6352c51fd6d64bc8826ec31dbefe79f390 | ba2bbbfae90a3c481d646c2f149c69e33b3ddf5b |
refs/heads/master | <file_sep>## Update the git version
sudo add-apt-repository ppa:git-core/ppa -y
sudo apt-get update
sudo apt-get install git -y
git --version
## Latest GCC Compiler:
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 50
| 526dff24efb52680d28a154915b593bfab7ecc44 | [
"Shell"
] | 1 | Shell | softctrl/ubuntu-development | efe391b790372319b15eead705bee74ffec94a49 | 7705b0930ef6f5fb36170fc30ff1acdc739d6756 |
refs/heads/master | <file_sep>class MCollective::Application::Migrate<MCollective::Application
description "Migrates an agent from one master to another"
option :to_fqdn,
:description => "Puppet Master FQDN to direct the agent to",
:arguments => ["-f", "--to_fqdn TO_FQDN"],
:required => true,
:type => String
option :to_ip,
:description => "Puppet Master IP Address to direct the agent to",
:arguments => ["-i", "--to_ip TO_IP"],
:required => true,
:type => String
#TODO: accept a purge? parameter, and optionally execute the purge for them.
# the puppet node purge commadn will not be accessible (root access) but puppetdb will be. Is that enough?
def colorize(text, color_code)
"\e[#{color_code}m#{text}\e[0m"
end
def red(text); colorize(text, 31); end
def green(text); colorize(text, 32); end
def white(text); colorize(text, 37); end
def main
mc = rpcclient("migrate")
purge_commands=[]
mc.puppet_agent(
:to_fqdn => configuration[:to_fqdn],
:to_ip => configuration[:to_ip],
:options => options) do |resp, simpleresp|
sender = simpleresp[:sender]
statusmsg = resp[:body][:statusmsg]
statuscode = resp[:body][:statuscode]
if statuscode == 0
printf("\n%-40s migration result: %s\n", sender, green(simpleresp[:data][:exitstatus]))
purge_commands << "puppet node purge #{sender}"
elsif statuscode == 1
printf("\n%-40s migration result: %s\n", sender, red(simpleresp[:data][:exitstatus]))
puts "The migrate agent returned an error: #{simpleresp[:data][:error]}"
puts "Commands ran with results:"
simpleresp[:data][:command_list].each do |cmd_result|
puts cmd_result
end
else
printf("\n%-40s migration result: %s\n", sender, red(simpleresp[:data][:exitstatus]))
puts red(" - returned status code =#{statuscode}")
puts red(" - Error: #{statusmsg}")
end
end
puts("Copy the commands below to purge certs from this puppet master:")
puts(" -- don't forget to run with sudo or as root --")
purge_commands.each do |cmd|
puts(white(cmd))
end
puts "\n"
puts "Sign your certs here:"
puts white("https://#{configuration[:to_fqdn]}/#/node_groups/inventory/nodes/certificates")
printrpcstats
halt mc.stats
end
end
# example simpleresp hash:
# {:msgtarget=>"/topic/mcollective.helloworld.reply",
# :senderid=>"dev2.your.net",
# :msgtime=>1261696663,
# :hash=>"2d37daf690c4bcef5b5380b1e0c55f0c",
# :body=>{:statusmsg=>"OK", :statuscode=>0, :data=>{:msg => "hello world"}},
# :requestid=>"2884afb0b52cb38ea4d4a3146d18ef5f",
# :senderagent=>"helloworld"}
<file_sep>module MCollective
module Agent
class Migrate<RPC::Agent
require 'date'
action 'agent_from_3_to_4' do
to_fqdn = request[:to_fqdn]
to_ip = request[:to_ip]
run_reinstall_migration(to_fqdn, to_ip)
end
action 'puppet_agent' do
to_fqdn = request[:to_fqdn]
to_ip = request[:to_ip]
run_migration(to_fqdn, to_ip)
end
action 'test_activation' do
reply[:fqdn] = run("hostname -f", :stdout => :out, :stderr => :err)
end
def run_migration(to_fqdn, to_ip)
update_host_entry_cmd="sed -i '/puppet/c#{to_ip} puppet #{to_fqdn}' /etc/hosts"
# update_puppet_conf_cmd="puppet resource ini_setting 'server' ensure=present path='/etc/puppetlabs/puppet/puppet.conf' section='main' setting='server' value='#{to_fqdn}'" #hmm, doesn't work?
update_puppet_conf_cmd="sed -i '/server/cserver = #{to_fqdn}' /etc/puppetlabs/puppet/puppet.conf"
nuke_ssl_dir_cmd="rm -rf /etc/puppetlabs/puppet/ssl"
# nuke_ssl_dir_cmd="puppet resource file '/etc/puppetlabs/puppet/ssl' ensure=absent force=true" #hmm, doesn't work?
restart_agent_cmd='/etc/init.d/puppet restart'
reply[:exitstatus] = "initialized"
reply[:command_list] = []
run_command(update_host_entry_cmd)
run_command(update_puppet_conf_cmd)
run_command(nuke_ssl_dir_cmd)
run_command(restart_agent_cmd)
certlink="https://#{to_fqdn}/#/node_groups/inventory/nodes/certificates"
reply[:msg] = "Migration complete. Go look for your cert at #{certlink}"
reply[:certlink]=certlink
end
def run_reinstall_migration(to_fqdn, to_ip)
reinstall_script=''
reinstall_script = <<REINSTALL
/usr/bin/wget --no-check-certificate https://prd-artifactory.sjrb.ad:8443/artifactory/shaw-private-core-devops-ext-release/com/puppetlabs/puppet-enterprise/2015.2.3/puppet-enterprise-2015.2.3-el-6-x86_64.tar.gz
/bin/tar -xvf puppet-enterprise-2015.2.3-el-6-x86_64.tar.gz
/bin/bash puppet-enterprise-2015.2.3-el-6-x86_64/puppet-enterprise-uninstaller -pdy
/bin/rm -rf puppet-enterprise-*
REINSTALL
full_script = <<OEF
#!/bin/bash
set -x
exec 2> >(logger)
[ -f /etc/init.d/pe-puppet ] && puppet resource service pe-puppet ensure=stopped
[ -f /etc/init.d/puppet ] && puppet resource service puppet ensure=stopped
sed -i '/puppet/c\\#{to_ip} puppet #{to_fqdn}' /etc/hosts
#{reinstall_script}
/usr/bin/curl -o install_puppet.sh -k https://#{to_fqdn}:8140/packages/current/install.bash
/bin/chmod +x install_puppet.sh
/bin/bash install_puppet.sh
/bin/rm -rf /etc/yum.repos.d/pe_repo.repo
/bin/rm -rf install_puppet.sh
[ -f /etc/init.d/puppet ] && /usr/local/bin/puppet resource service puppet ensure=running
OEF
reinstall_file='/tmp/reinstall_puppet_from_new_master.sh'
File.write(reinstall_file, full_script)
reply[:msg] = run("nohup /bin/bash #{reinstall_file} &", :stdout => :out, :stderr => :err, :cwd => "/tmp")
certlink="https://#{to_fqdn}/#/node_groups/inventory/nodes/certificates"
reply[:msg] = "Migration was triggered, and mcollective will uninstall now. Go look for your cert at #{certlink}"
reply[:certlink]=certlink
end
activate_when do
#deactivate if any puppet master services exist. Migrating a master would be bad.
#TODO: use a fact?
if (File.exists?("/etc/init.d/pe-puppetserver") ||
File.exists?("/etc/init.d/pe-httpd") ||
File.exists?("/etc/init.d/pe-console-services") ||
File.exists?("/etc/init.d/pe-memcached") ||
File.exists?("/etc/init.d/pe-postgresql") ||
File.exists?("/etc/init.d/pe-puppet-dashboard-workers") ||
File.exists?("/etc/init.d/pe-puppetdb")) then
return false
else
return true
end
end
private
def run_command(cmd)
Log.info("Executing: #{cmd}")
#create reply[:out] and reply[:error] entries in the hash.
status = run(cmd, :stdout => :out, :stderr => :error)
reply[:exitstatus] = "Success" if status
reply[:command_list] << "Command: #{cmd} exited with: #{status}"
Log.info("Status is: #{reply[:exitstatus]}")
Log.info("STDOUT:")
Log.info(reply[:out])
Log.info("Execution Success for: #{cmd}")
end
end
end
end
| 79638200f9921818ea9caa3761305b9938a4290c | [
"Ruby"
] | 2 | Ruby | cpeirens/puppet-agent_migration | 34356d4fceee9a515d6924129d616d41922dee33 | 443e83f89f19a06f34c213972ee9fcf4929e4c79 |
refs/heads/master | <repo_name>1codechic/budgetMe<file_sep>/app/views/api/expenses/index.json.jbuilder
json.array! @expenses.each do |expense|
json.partial! "expenses.json.jbuilder", expense:expense
end<file_sep>/app/controllers/api/categories_controller.rb
class Api::CategoriesController < ApplicationController
def index
@categories = Category.all
render 'index.json.jbuilder'
end
def create
category = Category.new(
name: params[:category_name]
)
if category.save
render json: {message: 'category created successfully'}, status: :created
else
render json: {errors: category.errors.full_message}, status: :bad_request
end
end
def show
@category = Category.find_by(id: params[:id])
render 'show.json.jbuilder'
end
def destroy
category_id = params[:id]
@category = category.find_by(id: category_id)
@category.destroy
render json: {message: 'category deleted'}
end
end
<file_sep>/app/controllers/api/budgets_controller.rb
class Api::BudgetsController < ApplicationController
def index
@budgets = Budget.all
render 'index.json.jbuilder'
end
def create
budget = Budget.new(
name: params[:category_name],
amount: params[:amount]
)
if budget.save
render json: {message: 'budget created successfully'}, status: :created
else
render json: {errors: budget.errors.full_message}, status: :bad_request
end
end
def show
@budget = budget.find_by(id: params[:id])
render 'show.json.jbuilder'
end
def destroy
budget_id = params[:id]
@budget = budget.find_by(id: budget_id)
@budget.destroy
render json: {message: 'budget deleted'}
end
end
<file_sep>/app/views/api/categories/index.json.jbuilder
json.array! @categories.each do |category|
json.partial! "categories.json.jbuilder", category:category
end<file_sep>/app/views/api/users/index.json.jbuilder
json.array! @users.each do |user|
json.partial! "users.json.jbuilder", user:user
end<file_sep>/app/views/api/budgets/_budgets.json.jbuilder
json.id budget.id
json.category budget.category
json.amount budget.amount
<file_sep>/app/views/api/expenses/show.json.jbuilder
json.partial! "expenses.json.jbuilder", expense: @expense<file_sep>/app/views/api/expenses/_expenses.json.jbuilder
json.id expense.id
json.amount expense.amount
json.date expense.date
json.notes expense.notes
json.category expense.category_id
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# Expense.create!(name: 'car payment', date: 'april 22, 2019', amount: '320', expense_type: 'expense', notes: 'added via seed file')
cat1 = Category.create(name: 'Mortgage/Rent')
cat2 = Category.create(name: 'Utilities')
cat3 = Category.create(name: 'Restuarant')
cat4 = Category.create(name: 'Vacation')
cat5 = Category.create(name: 'Transportation')
<file_sep>/app/views/api/categories/show.json.jbuilder
json.partial! "categories.json.jbuilder", category: @category<file_sep>/app/views/api/budgets/index.json.jbuilder
json.array! @budgets.each.do |budget|
json.partial! "budgets.json.jbuilder", budget:budget
end<file_sep>/app/views/api/users/show.json.jbuilder
json.partial! "users.json.jbuilder", user: @user<file_sep>/app/controllers/api/expenses_controller.rb
class Api::ExpensesController < ApplicationController
def index
@expenses = Expense.all
render 'index.json.jbuilder'
end
def create
@expense = Expense.create!(
# name: params[:name],
date: params[:date],
amount: sprintf("%2.2f", params[:amount]),
category_id: params[:category_id],
notes: params[:notes],
user_id: current_user.id
)
render 'show.json.jbuilder'
# if @expense.save
# render 'show.json.jbuilder'
# else
# #console.log('error')
# # render json: {errors: @expense.errors.full_message}, status: :unprocessable_entity
# end
end
def show
@expense = Expense.find_by(id: params[:id])
render 'show.json.jbuilder'
end
def update
@expense = Expense.find(params[:id])
#@expense.name = params[:name] || @expense.name
@expense.date = params[:date] || @expense.date
@expense.amount = sprintf("%2.2f", params[:amount]) || sprintf("%2.2f", params[:amount])
@expense.notes = params[:notes] || @expense.notes
if @expense.save
render 'show.json.jbuilder'
else
render json: {errors: @expense.errors.full_message}, status: :unprocessable_entity
end
end
def destroy
expense_id = params[:id]
@expense = expense.find_by(id: expense_id)
@expense.destroy
render json: {message: 'expense deleted'}
end
# private
#Use callbacks to share common setup or contrainsts between actions
# def expense_params
# params.require(:expense).permit(:id, :date, :notes, :amount)
# end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
# EXAMPLE HTML ROUTE
# get "/photos" => "photos#index"
# EXAMPLE JSON ROUTE WITH API NAMESPACE
# namespace :api do
# get "/photos" => "photos#index"
# end
namespace :api do
get '/users' => 'users#index'
post '/users' => 'users#create'
get '/users/:id' => 'users#show'
delete '/users/:id' => 'users#destroy'
post "/sessions" => "sessions#create"
get '/categories' => 'categories#index'
post '/categories' => 'categories#create'
get '/categories/:id' => 'categories#show'
delete '/categories/:id' => 'categories#destroy'
get '/budgets' => 'budgets#index'
post '/budgets' => 'budgets#create'
get '/budgets/:id' => 'budgets#show'
delete '/budgets/:id' => 'budgets#destroy'
get '/expenses' => 'expenses#index'
post '/expenses' => 'expenses#create'
get '/expenses/:id' => 'expenses#show'
patch '/expenses/:id' => 'expense#update'
delete '/expenses/:id' => 'expenses#destroy'
end
end
| 78b260c1d7d8d043c855458873dad530491e2ad3 | [
"Ruby"
] | 14 | Ruby | 1codechic/budgetMe | b0248ce307fc81958cf465dde76c034ab02e0934 | f71d278dd03d8a00611283fd09ac3617a14b7041 |
refs/heads/master | <repo_name>xsg2357/secstudent<file_sep>/README.md
### 集群session
描述
https://img-blog.csdnimg.cn/20190525201856587.png
https://img-blog.csdnimg.cn/20190525201856587.png
注意:session是有过期时间的,当session过期了,redis中的key也就会被自动删除。
实际场景中一个服务会至少有两台服务器在提供服务,
在服务器前面会有一个nginx做负载均衡,用户访问nginx,nginx再决定去访问哪一台服务器。
当一台服务宕机了之后,另一台服务器也可以继续提供服务,保证服务不中断。
如果我们将session保存在Web容器(比如tomcat)中,如果一个用户第一次访问被分配到服务器1上面需要登录,
当某些访问突然被分配到服务器二上,因为服务器二上没有用户在服务器一上登录的会话session信息,
服务器二还会再次让用户登录,用户已经登录了还让登录就感觉不正常了。
解决这个问题的思路是用户登录的会话信息不能再保存到Web服务器中,
而是保存到一个单独的库(redis、mongodb、jdbc等)中,
所有服务器都访问同一个库,都从同一个库来获取用户的session信息,如用户在服务器一上登录,将会话信息保存到库中,
用户的下次请求被分配到服务器二,服务器二从库中检查session是否已经存在,
如果存在就不用再登录了,可以直接访问服务了。
1. 引入spring session依赖
```md
dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
```
2.properties.application
```
spring:
session:
store-type: redis
redis:
host: localhost
port: 6379
server:
port: 8080
servlet:
session:
timeout: 600
```
3. 启动两个应用
mvn clean install
java -jar spring-security-example-0.0.1-SNAPSHOT.jar --server.port=8080
java -jar spring-security-example-0.0.1-SNAPSHOT.jar --server.port=8081
4. 测试
使用其中一个服务去登录 http://localhost:8080/login
使用另一个服务访问任意接口 http://localhost:8081/user/me 不需要再重新登录就可以直接访问
<file_sep>/src/main/java/com/example/secstudent/config/SecurityConfiguration.java
package com.example.secstudent.config;
import com.example.secstudent.filter.ImageValidateCodeFilter;
import com.example.secstudent.filter.SmsValidateCodeFilter;
import com.example.secstudent.handler.MyAuthenticationFailureHandler;
import com.example.secstudent.handler.MyAuthenticationSuccessHandler;
import com.example.secstudent.handler.MyLogoutSuccessHandler;
import com.example.secstudent.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private MyUserDetailsService myUserDetailsService;
@Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Autowired
private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
@Autowired
private MyLogoutSuccessHandler myLogoutSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
//图片验证码
ImageValidateCodeFilter imageValidateCodeFilter = new ImageValidateCodeFilter();
imageValidateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
//短信验证码
SmsValidateCodeFilter smsValidateCodeFilter = new SmsValidateCodeFilter();
smsValidateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
// maximumSessions:最大会话数量,设置为1表示一个用户只能有一个会话
// expiredSessionStrategy:会话过期策略
/*http.csrf().disable()
.antMatchers("/login", "/session/invalid").permitAll()
.sessionManagement()
.invalidSessionUrl("/session/invalid")
.maximumSessions(1)
.expiredSessionStrategy(new MyExpiredSessionStrategy())*/
// 阻止用户第二次登录
// sessionManagement也可以配置 maxSessionsPreventsLogin:boolean值,当达到maximumSessions设置的最大会话个数时阻止登录。
/*http.csrf().disable()
.antMatchers("/login", "/session/invalid").permitAll()
.sessionManagement()
.invalidSessionUrl("/session/invalid")
.maximumSessions(1)
.expiredSessionStrategy(new MyExpiredSessionStrategy())
.maxSessionsPreventsLogin(true)
.and().and()
.logout().permitAll();*/
http.csrf().disable()
// 配置需要认证的请求
.authorizeRequests()
.antMatchers("/login", "/session/invalid",
"/code/image","/code/sms", "/logout","/signOut").permitAll()
.anyRequest()
.authenticated()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(myLogoutSuccessHandler)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
//session会话管理
.sessionManagement()
.invalidSessionUrl("/session/invalid")
.maximumSessions(1)
.expiredSessionStrategy(new MyExpiredSessionStrategy())
.maxSessionsPreventsLogin(true)
.and()
.and()
.addFilterBefore(imageValidateCodeFilter, UsernamePasswordAuthenticationFilter.class)
// 登录表单相关配置
.addFilterBefore(smsValidateCodeFilter, UsernamePasswordAuthenticationFilter.class)
// 登录表单相关配置
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.successHandler(myAuthenticationSuccessHandler)
.failureUrl("/login?error")
.permitAll()
.and()
//记住我
.rememberMe()
.userDetailsService(myUserDetailsService)
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(60 * 60 * 60 * 30)
.and()
// 登出相关配置
.logout()
.permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/static/**");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
}
| f12cae21c0fe813690f968d45c00b805a87a1750 | [
"Markdown",
"Java"
] | 2 | Markdown | xsg2357/secstudent | 4b30ed691e24e374af70f66219cd653c3986f02d | 26acfbd7f622e42524db6933dc522b2cf1a4c729 |
refs/heads/main | <repo_name>MarcosBB/API_Blog<file_sep>/Autores/api/serializers.py
from rest_framework import serializers
from Autores import models
class AutoresSerializer(serializers.ModelSerializer):
class Meta:
model = models.Autor
fields = '__all__'
<file_sep>/Publicacoes/api/serializers.py
from rest_framework import serializers
from Publicacoes import models
class PublicacoesSerializer(serializers.ModelSerializer):
class Meta:
model = models.Publicacao
fields = 'titulo','descricao', 'autor', 'id_publicacao', 'criado'
<file_sep>/Publicacoes/models.py
from django.db import models
from django.db.models.base import Model
from uuid import uuid4
class Publicacao(models.Model):
id_publicacao = models.UUIDField(primary_key=True, default=uuid4, editable=False)
titulo = models.CharField('Titulo',max_length=255)
descricao = models.TextField('Descrição', max_length=200)
autor = models.ForeignKey('Autores.Autor', verbose_name='Autor', on_delete=models.CASCADE)
criado = models.DateField('Criação', auto_now_add=True)
class Meta:
verbose_name = 'Publicação'
verbose_name_plural = 'Publicações'
def __str__(self):
return self.titulo<file_sep>/Publicacoes/api/viewsets.py
from rest_framework import viewsets
from rest_framework.filters import SearchFilter, OrderingFilter
from Publicacoes.api import serializers
from Publicacoes import models
class PublicacaoViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PublicacoesSerializer
queryset = models.Publicacao.objects.all()
filter_backends = [SearchFilter]
search_fields =['autor__nome', 'autor__id_autor', 'autor__sobrenome']
<file_sep>/Autores/models.py
from django.db import models
from uuid import uuid4
class Autor(models.Model):
id_autor = models.UUIDField(primary_key=True, default=uuid4, editable=False)
nome = models.CharField('Nome',max_length=255)
sobrenome = models.CharField('Sobrenome',max_length=255)
class Meta:
verbose_name = 'Autor'
verbose_name_plural = 'Autores'
def __str__(self):
return self.nome<file_sep>/Autores/api/viewsets.py
from rest_framework import viewsets
from Autores.api import serializers
from Autores import models
class AutorViewSet(viewsets.ModelViewSet):
serializer_class = serializers.AutoresSerializer
queryset = models.Autor.objects.all()<file_sep>/Autores/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-07-01 19:23
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Autor',
fields=[
('id_autor', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('nome', models.CharField(max_length=255, verbose_name='Nome')),
('sobrenome', models.CharField(max_length=255, verbose_name='Sobrenome')),
],
options={
'verbose_name': 'Autor',
'verbose_name_plural': 'Autores',
},
),
]
<file_sep>/Publicacoes/migrations/0001_initial.py
# Generated by Django 3.2.5 on 2021-07-01 19:23
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('Autores', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Publicacao',
fields=[
('id_publicacao', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('titulo', models.CharField(max_length=255, verbose_name='Titulo')),
('descricao', models.TextField(max_length=200, verbose_name='Descrição')),
('criado', models.DateField(auto_now_add=True, verbose_name='Criação')),
('modificado', models.DateField(auto_now=True, verbose_name='Atualização')),
('autor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Autores.autor', verbose_name='Autor')),
],
options={
'verbose_name': 'Publicação',
'verbose_name_plural': 'Publicações',
},
),
]
<file_sep>/README.md
# API Blog
É uma `API Rest` feita em `Python` com o framework `Django` e `djangorestframework` que tem o propósito de cadastro e consulta de informações de postagens e autores de um blog.
Teste a API clickando [aqui](https://api-blog-marcosbb.herokuapp.com/).
(Lembrando que a primeira requisição demora um pouco pra responder, ja que está hospedado no Heroku gratuitamente)
## Sumário
- [API Blog](#api-blog)
- [Sumário](#sumário)
- [Rotas](#rotas)
- [Autores GET, POST](#autores-get-post)
- [Publicações GET, POST](#publicações-get-post)
- [Filtrando publicações por autores](#filtrando-publicações-por-autores)
- [Rodando localmente](#rodando-localmente)
- [Insomnia](#insomnia)
## Rotas
### Autores GET, POST
Rota para listagem de autores
```
/autores/
```
Exemplo de cadastro de autores:
```
{
"nome": "Marcos",
"sobrenome": "<NAME>"
}
```
### Publicações GET, POST
Rota para listagem de publicações
```
/publicacoes/
```
Exemplo de cadastro de publicações:
```
{
"titulo": "Política",
"descricao": "Bolsonaro vs Lula",
"autor": "922c26dd-88f1-493e-bbff-ace3308f8aea"
}
```
Lembrando que no campo autor deve-se colocar o id do autor e não seu nome.
#### Filtrando publicações por autores
Insira após o `?serch=` o nome, sobrenome ou id do autor que deseja filtrar as postagens.
Exemplo:
```
/publicacoes?search=Marcos
```
## Rodando localmente
Você deve criar um arquivo na raiz do projeto com nome `.env` contendo as informações de configurações do django e banco de dados.
Use este modelo e insira as informações à direita dos `=` sem adicionar nenhum espaço:
```
DEBUG=
SECRET_KEY=
ALLOWED_HOSTS=
NAME=
USER=
PASSWORD=
PORT=
```
## Insomnia
Clicke no botão abaixo para importar as configurações do insomnia para facilitar seus teste da api.
[](https://insomnia.rest/run/?label=API_Blog&uri=https%3A%2F%2Fraw.githubusercontent.com%2FMarcosBB%2FAPI_Blog%2Fmain%2Finsomnia%2Fexport.json)
<file_sep>/Publicacoes/migrations/0002_remove_publicacao_modificado.py
# Generated by Django 3.2.5 on 2021-07-02 13:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Publicacoes', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='publicacao',
name='modificado',
),
]
<file_sep>/API_Blog/urls.py
"""API_Blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from Autores.api import viewsets as autoresviewsets
from Publicacoes.api.viewsets import PublicacaoViewSet as publicacoesviewsets
route= routers.DefaultRouter()
route.register(r'autores', autoresviewsets.AutorViewSet, basename="Autores")
route.register(r'publicacoes', publicacoesviewsets , basename="Publicacoes")
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(route.urls))
]
| 7d6293a1b6715257d3c26c3e947debbad786bbbb | [
"Markdown",
"Python"
] | 11 | Python | MarcosBB/API_Blog | 49821357933db6be04bba9f2b00ab1916f9246d9 | 2134c473ca884246c2530c90bc0634d5e68e8a37 |
refs/heads/master | <repo_name>ses4j/project-system<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/PackageRestore/IPackageRestoreUnconfiguredDataSource.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Composition;
using NuGet.SolutionRestoreManager;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem.VS.PackageRestore
{
/// <summary>
/// Represents the data source of metadata needed for restore operations for a <see cref="UnconfiguredProject"/>
/// instance by resolving conflicts and combining the data of all implicitly active <see cref="ConfiguredProject"/>
/// instances.
/// </summary>
[ProjectSystemContract(ProjectSystemContractScope.UnconfiguredProject, ProjectSystemContractProvider.Private, Cardinality = ImportCardinality.ExactlyOne)]
internal interface IPackageRestoreUnconfiguredDataSource : IProjectValueDataSource<IVsProjectRestoreInfo2>
{
}
}
<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS/ProjectSystem/VS/PackageRestore/Snapshots/ProjectRestoreUpdate.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using NuGet.SolutionRestoreManager;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem.VS.PackageRestore
{
/// <summary>
/// Represents restore data for a single <see cref="ConfiguredProject"/>.
/// </summary>
internal class ProjectRestoreUpdate
{
public ProjectRestoreUpdate(ProjectConfiguration projectConfiguration, IVsProjectRestoreInfo2 restoreInfo)
{
Requires.NotNull(projectConfiguration, nameof(projectConfiguration));
Requires.NotNull(restoreInfo, nameof(restoreInfo));
ProjectConfiguration = projectConfiguration;
RestoreInfo = restoreInfo;
}
/// <summary>
/// Gets the restore information produced in this update.
/// </summary>
public IVsProjectRestoreInfo2 RestoreInfo
{
get;
}
/// <summary>
/// Gets the configuration of the <see cref="ConfiguredProject"/>
/// this update was produced from.
/// </summary>
public ProjectConfiguration ProjectConfiguration
{
get;
}
}
}
<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed/Annotations.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class AssertsTrueAttribute : Attribute
{
public AssertsTrueAttribute() { }
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class AssertsFalseAttribute : Attribute
{
public AssertsFalseAttribute() { }
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class EnsuresNotNullAttribute : Attribute
{
public EnsuresNotNullAttribute() { }
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class NotNullWhenFalseAttribute : Attribute
{
public NotNullWhenFalseAttribute() { }
}
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class NotNullWhenTrueAttribute : Attribute
{
public NotNullWhenTrueAttribute() { }
}
}
<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/Configuration/IProjectConfigurationDimensionsProvider4.cs
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.Build.Construction;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem
{
internal interface IProjectConfigurationDimensionsProvider4 : IProjectConfigurationDimensionsProvider3
{
IEnumerable<string> GetBestGuessDimensionNames(ImmutableArray<ProjectPropertyElement> properties);
}
}
<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/Mocks/IPackageRestoreUnconfiguredDataSourceFactory.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks.Dataflow;
using Moq;
using NuGet.SolutionRestoreManager;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem.VS.PackageRestore
{
internal static class IPackageRestoreUnconfiguredDataSourceFactory
{
public static IPackageRestoreUnconfiguredDataSource Create()
{
var sourceBlock = Mock.Of<IReceivableSourceBlock<IProjectVersionedValue<IVsProjectRestoreInfo2>>>();
// Moq gets really confused with mocking IProjectValueDataSource<IVsProjectRestoreInfo2>.SourceBlock
// because of the generic/non-generic version of it. Avoid it.
return new PackageRestoreUnconfiguredDataSource(sourceBlock);
}
private class PackageRestoreUnconfiguredDataSource : IPackageRestoreUnconfiguredDataSource
{
public PackageRestoreUnconfiguredDataSource(IReceivableSourceBlock<IProjectVersionedValue<IVsProjectRestoreInfo2>> sourceBlock)
{
SourceBlock = sourceBlock;
}
public IReceivableSourceBlock<IProjectVersionedValue<IVsProjectRestoreInfo2>> SourceBlock { get; }
public NamedIdentity DataSourceKey { get; }
public IComparable DataSourceVersion { get; }
ISourceBlock<IProjectVersionedValue<object>> IProjectValueDataSource.SourceBlock { get; }
public IDisposable Join()
{
return null;
}
}
}
}
<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/Mocks/IDependencyModelFactory.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.ProjectSystem.VS.Tree.Dependencies;
using Moq;
using Newtonsoft.Json.Linq;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem.VS
{
internal static class IDependencyModelFactory
{
public static IDependencyModel Create()
{
return Mock.Of<IDependencyModel>();
}
public static IDependencyModel Implement(string providerType = null,
string id = null,
string originalItemSpec = null,
string path = null,
string caption = null,
IEnumerable<string> dependencyIDs = null,
bool? resolved = null,
MockBehavior mockBehavior = MockBehavior.Default)
{
var mock = new Mock<IDependencyModel>(mockBehavior);
if (providerType != null)
{
mock.Setup(x => x.ProviderType).Returns(providerType);
}
if (id != null)
{
mock.Setup(x => x.Id).Returns(id);
}
if (originalItemSpec != null)
{
mock.Setup(x => x.OriginalItemSpec).Returns(originalItemSpec);
}
if (path != null)
{
mock.Setup(x => x.Path).Returns(path);
}
if (caption != null)
{
mock.Setup(x => x.Caption).Returns(caption);
}
if (dependencyIDs != null)
{
mock.Setup(x => x.DependencyIDs).Returns(ImmutableList<string>.Empty.AddRange(dependencyIDs));
}
if (resolved.HasValue)
{
mock.Setup(x => x.Resolved).Returns(resolved.Value);
}
return mock.Object;
}
public static TestDependencyModel FromJson(
string jsonString,
ProjectTreeFlags? flags = null,
ImageMoniker? icon = null,
ImageMoniker? expandedIcon = null,
ImageMoniker? unresolvedIcon = null,
ImageMoniker? unresolvedExpandedIcon = null,
Dictionary<string, string> properties = null,
IEnumerable<string> dependenciesIds = null)
{
if (string.IsNullOrEmpty(jsonString))
{
return null;
}
var json = JObject.Parse(jsonString);
var data = json.ToObject<TestDependencyModel>();
if (flags.HasValue)
{
data.Flags += flags.Value;
}
data.Flags += data.Resolved
? DependencyTreeFlags.Resolved
: DependencyTreeFlags.Unresolved;
if (icon.HasValue)
{
data.Icon = icon.Value;
}
if (expandedIcon.HasValue)
{
data.ExpandedIcon = expandedIcon.Value;
}
if (unresolvedIcon.HasValue)
{
data.UnresolvedIcon = unresolvedIcon.Value;
}
if (unresolvedExpandedIcon.HasValue)
{
data.UnresolvedExpandedIcon = unresolvedExpandedIcon.Value;
}
if (properties != null)
{
data.Properties = ImmutableStringDictionary<string>.EmptyOrdinal.AddRange(properties);
}
if (dependenciesIds != null)
{
data.DependencyIDs = ImmutableList<string>.Empty.AddRange(dependenciesIds);
}
return data;
}
}
}
<file_sep>/src/Microsoft.VisualStudio.ProjectSystem.Managed.VS.UnitTests/ProjectSystem/VS/Rename/SimpleRenamerTestsBase.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem.VS.Rename
{
public abstract class SimpleRenamerTestsBase
{
protected abstract string ProjectFileExtension { get; }
protected SolutionInfo InitializeWorkspace(ProjectId projectId, string fileName, string code, string language)
{
var solutionId = SolutionId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
return SolutionInfo.Create(
solutionId,
VersionStamp.Create(),
projects: new ProjectInfo[]
{
ProjectInfo.Create(
id: projectId,
version: VersionStamp.Create(),
name: "Project1",
assemblyName: "Project1",
filePath: $@"C:\project1.{ProjectFileExtension}",
language: language,
documents: new DocumentInfo[]
{
DocumentInfo.Create(
documentId,
fileName,
loader: TextLoader.From(TextAndVersion.Create(SourceText.From(code),
VersionStamp.Create())),
filePath: fileName)
})
});
}
}
}
| 4d208b48d185c64403030edad9c0105636db58b0 | [
"C#"
] | 7 | C# | ses4j/project-system | ac622116e70575bc62851d7e59bcc58ce9a13b3c | 488e5ad10f0dddf2c2a6a78fcc7d75492395fba7 |
refs/heads/main | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class GameController : MonoBehaviour {
public GameObject[] hazards;
public Vector3 spawnValues;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public Text scoreText;
public Text restartText;
public Text gameOverText;
public GameObject optionsPanel;
public AudioMixerSnapshot pausedSnapshot;
public AudioMixerSnapshot unpausedSnapshot;
private bool gameOver;
//private bool restart;
private int score;
private bool paused;
// Use this for initialization
void Start () {
gameOver = false;
paused = false;
//restart = false;
restartText.text = "";
gameOverText.text = "";
score = 0;
UpdateScore();
StartCoroutine (SpawnWaves());
}
private void Update()
{
/*
if (restart)
{
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene("Main");
//Application.LoadLevel(Application.loadedLevel);
}
}
*/
if (Input.GetKeyDown(KeyCode.Space) || Input.GetButtonDown("Pause"))
{
GamePaused();
}
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (!gameOver)
{
for (int i = 0; i < hazardCount; i++)
{
GameObject hazard = hazards[Random.Range(0, hazards.Length)];
/*
* bool flag = (Random.value > 0.5);
* if(flag){
* spawnValues.z (16 or -16)
* }
*/
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard, spawnPosition, spawnRotation);
// GameObject clone = Instantiate(hazard, spawnPosition, spawnRotation);
// ReverseDirection(clone);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
//if (gameOver)
//{
// restartText.text = "Press 'R' for Restart";
// restart = true;
// break;
//}
}
//restartText.text = "Press 'R' for Restart";
//restart = true;
}
/*
* void ReverseDirection(GameObject clone){
* clone.transform.rotation.y = 0;
* clone.GetComponent<Mover>().speed = 5;
* }
*/
public void AddScore(int newScoreValue)
{
score += newScoreValue;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
public void GamePaused()
{
paused = !paused;
if (paused)
{
Time.timeScale = 0;
pausedSnapshot.TransitionTo(.01f);
optionsPanel.SetActive(true);
foreach (Transform child in optionsPanel.transform)
{
if (child.name == "Resume") child.gameObject.GetComponent<Button>().Select();
}
}
else
{
Time.timeScale = 1;
unpausedSnapshot.TransitionTo(.01f);
optionsPanel.SetActive(false);
}
}
public void Restart()
{
if (paused) GamePaused();
SceneManager.LoadScene("Main");
}
public void GameOver()
{
gameOverText.text = "Game Over";
gameOver = true;
optionsPanel.SetActive(true);
foreach (Transform child in optionsPanel.transform)
{
if (child.name == "Resume") child.gameObject.GetComponent<Button>().enabled = false;
if (child.name == "Restart") child.gameObject.GetComponent<Button>().Select();
}
}
public void QuitGame()
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
<file_sep># NewSpaceShooter
Using basic assets provided by Unity Technologies, built-in components and writing simple custom code, understand how to work with imported Mesh Models, Audio, Textures and Materials while practicing more complicated Scripting principles.
https://learn.unity.com/project/space-shooter-tutorial
https://unitylist.com/p/ie/Unity3D-space-Shooter
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour {
public float speed;
public float tilt;
public Boundary boundary;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
public float initialVolume = 0.4f;
public float audioAddition = 0.6f;
private Rigidbody rb;
private AudioSource audioSource;
private float nextFire;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
private void Update()
{
if (Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
float menorVolume = 0;
float maiorVolume = 1.0f - initialVolume;
float menorPan = -0.8f;
float maiorPan = 0.8f;
audioSource.volume = initialVolume + ConvertScale(boundary.xMin, boundary.xMax, Mathf.Abs(transform.position.x), menorVolume, maiorVolume);
//audioSource.volume = initialVolume + (Mathf.Abs(transform.position.x) / boundary.xMax);
audioSource.panStereo = ConvertScale(boundary.xMin, boundary.xMax, transform.position.x, menorPan, maiorPan);
//audioSource.panStereo = Mathf.Clamp((transform.position.x / boundary.xMax), -0.8f, 0.8f);
audioSource.Play();
}
}
// Update is called once per frame
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.velocity = movement * speed;
rb.position = new Vector3
(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
0.0f,
Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax)
);
rb.rotation = Quaternion.Euler(0.0f, 0.0f, rb.velocity.x * -tilt);
}
private float ConvertScale(float initial, float end, float value, float initialTarget, float endTarget)
{
return ((value - initial) / (end - initial)) * (endTarget - initialTarget) + initialTarget;
}
}
| e2c7fd1eea76a428d5245f9e989fa30a681f1e3d | [
"Markdown",
"C#"
] | 3 | C# | salmo-jr/NewSpaceShooter | 137fb29a640c09a50262a67b7e6a458925062915 | 577452996cc6ada55bc44c1d55e4bd8fb41eb1e5 |
refs/heads/master | <file_sep>//index.js
const config = require('../../utils/config.js');
let app = getApp()
Page({
data: {
info:null,
STATUS:null
},
not_open_yet() {
config.mytoast('暂未开放,敬请期待...', (res) => { });
},
onLoad: function () {
},
onShow: function () {
this.getInit();
this.getStatus();
},
getStatus() {
let _this = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {
}, `/auth/status`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
this.setData({
STATUS: res.data
})
} else {
// config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
goDetail(e) {
console.log(e);
let type = e.currentTarget.dataset.type;
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (!this.data.STATUS.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
if (this.data.STATUS.userAuth != 1) {
config.mytoast('您尚未实名认证,请前往认证!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
}, 500)
return false;
}
wx.navigateTo({
url: `/pages/message/list/list?name=${type}`,
})
},
getInit() {
let that = this;
config.ajax('GET', {
}, `/message/`, (resp) => {
let res = resp.data;
if (res.code == 1) {
that.setData({
info: res.data
})
} else {
// config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
})
<file_sep>// pages/single/release/release.js
const config = require('../../../utils/config.js');
const amapFile = require('../../../component/libs/amap-wx.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
upload_list: [],
latitude:'',
longitude:'',
address_name:'',
addressList:[],
showActionsheet: false,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
previewImg(e) {
//预览图片
var src = e.currentTarget.dataset.src;//获取data-src
var imgList = e.currentTarget.dataset.list;//获取data-list
let urls = []
imgList.forEach((value) => {
urls.push(value.src);
})
console.log(urls);
wx.previewImage({
current: src, // 当前显示图片的http链接
urls: urls, // 需要预览的图片http链接列表
success: function (resp) {
console.log('success===', resp);
},
fail: function (resp) {
console.log('fail===', resp);
}
})
},
bindFormSubmit(e){
console.log(e.detail);
let type = e.detail.target.dataset.type;
if(type == 'release'){
//发布
this.releaseAjax(e.detail.value.description,2);
}else{
//草稿
this.releaseAjax(e.detail.value.description, 1);
}
},
closeImg(e){
let index = e.currentTarget.dataset.index;
let arr = this.data.upload_list;
arr.splice(index,1);
this.setData({
upload_list: arr
})
},
releaseAjax(description, status){
let _this = this;
console.log(description);
if (!description) {
config.mytoast('内容不能为空', (res) => { });
return false;
}
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
openId:app.globalData.uid,
singleCircleImg: _this.data.upload_list,
description: description,
latitude: _this.data.latitude,
longitude: _this.data.longitude,
status: status,
address: _this.data.address_name
}, `/circle/single-circle/add`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
wx.navigateBack()
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
chooseImage() {
let _this = this;
let arr = _this.data.upload_list;
if (arr.length >= 6) {
config.mytoast('图片不能大于6张', (res) => { });
return false;
}
wx.chooseImage({
count: 6,
// sizeType: 'original',
sizeType: 'compressed',
success: function (res) {
res.tempFilePaths.forEach((value,index)=>{
// let value = res.tempFilePaths[0];
let suffix = value.substring(value.lastIndexOf('.'));
wx.getFileSystemManager().readFile({
filePath: value, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
let arrList = _this.data.upload_list;
arrList.push({
src: value,
singleCircleImg: res.data,
singleCircleImgExt: suffix
});
_this.setData({
upload_list: arrList,
})
}
})
})
},
})
},
getLocation() {
// wx.getLocation({
// type: 'wgs84',
// success(res) {
// const latitude = res.latitude
// const longitude = res.longitude
// const speed = res.speed
// const accuracy = res.accuracy
// }
// })
let _this = this;
wx.getLocation({
type: 'gcj02 ',
success(res) {
const latitude = res.latitude
const longitude = res.longitude
console.log(res);
_this.setData({
latitude: latitude,
longitude: longitude
})
_this.getAddress(latitude, longitude)
}
})
},
getAddress(latitude, longitude){
let _this = this;
var myAmapFun = new amapFile.AMapWX({ key: 'e99502730e85d295e4f08cabf7c50ce1' });
myAmapFun.getRegeo({
location: `${longitude},${latitude}`,
success: function (e) {
console.log(e);
let arr = [];
for(var i = 0;i<=8;i++){
arr.push({
text: e[0].regeocodeData.pois[i].address,
value: e[0].regeocodeData.pois[i].address
})
}
_this.setData({
addressList: arr,
address_name: e[0].name,
showActionsheet: true
})
}
})
},
close: function () {
this.setData({
showActionsheet: false
})
},
open: function () {
this.setData({
showActionsheet: true
})
},
btnClick(e) {
console.log(e)
this.setData({
address_name: e.detail.value,
})
this.close()
}
})<file_sep>// pages/music/audio/audio.js
const config = require('../../../utils/config.js');
let app = getApp()
const bgMusic = wx.getBackgroundAudioManager()
Page({
/**
* 页面的初始数据
*/
data: {
id:null,
isOpen:false,
starttime: '00:00', //正在播放时长
duration: '00:00', //总时长,
audio:null,
list:null,
value:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
id: options.id
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.audioPlay();
this.getInit();
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
var that = this
that.listenerButtonStop()//停止播放
console.log("离开")
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.list.current < this.data.list.pages) {
let page = this.data.list.current + 1;
this.getInit(page);
}
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
var that = this;
// 设置菜单中的转发按钮触发转发事件时的转发内容
var shareObj = {
title: `${audio.title}`, // 默认是小程序的名称(可以写slogan等)
path: `pages/music/audio/audio?id=${that.id}`, // 默认是当前页面,必须是以‘/’开头的完整路径
imageUrl: '', //自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
};
// 来自页面内的按钮的转发
if (options.from == 'button') {
var eData = options.target.dataset;
// that.shareData(eData);
}
// 返回shareObj
return shareObj;
},
audioPlay: function () {
let that = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {
}, `/audio/${this.data.id}`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
this.audioDetail(res.data);
this.setData({
poster: res.data.imgUrl,
audio: res.data
})
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
audioDetail(audio){
let that = this;
//bug ios 播放时必须加title 不然会报错导致音乐不播放
bgMusic.title = audio.title;
bgMusic.epname = audio.title;
bgMusic.src = audio.audioUrl;
bgMusic.onTimeUpdate(() => {
//bgMusic.duration总时长 bgMusic.currentTime当前进度
var duration = bgMusic.duration;
var offset = bgMusic.currentTime;
var currentTime = parseInt(bgMusic.currentTime);
var min = "0" + parseInt(currentTime / 60);
var sec = currentTime % 60;
var max = parseInt(bgMusic.duration);
var total_min = parseInt(duration / 60);
var total_sec = parseInt(duration % 60);
if (total_min < 10) {
total_min = "0" + total_min;
};
if (sec < 10) {
sec = "0" + sec;
};
if (total_sec < 10) {
total_sec = "0" + total_sec;
};
var starttime = min + ':' + sec; /* 00:00 */
var endtime = total_min + ':' + total_sec; /* 00:00 */
that.setData({
offset: currentTime,
starttime: starttime,
duration: endtime,
max: max,
changePlay: true
})
})
//播放结束
bgMusic.onEnded(() => {
that.setData({
starttime: '00:00',
isOpen: false,
offset: 0
})
console.log("音乐播放结束");
})
bgMusic.play();
that.setData({
isOpen: true,
})
},
audioPause: function () {
var that = this
bgMusic.pause()
that.setData({
isOpen: false,
})
},
listenerButtonStop(){
bgMusic.pause()
},
audio14: function () {
this.audioCtx.seek(14)
},
audioStart: function () {
this.audioCtx.seek(0)
},
// 进度条拖拽
sliderChange(e) {
var that = this
var offset = parseInt(e.detail.value);
console.log(offset);
bgMusic.play();
bgMusic.seek(offset);
that.setData({
isOpen: true,
})
},
commentBlur(e){
let content = e.detail.value
config.ajax('POST', {
audioId: this.data.id,
content: content
}, `/audio/audio-comment/add`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.getInit();
this.setData({
value:''
})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
getInit(page = 1) {
let that = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
pageNum: page
}, `/audio/audio-comment/page`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (page != 1) {
this.data.list.data.push.apply(this.data.list.data, res.data.data);
this.data.list.current = res.data.current;
that.setData({
list: that.data.list
})
} else {
that.setData({
list: res.data
})
}
}, (res) => {
})
},
goUrl(e) {
let url = e.currentTarget.dataset.url;
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (url) {
wx.navigateTo({
url: url,
})
} else {
config.mytoast('暂未开放,敬请期待...', (res) => { });
}
},
not_open_yet() {
config.mytoast('暂未开放,敬请期待...', (res) => { });
},
goBack(){
wx.navigateTo({
url: '/pages/music/index',
})
}
})<file_sep>// pages/index/exact_match/exact_match.js
const config = require('../../../utils/config.js');
let app = getApp()
Page({
data: {
mate: null,
nowResidence: [],
nowResidence2:[],
info: {},
STATUS:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getInit();
this.getStatus();
},
getStatus() {
let _this = this;
config.ajax('GET', {
}, `/auth/status`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
STATUS: res.data
})
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
getArrayIndex(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i].name === obj) {
return i;
}
}
return -1;
},
getInit() {
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {}, `/home/initHomeFilter`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
this.setData({
mate: res.data
})
this.getDetail()
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
getDetail() {
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {}, `/home/getHomeFilterList`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
let arr = res.data;
// let advanced = arr.advanced;
// let arbaseInfor = arr.baseInfo;
let json = {};
arr.forEach((value) => {
json[value.ruleName] = {
ruleName: value.ruleName,
ruleDesc: value.ruleDesc,
ruleValue: value.ruleValue
}
})
this.setData({
info: json
})
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
bindPickerChangeAddress: function (e) {
let address = e.detail.value.join('-');
console.log(address);
let type = e.currentTarget.dataset.value;
//获取数组下标
let mate_index = this.getArrayIndex(this.data.mate.advanced, type);
//获取已选择的参数
let _name = this.data.mate.advanced[mate_index].value
let _value = address
let _desc = address
let _ruleType = '='
let info = {};
info[type] = {
ruleNameZh: _name,
ruleName: type,
ruleValue: _value,
ruleDesc: _desc,
ruleType: _ruleType
};
let _info = Object.assign({}, this.data.info, info)
this.add(info[type]);
this.setData({
info: _info
})
},
bindPickerChangeAddress2: function (e) {
let address = e.detail.value.join('-');
this.setData({
"nowResidence2": e.detail.value,
"info.nowResidence2": address
})
},
bindPickerChangeBaseInfo: function(e) {
// console.log('picker发送选择改变,携带值为', e)
let _index = e.detail.value;
let type = e.currentTarget.dataset.value;
//获取数组下标
let mate_index = this.getArrayIndex(this.data.mate.baseInfo, type);
//获取已选择的参数
let _name = this.data.mate.baseInfo[mate_index].value
let _value = this.data.mate.baseInfo[mate_index].properties[_index].value
let _desc = this.data.mate.baseInfo[mate_index].properties[_index].desc
let _ruleType = this.data.mate.baseInfo[mate_index].properties[_index].type
let info = {};
info[type] = {
ruleNameZh: _name,
ruleName: type,
ruleValue: _value,
ruleDesc: _desc,
ruleType: _ruleType
};
let _info = Object.assign({}, this.data.info, info)
this.add(info[type]);
this.setData({
info: _info
})
// console.log(this.data.info);
},
bindPickerChange: function (e) {
if (!this.data.STATUS.vipLevel) {
config.mytoast('请购买会员后查看~', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/member/member',
})
}, 500)
return false;
}
// console.log('picker发送选择改变,携带值为', e)
let _index = e.detail.value;
let type = e.currentTarget.dataset.value;
//获取数组下标
let mate_index = this.getArrayIndex(this.data.mate.advanced, type);
//获取已选择的参数
let _name = this.data.mate.advanced[mate_index].value
let _value = this.data.mate.advanced[mate_index].properties[_index].value
let _desc = this.data.mate.advanced[mate_index].properties[_index].desc
let _ruleType = this.data.mate.advanced[mate_index].properties[_index].type
let info = {};
info[type] = {
ruleNameZh: _name,
ruleName: type,
ruleValue: _value,
ruleDesc: _desc,
ruleType: _ruleType
};
let _info = Object.assign({}, this.data.info, info)
this.add(info[type]);
this.setData({
info: _info
})
// console.log(this.data.info);
},
add(json) {
let info = this.data.info;
// wx.showLoading({
// title: '数据保存中...',
// mask: true,
// success: function (res) { },
// fail: function (res) { },
// complete: function (res) { },
// })
console.log(info);
config.ajax('POST', json, `/home/addHomeFilter`, (res) => {
// wx.hideLoading();
if (res.data.code == 1) {
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
btn() {
let info = this.data.info;
// wx.navigateBack({})
console.log(info);
wx.navigateTo({
url: '/pages/index/list/list',
})
},
resetHomeFilter() {
config.ajax('POST', {}, `/home/resetHomeFilter`, (res) => {
if (res.data.code == 1) {
config.mytoast('重置成功', (res) => { })
this.getDetail()
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
})<file_sep>// pages/music/index.js
const config = require('../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*
* danmuList = [
{
text: '第 1s 出现的弹幕',
color: '#ff0000',
time: 1
}]
*/
data: {
is_match: false,
danmuList: [],
videoList:null,
audioList: null,
is_comment: false,
commentInfo: null,
STATUS:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if (this.is_match){
//音频
this.getAudio();
}else{
//视频
this.getVideo();
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function (res) {
this.getStatus();
// this.videoContext = wx.createVideoContext('myVideo')
},
getStatus() {
let _this = this;
config.ajax('GET', {
}, `/auth/status`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
STATUS: res.data
})
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
wx.showNavigationBarLoading();
if (this.is_match) {
//音频
this.getAudio();
} else {
//视频
this.getVideo();
}
wx.hideNavigationBarLoading();
wx.stopPullDownRefresh();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.videoList.current < this.data.videoList.pages) {
let page = this.data.videoList.current + 1;
if (this.is_match) {
//音频
this.getAudio(page);
} else {
//视频
this.getVideo(page);
}
}
},
getVideo(page = 1) {
let _this = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
pageNum: page
}, `/video/page`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
if (page != 1) {
this.data.videoList.data.push.apply(this.data.videoList.data, res.data.data);
this.data.videoList.current = res.data.current;
_this.setData({
videoList: _this.data.videoList
})
} else {
_this.setData({
videoList: res.data
})
}
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
getAudio(page = 1) {
let _this = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
pageNum: page
}, `/audio/page`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
if (page != 1) {
this.data.audioList.data.push.apply(this.data.audioList.data, res.data.data);
this.data.audioList.current = res.data.current;
_this.setData({
audioList: _this.data.audioList
})
} else {
_this.setData({
audioList: res.data
})
}
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
clickNav(e) {
let type = e.currentTarget.dataset.type;
if (type == 'music') {
this.getAudio(1);
this.setData({
is_match: true
})
} else {
this.getVideo(1);
this.setData({
is_match: false
})
}
},
clickPlayer(e) {
let id = e.currentTarget.dataset.id;
wx.navigateTo({
url: `/pages/music/audio/audio?id=${id}`,
})
},
clickMessage(e){
let id = e.currentTarget.dataset.id;
wx.navigateTo({
url: `/pages/music/video/video?id=${id}`,
})
// config.mytoast('暂未开放,敬请期待...', (res) => { });
},
clickCollect(){
config.mytoast('暂未开放,敬请期待...', (res) => { });
},
clickComment(e) {
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (!this.data.STATUS.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
if (this.data.STATUS.userAuth != 1) {
config.mytoast('您尚未实名认证,请前往认证!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
}, 500)
return false;
}
if (!this.data.STATUS.vipLevel) {
config.mytoast('请购买会员后再评论~', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/member/member',
})
}, 500)
return false;
}
let id = e.currentTarget.dataset.id;
// is_comment
this.setData({
is_comment: true,
commentInfo: {
id: id
}
})
},
formSubmitComment(e) {
let content = e.detail.value.content
console.log(
'videoId:' + this.data.commentInfo.id,
"content:" + content);
config.ajax('POST', {
videoId: this.data.commentInfo.id,
content: content
}, `/video/video-comment/add`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
if (this.is_match) {
//音频
this.getAudio();
} else {
//视频
this.getVideo();
}
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
commentBlur() {
this.setData({
is_comment: false,
})
},
video_play(e){
let that = this;
console.log(that.data.current);
if (!that.data.current) {//判断是否有播放的视频
// that.data.videoList.data.forEach((value)=>{
// let video = wx.createVideoContext('myVideo_' + value.id)
// video.stop()
// })
this.setData({//没有视频播放时
current: e.currentTarget.id
})
this.videoContext = wx.createVideoContext(e.currentTarget.id)
this.videoContext.play()
} else {
if(e.currentTarget.id != this.data.current){
this.videoContext.stop()
}
this.setData({
current: e.currentTarget.id
})
this.videoContext = wx.createVideoContext(e.currentTarget.id)
this.videoContext.play()
}
}
})<file_sep>
const config = require('../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
desc:'',
upload_list: [],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
changeLength(e){
if(e.detail.value.length > 120){
config.mytoast('字符大于120,请精简!', (res) => { })
}
this.setData({
desc: e.detail.value
})
},
closeImg(e){
let index = e.currentTarget.dataset.index;
let arr = this.data.upload_list;
arr.splice(index,1);
this.setData({
upload_list: arr
})
},
chooseImage() {
let _this = this;
let arr = _this.data.upload_list;
if (arr.length >= 9) {
config.mytoast('图片不能大于9张', (res) => { });
return false;
}
wx.chooseImage({
count: 9,
// sizeType: 'original',
sizeType: 'compressed',
success: function (res) {
res.tempFilePaths.forEach((value,index)=>{
// let value = res.tempFilePaths[0];
let suffix = value.substring(value.lastIndexOf('.'));
wx.getFileSystemManager().readFile({
filePath: value, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
let arrList = _this.data.upload_list;
arrList.push({
src: value,
img: res.data,
imgExt: suffix
});
_this.setData({
upload_list: arrList,
})
}
})
})
},
})
},
addSelfIntroduce(e) {
let _this = this;
console.log(e.detail);
if (!e.detail.value.remark){
config.mytoast('描述信息不能为空', (res) => { })
return false;
}
if (!e.detail.value.phone ){
config.mytoast('联系方式不能为空', (res) => { })
return false;
}
if (e.detail.value.phone.length != 11){
config.mytoast('请输入正确的手机号', (res) => { })
return false;
}
wx.showLoading({
title: '数据提交中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
remark: e.detail.value.remark,
phone: e.detail.value.phone,
imgList:_this.data.upload_list
}, `/feedback/add`, (res) => {
wx.hideLoading();
if (res.data.code == 1) {
config.mytoast('提交成功,正在跳转...', (res) => { })
wx.navigateBack({})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
})<file_sep>// pages/myself/setting/setting.js
const config = require('../../../utils/config.js');
let app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
switchChecked:true,
STATUS: null,
noCode: false,
isShow_wx:false,
},
ready:function(){
this.getStatus();
},
/**
* 组件的方法列表
*/
methods: {
showWx(){
this.setData({
isShow_wx:true
})
},
closeMask() {
this.setData({
isShow_wx: false
})
},
not_open_yet() {
config.mytoast('暂未开放,敬请期待...', (res) => { });
},
edit() {
this.setData({
noCode: true
})
},
cancel() {
this.setData({
noCode: false
})
},
addSelfIntroduce(e) {
console.log(e.detail);
if (!e.detail.value.remark){
config.mytoast('注销原因不能为空', (res) => { })
return false;
}
wx.showLoading({
title: '资料注销中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
remark: e.detail.value.remark
}, `/user/unsubscribe`, (res) => {
wx.hideLoading();
if (res.data.code == 1) {
config.mytoast('资料注销成功,正在跳转...', (res) => { })
// wx.setStorageSync('token', null)
// wx.navigateTo({
// url: '/pages/login/index',
// })
wx.navigateBack({})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
switchChecked(e){
let value = e.detail.value;
if (!this.data.STATUS.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
this.setData({
switchChecked: !value
})
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
if (this.data.STATUS.userAuth != 1) {
config.mytoast('您尚未实名认证,请前往认证!', (res) => { });
this.setData({
switchChecked: !value
})
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
}, 500)
return false;
}
if (!this.data.STATUS.vipLevel) {
config.mytoast('请购买会员后查看~', (res) => { });
this.setData({
switchChecked: !value
})
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/member/member',
})
}, 500)
return false;
}
},
getStatus() {
let _this = this;
config.ajax('GET', {
}, `/auth/status`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
STATUS: res.data
})
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
},
})
<file_sep>var WxParse = require('../../../wxParse/wxParse.js');
const config = require('../../../utils/config.js');
//获取应用实例
const app = getApp()
Page({
data: {
id: null,
article: ``,
info: null,
},
onLoad: function (e) {
this.setData({
id: e.id
});
this.getInit(e.id);
},
getInit(id) {
let that = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {}, `/article/${id}`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
that.setData({
info: res.data
})
WxParse.wxParse('article', 'html', res.data.content, this, 0);
}else{
config.mytoast('id不能为空', (res) => { })
wx.navigateBack({
})
}
}, (res) => {
}, (resp) => {})
},
})<file_sep>// pages/login/login/login.js
const config = require('../../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
back_url:null,
isShow_wx:false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if(options.back_url){
this.setData({
back_url: options.back_url
})
}
},
formSubmit(e) {
let form = e.detail.value;
console.log(form);
if (form.loginName == '') {
config.mytoast('手机号不能为空', (res) => { })
return false
}
if (form.password == '') {
config.mytoast('密码不能为空', (res) => { })
return false
}
config.ajax('POST', {
openId: app.globalData.uid,
loginName: form.loginName,
password: <PASSWORD>
}, config.userlogin, (res) => {
console.log(res.data);
if (res.data.code == 1) {
wx.setStorageSync('token', res.data.data)
if (this.data.back_url){
wx.navigateBack({})
}else{
wx.reLaunch({
url: '/pages/home/index'
})
}
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
showWx() {
this.setData({
isShow_wx: true
})
},
closeMask() {
this.setData({
isShow_wx: false
})
},
})<file_sep>const config = require('../../../../utils/config.js');
let app = getApp()
Page({
data: {
src: '',
width: 300,//宽度
height: 168,//高度,
angle:0
},
onLoad: function (options) {
//获取到image-cropper实例
this.cropper = this.selectComponent("#image-cropper");
//开始裁剪
this.setData({
src: options.src
});
wx.showLoading({
title: '加载中'
})
},
cropperload(e) {
console.log("cropper初始化完成");
},
loadimage(e) {
console.log("图片加载完成", e.detail);
wx.hideLoading();
//重置图片角度、缩放、位置
this.cropper.imgReset();
},
imgResets(e) {
this.setData({
angle: 0
})
//重置图片角度、缩放、位置
this.cropper.imgReset();
},
clickcut(e) {
console.log(e.detail);
//点击裁剪框阅览图片
wx.previewImage({
current: e.detail.url, // 当前显示图片的http链接
urls: [e.detail.url] // 需要预览的图片http链接列表
})
},
uploadTap() {
this.cropper.upload()
},
rotateImg(){
let angle = this.data.angle;
console.log(angle);
// if (angle > 270){
// angle = 0;
// }
angle += 90
this.cropper.setAngle(angle)
this.setData({
angle: angle
})
},
//这个是保存上传裁剪后的图片的方法
getCropperImage() {
var that = this
this.cropper.getImg((avatar) => {
if (avatar) {
uploadImage(avatar, function (res) { })
function uploadImage(filePathJson, cb) {
let filePath = filePathJson.url;
console.log(filePath);
let suffix = filePath.substring(filePath.lastIndexOf('.'));
wx.getFileSystemManager().readFile({
filePath: filePath, //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
let json = {
"image": res.data,
"imageExt": suffix,
}
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', json, `/user/updateUserImage`, (resp) => {
let res = resp.data;
wx.hideLoading();
cb(res);
if (res.code == 1) {
wx.showToast({
title: '上传成功',
})
wx.redirectTo({
url: '/pages/myself/introduction/introduction',
})
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
}
})
}
} else {
console.log('获取图片失败,请稍后重试')
}
})
},
})<file_sep>// pages/index/exact_match/exact_match.js
const config = require('../../../utils/config.js');
let app = getApp()
Page({
data: {
sexArray: ['女', '男'],
ageArray: [],
heightArray: [],
weightArray:[],
educationArray: ['初中', '高中', '大专', '本科', '研究生', '博士', '博士后'],
maritalStatusArray: ['未婚', '丧偶', '离异'],
hasChildArray: ['无', '1个', '2个', '3个及以上'],
expectMarriedArray: ['半年内', '一年内', '两年内'],
annualIncomeArray: ['3-8万', '8-12万', '12-20万', '20-30万', '30-100万', '100万以上'],
zodiacArray: ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'],
constellationArray: ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'],
age: null,
height: null,
weight:null,
education: null,
maritalStatus: null,
hasChild: null,
// profession: null, //职业
expectMarried:null, //期望多久结婚
nowResidence:[],
nativePlace:[], //户籍
annualIncome:null,
constellation:null,
zodiac:null,
info:{
sex: null,
age:null,
height: null,
weight: null,
education: null,
maritalStatus: null,
hasChild: null,
profession: null, //职业
nation: null, //民族
expectMarried:null,
nowResidence: null,
nativePlace:null, //户籍
annualIncome: null,
constellation: null,
zodiac: null,
wechatAccount:null //微信账户
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let ageArray = [];
let heightArray = [];
let weightArray = [];
for (let i = 18; i <= 60; i++) {
ageArray.push(i);
}
for (let i = 140; i <= 240; i++) {
heightArray.push(i);
}
for (let i = 40; i <= 120; i++) {
weightArray.push(i);
}
this.setData({
"ageArray": ageArray,
"heightArray": heightArray,
"weightArray": weightArray,
})
this.getInit();
},
clickProfession(e) {
this.setData({
"info.profession": e.detail.value,
})
},
clickNation(e) {
this.setData({
"info.nation": e.detail.value,
})
},
clickWechat(e) {
this.setData({
"info.wechatAccount": e.detail.value,
})
},
getArrayIndex(arr, obj) {
var i = arr.length;
while(i--) {
if (arr[i] === obj) {
return i;
}
}
return -1;
},
getInit(){
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {}, `/user/`, (res) => {
wx.hideLoading();
if (res.data.code == 1) {
let date = res.data.data
let _age = this.getArrayIndex(this.data.ageArray, date.age)
let _height = this.getArrayIndex(this.data.heightArray, Number(date.height))
let _constellation = this.getArrayIndex(this.data.constellationArray, date.constellation)
let _zodiac = this.getArrayIndex(this.data.zodiacArray, date.zodiac)
this.setData({
info: date,
age: _age,
height: _height,
education: Number(date.education) - 1,
maritalStatus: date.maritalStatus,
hasChild: date.hasChild,
expectMarried: date.expectMarried,
nowResidence: date.nowResidence.split('-'),
nativePlace: date.nativePlace.split('-'),
annualIncome: date.annualIncome,
constellation: _constellation,
zodiac: _zodiac
})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
bindPickerChangeSex: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
"info.sex": e.detail.value
})
},
bindPickerChangeAge: function (e) {
let age = this.data.ageArray[e.detail.value];
this.setData({
"age": e.detail.value,
"info.age": age
})
},
bindPickerChangeHeight: function (e) {
let value = this.data.heightArray[e.detail.value];
this.setData({
"height": e.detail.value,
"info.height": value
})
},
bindPickerChangeWeight: function (e) {
let value = this.data.weightArray[e.detail.value];
console.log(value);
this.setData({
"weight": e.detail.value,
"info.weight": value
})
},
bindPickerChangeEducation: function (e) {
this.setData({
"education": e.detail.value,
"info.education": Number(e.detail.value)+1
})
},
bindPickerChangeMaritalStatus: function (e) {
this.setData({
"maritalStatus": e.detail.value,
"info.maritalStatus": Number(e.detail.value)
})
},
bindPickerChangeHasChild: function (e) {
this.setData({
"hasChild": e.detail.value,
"info.hasChild": Number(e.detail.value)
})
},
bindPickerChangeExpectMarried: function (e) {
this.setData({
"expectMarried": e.detail.value,
"info.expectMarried": Number(e.detail.value)
})
},
bindPickerChangeAddress: function (e) {
let address = e.detail.value.join('-');
this.setData({
"nowResidence": e.detail.value,
"info.nowResidence": address
})
},
bindPickerChangeAddressNativePlace: function (e) {
let address = e.detail.value.join('-');
this.setData({
"nativePlace": e.detail.value,
"info.nativePlace": address
})
},
bindPickerChangeAnnualIncome: function (e) {
this.setData({
"annualIncome": e.detail.value,
"info.annualIncome": Number(e.detail.value)
})
},
bindPickerChangeConstellation: function (e) {
let value = this.data.constellationArray[e.detail.value];
this.setData({
"constellation": e.detail.value,
"info.constellation": value
})
},
bindPickerChangeZodiac: function (e) {
let value = this.data.zodiacArray[e.detail.value];
this.setData({
"zodiac": e.detail.value,
"info.zodiac": value
})
},
btn(){
let info = this.data.info;
if (info.sex == null) {
config.mytoast('性别不能为空', (res) => { })
return false;
}
if (!info.age) {
config.mytoast('年龄不能为空', (res) => { })
return false;
}
if (!info.height) {
config.mytoast('身高不能为空', (res) => { })
return false;
}
if (!info.education) {
config.mytoast('学历不能为空', (res) => { })
return false;
}
if (info.maritalStatus == null) {
config.mytoast('婚况不能为空', (res) => { })
return false;
}
if (info.hasChild == null) {
config.mytoast('有无子女不能为空', (res) => { })
return false;
}
if (info.expectMarried == null) {
config.mytoast('期望多久结婚不能为空', (res) => { })
return false;
}
if (!info.nativePlace) {
config.mytoast('户籍不能为空', (res) => { })
return false;
}
if (!info.nowResidence) {
config.mytoast('现居住地不能为空', (res) => { })
return false;
}
if (info.annualIncome == null) {
config.mytoast('年收入不能为空', (res) => { })
return false;
}
if (!info.constellation) {
config.mytoast('星座不能为空', (res) => { })
return false;
}
if (!info.zodiac) {
config.mytoast('属相不能为空', (res) => { })
return false;
}
if (!info.nation) {
config.mytoast('民族不能为空', (res) => { })
return false;
}
if (!info.profession) {
config.mytoast('职业不能为空', (res) => { })
return false;
}
wx.showLoading({
title: '数据保存中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', info, `/user/user/update`, (res) => {
wx.hideLoading();
if (res.data.code == 1) {
config.mytoast('保存成功,正在跳转...', (res) => { })
// wx.switchTab({
// url: '/pages/home/index',
// })
wx.navigateBack({})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
}
})<file_sep>// pages/index/exact_match/exact_match.js
const config = require('../../../../utils/config.js');
let app = getApp()
Page({
data: {
mate:null,
info:{}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getInit();
},
getArrayIndex(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i].name === obj) {
return i;
}
}
return -1;
},
getInit() {
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {}, `/personal/mate-choice/initMateChoise`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
this.setData({
mate:res.data
})
this.getDetail()
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
getDetail() {
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {}, `/personal/mate-choice/getMateChoiseList`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
let arr = res.data;
let json = {};
arr.forEach((value)=>{
json[value.ruleName] = {
ruleName: value.ruleName,
ruleDesc: value.ruleDesc,
ruleValue: value.ruleValue
}
})
this.setData({
info: json
})
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
bindPickerChange: function (e) {
// console.log('picker发送选择改变,携带值为', e)
let _index = e.detail.value;
let type = e.currentTarget.dataset.value;
//获取数组下标
let mate_index = this.getArrayIndex(this.data.mate,type);
//获取已选择的参数
let _name = this.data.mate[mate_index].value
let _value = this.data.mate[mate_index].properties[_index].value
let _desc = this.data.mate[mate_index].properties[_index].desc
let _ruleType = this.data.mate[mate_index].properties[_index].type
let info = {};
info[type] = {
ruleNameZh:_name,
ruleName: type,
ruleValue: _value,
ruleDesc: _desc,
ruleType: _ruleType
};
let _info = Object.assign({}, this.data.info,info)
this.add(info[type]);
this.setData({
info: _info
})
// console.log(this.data.info);
},
bindPickerChangeAddress: function (e) {
let address = e.detail.value.join('-');
console.log(address);
let type = e.currentTarget.dataset.value;
//获取数组下标
let mate_index = this.getArrayIndex(this.data.mate, type);
//获取已选择的参数
let _name = this.data.mate[mate_index].value
let _value = address
let _desc = address
let _ruleType = '='
let info = {};
info[type] = {
ruleNameZh: _name,
ruleName: type,
ruleValue: _value,
ruleDesc: _desc,
ruleType: _ruleType
};
let _info = Object.assign({}, this.data.info, info)
this.add(info[type]);
this.setData({
info: _info
})
},
add(json) {
let info = this.data.info;
wx.showLoading({
title: '数据保存中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', json, `/personal/mate-choice/add`, (res) => {
wx.hideLoading();
if (res.data.code == 1) {
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
btn() {
let info = this.data.info;
wx.navigateBack({})
// wx.showLoading({
// title: '数据保存中...',
// mask: true,
// success: function (res) { },
// fail: function (res) { },
// complete: function (res) { },
// })
// config.ajax('POST', info, `/personal/mate-choice/add`, (res) => {
// wx.hideLoading();
// if (res.data.code == 1) {
// config.mytoast('保存成功,正在跳转...', (res) => { })
// wx.navigateBack({})
// } else {
// config.mytoast(res.data.msg, (res) => { })
// }
// }, (res) => {
// })
}
})<file_sep>// Components/myToast.js
Component({
/**
* 组件的属性列表
*/
properties: {
noCode: {
type: Boolean,
value: false
},
otherdetail: {
type: String,
value: '您尚未注册,点击立即注册'
},
step: {
type: Object,
value: null
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
hideMask() {
// this.setData({
// noCode:false
// })
wx.switchTab({
url: '/pages/home/index',
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
},
goloading() {
if (!this.data.step.completeInfo) {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
} else if (this.data.step.userAuth != 1) {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
} else {
wx.navigateTo({
url: '/pages/home/index/',
})
}
}
}
})
<file_sep>
const config = require('../../../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
img:{
frontImgSrc: '',
"frontImg": "string //身份证正面照 base64",
"frontImgExt": "string //身份证正面照后缀",
"backImg": "string //身份证反面照base64",
"backImgExt": "string //身份证反面照后缀",
backImgSrc:''
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
chooseImageFront() {
let _this = this;
wx.chooseImage({
count: 1,
// sizeType: 'original',
sizeType: 'compressed',
success: function (res) {
let str = res.tempFilePaths[0];
_this.setData({
"img.frontImgSrc": str
})
let suffix = str.substring(str.lastIndexOf('.'));
wx.getFileSystemManager().readFile({
filePath: res.tempFilePaths[0], //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
_this.setData({
"img.frontImg": res.data,
"img.frontImgExt": suffix,
})
}
})
},
})
},
chooseImageBack() {
let _this = this;
wx.chooseImage({
count: 1,
// sizeType: 'original',
sizeType: 'compressed',
success: function (res) {
let str = res.tempFilePaths[0];
_this.setData({
"img.backImgSrc": str
})
let suffix = str.substring(str.lastIndexOf('.'));
wx.getFileSystemManager().readFile({
filePath: res.tempFilePaths[0], //选择图片返回的相对路径
encoding: 'base64', //编码格式
success: res => { //成功的回调
_this.setData({
"img.backImg": res.data,
"img.backImgExt": suffix,
})
}
})
},
})
},
validate(card){
const REGS = {
ID_CARD_REG: /^(\d{18}$|^\d{17}(\d|X|x))$/,
};
return REGS.ID_CARD_REG.test(card.trim())
},
bindFormSubmit(e){
let _this = this;
if (!this.validate(e.detail.value.identityCard)) {
config.mytoast('请填写正确的身份证号码', (res) => { });
return false;
}
if (!e.detail.value.name) {
config.mytoast('姓名不能为空', (res) => { });
return false;
}
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
openId: app.globalData.uid,
name: e.detail.value.name,
identityCard: e.detail.value.identityCard,
frontImg: _this.data.img.frontImg,
frontImgExt: _this.data.img.frontImgExt,
backImg: _this.data.img.backImg,
backImgExt: _this.data.img.backImgExt,
}, `/auth/user`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
config.mytoast('认证成功', (res) => { });
wx.navigateBack()
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
}
})<file_sep>// pages/music/video/video.js
const config = require('../../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
id: null,
isOpen: false,
starttime: '00:00', //正在播放时长
duration: '00:00', //总时长,
video: null,
list: null,
value: null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
id: options.id
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.videoPlay();
this.getInit();
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.list.current < this.data.list.pages) {
let page = this.data.list.current + 1;
this.getInit(page);
}
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
var that = this;
// 设置菜单中的转发按钮触发转发事件时的转发内容
var shareObj = {
title: `${video.title}`, // 默认是小程序的名称(可以写slogan等)
path: `pages/music/video/video?id=${that.id}`, // 默认是当前页面,必须是以‘/’开头的完整路径
imageUrl: '', //自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
};
// 来自页面内的按钮的转发
if (options.from == 'button') {
var eData = options.target.dataset;
// that.shareData(eData);
}
// 返回shareObj
return shareObj;
},
videoPlay: function () {
let that = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {
}, `/video/${this.data.id}`, (resp) => {
let res = resp.data;
wx.hideLoading();
if (res.code == 1) {
// this.videoDetail(res.data);
this.setData({
poster: res.data.imgUrl,
video: res.data
})
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
commentBlur(e) {
let content = e.detail.value
config.ajax('POST', {
videoId: this.data.id,
content: content
}, `/video/video-comment/add`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.getInit();
this.setData({
value: ''
})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
getInit(page = 1) {
let that = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
pageNum: page
}, `/video/video-comment/page`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (page != 1) {
this.data.list.data.push.apply(this.data.list.data, res.data.data);
this.data.list.current = res.data.current;
that.setData({
list: that.data.list
})
} else {
that.setData({
list: res.data
})
}
}, (res) => {
})
},
goUrl(e) {
let url = e.currentTarget.dataset.url;
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (url) {
wx.navigateTo({
url: url,
})
} else {
config.mytoast('暂未开放,敬请期待...', (res) => { });
}
},
not_open_yet() {
config.mytoast('暂未开放,敬请期待...', (res) => { });
},
})<file_sep>// pages/login/index.js
const config = require('../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
type:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if(options.url){
this.setData({
type: options.url
})
}
},
onUnload:function(){
// if (this.data.type == 'back_home') {
// wx.reLaunch({
// url: '/pages/myself/myself?url=back_home'
// })
// }
},
/**
* 保存用户头像
*/
savaUserInfo() {
config.ajax('POST', {
openId: app.globalData.uid,
avatarUrl: app.globalData.userInfo.avatarUrl,
nickName: app.globalData.userInfo.nickName,
gender: app.globalData.userInfo.gender,
province: app.globalData.userInfo.province,
city: app.globalData.userInfo.city,
country: app.globalData.userInfo.country
}, config.saveInfo, (res) => {
if (res.data.msg == "成功") {
wx.redirectTo({
url: '/pages/login/login/login'
})
}
}, (res) => {
})
},
/**
* 获取用户信息
*/
onGotUserInfo(e) {
console.log(e.detail.userInfo)
app.globalData.userInfo = e.detail.userInfo
config.getuid((res) => {
console.log('onGotUserInfo---', res);
if (res.data.code == 1) {
app.globalData.uid = res.data.data
this.savaUserInfo()
} else {
config.mytoast('服务器错误,请稍后再试', (res) => { })
}
}, (res) => { })
}
})<file_sep>// pages/home/index.js
const config = require('../../utils/config.js');
let app = getApp()
let timer = null
Page({
/**
* 页面的初始数据
*/
data: {
currentSwiper: 0,
currentSwiperNav: 0,
background: [],
topList: [],
recommendUserList:[],
annualIncomeArray: ['3-8万', '8-12万', '12-20万', '20-30万', '30-100万', '100万以上'],
expectMarriedArray: ['半年内', '一年内', '两年内'],
hasUserInfo:false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
noCode: false,
info:null,
home:null,
vipLevel:false,
isShow_wx:false,
backTopValue:false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let _this = this;
let token = wx.getStorageSync('token') || null;
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
if (!token) {
wx.navigateTo({
url: '/pages/login/login/login'
})
return false;
}
} else if (this.data.canIUse) {
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
if (this.data.hasUserInfo == false) {
clearTimeout(timer);
wx.navigateTo({
url: '/pages/login/index'
})
return false;
}
if (!token) {
clearTimeout(timer);
wx.navigateTo({
url: '/pages/login/login/login'
})
return false;
}
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
},
})
if (this.data.hasUserInfo == false) {
wx.navigateTo({
url: '/pages/login/index'
})
return false;
}
if (!token) {
wx.navigateTo({
url: '/pages/login/login/login'
})
return false;
}
}
// timer = setTimeout(function () {
// console.log('hasUserInfo-4--', _this.data.hasUserInfo);
// if (_this.data.hasUserInfo == false) {
// wx.navigateTo({
// url: '/pages/login/index'
// })
// }
// if (!token) {
// wx.navigateTo({
// url: '/pages/login/login/login'
// })
// }
// }, 2000)
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.getHome();
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.getInit();
// this.getBanner();
this.getTopList()
this.getRecommendUser();
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.recommendUserList.current < this.data.recommendUserList.pages) {
let page = this.data.recommendUserList.current + 1;
this.getRecommendUser(page);
}
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
getInit() {
let _this = this;
config.ajax('GET', {
}, `/auth/status`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
info: res.data
})
} else {
}
}, (res) => {
})
},
isVip(e){
let id = e.currentTarget.dataset.id;
var token = wx.getStorageSync('token')
console.log(app.globalData.userInfo);
console.log(token);
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (this.data.info.vipLevel){
let url = `/pages/introduction/introduction?id=${id}`
wx.navigateTo({
url: url,
})
}else{
config.mytoast('您还不是会员,暂不能查看他/她的个人信息', (res) => { })
wx.navigateTo({
url: '/pages/myself/member/member',
})
}
},
getHome() {
config.ajax('GET', {
}, config.getHome, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
home: res.data
});
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
getBanner() {
config.ajax('POST', {
type:1
}, config.getBanner, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.setData({
background: res.data.data.data
});
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
getTopList() {
config.ajax('GET', {
pageSize: 100,
pageNum: 1
}, `/user/topList`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
topList: res.data
});
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
getRecommendUser(page = 1) {
let that = this;
config.ajax('GET', {
pageSize: 10,
pageNum: page
}, `/user/topList`, (resp) => {
let res = resp.data;
if (res.code == 1) {
if (page != 1) {
this.data.recommendUserList.data.push.apply(this.data.recommendUserList.data, res.data.data);
this.data.recommendUserList.current = res.data.current;
that.setData({
recommendUserList: that.data.recommendUserList
})
} else {
that.setData({
recommendUserList: res.data
})
}
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
not_open_yet(){
config.mytoast('暂未开放,敬请期待...', (res) => { });
},
goUrl(e) {
let url = e.currentTarget.dataset.url;
var token = wx.getStorageSync('token')
console.log(app.globalData.userInfo);
console.log(token);
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function(){
wx.navigateTo({
url: '/pages/login/index',
})
},500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
console.log(url);
if (url) {
wx.navigateTo({
url: url,
})
} else {
config.mytoast('暂未开放,敬请期待...', (res) => { });
}
},
showWx(){
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (!this.data.info.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
if (this.data.info.userAuth != 1) {
config.mytoast('您尚未实名认证,请前往认证!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
}, 500)
return false;
}
if (!this.data.info.vipLevel) {
config.mytoast('请购买会员后查看~', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/member/member',
})
}, 500)
return false;
}
this.setData({
isShow_wx:true
})
},
closeMask() {
this.setData({
isShow_wx: false
})
},
swiperChange(e) {
this.setData({
currentSwiperNav: e.detail.current
})
},
onPageScroll(e){
var that = this
var scrollTop = e.scrollTop
var backTopValue = scrollTop > 500 ? true : false
that.setData({
backTopValue: backTopValue
})
},
backTop(){
wx.pageScrollTo({
scrollTop: 0,
})
}
})<file_sep>
const config = require('../../utils/config.js');
var WxParse = require('../../wxParse/wxParse.js');
let app = getApp()
let timer = null
Page({
/**
* 页面的初始数据
*/
data: {
info: null,
list: null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.getStatus();
this.getInit();
},
/**
* 页面下拉刷新
*/
onPullDownRefresh() {
wx.showNavigationBarLoading();
this.getInit();
wx.hideNavigationBarLoading();
wx.stopPullDownRefresh();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.list.current < this.data.list.pages) {
let page = this.data.list.current + 1;
this.getInit(page);
}
},
getStatus() {
let _this = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {
}, `/auth/status`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
this.setData({
info: res.data
})
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
isVip(e) {
let id = e.currentTarget.dataset.id;
if (this.data.info.vipLevel) {
let url = `/pages/introduction/introduction?id=${id}`
wx.navigateTo({
url: url,
})
} else {
config.mytoast('您还不是会员,暂不能查看他/她的个人信息', (res) => { })
wx.navigateTo({
url: '/pages/myself/member/member',
})
}
},
getInit(page = 1) {
let that = this;
config.ajax('POST', {
}, `/article/page`, (resp) => {
let res = resp.data;
if (res.code == 1) {
if (page != 1) {
this.data.list.data.push.apply(this.data.list.data, res.data.data);
this.data.list.current = res.data.current;
that.setData({
list: that.data.list
})
} else {
// WxParse.wxParse('article', 'html', res.data.content, this, 0);
that.setData({
list: res.data
})
}
} else {
config.mytoast(res.msg, (res) => { })
}
}, (res) => {
})
},
})<file_sep>// pages/single/my_single/my_single.js
const config = require('../../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
draftCount: [],
list: [],
is_comment: false,
commentInfo: null,
STATUS: null,
user_id: null,
show: true
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.getInit();
this.getStatus();
this.getUserId();
},
previewImg(e) {
//预览图片
var src = e.currentTarget.dataset.src;//获取data-src
var imgList = e.currentTarget.dataset.list;//获取data-list
let urls = []
imgList.forEach((value) => {
urls.push(value.url);
})
wx.previewImage({
current: src, // 当前显示图片的http链接
urls: urls, // 需要预览的图片http链接列表
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面下拉刷新
*/
onPullDownRefresh() {
wx.showNavigationBarLoading();
this.getInit();
wx.hideNavigationBarLoading();
wx.stopPullDownRefresh();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.list.current < this.data.list.pages) {
let page = this.data.list.current + 1;
this.getInit(page);
}
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
var that = this;
// 设置菜单中的转发按钮触发转发事件时的转发内容
var shareObj = {
title: `单身圈`, // 默认是小程序的名称(可以写slogan等)
path: `/pages/single/index`, // 默认是当前页面,必须是以‘/’开头的完整路径
imageUrl: '', //自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
success: function (res) {
// 转发成功之后的回调
if (res.errMsg == 'shareAppMessage:ok') { }
},
fail: function (res) {
// 转发失败之后的回调
if (res.errMsg == 'shareAppMessage:fail cancel') {
// 用户取消转发
} else if (res.errMsg == 'shareAppMessage:fail') {
// 转发失败,其中 detail message 为详细失败信息
}
}
};
// 来自页面内的按钮的转发
if (options.from == 'button') {
var eData = options.target.dataset;
shareObj = {
title: `${eData.name}的单身圈`,
path: `/pages/single/user_single/user_single?id=${eData.id}`,
imageUrl: '',
};
that.shareData(eData);
}
// 返回shareObj
return shareObj;
},
shareData(data) {
let id = data.id;
let index = data.index;
config.ajax('POST', {
}, `/circle/single-circle/addForwardCount/${id}`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.getInit(1);
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
getInit(page = 1) {
let that = this;
this.setData({
show: true
})
config.ajax('GET', {
pageNum: page
}, `/circle/single-circle/self`, (resp) => {
let res = resp.data;
console.log(res);
if (page != 1) {
this.data.list.data.push.apply(this.data.list.data, res.data.singleCircle.data);
this.data.list.current = res.data.singleCircle.current;
that.setData({
list: that.data.list,
draftCount: res.data.draftCount
})
} else {
that.setData({
list: res.data.singleCircle,
draftCount: res.data.draftCount
})
}
that.setData({
show: false
})
}, (res) => {
that.setData({
show: false
})
})
},
clickShare(e) {
let id = e.currentTarget.dataset.id;
let index = e.currentTarget.dataset.index;
config.ajax('POST', {
}, `/circle/single-circle/addForwardCount/${id}`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.getInit(1);
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
clickPraise(e) {
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (!this.data.STATUS.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
let id = e.currentTarget.dataset.id;
let is_praise = e.currentTarget.dataset.is_praise;
let url = !is_praise ? '/praise/praise/add' : '/praise/praise/cancel';
config.ajax('POST', {
singleCircleId: id
}, url, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.getInit(1);
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
clickComment(e) {
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (!this.data.STATUS.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
if (this.data.STATUS.userAuth != 1) {
config.mytoast('您尚未实名认证,请前往认证!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
}, 500)
return false;
}
if (!this.data.STATUS.vipLevel) {
config.mytoast('请购买会员后再评论~', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/member/member',
})
}, 500)
return false;
}
let id = e.currentTarget.dataset.id;
let nickName = app.globalData.userInfo.nickName
// is_comment
this.setData({
is_comment: true,
commentInfo: {
id: id,
nickName: nickName
}
})
},
commentBlur() {
this.setData({
is_comment: false,
})
},
commentMore(e) {
let id = e.currentTarget.dataset.id;
let index = e.currentTarget.dataset.index;
let is_show_more = e.currentTarget.dataset.is_show_more;
if (is_show_more) {
this.getInit(1);
return false;
}
config.ajax('GET', {}, `/comment/comment/all/${id}`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
let commentList = res.data.data;
let list = this.data.list;
list.data[index].commentList = commentList;
list.data[index].is_show_more = true;
this.setData({
list: list
})
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
formSubmitComment(e) {
let content = e.detail.value.content
console.log(
'singleCircleId:' + this.data.commentInfo.id,
"nickName:" + this.data.commentInfo.nickName,
"content:" + content);
config.ajax('POST', {
singleCircleId: this.data.commentInfo.id,
nickName: this.data.commentInfo.nickName,
content: content
}, `/comment/comment/add`, (res) => {
console.log(res.data);
if (res.data.code == 1) {
this.getInit(1);
} else {
config.mytoast(res.data.msg, (res) => { })
}
}, (res) => {
})
},
getStatus() {
let _this = this;
config.ajax('GET', {
}, `/auth/status`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
STATUS: res.data
})
} else {
// config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
goUrl(e) {
let url = e.currentTarget.dataset.url;
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (url) {
wx.navigateTo({
url: url,
})
} else {
config.mytoast('暂未开放,敬请期待...', (res) => { });
}
},
deleteSingle(e) {
let id = e.currentTarget.dataset.id;
let _this = this;
console.log(e);
console.log(id);
wx.showLoading({
title: '删除中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('POST', {
}, `/circle/single-circle/delete/${id}`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
this.getInit();
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
getUserId() {
let _this = this;
config.ajax('GET', {
}, `/user/`, (resp) => {
let res = resp.data;
if (res.code == 1) {
if (res.data) {
this.setData({
user_id: res.data.id
})
}
} else {
// config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
}
})<file_sep>
const config = require('../../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
info:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
this.getStatus()
},
getStatus(){
let _this = this;
wx.showLoading({
title: '数据加载中...',
mask: true,
success: function (res) { },
fail: function (res) { },
complete: function (res) { },
})
config.ajax('GET', {
}, `/auth/status`, (resp) => {
wx.hideLoading();
let res = resp.data;
if (res.code == 1) {
this.setData({
info:res.data
})
if (res.data.userAuth == 2){
config.mytoast('认证失败,请重新认证!', (res) => { });
}
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
goUrl(e) {
let url = e.currentTarget.dataset.url;
let status = e.currentTarget.dataset.status;
if (status == 1 || status == 3){
return false;
}
wx.navigateTo({
url: url,
})
}
})<file_sep>const config = require('../../../utils/config.js');
let app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
info: null,
expectMarriedArray: ['半年内', '一年内', '两年内'],
list: null,
show: true,
isShow_wx: false,
url:'/user/page',
type:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
console.log(options);
if (options.url == 'sysMatch'){
this.setData({
url:'/user/sysMatch',
type:options.url
})
}
this.getStatus();
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
if (this.data.type == 'sysMatch'){
this.getInitGet();
}else{
this.getInit();
}
},
/**
* 页面下拉刷新
*/
onPullDownRefresh() {
wx.showNavigationBarLoading();
if (this.data.type == 'sysMatch') {
this.getInitGet();
} else {
this.getInit();
}
wx.hideNavigationBarLoading();
wx.stopPullDownRefresh();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
if (this.data.list.current < this.data.list.pages) {
let page = this.data.list.current + 1;
if (this.data.type == 'sysMatch') {
this.getInitGet(page);
} else {
this.getInit(page);
}
}
},
getStatus() {
let _this = this;
config.ajax('GET', {
}, `/auth/status`, (resp) => {
let res = resp.data;
if (res.code == 1) {
this.setData({
info: res.data
})
} else {
config.mytoast(res.msg, (res) => { });
}
}, (res) => {
})
},
isVip(e) {
let id = e.currentTarget.dataset.id;
if (this.data.info.vipLevel) {
let url = `/pages/introduction/introduction?id=${id}`
wx.navigateTo({
url: url,
})
} else {
config.mytoast('您还不是会员,暂不能查看他/她的个人信息', (res) => { })
wx.navigateTo({
url: '/pages/myself/member/member',
})
}
},
getInit(page = 1) {
let that = this;
this.setData({
show: true
})
config.ajax('POST', {
pageNum: page
}, `${that.data.url}`, (resp) => {
let res = resp.data;
if (res.code == 1) {
if (page != 1) {
this.data.list.data.push.apply(this.data.list.data, res.data.data);
this.data.list.current = res.data.current;
that.setData({
list: that.data.list
})
} else {
that.setData({
list: res.data
})
}
} else {
config.mytoast(res.msg, (res) => { })
}
that.setData({
show: false
})
}, (res) => {
that.setData({
show: false
})
})
},
getInitGet(page = 1) {
let that = this;
this.setData({
show: true
})
config.ajax('GET', {
pageNum: page
}, `${that.data.url}`, (resp) => {
let res = resp.data;
if (res.code == 1) {
if (page != 1) {
this.data.list.data.push.apply(this.data.list.data, res.data.data);
this.data.list.current = res.data.current;
that.setData({
list: that.data.list
})
} else {
that.setData({
list: res.data
})
}
} else {
config.mytoast(res.msg, (res) => { })
}
that.setData({
show: false
})
}, (res) => {
that.setData({
show: false
})
})
},
showWx() {
var token = wx.getStorageSync('token')
if (!app.globalData.userInfo) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/index',
})
}, 500)
return false;
}
if (!token) {
config.mytoast('您还未登录,请先登录', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/login/login/login',
})
}, 500)
return false;
}
if (!this.data.info.completeInfo) {
config.mytoast('您尚未完善个人资料,请前往填写!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/person_info/person_info',
})
}, 500)
return false;
}
if (this.data.info.userAuth != 1) {
config.mytoast('您尚未实名认证,请前往认证!', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/my_certification/my_certification',
})
}, 500)
return false;
}
if (!this.data.info.vipLevel) {
config.mytoast('请购买会员后查看~', (res) => { });
setTimeout(function () {
wx.navigateTo({
url: '/pages/myself/member/member',
})
}, 500)
return false;
}
this.setData({
isShow_wx: true
})
},
closeMask() {
this.setData({
isShow_wx: false
})
},
}) | 63901b8220caab40a8ac864ea5f56947200f5e2b | [
"JavaScript"
] | 21 | JavaScript | itliuzheng/beautiful_way_marriage | a2931d4235a86de40eea46442f80d4aa6fdcc168 | f078b1d23e784aca65adf4fffc47b341a5ae44b7 |
refs/heads/master | <file_sep>FROM ingemoen/ubuntu-pysql
RUN apt-get upgrade -y
RUN apt-get update
# This prevents Python from writing out pyc files
ENV PYTHONDONTWRITEBYTECODE 1
# This keeps Python from buffering stdin/stdout
ENV PYTHONUNBUFFERED 1
WORKDIR /usr/src/app
COPY . .
RUN pip3 install --no-cache-dir --upgrade pip && \
pip3 install --no-cache-dir -r requirements.txt
EXPOSE 8080
ENV FLASK_DEBUG 1
ENV FLASK_ENV development
ENTRYPOINT [ "/bin/bash", "./server.sh" ]
# ENTRYPOINT [ "/bin/bash" ]
# ENTRYPOINT [ "python", "src/app.py" ]<file_sep>Flask
requests
redis
pymssql
<file_sep>{% extends "base.html" %}
{% block header %}
<title>Kroppskunst.no - Om oss</title>
{% endblock %}
{% block content %}
<h1>Privacy Policy</h1>
<p>
Your privacy is important to us. So we’ve developed a Privacy Policy that covers how we collect, use, disclose,
transfer, and store your information. Please take a moment to familiarize yourself with our privacy practices and
let us know if you have any questions.
<br><br>
<b>Collection and Use of Personal Information</b><br>
Personal information is data that can be used to uniquely identify or contact a single person.
<br><br>
You may be asked to provide your personal information.
<br><br>
Here are some examples of the types of personal information we may collect and how we may use it.
<br><br>
<b>What personal information we collect</b><br>
When you create a Customer ID, we collect your e-mail address, country of residence and a password of your
choice.
We also store a preferred currency, who are linked to your country.
If you choose to buy anything, or if you choose to fill out the personal profile, we collect your full name,
street address, zip/city and optionally your phone number.
All credit card and/or payment handling are done by 3rd party companies like Visa, MasterCard, PayPal,
Vipps.
We do NOT under any circumstances store ANY payment information that might be linked to you or your account.
<br><br>
<b>How we use your personal information</b><br>
The personal information we collect allows us to ship you your purchased products.
We will send you our weekly newsletter as long as you have not deselected the newsletter by registration. If you
don’t want to be on our mailing list, you can opt out anytime by updating your preferences on your profile or click
on the unsubscribe link at the bottom of every newsletter.
We will NOT under any circumstances let any 3rd party companies access or use your personal information.
<br><br>
<b>Collection and Use of Non-Personal Information</b><br>
We also collect non-personal information - data in a form that does not permit direct association with any specific
individual. We may collect, use, transfer, and disclose non-personal information for any purpose. The following are
some examples of non-personal information that we collect and how we may use it:<br />
We may collect information such as type of device, location, what is clicked and time spent on a page, so that we
can better understand customer behaviour and improve our products, services, and advertising. If we do combine
non-personal information with personal information the combined information will be treated as personal information
for as long as it remains combined.
<br><br>
<b>Cookies and Other Technologies</b><br>
Our website use “cookies” and other technologies as pixel tags and web beacons. These technologies help us better
understand user behaviour, tell us which parts of our website people have visited, and facilitate and measure the
effectiveness of advertisements and web searches. We treat information collected by cookies and other technologies
as non-personal information, and does not link it you your account.
<br /><br />
We also use cookies and other technologies to remember personal information when you use our website. This is
information like your login ID etc.
<br /><br />
You may disable cookies for our site in your browser. Please note that certain features, as placing an order, will
not be possible once cookies are disabled.
<br /><br />
As is true of most websites, we gather some information automatically and store it in log files. This information
includes Internet Protocol (IP) addresses, browser type and language, Internet service provider (ISP), referring and
exit pages, operating system, date/time stamp, and clickstream data.
<br /><br />
We use this information to understand and analyse trends, to administer the site, to learn about user behaviour on
the site, and to gather demographic information about our user base as a whole.
<br /><br />
In some of our email messages, we use a “click-through URL” linked to content on our website. When customers click
one of these URLs, they pass through a separate web server before arriving at the destination page on our website.
We track this click-through data to help us determine interest in particular topics and measure the effectiveness of
our customer communications. If you prefer not to be tracked in this way, you should not click text or graphic links
in the email messages.
<br /><br />
Pixel tags enable us to send email messages in a format customers can read, and they tell us whether mail has been
opened. We may use this information to reduce or eliminate messages sent to customers.
<br><br>
<b>Disclosure to Third Parties</b><br>
We do NOT display or give any personal information to 3rd parties, except mandatory information to our 3rd party
payment partners as VISA, MasterCard, PayPal and Vipps upon payment of an order. Your information will NOT be
shared with third parties for their marketing purposes.
<br><br>
<b>Others</b><br>
It may be necessary - by law, legal process, litigation, and/or requests from public and governmental authorities
within or outside your country of residence - for us to disclose your personal information. As our operation is
placed in Norway, a Court Order from a Norwegian Court will be necessary for us to disclose any personal
information.
<br><br>
<b>Access to Personal Information</b><br>
You can help ensure that your contact information and preferences are accurate, complete, and up to date by logging
in to your account and update your profile. We do not store ANY other personal information other than the
information on your profile page.
<br><br>
<b>Privacy Questions</b><br>
If you have any questions or concerns about our Privacy Policy or data processing, please contact us.
</p>
{% endblock %}<file_sep>import pymssql
import os
sqlServer = os.getenv('SQL_SERVER', 'none')
sqlUser = os.getenv('SQL_USER', 'none')
sqlPass = os.getenv('SQL_PASS', '<PASSWORD>')
sqlDb = os.getenv('SQL_DB', 'none')
def db():
return pymssql.connect(server=sqlServer, user=sqlUser, password=<PASSWORD>, database=sqlDb)
def mySqlQuery(query, one=False):
cur = db().cursor()
cur.execute(query)
r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
cur.connection.close()
return (r[0] if r else None) if one else r
<file_sep>from flask import session
import os
import redis
import json
import uuid
redis_host = os.getenv('REDIS_SERVER', 'redis')
redis_port = os.getenv('REDIS_PORT', '6379')
redis_expire = os.getenv('REDIS_EXPIRE', '14400')
print(f"Using redis host at : {redis_host}:{redis_port}, with expire {redis_expire} seconds")
try:
redisClient = redis.Redis(redis_host, port=redis_port, db=0, decode_responses=True) # short timeout for the test
redisClient.ping()
except:
print(f"Redis is not running.")
exit(0)
def getOrder():
if not session.get('uuid'):
session['uuid'] = uuid.uuid4().hex
key = session.get('uuid')
order = redisClient.get(key)
if ((order == None) or ("uuid" not in order)):
print(f"Order is None")
order = {
'uuid' : key
}
setOrder(order)
return order
else:
# print(f"Order : {order}")
j = json.loads(order)
return j
def setOrder(order):
key = session.get('uuid')
res = redisClient.setex(key, redis_expire, json.dumps(order))
<file_sep>{% extends "base.html" %}
{% block header %}
<title>Kroppskunst.no - Om oss</title>
{% endblock %}
{% block content %}
<h1>Angre rett / Returer</h1>
<p>
<b>Den korte versjonen</b><br />
<ol>
<li>Hvis du vil returnere noe. Bare returner det til adressen på bunnen av denne siden.</li>
<li>Returner kun produkter hvor forseglingen ikke er brutt, hvis produktet ble levert forseglet.</li>
<li>Legg ved en eller annen identifikasjon på returen, og skriv på RETUR. Pakkseddelen er helt fin å bruke.</li>
<li>Vi aksepterer retur i 14 dager, og pengene vil innen 3 dager bli tilbakeført på samme måte som du betalte.</li>
<li>Vennligst gi VISA/Mastercard noen dager til sin prosessering (opptil 14 dager), PayPal prosseserer med en gang.</li>
</ol>
<b>Den lange utfyllende versjonen</b><br />
Vi følger norsk lov om angre rett og gir alle våre privatkunder rett til å angre i 14 dager.
<br /><br />
Noen produkter leveres med en hologram forsegling for å sikre at produktene ikke er brukt. Vennligst merk deg at vi IKKE GODTAR RETUR PÅ PRODUKTER HVOR FORSEGLINGEN ER BRUTT.
<br /><br />
For å kanselere ditt kjøp trenger du bare å returnere de produktene du ikke vil ha tilbake til oss innenfor 14 dager. Vennligst merk at du er ansvarlig for forsendelsen, og vi anbefaller at du pakker og sender varene på en forsvarlig måte.
<br /><br />
For din egen sikkerhet anbefaller vi at du sender varene sporbart om verdien på forsendelsen er høy. Vennligst merk deg at vi ikke mottar returer levert hos oss.
<br /><br />
Vi vil ved retur heve kjøpet for de produktene du har returnert. Vi vil også returnere relevant del av portokostnaden for prosendelsen. Vennligst merk deg at hvis du har hatt "gratis frakt" og ved returen kommer under grensen for gratis frakt, vil fraktkostnaden trekkes fra retur beløpet.
<br /><br />
Du kan velge mellom pengene tilbake eller en "tilgodelapp" i nettbutikken. Om du velger pengene tilbake vil pengene tilbakeføres på samme måte du betalte. Betalte du med kredittkort, tilbakeføres pengene på ditt kredittkort. (Vi trenger ikke ditt kredittkort, vennligst ikke send oss kort opplysninger. Av sikkerhetsmessige årsaker behandles alle kredittkort opplysninger av vår innløser, ettersom vi ikke lagrer dette hos oss).
<br /><br />
Nordiske kunder som betalte via bank overføring vil få sine penger tilbakeført dit. Når det gjelder tilbakeføringer til bank konto må du sende oss konto nummer, da vi kke lagrer dette hos oss.
<br /><br />
Vennligst noter klart og tydelig på returen om du ønsker gavekort eller pengene tilbake.
<br /><br />
Vi returnerer ikke penger fra kjøp gjort med kredittkort til bank konto, dette er ikke tillatt med den innløseravtalen vi har.
<br /><br />
Vennligst merk det at vi kun tilbyr retur for kreditt eller gavekort. Vi bytter ikke størrelser eller farger. Du trenger å gjøre en ny ordre for nye varer.
<br /><br />
For mer infoirmasjon om din rett til å angre ta kontakt med oss på <EMAIL>.
<br /><br />
Retten til å angre er KUN gjeldende for våre privatkunder. Forhandlere har andre kjøpsavtaler.
<br /><br />
<b>Retur adresse :</b>
<br /><br />
Inge Moen ENK<br />
Fransåsveien 11<br />
NO-3475 Sætre<br />
Norge<br />
</p>
{% endblock %}<file_sep>from flask import Blueprint, render_template
about = Blueprint('about', __name__, template_folder='templates')
@about.route('/')
@about.route('/us')
def index():
return render_template('us.html')
@about.route('/faq')
def faq():
return render_template('faq.html')
@about.route('/privacy')
def privacy():
return render_template('privacy.html')
@about.route('/returns')
def returns():
return render_template('returns.html')
@about.route('/sizes')
def sizes():
return render_template('sizes.html')
@about.route('/tc')
def tc():
return render_template('tc.html')
@about.route('/warranty')
def warranty():
return render_template('warranty.html')
<file_sep>#/bin/sh
python3 app/main.py<file_sep>import uuid
import os
import pprint
from flask import Flask, request, session, render_template, Response
########################
## Import MyLibs
########################
from lib.mySql import mySqlQuery
########################
## Import Modules
########################
from about.about import about
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'SetThisAsEnv')
app.register_blueprint(about, url_prefix='/about')
@app.route('/')
def index():
products = mySqlQuery('dbo.sp_ProductsGet_v3_00 @guid=76393978, @language=no, @page=0, @level0=1, @level1=1, @level2=185, @qtyin=100')
return render_template('index.html', products=products)
@app.route("/test")
def test():
str = pprint.pformat(request.environ, depth=5)
return Response(str, mimetype='text/plain')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080) | c48b740f78a432db9d28b97c48f73b6924793c61 | [
"HTML",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 9 | Dockerfile | ingemoen/kroppskunst | 3e365a58ca52e9e6413c3f7b9f7bd7b6054800bc | 2afca3126c14af0f4e623467f0d7146d545986db |
refs/heads/master | <file_sep>/*
하위요소에 각각 이벤트를 붙이지 않고
상위에서 하위 요소들의 이벤트를 제어하는 방식
*/
const itemList = document.querySelector('.itemList');
// let inputs = document.querySelectorAll('input');
// inputs.forEach(function(input){
// input.addEventListener('click', e => {
// console.log('clicked');
// })
// })
//상위요소에만 이벤트를 달아서 하위 이벤트 감지
//e.currentTarget와 target은 다름
//e.target는 실제 이벤트가 시작된 '타겟'
//e.currentTarget = this와 유사. 이벤트 등록된 주체?
//즉, 실제 눌린 곳(타겟)과 이벤트를 담고있는 그릇(currentTarget)
itemList.addEventListener('click', e =>{
console.log(e.currentTarget);
})
/*
기존에 이벤트를 추가했지만 더 요소들을 추가시킨다면
이벤트리스너등록이 안되어있을 것임
*/
let li = document.createElement('li');
let input = document.createElement('input');
let label = document.createElement('label');
let labelText = document.createTextNode('이벤트 위임 학습');
input.setAttribute('type', 'checkbox');
input.setAttribute('id', 'item3');
label.setAttribute('for', 'item3');
label.appendChild(labelText);
li.appendChild(input);
li.appendChild(label);
itemList.appendChild(li);<file_sep>import View from "./View.js";
const tag = "[ModeChangeView.js]";
/* theme changing element object*/
const DOM = {
headerTitleEl : document.querySelector('.header-title'),
headerDescribeEl : document.querySelector('.header-describe'),
contentEl: document.querySelector('.wrapper'),
body: document.body,
// todoSectionEl: document.querySelector(".todo-container"),
};
/* theme status object */
const status = {
currentTheme: localStorage.getItem("theme"),
preferDarkScheme: window.matchMedia("(prefers-color-scheme: dark)"),
};
const ModeChangeView = Object.create(View);
ModeChangeView.setup = function (el) {
this.init(el);
this.getUserConfigTheme()
.setUserConfigTheme()
.bindClickEvent();
return this;
};
ModeChangeView.bindClickEvent = function () {
this.el.addEventListener("click", (e) => this.onToggle(e));
};
ModeChangeView.onToggle = function (e) {
//theme item이 light => on, dark => off
this.toggleDarkAttribute();
DOM.contentEl.classList.contains("dark")
? localStorage.setItem("theme", "dark")
: localStorage.setItem("theme", "light");
};
ModeChangeView.toggleDarkAttribute = function () {
for (let element in DOM) {
DOM[element].classList.toggle("dark");
}
};
ModeChangeView.setUserConfigTheme = function () {
if (status.currentTheme == "dark") {
this.toggleDarkAttribute();
}
return this;
};
ModeChangeView.getUserConfigTheme = function () {
//If hasn't localStorage
if (!status.currentTheme) {
//false= light
status.preferDarkScheme.matches
? localStorage.setItem("theme", "dark")
: localStorage.setItem("theme", "light");
status.currentTheme = localStorage.getItem("theme");
}
return this;
};
export default ModeChangeView;
<file_sep>/*
1. fetch() 호출
2. 브라우저는 네트워크 요청을 보냄
3. 프로미스가 반환됨
좀 더 자세히 다루면 1, 2단계로 나눌 수 있는데
1단계
함수 호출 후 서버로부터 응답을 받는다.(promise)
아직 본문(body) 도착전이지만, 응답헤더를 보고 요청이 성공적인지 확인할 수 있음
2단계
추가 메소드를 호출해 응답 본문을 받는다.
fetch를 통해 반환받은 값은 response에는
다음과 같은 메소드를 가지고 이를 수행할 수 있음.
- .text()
- .json() 등,
예제 작성으로 넘어가자.
*/
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
.then(response => response.json())
.then(commits => console.log(commits[0].author.login));
let url = 'https://api.github.com/repos/javascript-tutorial/ko.javascript.info/commits';
let response = await fetch(url);
let commits = await response.json(); // 응답 본문을 읽고 JSON 형태로 파싱함
alert(commits[0].author.login);<file_sep>import App from './App.js';
new App(document.querySelector('main.App'));<file_sep>import { React, useState, useCallback } from 'react';
import { MdAdd } from 'react-icons/md';
import './TodoInsert.scss';
const TodoInsert = ({ onInsert }) => {
const [value, setValue] = useState('');
const [timer, setTimer] = useState(0);
const onChange = useCallback((e) => {
setValue(e.target.value);
//debouncing => 마지막 요청만 setTimeout내용 수행.
//Api 호출할 때 적용. 1초안에 그 요청이 있으면 clear하므로 내용 수행 X
if (timer) {
clearTimeout(timer);
}
const newTimer = setTimeout(() => {
// API CALL; 1초뒤에 수행되는 내용들
// 수행되기전에 같은 요청 다시 보내면 clear되버림.
}, 1000);
setTimer(newTimer);
});
const onSubmit = useCallback((e) => {
onInsert(value);
setValue('');
e.preventDefault();
//함수 안에서 사용되는 상태는 props로 받아온 함수도 포함 => 최신걸 참조하기 위해 다 적어줘
},[onInsert, value],)
return (
<form className="TodoInsert" onSubmit={onSubmit}>
<input
placeholder="Insert your something to do"
value={value}
onChange={onChange}
></input>
<button type="submit">
<MdAdd />
</button>
</form>
);
};
export default TodoInsert;
<file_sep>class SearchHistory {
historyData = {};
constructor({ $target, onSearch, prevSearchKeyword }) {
// localStorage.clear()
this.$target = $target;
this.onSearch = onSearch;
this.prevSearchKeyword = prevSearchKeyword;
this.initElement();
this.render();
this.bindClickEvent();
}
initElement() {
this.$historyWrapper = document.createElement("div");
this.$historyWrapper.className = "history-wrapper";
this.$historyList = document.createElement("ul");
this.$historyList.className = "history-list";
this.searchHistoryData = this.getLocalSearchHistory();
this.$target.appendChild(this.$historyWrapper);
this.$historyWrapper.appendChild(this.$historyList);
}
bindClickEvent() {
this.$historyList.addEventListener("click", (e) => {
e.stopPropagation();
let clickedKeyword = e.target.getAttribute("data-keyword");
this.$target.querySelector('.SearchInput').value = clickedKeyword;
this.onSearch(clickedKeyword);
});
}
getLocalSearchHistory() {
if (!localStorage.getItem("SearchHistoryData")) {
localStorage.setItem("SearchHistoryData", "[]"); //초기화
}
return JSON.parse(localStorage.getItem("SearchHistoryData"));
}
render() {
if (this.searchHistoryData) {
this.$historyList.innerHTML = this.searchHistoryData
.map((data) => {
return `<li data-keyword=${data.keyword} class="history-data">${data.keyword}
<button class="btn-history-remove">X</button></li>`;
})
.join("");
}
}
addSearchHistory(keyword = "") {
this.searchHistoryData = this.getLocalSearchHistory();
if (keyword === "" || keyword == null) return;
keyword = keyword.trim();
//현재 일 최근검색어에 추가
if (this.searchHistoryData.some((item) => item.keyword === keyword)) {
this.remove(keyword);
}
this.setData(keyword);
this.searchHistoryData.unshift(this.historyData);
if (this.searchHistoryData.length > 5) {
this.searchHistoryData.pop();
}
this.render();
localStorage.setItem(
"SearchHistoryData",
JSON.stringify(this.searchHistoryData)
);
}
setData(keyword) {
let dateObj = new Date();
let year = dateObj.getFullYear();
let month = dateObj.getMonth() + 1;
let day = dateObj.getDate();
this.historyData.keyword = keyword;
this.historyData.date = year + "/" + month + "/" + day;
localStorage.setItem("prevSearchKeyword", keyword)
}
remove(keyword) {
this.searchHistoryData = this.searchHistoryData.filter(
(item) => item.keyword !== keyword
);
}
}
<file_sep>import { React, useEffect, useState } from 'react';
const useDebounce = (value, delay) => {
const [deValue, setDeValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => {
setDeValue(value);
}, delay);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return deValue;
};
export default useDebounce;
<file_sep>function NavItemShowHOC(WrapperedComponent){
return function showWrapped(props){
return props.show && <WrapperedComponent {...props}/>
}
}
export default NavItemShowHOC;<file_sep>## FE
---
여러 예제들을 직접 구현해보고 있습니다.
<br>
| 주제 | 요약 | - |
| :----------------------------------------------------------: | :----------------------------------------------------------: | :-------------------------------: |
| [모달창 구현](https://github.com/SeongsangCHO/port/tree/master/Modal) | 모달창을 구현하고 Fade in, out의 효과 추가 | |
| [Lazy Load구현](https://github.com/SeongsangCHO/port/tree/master/SearchAPI/lazyload) | fech를 이용해 비동기로 더미데이터 API호출, 해당 데이터 Lazy Load 구현 | 디바운싱, 쓰로틀링 구현예정 |
| [시계, 다크모드 구현](https://github.com/SeongsangCHO/port/tree/master/clock) | setTimout으로 시계를 구현하고 사용자 OS테마에 맞는 색상을 default로 모드를 지정하고 localStorage를 이용해 해당 모드 저장기능 | |
| [프로그래머스 프론트엔드 과제 고양이사진 검색](https://github.com/SeongsangCHO/port/tree/master/programmers_frontend_subject) | 프로그래머스사이트의 과제 구현. 요구사항에 맞게 기능추가 | 구현완료 후 4시간안에 작성해볼 것 |
| [MVC패턴 + JS 예제](https://github.com/SeongsangCHO/port/tree/master/valina-mvc) | MVC패턴으로 작성한 검색 예제 | |
| [React_todolist](https://github.com/SeongsangCHO/port/tree/master/todo-react) | 리액트 todolist | |
| [카카오 로그인 api](https://github.com/SeongsangCHO/port/tree/master/social-login) | 카카오 로그인 api 예제 with 리액트 | 간단한 사용 예제 |
| | | |
| | | |
| | | 교재 |
- HTML, JS, CSS, SCSS, React<file_sep>const one = document.querySelector('.one');
const two = document.querySelector('.two');
const three = document.querySelector('.three');
function onClick(e){
console.log(e.currentTarget.className);
}
/*
이벤트 버블링
브라우저가 이벤트 발생을 감지하기 위한 하나의 방법.
브라우저는 특정 요소 이벤트 발생시 그 이벤트를 최상위 요소까지 전달한다.
모든 div태그에 이벤트리스너가 등록되어있다.
가장 하위태그인 three 클릭시 , 상위로 이벤트를 전달한다.
특정 태그에만 이벤트가 달려있다면 이벤트 전파가 되지 않는다.
*/
//모든 요소에 이벤트 전파
document.querySelectorAll('div').forEach(div => {
div.addEventListener('click', e => onClick(e))
})
//특정 요소만 이벤트발생
three.addEventListener('click', e=> console.log(e.currentTarget.className))<file_sep>import View from "./View.js";
/*
! 시계는 setInterVal추가해야함, 버튼 필요 없음.
*/
const tag = "[ClockView.js]";
const ClockView = Object.create(View);
ClockView.setup = function (el) {
this.init(el);
this.isInterval = '';
this.clockEl = this.el.querySelector("#clock");
this.initClockContent();
return this;
};
ClockView.getTime = function () {
let result = "";
const date = new Date();
let hour = String(date.getHours()).padStart(2, "0");
let minutes = String(date.getMinutes()).padStart(2, "0");
let seconds = String(date.getSeconds()).padStart(2, "0");
return result.concat(hour, ":", minutes, ":", seconds);
};
ClockView.initClockContent = function () {
this.clockEl.innerText = this.getTime();
};
ClockView.stopWorker = function () {
if (this.isInterval) {
clearInterval(this.isInterval);
}
return this;
};
/*
* 클릭될 때마다 타이머 생성되네.
! 초기 진입시 인터벌 수행이면 인터벌 삭제
! 매번 진입해도 이전인터벌 삭제 후 재생성
*/
ClockView.clockWorker = function () {
this.initClockContent();
if (this.isInterval) {
this.stopWorker();
}
const updateTime = () => {
this.clockEl.innerText = this.getTime();
};
this.isInterval = setInterval(updateTime, 1000);
};
export default ClockView;
<file_sep>const tag = '[StopWatchModel]';
export default {
data : {},
init(){
this.setLocalData("time", 0);
this.setLocalData("isRunning", false);
},
getLocalData(id){
return localStorage.getItem(id);
},
setLocalData(id, data){
if(this.getLocalData(id))
return tag+'setLocalData';
return localStorage.setItem(id, data);
},
clearLocalData(){
return localStorage.clear();
}
}<file_sep>/*
수행과정
init로 이벤트리스너 등록(click, keyup)
해당 클릭이벤트 수행
이벤트에는 emit 호출(이벤트 수행했을 때 처리되는 부수효과같은것, 커스텀이벤트 호출)
메인문에서 클릭이벤트를 통해 따라오는 커스텀이벤트의 결과를 핸들링하는 handler호출
*/
import View from "./View.js";
const tag = "[FormView]";
/*View 객체 복사
복사하는 이유?
재사용성을 위해 미리 만들어놓고 복사해서 쓰는듯?
*/
const FormView = Object.create(View);
//el = MainController에서 주입받은 form태그
//this는 FormView를 가리킴.
FormView.setup = function (el) {
this.init(el);
this.inputEl = el.querySelector("[type=text]");
this.resetEl = el.querySelector("[type=reset]");
// reset el 숨김처리
this.showResetBtn(false);
this.bindEvents();
//MainController에서 체이닝으로 다른 메소드 호출하기 위해서 return this
return this;
};
//defalut는 true, 인자를 받으면 그에 맞게 들어감
//show값이 true면 보이고 false면 X버튼 안보이도록 처리
FormView.showResetBtn = function (show = true) {
this.resetEl.style.display = show ? "block" : "none";
};
FormView.bindEvents = function () {
this.on("submit", (e) => e.preventDefault());
this.inputEl.addEventListener("keyup", (e) => this.onKeyUp(e));
this.resetEl.addEventListener("click", (e) => this.onClickReset(e)); //클릭이벤트 등록
};
// 엔터입력하면 검색결과가 보인다.
FormView.onKeyUp = function (e) {
//엔터키인지 키값으로 구별할 수 있음
const enterKey = 13;
this.showResetBtn(this.inputEl.value.length);
//입력된 데이터 길이가 0일 때 @reset호출. 근데 detail에 아무런 내용도 없으니 detail:null
if (!this.inputEl.value.length) { this.emit('@reset'); }
if (e.keyCode !== enterKey) {
return;
}
//..todo 엔터일 때 메인컨트롤러에게 해당 이벤트발생함과 데이터를 전달해줌.
this.emit("@submit", { input: this.inputEl.value });
};
FormView.onClickReset = function (e) {
this.emit('@reset');
this.showResetBtn(false);
};
FormView.setValue = function(value){
this.inputEl.value = value;
this.showResetBtn(this.inputEl.value.length);
}
export default FormView;
<file_sep>const TEMPLATE = '<input type="text">';
class SearchInput {
historyData = [];
timer;
randomTimer;
constructor({ $target, onSearch, onRandomSearch }) {
const $header = document.createElement("header");
const $searchInput = document.createElement("input");
const $randomButton = document.createElement("button");
const $historyList = document.createElement("ul");
this.$header = $header;
this.$historyList = $historyList;
this.$searchInput = $searchInput;
this.$randomButton = $randomButton;
this.$randomButton.classList.add("random-fetch-btn");
this.$randomButton.innerText = "랜덤 냐옹이 보기";
this.$searchInput.placeholder = "고양이를 검색해보세요.|";
$searchInput.className = "SearchInput";
$target.appendChild($header);
$header.classList.add("header");
$header.appendChild($searchInput);
$header.appendChild($historyList);
$header.appendChild($randomButton);
this.$searchInput.focus();
$searchInput.addEventListener("click", (e) => {
console.log("hhh");
if (e.target.value.length > 0) {
e.target.value = "";
}
});
$searchInput.addEventListener("keyup", (e) => {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
if (e.keyCode === 13) {
onSearch(e.target.value);
this.setState(e.target.value);
}
}, 200);
});
$randomButton.addEventListener("click", (e) => {
if (this.randomTimer) {
clearTimeout(this.randomTimer);
}
this.randomTimer = setTimeout(() => {
onRandomSearch();
}, 200);
});
console.log("SearchInput created.", this);
}
setState(keyword) {
this.historyData.unshift(keyword);
this.historyData = this.historyData.slice(0, 5);
this.render();
}
render() {
if (this.historyData.length > 0) {
this.$historyList.innerHTML = this.historyData
.map((item) => {
return `<li>${item}</li>`;
})
.join("");
}
}
}
<file_sep>class ModeToggle {
constructor({ $target }) {
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const $modeToggle = document.createElement("input");
this.$modeToggle = $modeToggle;
this.$modeToggle.className = "ModeToggle";
this.$modeToggle.type = "checkbox";
// OS 다크모드에 따른 디폴트 체크값 설정
this.$modeToggle.checked = prefersDarkScheme.matches ? true : false;
$target.prepend($modeToggle);
// 체크박스 클릭에 따른 테마 토글링
$modeToggle.addEventListener('click', e=>{
if (prefersDarkScheme.matches){
document.body.classList.toggle("light-theme");
} else{
document.body.classList.toggle("dark-theme");
}
})
};
}<file_sep>class SearchResult {
$searchResult = null;
data = null;
onClick = null;
constructor({ $target, initialData, onClick }) {
// sessionStorage.clear();
this.$searchResult = document.createElement("div");
this.$searchResult.className = "SearchResult";
$target.appendChild(this.$searchResult);
this.data = null;
this.onClick = onClick;
this.getLocalSearchKeyword();
this.setState();
this.render();
// this.lazyLoad();
}
getLocalSearchKeyword() {
if (!localStorage.getItem("prevSearchKeyword")) {
localStorage.setItem("prevSearchKeyword", ""); //init
}
}
setState(nextData) {
if (nextData === undefined) {
let prevData = sessionStorage.getItem("prevSearchData");
nextData = JSON.parse(prevData);
}
if (nextData == null) return;
this.data = nextData;
sessionStorage.setItem("prevSearchData", JSON.stringify(this.data));
this.render();
}
lazyLoad() {
const lazyLoadImages = [].slice.call(
this.$searchResult.querySelectorAll("img.lazy")
);
let lazyObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
let lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
console.log(lazyImage);
lazyImage.remove("lazy");
lazyObserver.unobserve(lazyImage);
}
});
});
lazyLoadImages.forEach(function (lazyImage) {
lazyObserver.observe(lazyImage);
});
}
render() {
if (!this.data) {
return;
}
this.$searchResult.innerHTML =
this.data.length > 0
? this.data
.map((cat) => {
return `
<div class="item">
<img class="lazy" data-src=${cat.data.url} alt=${cat.data?.name} />
</div>
`;
})
.join("")
: `<div> no search Data </div>`;
this.$searchResult.querySelectorAll(".item").forEach(($item, index) => {
$item.addEventListener("click", () => {
this.onClick(this.data[index]);
});
});
}
}
<file_sep>class Lazyload {
API_URL = "https://dummyapi.io/data/api";
APP_KEY = "5ff574fb2b98d0966946eb3a";
// https://img.dummyapi.io/photo-1564694202779-bc908c327862.jpg
constructor($target) {
this.$target = $target;
this.$imageWrapper = document.createElement("div");
this.$imageWrapper.className = "wrapper";
this.data = [];
this.options = {
rootMargin: '1px 1px 1px 1px',
threshold: [0.3],
};
this.imageAPI();
// this.bindEvent();
}
observerHandler(entries, observer) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
console.log("print");
const image = entry.target;
const src = image.dataset.src; // img 태그의 data-lazy에 저장해둔 이미지 경로를 붙여준다.
image.setAttribute("src", src);
image.removeAttribute("data-src");
observer.unobserve(entry.target);
}
});
}
lazyLoadHandler() {
this.lazyImages = Array.prototype.slice.call(
document.body.querySelectorAll(".image")
);
this.intersectionObserver = new IntersectionObserver(this.observerHandler.bind(this), this.options);
console.log(this.intersectionObserver);
this.lazyImages.forEach((item) => this.intersectionObserver.observe(item));
}
async imageAPI() {
const response = await fetch(this.API_URL + "/post", {
headers: { "app-id": this.APP_KEY },
method: "GET",
}).then((result) => result.json());
await this.render(response.data);
}
render(response) {
this.$target.appendChild(this.$imageWrapper);
this.$target.innerHTML = response
.map((data) => {
return `<img class="image" data-src=${data.image}></img>`;
})
.join("");
this.data = document.querySelectorAll(".image");
this.lazyLoadHandler();
}
}
new Lazyload(document.querySelector("#App"));
<file_sep># Todo_React
- todo list
### **요구사항**
- 할 일을 추가할 수 있다.
- 할 일을 삭제할 수 있다.
### **라이브러리**
- create-react-app
- node-sass
- classnames
- react-icons
## 파일
### TodoTemplate
- 컴포넌트들을 children으로 받아 뿌려주는 부분
### App
- TodoTemplate 출력부이자 최상단
- todos데이터 관리 및 함수 정의, props 전달부
- useCallback으로 함수 재생성 방지
- useReducer로 랜더링 최적화( useState로도 사용 가능 )
### TodoList
- TodoList Item 컨테이너 `map` 으로 TodoListItem 출력
### TodoListItem
- classnames 라이브러리로 checked값으로 완료 사항 조건부 랜더링
- done - undo 부분 toggle
- todo 데이터 삭제
### TodoInsert
- form으로 todo 추가하는 부분
- 디바운싱 적용

<file_sep># 바닐라 JS 강의 예제
---

## 요구사항 분석
### 검색폼 구현
- [x] 검색 상품명 입력 폼이 위치한다. 검색어가 없는 경우이므로 x 버튼을 숨긴다
- [x] 검색어를 입력하면 x버튼이 보인다
- [x] 엔터를 입력하면 검색 결과가 보인다
- [x] x 버튼을 클릭하거나, 검색어를 삭제하면 검색 결과를 삭제한다
### 검색 결과 구현
- [x] 검색 결과가 검색폼 아래 위치한다
- [x] 검색 결과가 보인다
- [x] x버튼을 클릭하면 검색폼이 초기화 되고, 검색 결과가 사라진다
### 탭 구현
- [x] 추천 검색어, 최근 검색어 탭이 검색폼 아래 위치한다
- [x] 기본으로 추천 검색어 탭을 선택한다
- [x] 각 탭을 클릭하면 탭 아래 내용이 변경된다 추천 검색어 구현
- [x] 번호, 추천 검색어 목록이 탭 아래 위치한다
- [x] 목록에서 검색어를 클릭하면 선택된 검색어로 검색 결과 화면으로 이동
- [x] 검색폼에 선택된 추천 검색어 설정 최근 검색어 구현
- [x] 최근 검색어, 목록이 탭 아래 위치한다
- [x] 목록에서 검색어를 클릭하면 선택된 검색어로 검색 결과 화면으로 이동
- [x] 검색일자, 버튼 목록이 있다
- [x] 목록에서 x 버튼을 클릭하면 선택된 검색어가 목록에서 삭제
- [x] 검색시마다 최근 검색어 목록에 추가된다<file_sep># 과제
---
### **HTML, CSS 관련**
- 현재 HTML 코드가 전체적으로 `<div>` 로만 이루어져 있습니다. 이 마크업을 시맨틱한 방법으로 변경해야 합니다.
=> 음, 어떤걸? 시맨틱으로?.
- [x] 유저가 사용하는 디바이스의 가로 길이에 따라 검색결과의 row 당 column 갯수를 적절히 변경해주어야 합니다.
- 992px 이하: 3개
- 768px 이하: 2개
- 576px 이하: 1개
=> `display:grid, grid-template-column의 비율을 media쿼리 각 가로길이에 따라 작성`
- [x] ]다크 모드(Dark mode)를 지원하도록 CSS를 수정해야 합니다.
- CSS 파일 내의 다크 모드 관련 주석을 제거한 뒤 구현합니다.
- 모든 글자 색상은 `#FFFFFF` , 배경 색상은 `#000000` 로 한정합니다.
- 기본적으로는 OS의 다크모드의 활성화 여부를 기반으로 동작하게 하되, 유저가 테마를 토글링 할 수 있도록 좌측 상단에 해당 기능을 토글하는 체크박스를 만듭니다.
##### 다크모드
다크모드를 구현할 수 있는 방법으로 CSS, JS가 있다.
CSS는 OS설정을 감지한 속성을 미디어쿼리로 사용해 구현할 수 있고
JS는 브라우저상의 `matchedMedia()` 로 사용자 선호도(?)를 감지할 수 있다.
- CSS의 `prefers-color-scheme` 속성으로, 사용자 시스템설정(다크모드)을 감지할 수 있다.
- `@media (prefers-color-scheme: dark 또는 light){...}` 로 적용한다
```css
/* Default colors */
body {
--text-color: #222;
--bkg-color: #fff;
}
/* Dark theme colors */
body.dark-theme {
--text-color: #eee;
--bkg-color: #121212;
}
@media (prefers-color-scheme: dark) {
/* defaults to dark theme */
body {
--text-color: #eee;
--bkg-color: #121212;
}
/* Override dark mode with light mode styles if the user decides to swap */
body.light-theme {
--text-color: #222;
--bkg-color: #fff;
}
}
```
- 사용자는 OS설정을 따르는 것을 싫어할 수 있기에 토글버튼으로 제공한다.
```js
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
// Listen for a click on the button
btn.addEventListener("click", function() {
// If the OS is set to dark mode...
if (prefersDarkScheme.matches) {
// ...then apply the .light-theme class to override those styles
document.body.classList.toggle("light-theme");
// Otherwise...
} else {
// ...apply the .dark-theme class to override the default light styles
document.body.classList.toggle("dark-theme");
}
});
```
과제에서는 OS다크모드 활성화 여부기반이라고 했으니 해당 방식으로 구현해야한다고 생각한다.
기본값으로 css의 OS색을 존중하고, 다크모드 활성화여부를 체크박스를 통해 구현한다.
JS는 현재 설정된 색을 `matchMedia` 를 통해 확인하고, 다크가 설정되있다면, `light-theme` 토글을 진행한다 -> 디폴트 dark
반대의 경우 `dark-theme` 토글을 진행한다 -> 디폴트 light
`dark` 일때 미디어쿼리 수행, 아니면 바깥 수행이므로 밖은 다크모드 색, 쿼리 안은 디폴트 다크에서 라이트로 넘어갈 테마를 작성해야한다.
---
#### 구현
사용자 설정에 따라 체크박스를 체크해둘 것. (Dark -> checked)
클릭이벤트시 `matchMedia()`로 설정확인한 후 해당 값에 따라 테마 토글링
자손까지 ?(명세에없음)모든 글자 색상 #FFF, 배경색 #000
```js
//ModeToggle.js
class ModeToggle {
constructor({ $target }) {
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
console.log(prefersDarkScheme);
const $modeToggle = document.createElement("input");
this.$modeToggle = $modeToggle;
this.$modeToggle.className = "ModeToggle";
this.$modeToggle.type = "checkbox";
// OS 다크모드에 따른 디폴트 체크값 설정
this.$modeToggle.checked = prefersDarkScheme.matches ? true : false;
$target.prepend($modeToggle);
// 체크박스 클릭에 따른 테마 토글링
$modeToggle.addEventListener('click', e=>{
if (prefersDarkScheme.matches){
document.body.classList.toggle("light-theme");
} else{
document.body.classList.toggle("dark-theme");
}
})
};
}
```
- 체크박스 생성
- 체크박스 디폴트 값을 OS 설정에 따라 지정 -> 다크모드면, 체크활성화
- 체크박스 클릭시, 현재설정이 다크모드이면 light 테마 토글링, 반대의 경우 dark테마 토글
### **이미지 상세 보기 모달 관련**
- [x] 디바이스 가로 길이가 768px 이하인 경우, 모달의 가로 길이를 디바이스 가로 길이만큼 늘려야 합니다. - style: modal max-width : 768px => modal width 100% 스크롤사이즈 어떻게 처리하지?
- [x] **`필수`** 이미지를 검색한 후 결과로 주어진 이미지를 클릭하면 모달이 뜨는데, 모달 영역 밖을 누르거나 / 키보드의 ESC 키를 누르거나 / 모달 우측의 닫기(x) 버튼을 누르면 닫히도록 수정해야 합니다.
=> window에 keydown, click, close에 click이벤트리스너 등록
=> 바깥클릭은 e.target으로 안쪽이랑 구분해서 처리.
=> window에 등록하면 한번 수행된 이후에 매번 이벤트가 발생하는데 이렇게하는 방법밖에 없는지 궁금함.
- [x] 모달에서 고양이의 성격, 태생 정보를 렌더링합니다. 해당 정보는 `/cats/:id` 를 통해 불러와야 합니다.
=> api.js에 구현. 검색어기반으로 api호출 후 반환받은 데이터 중 id로 다시 api호출해서 전체데이터를 받아옴
- `추가` 모달 열고 닫기에 fade in/out을 적용해 주세요.
=> 애니메이션 적용. 서서히 나타나고, 사라지는 것 opcatiy?
=> transition으로 모달 열면 .open 클래스추가, content-wrapper 기본 opcatity :0 , transition: 시간으로 지정, .open은 opacity : 1
#### 모달 페이드인, 아웃의 문제
- 현재 모달 생성방식은 `display`의 block, none인데, 초기 진입시 `ImageInfo` 클래스는 `none`상태이고 카드클릭시 `data.visible` 를 전달해 모달창을 그린다. 그리고 배경인(ImageInfo)를 block하여 배경 + 모달을 그린다.
문제점 => ImageInfo가 모달창까지 감싸고 있고 이 방법이 display none, block으로 요소를 없애거나 추가하는 동적방식으로하고있기 때문에 transition의 시작점을 알 수 없어 트랜지션을 적용할 수 없다.
##### 방안
- `visibility`로 기본값을 hidden으로 하고 클릭시 visible 해주는 `open` 클래스를 추가한다.
- 닫고나서 재클릭할 수 없음 배경의 크기가 100vh므로 카드요소들을 덮어 씌우거나 첫 진입시 검색창을 가린다.
- Position: fixed이니까 화면밖으로 밀어내볼까?
##### 적용
- z-index를 두어서 해결, position 속성을 가진 것에만 적용 가능
- 모달창엔 -9999, open했을 땐 9999로 두어서 적용함
##### 질문사항 (ImageInfo, render(), bindEvent부분)
이미지클릭시 `render()` 을 호출하는데 이 때 생성되는 `close div` 에다가 이벤트등록을 시켜주어야함. 그러나 if문 안에 이벤트등록을하면 다른 이미지클릭시 새로운 객체를 생성하므로 계속해서 이벤트가 중복해서 등록됨. => 어떻게 해결해야할지.
### API
---
- fetch로 api호출해서 데이터 불러오기
- 실패에 대한 처리하기 [fetchAPI](http://www.gisdeveloper.co.kr/?p=6121)
##### fetch
- `fetch('요청URL')` URL에 요청해 Promise객체를 반환받는다.
- `Promise 객체` 비동기 작업에 대한 완료, 실패의 결과값
- 응답으로 받은 결과에 대한 오류를 해결하기 위한 객체임.
- 대기, 이행, 거부 중 하나의 상태를 가짐
- reject, resolve함수가 있고 프로토타입엔 then, catch, finally이 있음
```js
const API_ENDPOINT =
"https://oivhcpn8r9.execute-api.ap-northeast-2.amazonaws.com/dev";
// iyFN2mF8l
async function request(url) {
try {
//요청을 통해 응답을 받는다.
const response = await fetch(url);
//헤더를 받아서 성공인지에 대한 분기 처리를 한다.
if (response.ok) {
// 응답 본문을 받기 위해 메소드를 사용한다.
const data = await response.json();
return data;
} else {
const errorData = await response.json();
return errorData;
}
} catch (e) {
throw {
message : e.message,
status : e.status,
}
}
}
const api = {
fetchCats: async (keyword) => {
try {
//응답 본문 배열
const specifies = await request(
`${API_ENDPOINT}/api/cats/search?q=${keyword}`
);
//각 요청에 대해 기다릴 수 없으므로 fetch로 요청을 보내놓고
//프로미스 객체를 반환받아 놓은 상태
const requests = specifies.data.map(
async (specify) =>{
return await request(`${API_ENDPOINT}/api/cats/${specify.id}`)}
);
//requests = [promises...]
const result = await Promise.all(requests);
//프로미스 배열을 순서상관없이 이행하는 단계
return {
data:result,
isError: false,
};
} catch (e) {
return {
data: e,
isError:true
}
}
},
};
```
- async await는 콜백의 단점을 보완하기 위해 등장한 비동기처리 문법
- await가 붙는 코드엔 프로미스객체를 반환해야한다.
### **검색 페이지 관련**
- [x] 페이지 진입 시 포커스가 `input` 에 가도록 처리하고, 키워드를 입력한 상태에서 `input` 을 클릭할 시에는 기존에 입력되어 있던 키워드가 삭제되도록 만들어야 합니다.
=> `focus()`, value에 대한 처리
- [x] **`필수`** 데이터를 불러오는 중일 때, 현재 데이터를 불러오는 중임을 유저에게 알리는 UI를 추가해야 합니다.
=> api호출(onSearch)할 때 toggle로 `toggleSpinner() 호출`, 검색이 완료되었을 때 `setState` 에 토글링
- [x] **`필수`** 검색 결과가 없는 경우, 유저가 불편함을 느끼지 않도록 UI적인 적절한 처리가 필요합니다.
=> searchData값이 0인경우 no search Data 문구 출력함.
- [x] 최근 검색한 키워드를 `SearchInput` 아래에 표시되도록 만들고, 해당 영역에 표시된 특정 키워드를 누르면 그 키워드로 검색이 일어나도록 만듭니다. 단, 가장 최근에 검색한 5개의 키워드만 노출되도록 합니다.
=> `localStorage로 해야겠네.` , App.js에서 생성자 만들어서 초기랜더링해야함.

li태그가 하나씩 더 생기는 이슈가 있는데.,. 현재 map.join으로 생성하고 있는데 어떤게 원인인지 모르겠다.;; => **닫는 태그를 <li>로 하고 있었네;;
=>5개만 노출되도록 하려면, 5개만 저장할지, 최상위 5개만보여줄지? , 5개만 저장하는게 낫겠다. 계속 저장하면 불필요한 연산해야하니깐.
- [x] 페이지를 새로고침해도 마지막 검색 결과 화면이 유지되도록 처리합니다.
=> localStorage, SessionStorage 둘 중 하나에 저장시킬 수 있는데, 세션을 끄면 없어져야하니까 세션에 저장. (새로고침시 마지막검색어를 local에 저장해서 이를 키워드로 검색하는 방법을 생각했으나 세션에 넣는게 더 좋다고 생각함.)
- [x] **`필수`** SearchInput 옆에 버튼을 하나 배치하고, 이 버튼을 클릭할 시 `/api/cats/random50` 을 호출하여 화면에 뿌리는 기능을 추가합니다. 버튼의 이름은 마음대로 정합니다.
- [ ] lazy load 개념을 이용하여, 이미지가 화면에 보여야 할 시점에 load 되도록 처리해야 합니다.
=> 기존에 한번씩받아오는데 `api.js` 의 promise.all하지말고 각 `for of` 해서 스크롤이벤트마다 제너레이터 해야하나.,.?
- [ ] `추가` 검색 결과 각 아이템에 마우스 오버시 고양이 이름을 노출합니다.
##### 참고
- [캡틴판교 async await](https://joshua1988.github.io/web-development/javascript/js-async-await/)
<file_sep>const API_ENDPOINT =
"https://oivhcpn8r9.execute-api.ap-northeast-2.amazonaws.com/dev";
const api = {
fetchCats: (keyword) => {
return fetch(`${API_ENDPOINT}/api/cats/search?q=${keyword}`).then((res) =>
res.json()
);
},
fetchCatsModalData: (id) => {
return fetch(`${API_ENDPOINT}/api/cats/${id}`).then((res) => res.json());
},
fetchRandomCats: () =>{
return fetch(`${API_ENDPOINT}/api/cats/random50`).then((res) => res.json());
}
};
<file_sep>class SessionStorage{
constructor({setState, searchResultObj}){
const bindSearchResult = {};
console.log(searchResultObj);
// console.log(sessionStorage.getItem("prevSearchData"));
}
setItem(keyword){
sessionStorage.setItem("prevSearchKeyword", keyword);
}
}
//SearchResult.js 의 해당 메소드를 호출.
// 검색결과 데이터를 세션스토리지에 저장시킴 => 시점은, 해당 메소드에서.
// setState(nextData) {
// this.data = nextData;
// 여기서 스토리지에 저장하는 메소드 구현.
// this.render();
// }<file_sep>import styles from "./App.module.css";
import { useState, useEffect } from "react";
import { Route, useHistory } from 'react-router-dom';
function App() {
const JAVASCRIPT_KEY = "00743ed6c413ea402f7d277ce57493a6";
const { Kakao } = window;
const history = useHistory();
const [user, setUser] = useState({});
const onLogin = (e) => {
Kakao.Auth.login({
success: function (response) {
console.log(response);
console.log("Login success");
history.push("/logined");
setUser({
access_token: response.access_token,
});
},
fail: function (error) {
console.log(error);
},
});
};
const onShareLink = () => {
Kakao.Link.createDefaultButton({
container: '#create-kakao-link-btn',
objectType: 'feed',
content: {
title: '딸기 치즈 케익',
description: '#케익 #딸기 #삼평동 #카페 #분위기 #소개팅',
imageUrl:
'http://k.kakaocdn.net/dn/Q2iNx/btqgeRgV54P/VLdBs9cvyn8BJXB3o7N8UK/kakaolink40_original.png',
link: {
mobileWebUrl: 'https://developers.kakao.com',
webUrl: 'https://developers.kakao.com',
},
},
social: {
likeCount: 286,
commentCount: 45,
sharedCount: 845,
},
buttons: [
{
title: '웹으로 보기',
link: {
mobileWebUrl: 'https://developers.kakao.com',
webUrl: 'https://developers.kakao.com',
},
},
{
title: '앱으로 보기',
link: {
mobileWebUrl: 'https://developers.kakao.com',
webUrl: 'https://developers.kakao.com',
},
},
],
})
}
useEffect(() => {
console.log("init..");
Kakao.init(JAVASCRIPT_KEY);
}, []);
return (
<div className="App">
<Route path="/" exact>
<button onClick={onLogin} className={styles.loginButton}>
Continue with Kakao
</button>
</Route>
<Route path="/logined" exact>
<h4>로그인 완료.</h4>
<button id="create-kakao-link-btn" onClick={onShareLink}>친구에게 공유하기</button>
</Route>
</div>
);
}
export default App;
<file_sep># LazyLoad, 디바운싱, 쓰로틀링
---
웹 페이지를 열 때 `img`태그의 src속성은 현재 뷰 포트가 어디있건간에 이미지소스를 다운로드받는다.
만약 몇천 몇만의 이미지태그가 있으면 이를 다 다운받을 때까지 엄청난 시간이 들 것이다.(사용자가 보고있지 않아도.)
따라서 이런 리소스낭비를 줄이기 위해 등장한 것이 레이지로드이다.
예시로는
유투브에서 스크롤링할 때 썸네일에 해당하는 부분이 회색으로 가려져있다.
무한스크롤이 적용된 사이트에서 스크롤할 때 로딩창이 생기면서 이미지를 불러온다.
모든 리소스를 받지않고 그때그때 받아오는 것 이 때 사용되는 것이 이 개념이다.
레이지로딩은 스크롤 애니메이션을 통해 구현한다.
이 때 스크롤 이벤트는 모든 이미지가 로딩이되면 종료되어야한다.
스크롤이벤트는 리소스를 매우 많이 잡아먹으므로 [디바운싱, 쓰로틀링](https://webclub.tistory.com/607)기법으로 이 낭비를 줄일 수 있다.
그리고 src속성을 사용하지 않고 다른 속성`data-src`에 경로를 저장해두고 해당 뷰포트에 진입하면 src속성에 해당 경로를 부여함으로써 로딩시킬 수 있다.
##### 구현 방법에는 3가지. 이번엔 이벤트 핸들러로 구현해볼 것.
- [IntersectionObserver API](https://krpeppermint100.medium.com/js-%EB%A0%88%EC%9D%B4%EC%A7%80-%EB%A1%9C%EB%94%A9-%EA%B8%B0%EB%B2%95-5e3d5dfcb4c1)
- [라이브러리](https://www.codingfactory.net/11943)
- [이벤트핸들러](https://blog.naver.com/dilrong/221544559266)
### 이미지 API 사이트, 이미지 불러오기
레이지로딩을 구현하기 위해서 먼저 이미지소스가 필요하다.
이미지 소스 및 여러 더미데이터 api제공하는 [예제사이트](https://dummyapi.io/documentation/static-data-api)에서 데이터를 불러온다
```js
class Lazyload {
API_URL = "https://dummyapi.io/data/api";
APP_KEY = "5ff574fb2b98d0966946eb3a";
// https://img.dummyapi.io/photo-1564694202779-bc908c327862.jpg
constructor($target) {
this.$target = $target;
this.$imageWrapper = document.createElement("div");
this.$imageWrapper.className = "wrapper";
this.data = [];
this.imageAPI();
// this.bindEvent();
}
}
async imageAPI() {
const response = await fetch(this.API_URL + "/post", {
headers: { "app-id": this.APP_KEY },
method: "GET",
}).then((result) => result.json());
await this.render(response.data);
}
}
new Lazyload(document.querySelector("#App"));
```
### 이미지 표시 및 스크롤이벤트 등록
```js
class Lazyload {
API_URL = "https://dummyapi.io/data/api";
APP_KEY = "5ff574fb2b98d0966946eb3a";
// https://img.dummyapi.io/photo-1564694202779-bc908c327862.jpg
constructor($target) {
this.$target = $target;
this.$imageWrapper = document.createElement("div");
this.$imageWrapper.className = "wrapper";
this.data = [];
this.imageAPI();
// this.bindEvent();
}
lazyLoadHandler() {
let lazyImages = Array.prototype.slice.call(document.body.querySelectorAll('.image'));
const lazyLoad = () =>{
lazyImages.forEach((image,index)=> {
console.log(index, image.getBoundingClientRect().top);
});
}
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
}
async imageAPI() {
const response = await fetch(this.API_URL + "/post", {
headers: { "app-id": this.APP_KEY },
method: "GET",
}).then((result) => result.json());
await this.render(response.data);
this.lazyLoadHandler();
}
render(response) {
this.$target.appendChild(this.$imageWrapper);
this.$target.innerHTML = response.map((data) => {
return `
<img class="image" src=${data.image}></img>
<img class="image" src=${data.image}></img>`;
});
this.data = document.querySelectorAll(".image");
}
}
new Lazyload(document.querySelector("#App"));
```
이미지를 불러오고 이미지 로딩이 완료되었으면 `lazyLoadHandler` 를 호출해 레이지로드를 처리한다.
`getBoundingClientRect().top`는 브라우저의 꼭대기 지점기준으로 각 요소의 맨윗지점을 나타낸다. 예를들어 높이 100짜리요소 10개가 있으면 각 요소의 top값은 맨 위부터
0, 100, 200, 300..이 되고 스크롤을 해서 두번째 요소를 현재 브라우저의 꼭대기에 위치시켰으면 -100, 0, 100, 200, 300으로 계산된다.
내가 필요한 구간은 각 요소들이 현재 브라우저상에 위치하는지를 확인해야한다.
top이 툴바 높이를 제외한 순수 윈도우크기(window.innerHeight)내에 있는지 체크해서 안에 있다면 이미지 src에 값을 주는 방식으로 진행한다. => **(top <= window.innerHeight)**
### 구현
```js
class Lazyload {
API_URL = "https://dummyapi.io/data/api";
APP_KEY = "5ff574fb2b98d0966946eb3a";
// https://img.dummyapi.io/photo-1564694202779-bc908c327862.jpg
constructor($target) {
this.$target = $target;
this.$imageWrapper = document.createElement("div");
this.$imageWrapper.className = "wrapper";
this.data = [];
this.imageAPI();
// this.bindEvent();
}
lazyLoadHandler() {
let lazyImages = Array.prototype.slice.call(
document.body.querySelectorAll(".image")
);
const lazyLoad = () => {
console.log("load");
lazyImages.forEach((image, index) => {
let imageTop = image.getBoundingClientRect().top;
let windowHeight = window.innerHeight;
if (
imageTop <= windowHeight &&
image.getAttribute("data-src")
) {
const src = image.dataset.src; // img 태그의 data-lazy에 저장해둔 이미지 경로를 붙여준다.
image.setAttribute("src", src);
image.removeAttribute("data-src");
}
});
};
lazyLoad();
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
}
async imageAPI() {
const response = await fetch(this.API_URL + "/post", {
headers: { "app-id": this.APP_KEY },
method: "GET",
}).then((result) => result.json());
await this.render(response.data);
this.lazyLoadHandler();
}
render(response) {
this.$target.appendChild(this.$imageWrapper);
this.$target.innerHTML = response
.map((data) => {
return `<img class="image" data-src=${data.image}></img>`;
})
.join("");
this.data = document.querySelectorAll(".image");
}
}
new Lazyload(document.querySelector("#App"));
```
- 현재 `lazyLoad`함수를 스크롤 또는 이벤트마다 호출하고 있는데 쓰로틀링 및 디바운싱을 배우고 적용해봐야겠다.
### 이슈..였던 것
- 이미지를 출력하는데 이미지 사이사이에 ","값이 같이 나왔었다.
- ```js
this.$target.innerHTML = response
.map((data) => {
return `<img class="image" data-src=${data.image}></img>`;
})
.join("");
```
`map`의 반환을 문자열로 하면 구분되는 지점마다 ","이 같이 출력되는 경우였기에 join으로 묶음!
- 카카오 검색 API 써보려고 했다가 ajax로 하길래 fetch로 시도했지만 음,, 계속 헤매가지고 나중에 다시 해보기로 결정. => 검색기능이 사실 필요가 없어서..

##### 참고
- [쉼표출력](https://velog.io/@takeknowledge/map%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%96%88%EB%8A%94%EB%8D%B0-%EC%9D%98%EB%8F%84%ED%95%98%EC%A7%80-%EC%95%8A%EC%9D%80-%EC%89%BC%ED%91%9C%EA%B0%80-%EC%B6%9C%EB%A0%A5%EB%90%9C%EB%8B%A4%EB%A9%B4)
- [레이지로딩기법](https://krpeppermint100.medium.com/js-%EB%A0%88%EC%9D%B4%EC%A7%80-%EB%A1%9C%EB%94%A9-%EA%B8%B0%EB%B2%95-5e3d5dfcb4c1)
- [참고코드](https://blog.naver.com/dilrong/221544559266)
- [디바운싱, 쓰로틀링](https://webclub.tistory.com/607)
<file_sep>import View from './View.js';
const tag = '[ModalView.js]';
const ModalView = Object.create(View);
ModalView.setup = function(el){
this.init(el);
this.modalBg = document.querySelector('.modal-background');
this.closeBtn = this.el.querySelector('.btn-modal-close');
this.closeModal();
this.bindCloseEvent();
return this;
}
ModalView.bindCloseEvent = function(){
this.closeBtn.addEventListener('click', e => this.onClickCloseModal(e));
this.modalBg.addEventListener('click', e => this.onClickCloseModal(e));
}
ModalView.onClickCloseModal = function(e){
this.closeModal();
}
ModalView.closeModal = function(){
this.modalBg.classList.remove("modal-open");
this.el.classList.remove("modal-open");
}
ModalView.showModal = function(){
this.modalBg.classList.add("modal-open");
this.el.classList.add("modal-open");
}
ModalView.openModal = function (tagName){
}
export default ModalView;<file_sep>/* DOM */
const DOM = {
toggleButton: document.getElementById("theme-toggle-button"),
};
DOM.toggleButton.innerHTML = "Hello";
/* Status */
const status = {
isToggled: true,
};
status.currentTheme = localStorage.getItem("theme");
status.preferDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const currentThemeApply = () => {
if (status.currentTheme == "dark") document.body.classList.toggle("dark");
else if (status.currentTheme == "light")
document.body.classList.toggle("light");
};
currentThemeApply();
DOM.toggleButton.addEventListener("click", () => {
document.body.classList.toggle("dark");
});
<file_sep># 바닐라 JS 시계 + 다크모드 토글
---

## 요구사항 분석
### 시계 구현
- [x] 화면이 전환될 때 setInterval 제거
### Dark mode 토글 구현
- `ModeChangeView.js` 을 다른 프로젝트에도 적용할 수 있도록 구성
- `DOM` 객체에 모드가 적용될 객체 선택해서 나열
- `status` : 로컬스토리지에 테마 확인, 현재 사용자가 이용중인 모드 확인
- `setup` : 이벤트 바인딩
- `toggleDarkAttribute` : `DOM` 의 요소들 순회하면서 다크모드 적용
- `classList.toggle` 로 다크모드 토글링
- [x] 다크모드 설정
- [x] 다크모드 on / off는 toggle버튼으로 구현한다
- [x] 기본 default는 사용자의 현재 설정사항으로 진행한다.
- [x] 사용자가 버튼클릭시 현재설정사항과 반대로 모드가 변경된다.
<file_sep>
<file_sep>import View from './View.js';
const ResultView = Object.create(View);
export default ResultView;<file_sep>import ModeChangeView from '../View/ModeChangeView.js';
import HeaderView from '../View/HeaderView.js';
const tag = '[MainController.js]'
export default {
init() {
console.log(tag);
ModeChangeView.setup(document.querySelector("#btn-toggle"));
HeaderView.setup(document.querySelector(".header"));
},
};<file_sep>import View from './View.js';
const StopWatchView = Object.create(View);
StopWatchView.setup = function (el){
this.init(el);
console.log(el);
return this;
}
StopWatchView.initRender = function (){
console.log(localStorage.getItem("isRunning"));
console.log(localStorage.getItem("time"));
if(localStorage.getItem("time") == 0){
//00,재설정(unable), 시작버튼 뷰 랜더
this.renderStartView();
}
}
StopWatchView.renderStartView = function (){
// this.el.innerHTML += `<span class="clock-ms">.00</span>`;
}
export default StopWatchView;<file_sep>const one = document.querySelector('.Cone');
const two = document.querySelector('.Ctwo');
const three = document.querySelector('.Cthree');
function onClick(e){
//전달하는 것을 막기위해 해당 메소드 사용
//one만 출력됨 (가장 상위요소)
e.stopPropagation();
console.log(e.currentTarget.className);
}
/*
캡쳐링은 버블링과 반대방향으로 전파되는 방식
상위 요소에서 하위로 전달
capture true로 설정하면 반대로 탐색
*/
document.querySelectorAll('div').forEach((div) => {
div.addEventListener('click', e => onClick(e),{
capture:true
})
})<file_sep>const toggleBtn = document.body.querySelector(".fade-toggle");
const wrapper = document.body.querySelector(".wrapper");
const content = document.body.querySelector(".content");
wrapper.style.display="none"
content.style.display="none"
toggleBtn.addEventListener("click", (e) => {
content.classList.toggle("open");
wrapper.classList.toggle("open");
//display : none, block는 트랜지션을 먹지 못함.
//랜더링트리에서 동적으로 바뀌기 떄문에, 시작점을 알 수 없기에.
if (content.classList.contains("open")) {
// content.style.visibility = "visible";
wrapper.style.display="block"
content.style.display="block"
} else {
// content.style.visibility = "hidden";
wrapper.style.display="none"
content.style.display="none"
}
});
<file_sep>import ModeChangeView from "../views/ModeChangeView.js";
import TabView from "../views/TabView.js";
import ClockView from "../views/ClockView.js";
import ClockContentsView from "../views/ClockContentsView.js";
import StopWatchView from "../views/StopWatchView.js";
import TodoListView from '../views/TodoListView.js';
import ModalView from '../views/ModalView.js';
import StopWatchModel from '../Model/StopWatchModel.js';
const tag = "[MainController.js]";
export default {
init() {
this.selectedTab = "시계";
// ResultView.setup(document.querySelector("div#timer"));
ModeChangeView.setup(document.querySelector("#btn-toggle"));
TabView.setup(document.querySelector(".side-menu"))
.on('@changeTab', e => this.onChangeTab(e.detail.tabName));
ClockView.setup(document.querySelector("div.content"))
StopWatchView.setup(document.querySelector("div#timer"))
// .on('@reset', e => this.resetStopWatch(e))// 리셋버튼 -> lap, 시작버튼으로 변경 // 시간이 0초일 때 unable
// .on('@start', e => this.startStopWatch(e))// 시작버튼 -> 중지버튼으로 바뀜, 재설정 enable
// .on('@lap', e => this.recordLap(e)) // 현재 타이머가 기록됨++
// .on('@stop', e => this.stopStopWatch(e)) //중지버튼이 시작버튼으로 바뀜 //
// TodoListView.setup(document.querySelector(".todo-container"))
// .on('@openModal', e => this.openModalWindow(e.detail.tagId))
ModalView.setup(document.querySelector(".modal-window"))
.on('@closeModal', e => this.closeModalWindow(e))
this.renderView();
},
renderView(){
/*
* 클릭되었을 때 타이머가 있는지부터 확인하고, 없다면
* 타이머 생성, 있으면 이미 돌아가고 있는 상태.
*/
if(this.selectedTab == "시계"){
ClockView.clockWorker();
}
if(this.selectedTab == "스톱워치"){
/* 현재 실행중인 interval 스톱해야함. */
StopWatchModel.init();
ClockView.stopWorker();
}
},
onChangeTab(tabName){
this.selectedTab = tabName;
//renderView 되기전 이전 interval stop하고 숨겨야함.
this.renderView();
},
openModalWindow(tagId){
// ModalView.openModal(tagId);
ModalView.showModal();
},
closeModalWindow(){
ModalView.closeModal();
},
startStopWatch(){
StopWatchModel.setLocalData("isRunning", true);
},
stopStopWatch(){
StopWatchModel.setLocalData("isRunning", false);
},
resetStopWatch(){
StopWatchModel.setLocalData("time", 0);
}
};
<file_sep>class DarkModeToggle {
constructor({ $target }) {
this.$target = $target;
this.$toggleCheckBox = document.createElement("input");
this.$toggleCheckBox.setAttribute("type", "checkbox");
this.checkDefaultSetting();
this.bindToggleEvent();
this.$target.appendChild(this.$toggleCheckBox);
}
checkDefaultSetting() {
this.userPreferSetting = window.matchMedia(
"(prefers-color-scheme: dark)"
).matches;
if (this.userPreferSetting) {
document.body.classList.toggle("dark-theme");
this.$toggleCheckBox.checked = true;
}
}
bindToggleEvent() {
this.$toggleCheckBox.addEventListener("click", (e) => {
document.body.classList.toggle("dark-theme");
});
}
}
<file_sep>import React, { useState } from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import "./App.css";
import NavItem from "./NavItem";
function App() {
const [user, setUser] = useState(null);
//로그인 안되었으면 link login, register show
//되어있으면 logout show
const onLogin = () => {
setUser({
name: "seongsang",
});
};
const onLogOut = () => {
setUser(null);
};
return (
<Switch>
<Route path="/" exact>
<div className="App">
<button onClick={onLogin}>로그인 하기</button>
<button onClick={onLogOut}>로그아웃 하기</button>
</div>
<NavItem to="/" show={true} text="root"></NavItem>
<NavItem to="login" show={!user} text="로그인하기"></NavItem>
<NavItem to="resgister" show={!user} text="회원가입하기"></NavItem>
<NavItem to="logout" show={user} text="로그아웃"></NavItem>
</Route>
<Route path="/login" exact>
<Link to="/">root</Link>
<h4>로그인 하는 구역.</h4>
</Route>
<Route path="/resgister" exact>
<Link to="/">root</Link>
<h4>회원가입하기</h4>
</Route>
<Route path="/logout" exact>
<Link to="/">root</Link>
<h4>로그아웃 수행</h4>
</Route>
</Switch>
);
}
export default App;
<file_sep>class ImageInfo {
$imageInfo = null;
data = null;
constructor({ $target, data }) {
const $imageInfo = document.createElement("div");
$imageInfo.className = "ImageInfo";
this.$imageInfo = $imageInfo;
this.$loading = document.createElement("div");
this.$loading.style.display = "none";
this.$loading.innerText = "Loading..";
this.$loading.classList.add("modal-loading");
$target.appendChild(this.$loading);
$target.appendChild($imageInfo);
this.hide = this.hide.bind(this);
this.hidePressEscKey = this.hidePressEscKey.bind(this);
this.hideOutSideClick = this.hideOutSideClick.bind(this);
this.data = data;
this.render();
}
isLoadding() {
this.$loading.style.display = "block";
}
setState(nextData) {
this.data = nextData;
console.log(nextData);
this.render();
}
render() {
if (this.data.visible) {
this.$loading.style.display = "none";
const { name, url, temperament, origin } = this.data.image;
this.$imageInfo.innerHTML = `
<div class="content-wrapper">
<div class="title">
<span>${name}</span>
<div class="close">x</div>
</div>
<img src="${url}" alt="${name}"/>
<div class="description">
<div>성격: ${temperament}</div>
<div>태생: ${origin}</div>
</div>
</div>`;
this.$imageInfo.style.display = "block";
setTimeout(() => {
this.$imageInfo.classList.add("modal-open");
}, 10);
this.bindCloseEvent();
this.scrollHidden();
} else {
this.$imageInfo.style.display = "none";
}
}
scrollHidden() {
document.body.classList.add("scroll-hidden");
}
removeEvent() {
this.$imageInfo.querySelector(".close").removeEventListener('click', this.hide)
window.removeEventListener("keydown", this.hide);
window.removeEventListener("click", this.hide);
}
hide() {
console.log('click');
this.removeEvent();
document.body.classList.remove("scroll-hidden");
setTimeout(() => {
this.$imageInfo.style.display = "none";
}, 1000);
this.$imageInfo.classList.remove("modal-open");
}
hidePressEscKey(e){
console.log('click');
if (e.keyCode == 27) {
this.hide();
}
}
hideOutSideClick(e){
if (e.target == this.$imageInfo) {
this.hide();
}
}
/*
이벤트 리무브가 안됨. 중첩해서 계속 생성됨.
*/
bindCloseEvent() {
this.$imageInfo.querySelector(".close").addEventListener("click", this.hide);
window.addEventListener("keydown", this.hidePressEscKey);
window.addEventListener("click", this.hideOutSideClick);
}
}
<file_sep>import KeywordView from "./KeywordView.js";
const tag = "[HistoryView]";
const HistoryView = Object.create(KeywordView);
//override
HistoryView.getKeywordsHtml = function (data) {
return (
data.reduce((html, item) => {
html += `<li data-keyword=${item.keyword}>
${item.keyword}
<span class="date">${item.date}</span>
<button class="btn-remove"></button>
</li>`;
return html;
}, `<ul class="list">`) + `</ul>`
);
};
HistoryView.bindRemoveBtn = function () {
Array.from(
this.el.querySelectorAll("button.btn-remove")
).forEach((btn) => {
btn.addEventListener('click', e =>{
// 추가하지 않으면 버튼클릭시 clickHistory가 수행됨.
//현재 btn-remove는 search-history의 자손임.
//이벤트가 상위 element로 전파되는 것을 막음
e.stopPropagation(); // 이 방법이 더 직관적임.
this.onRemove(btn.parentElement.dataset.keyword);
})
});
};
HistoryView.onRemove = function (keyword) {
this.emit('@remove', {keyword});
}
export default HistoryView;
| bf134d76b0a1f858e50a249eb5cf7c0c460df6e9 | [
"JavaScript",
"Markdown"
] | 38 | JavaScript | SeongsangCHO/FE_Study | 04bb46cde45b180124b1d1dee776696b14faf856 | 734a56d3853a912fe91b208066ca215d92fa459c |
refs/heads/master | <repo_name>pwilken/ClashBuddy<file_sep>/src/Robi.Clash.DefaultSelectors/Apollo/Classification.cs
using Robi.Common;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Robi.Clash.DefaultSelectors.Apollo
{
class Classification
{
private static readonly ILogger Logger = LogProvider.CreateLogger<Classification>();
public static IEnumerable<Handcard> GetOwnHandCards(Playfield p, boardObjType cardType, SpecificCardType sCardType)
{
var cardsOfType = p.ownHandCards.Where(n => n.card.type == cardType).ToArray();
if (cardsOfType.Length == 0)
return cardsOfType;
Func<Handcard, bool> @delegate = (n) => true;
switch (sCardType)
{
case SpecificCardType.All:
break;
// Mobs
case SpecificCardType.MobsTank:
@delegate = IsMobsTank;
break;
case SpecificCardType.MobsDamageDealer:
@delegate = IsMobsDamageDealer;
break;
case SpecificCardType.MobsBuildingAttacker:
@delegate = IsMobsBuildingAttacker;
break;
case SpecificCardType.MobsRanger:
@delegate = IsMobsRanger;
break;
case SpecificCardType.MobsAOEGround:
@delegate = IsMobsAOEGround;
break;
case SpecificCardType.MobsAOEAll:
@delegate = IsMobsAOEAll;
break;
case SpecificCardType.MobsFlyingAttack:
@delegate = IsMobsFlyingAttack;
break;
case SpecificCardType.MobsNoTank:
@delegate = IsMobsNoTank;
break;
// Buildings
case SpecificCardType.BuildingsDefense:
@delegate = IsBuildingsDefense; // TODO: Define
break;
case SpecificCardType.BuildingsAttack:
@delegate = IsBuildingsAttack; // TODO: Define
break;
case SpecificCardType.BuildingsSpawning:
@delegate = IsBuildingsSpawning;
break;
case SpecificCardType.BuildingsMana:
@delegate = (n) => false;
break; // TODO: ManaProduction
// Spells
case SpecificCardType.SpellsDamaging:
@delegate = IsSpellsDamaging;
break;
case SpecificCardType.SpellsNonDamaging:
@delegate = IsSpellsNonDamaging;
break;
case SpecificCardType.SpellsTroopSpawning:
@delegate = IsSpellsTroopSpawning; // TODO: Check
break;
case SpecificCardType.SpellsBuffs:
@delegate = IsSpellBuff; // TODO: Check
break;
default:
@delegate = (n) => false;
break;
}
return cardsOfType.Where(@delegate).ToArray();
}
public static SpecificCardType GetSpecificCardType(Handcard hc)
{
switch (hc.card.type)
{
case boardObjType.BUILDING:
if (IsBuildingsDefense(hc)) return SpecificCardType.BuildingsDefense;
if (IsBuildingsAttack(hc)) return SpecificCardType.BuildingsAttack;
if (IsBuildingsMana(hc)) return SpecificCardType.BuildingsMana;
if (IsBuildingsSpawning(hc)) return SpecificCardType.BuildingsSpawning;
return SpecificCardType.All;
case boardObjType.MOB:
if (IsMobsDamageDealer(hc) && IsMobsAOEGround(hc)) return SpecificCardType.MobsDamageDealerAOE;
if (IsMobsRanger(hc)) return SpecificCardType.MobsRanger;
if (IsMobsAOEAll(hc)) return SpecificCardType.MobsAOEAll;
if (IsMobsAOEGround(hc)) return SpecificCardType.MobsAOEGround;
if (IsMobsBuildingAttacker(hc)) return SpecificCardType.MobsBuildingAttacker;
if (IsMobsDamageDealer(hc)) return SpecificCardType.MobsDamageDealer;
if (IsMobsFlyingAttack(hc)) return SpecificCardType.MobsFlyingAttack;
if (IsMobsTank(hc)) return SpecificCardType.MobsTank;
if (IsMobsNoTank(hc)) return SpecificCardType.MobsNoTank;
return SpecificCardType.All;
case boardObjType.AOE:
case boardObjType.PROJECTILE:
if (IsSpellBuff(hc)) return SpecificCardType.SpellsBuffs;
if (IsSpellsDamaging(hc)) return SpecificCardType.SpellsDamaging;
if (IsSpellsNonDamaging(hc)) return SpecificCardType.SpellsNonDamaging;
if (IsSpellsTroopSpawning(hc)) return SpecificCardType.SpellsTroopSpawning;
return SpecificCardType.All;
default:
return SpecificCardType.All;
}
}
// Conditions
// Spells
public static Func<Handcard, bool> IsSpellBuff = (Handcard hc) => (hc.card.affectType == affectType.ONLY_OWN);
public static Func<Handcard, bool> IsSpellsTroopSpawning = (Handcard hc) => (hc.card.SpawnNumber > 0);
public static Func<Handcard, bool> IsSpellsNonDamaging = (Handcard hc) => (hc.card.DamageRadius == 0);
public static Func<Handcard, bool> IsSpellsDamaging = (Handcard hc) => (hc.card.DamageRadius > 0);
//Buildings
public static Func<Handcard, bool> IsBuildingsDefense = (Handcard hc) => (hc.card.Atk > 0);
public static Func<Handcard, bool> IsBuildingsAttack = (Handcard hc) => (hc.card.Atk > 0);
public static Func<Handcard, bool> IsBuildingsSpawning = (Handcard hc) => (hc.card.SpawnNumber > 0);
public static Func<Handcard, bool> IsBuildingsMana = (Handcard hc) => (false); // ToDo: Implement mana production
// Mobs
public static Func<Handcard, bool> IsMobsNoTank = (Handcard hc) => (hc.card.TargetType != targetType.BUILDINGS && hc.card.MaxHP < Setting.MinHealthAsTank);
public static Func<Handcard, bool> IsMobsFlyingAttack = (Handcard hc) => (hc.card.TargetType == targetType.ALL);
public static Func<Handcard, bool> IsMobsAOEAll = (Handcard hc) => (hc.card.aoeAir);
public static Func<Handcard, bool> IsMobsAOEGround = (Handcard hc) => (hc.card.aoeGround);
public static Func<Handcard, bool> IsMobsRanger = (Handcard hc) => (hc.card.MaxRange > 4500);
public static Func<Handcard, bool> IsMobsBuildingAttacker = (Handcard hc) => (hc.card.TargetType == targetType.BUILDINGS);
public static Func<Handcard, bool> IsMobsDamageDealer = (Handcard hc) => ((hc.card.Atk * hc.card.SummonNumber) > 100);
public static Func<Handcard, bool> IsMobsTank = (Handcard hc) => (hc.card.MaxHP >= Setting.MinHealthAsTank);
public static Func<BoardObj, bool> IsMobsTankCurrentHP = (BoardObj bo) => (bo.HP >= Setting.MinHealthAsTank);
public static Func<Handcard, bool> IsCycleCard = (Handcard hc) => (hc.manacost <= 2);
public static Func<Handcard, bool> IsPowerCard = (Handcard hc) => (hc.manacost >= 5);
}
}
<file_sep>/src/Robi.Clash.DefaultSelectors/Apollo/Extensions.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Robi.Clash.DefaultSelectors.Apollo
{
public static class Extensions
{
public static bool IsPositionInArea(this BoardObj bo, Playfield p, VectorAI position)
{
bool isInArea = position.X >= bo.Position.X - bo.Range &&
position.X <= bo.Position.X + bo.Range &&
position.Y >= bo.Position.Y - bo.Range &&
position.Y <= bo.Position.Y + bo.Range;
return isInArea;
}
}
}
<file_sep>/src/Robi.Clash.DefaultSelectors/ApolloOld/Enemy/EnemyCharacterPositionHandling.cs
using Robi.Clash.DefaultSelectors.Utilities;
using Robi.Clash.Engine.NativeObjects.Native;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Robi.Clash.DefaultSelectors.Enemy
{
class EnemyCharacterPositionHandling
{
public static void SetPositions()
{
EnemyLeftPrincessTower = EnemyCharacterHandling.EnemyPrincessTower.FirstOrDefault().StartPosition;
EnemyRightPrincessTower = EnemyCharacterHandling.EnemyPrincessTower.LastOrDefault().StartPosition;
}
public static Vector2f GetPositionOfTheMostDangerousAttack()
{
// comes later
return Vector2f.Zero;
}
public static Vector2f EnemyLeftPrincessTower { get; set; }
public static Vector2f EnemyRightPrincessTower { get; set; }
}
}
| ebd8ac8b298780cc80f9dde40be5e383b4547458 | [
"C#"
] | 3 | C# | pwilken/ClashBuddy | 0e0ed30c4c5ebc6c67e7a682ef2fbf7f64f1d20b | 0527c418406fc4743a0adbd6ef2cd0657bbfda83 |
refs/heads/master | <repo_name>rubicon-project/RFMSDKAdapterSamples-Android-DFP<file_sep>/RFMDFPSample/app/src/main/java/com/rfm/admobadaptersample/sample/AdDataSource.java
/*
* Copyright (c) 2016. Rubicon Project. All rights reserved
*
*/
package com.rfm.admobadaptersample.sample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.rfm.admobadaptersample.sample.AdUnit.AdType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_AD_HEIGHT;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_AD_WIDTH;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_APP_ID;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_ID;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_AD_TYPE;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_AD_ID;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_IS_CUSTOM;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_LAT;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_LOCATION_PRECISION;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_LONG;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_PUB_ID;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_REFRESH_COUNT;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_REFRESH_INTERVAL;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_RFM_SERVER;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_SITE_ID;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_TARGETING_KEY_VALUE;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_TEST_CASE_NAME;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_TEST_MODE;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.COLUMN_LOCATION_TYPE;
import static com.rfm.admobadaptersample.sample.SQLiteHelper.SAMPLE_ADS_TABLE;
class AdDataSource {
String LOG_TAG = "AdDataSource";
private static AdDataSource adDataSourceInstance = null;
private SQLiteHelper mDatabaseHelper;
private String[] mAllColumns = {
COLUMN_ID,
COLUMN_TEST_CASE_NAME,
COLUMN_SITE_ID,
COLUMN_AD_TYPE,
COLUMN_REFRESH_COUNT,
COLUMN_REFRESH_INTERVAL,
COLUMN_LOCATION_TYPE,
COLUMN_LOCATION_PRECISION,
COLUMN_LAT,
COLUMN_LONG,
COLUMN_TARGETING_KEY_VALUE,
COLUMN_AD_WIDTH,
COLUMN_AD_HEIGHT,
COLUMN_TEST_MODE,
COLUMN_AD_ID,
COLUMN_IS_CUSTOM,
COLUMN_RFM_SERVER,
COLUMN_APP_ID,
COLUMN_PUB_ID,
};
private AdDataSource(final Context context) {
mDatabaseHelper = new SQLiteHelper(context);
}
static AdDataSource getInstance(Context context) {
if (adDataSourceInstance == null) {
synchronized (AdDataSource.class) {
if (adDataSourceInstance == null) {
adDataSourceInstance = new AdDataSource(context);
}
}
}
return adDataSourceInstance;
}
AdUnit createAdUnit(final AdUnit adUnit) {
try {
final ContentValues values = new ContentValues();
values.put(COLUMN_TEST_CASE_NAME, adUnit.getTestCaseName());
values.put(COLUMN_SITE_ID, adUnit.getSiteId());
values.put(COLUMN_AD_TYPE, adUnit.getActivityClassName());
values.put(COLUMN_REFRESH_COUNT, adUnit.getRefreshCount());
values.put(COLUMN_REFRESH_INTERVAL, adUnit.getRefreshInterval());
values.put(COLUMN_LOCATION_TYPE, adUnit.getLocationType().getLocType());
values.put(COLUMN_LOCATION_PRECISION, adUnit.getLocationPrecision());
values.put(COLUMN_LAT, adUnit.getLat());
values.put(COLUMN_LONG, adUnit.getLong());
values.put(COLUMN_TARGETING_KEY_VALUE, adUnit.getTargetingKeyValue());
values.put(COLUMN_AD_WIDTH, adUnit.getAdWidth());
values.put(COLUMN_AD_HEIGHT, adUnit.getAdHeight());
values.put(COLUMN_TEST_MODE, adUnit.getTestMode());
values.put(COLUMN_AD_ID, adUnit.getAdId());
values.put(COLUMN_IS_CUSTOM, adUnit.getAdIsCustom());
values.put(COLUMN_RFM_SERVER, adUnit.getRfmServer());
values.put(COLUMN_APP_ID, adUnit.getAppId());
values.put(COLUMN_PUB_ID, adUnit.getPubId());
final SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
final long insertId = database.insert(SAMPLE_ADS_TABLE, null, values);
final Cursor cursor = database.query(SAMPLE_ADS_TABLE, mAllColumns,
COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
final AdUnit newAdUnit = convertCursorToAdUnit(cursor);
cursor.close();
database.close();
return newAdUnit;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
AdUnit getRowById(long id) {
AdUnit selectedAdUnit = null;
String sqlQuery = "select * from " + SAMPLE_ADS_TABLE + " where _id=" + id;
final SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
final Cursor cursor = database.rawQuery(sqlQuery, null);
if (cursor != null) {
if (cursor.moveToFirst())
selectedAdUnit = convertCursorToAdUnit(cursor);
cursor.close();
}
database.close();
return selectedAdUnit;
}
void deleteSampleAdUnit(final AdUnit adUnit) {
final long id = adUnit.getId();
SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
database.delete(SAMPLE_ADS_TABLE, COLUMN_ID + " = " + id, null);
Log.d(LOG_TAG, "AdUnit deleted with id: " + id);
database.close();
}
void updateSampleAdUnit(final long adUnitId, HashMap<String, String> newValuesHashMap) {
ContentValues newValues = new ContentValues();
for (Map.Entry<String, String> entry : newValuesHashMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.equals(COLUMN_REFRESH_COUNT) || key.equals(COLUMN_REFRESH_INTERVAL) ||
key.equals(COLUMN_AD_WIDTH) || key.equals(COLUMN_AD_HEIGHT))
newValues.put(key, Integer.parseInt(value));
else
newValues.put(key, value);
}
SQLiteDatabase database = mDatabaseHelper.getWritableDatabase();
if (adUnitId != -1) {
database.update(SAMPLE_ADS_TABLE, newValues, COLUMN_ID + "=" + adUnitId, null);
} else {
// update all rows with same value
database.update(SAMPLE_ADS_TABLE, newValues, null, null);
}
}
List<AdUnit> getAllAdUnits() {
final List<AdUnit> allAdUnits = new ArrayList<AdUnit>();
SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
final Cursor cursor = database.query(SAMPLE_ADS_TABLE,
mAllColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
final AdUnit adUnit = convertCursorToAdUnit(cursor);
allAdUnits.add(adUnit);
cursor.moveToNext();
}
cursor.close();
database.close();
return allAdUnits;
}
private AdUnit convertCursorToAdUnit(final Cursor cursor) {
final long id = cursor.getLong(0);
final String testCaseName = cursor.getString(1);
final String siteId = cursor.getString(2);
final AdType adType = AdType.fromActivityClassName(cursor.getString(3));
final int refreshCount = cursor.getInt(4);
final int refreshInterval = cursor.getInt(5);
final String locationType = cursor.getString(6);
final String locationPrecision = cursor.getString(7);
final String lat = cursor.getString(8);
final String lng = cursor.getString(9);
final String targetingKeyValue = cursor.getString(10);
final int adWidth = cursor.getInt(11);
final int adHeight = cursor.getInt(12);
final int testMode = cursor.getInt(13);
final String adId = cursor.getString(14);
final int isCustom = cursor.getInt(15);
final String rfmServer = cursor.getString(16);
final String appId = cursor.getString(17);
final String pubId = cursor.getString(18);
if (adType == null) {
return null;
}
return new AdUnit(id, testCaseName, siteId, adType, refreshCount, refreshInterval,
AdUnit.LocationType.fromLocationName(locationType), locationPrecision, lat, lng, targetingKeyValue, adWidth, adHeight,
testMode == 1, adId, isCustom == 1, rfmServer, appId, pubId, 0);
}
void cleanUp() {
if(mDatabaseHelper != null) {
mDatabaseHelper.close();
mDatabaseHelper = null;
adDataSourceInstance = null;
}
}
}
<file_sep>/RFMDFPSample/app/src/main/java/com/rfm/admobadaptersample/FastLaneSimpleBanner.java
/*
* Copyright (c) 2016. Rubicon Project. All rights reserved
*
*/
package com.rfm.admobadaptersample;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.doubleclick.AppEventListener;
import com.google.android.gms.ads.doubleclick.PublisherAdRequest;
import com.google.android.gms.ads.doubleclick.PublisherAdView;
import com.rfm.admobadaptersample.sample.BaseActivity;
import com.rfm.sdk.RFMAdRequest;
import com.rfm.sdk.RFMAdView;
import com.rfm.sdk.RFMFastLane;
import java.util.Map;
public class FastLaneSimpleBanner extends BaseActivity implements AppEventListener {
private final String LOG_TAG = "FastLaneSimpleBanner";
private PublisherAdView adView;
private RFMFastLane rfmFastLane;
private RFMAdRequest rfmAdRequest;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admob_banner);
adView = new PublisherAdView(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.adcontainer);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(mAdWidth * displayDesity, mAdHeight * displayDesity);
llp.gravity = Gravity.CENTER;
// Add the adView to it.
if (layout != null)
layout.addView(adView, llp);
updateAdView();
createBannerRequest();
setLoadAdAction();
rfmFastLane = new RFMFastLane(this);
rfmAdRequest = new RFMAdRequest();
}
@Override
public void onDestroy() {
super.onDestroy();
if (adView != null) {
adView.destroy();
}
RFMAdView.clearAds();
}
@Override
public void updateAdView() {
setAdRequestSize(mAdWidth, mAdHeight, adView);
adView.setAdSizes(new com.google.android.gms.ads.AdSize(mAdWidth, mAdHeight));
}
private void createRFMFastLaneRequest() {
if (rfmAdId != null && !rfmAdId.trim().equalsIgnoreCase("0")) {
rfmAdRequest.setRFMTestAdId(rfmAdId);
}
rfmAdRequest.setRFMParams(rfmServer, rfmPubId, rfmAppId);
rfmAdRequest.setAdDimensionParams(mAdWidth, mAdHeight);
}
@Override
public void loadAd() {
createRFMFastLaneRequest();
rfmFastLane.preFetchAd(rfmAdRequest, new RFMFastLane.RFMFastLaneAdListener() {
@Override
public void onAdReceived(Map<String, String> serverExtras) {
appendTextToConsole("FASTLANE onAdReceived " +
(serverExtras != null ? serverExtras.size() : "serverExtras is null!"));
requestDfpAd(serverExtras);
}
@Override
public void onAdFailed(String errorMessage) {
appendTextToConsole("FASTLANE onAdFailed " +
(errorMessage != null ? errorMessage : ""));
requestDfpAd(null);
}
});
}
private void requestDfpAd(Map<String, String> serverExtras) {
PublisherAdRequest req = null;
if (serverExtras != null && serverExtras.size() > 0) {
Map.Entry<String, String> entry = serverExtras.entrySet().iterator().next();
String firstKey = entry.getKey();
String firstValue = entry.getValue();
req = new PublisherAdRequest.Builder().addCustomTargeting(firstKey, firstValue).build();
} else {
req = new PublisherAdRequest.Builder().build();
}
adView.loadAd(req);
mNumberOfRequests = mNumberOfRequests + 1;
updateCountersView();
}
@Override
public void onAppEvent(String name, String info) {
String message = String.format("Received app event (%s, %s)", name, info);
Log.v(LOG_TAG, "Message for App event " + message);
}
/**
* Gets a string error reason from an error code.
*/
private String getErrorReason(int errorCode) {
String errorReason = "";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
private void createBannerRequest() {
adView.setAdUnitId(siteId);
adView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
appendTextToConsole("Ad loaded");
mNumberOfSuccess = mNumberOfSuccess + 1;
updateCountersView();
}
@Override
public void onAdFailedToLoad(int errorCode) {
String message = String.format("Ad failed %s", getErrorReason(errorCode));
appendTextToConsole(message);
mNumberOfFailures = mNumberOfFailures + 1;
updateCountersView();
}
@Override
public void onAdOpened() {
appendTextToConsole("Ad opened");
}
@Override
public void onAdClosed() {
appendTextToConsole("Ad closed");
}
@Override
public void onAdLeftApplication() {
appendTextToConsole("Ad left Application ");
}
});
}
}
<file_sep>/RFMDFPSample/app/src/main/java/com/rfm/admobadaptersample/SimpleBanner.java
/*
* Copyright (c) 2016. Rubicon Project. All rights reserved
*
*/
package com.rfm.admobadaptersample;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.doubleclick.AppEventListener;
import com.google.android.gms.ads.doubleclick.PublisherAdRequest;
import com.google.android.gms.ads.doubleclick.PublisherAdView;
import com.rfm.admobadaptersample.sample.BaseActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
public class SimpleBanner extends BaseActivity implements AppEventListener {
private final String LOG_TAG = "SimpleBanner";
private PublisherAdView adView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admob_banner);
adView = new PublisherAdView(this);
LinearLayout layout = (LinearLayout) findViewById(R.id.adcontainer);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(mAdWidth * displayDesity, mAdHeight * displayDesity);
llp.gravity= Gravity.CENTER;
// Add the adView to layout
if (layout != null)
layout.addView(adView, llp);
updateAdView();
createBannerRequest();
setLoadAdAction();
}
@Override
public void onDestroy() {
super.onDestroy();
if (adView != null) {
adView.destroy();
}
}
@Override
public void updateAdView() {
setAdRequestSize(mAdWidth, mAdHeight, adView);
adView.setAdSizes(new com.google.android.gms.ads.AdSize(mAdWidth, mAdHeight));
}
@Override
public void loadAd() {
adView.loadAd(new PublisherAdRequest.Builder().build());
mNumberOfRequests = mNumberOfRequests + 1;
updateCountersView();
}
@Override
public void onAppEvent(String name, String info) {
String message = String.format("Received app event (%s, %s)", name, info);
appendTextToConsole(message);
Log.v(LOG_TAG, "Message for App event " + message);
}
/**
* Gets a string error reason from an error code.
*/
private String getErrorReason(int errorCode) {
String errorReason = "";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
private void createBannerRequest() {
adView.setAdUnitId(siteId);
adView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
appendTextToConsole("Ad loaded");
mNumberOfSuccess = mNumberOfSuccess + 1;
updateCountersView();
}
@Override
public void onAdFailedToLoad(int errorCode) {
String message = String.format("Ad failed %s", getErrorReason(errorCode));
appendTextToConsole(message);
mNumberOfFailures = mNumberOfFailures + 1;
updateCountersView();
}
@Override
public void onAdOpened() {
appendTextToConsole("Ad opened");
}
@Override
public void onAdClosed() {
appendTextToConsole("Ad closed");
}
@Override
public void onAdLeftApplication() {
appendTextToConsole("Ad left Application ");
}
});
}
}
<file_sep>/RFMAdapter/com/rfm/extras/adapters/RFMAdmobInterstitialAdapter.java
/*
* Copyright (C) 2016 Rubicon Project. All rights reserved
*
* @author: Rubicon Project.
* file for integrating RFM SDK with Admob SDK
* RFM SDK will be triggered via Admob Custom Interstitial Event
*/
package com.rfm.extras.adapters;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.mediation.MediationAdRequest;
import com.google.android.gms.ads.mediation.customevent.CustomEventInterstitial;
import com.google.android.gms.ads.mediation.customevent.CustomEventInterstitialListener;
import com.rfm.sdk.RFMAdRequest;
import com.rfm.sdk.RFMAdView;
import com.rfm.sdk.RFMInterstitialAd;
import com.rfm.sdk.RFMInterstitialAdViewListener;
import com.rfm.util.RFMLog;
import java.util.HashMap;
public class RFMAdmobInterstitialAdapter implements CustomEventInterstitial {
private final String LOG_TAG = "RFMAdmobInterstitialAdp";
private CustomEventInterstitialListener mCustomEventInterstitialListener;
private RFMInterstitialAd mRFMInterstitialAdView;
private RFMAdRequest mAdRequest;
private Context mContext;
////RFM Placement Settings
private static final String RFM_SERVER_NAME = "http://mrp.rubiconproject.com/";
private static final String RFM_PUB_ID = "111008";
private HashMap<String, String> localTargetingInfoHM = new HashMap<String, String>();
public RFMAdmobInterstitialAdapter() {
localTargetingInfoHM.put("adp_version", "dfp_adp_3.4.0");
}
@Override
public void requestInterstitialAd(Context _context, CustomEventInterstitialListener _customEventInterstitialListener, String serverParameter, MediationAdRequest mediationAdRequest, Bundle bundle) {
mContext = _context;
Log.d(LOG_TAG, "custom interstitial event trigger, appId: " + serverParameter);
mCustomEventInterstitialListener = _customEventInterstitialListener;
if (mContext == null) {
mCustomEventInterstitialListener.onAdFailedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST);
return;
}
// Create RFM Interstitial Ad
if (mRFMInterstitialAdView == null) {
mRFMInterstitialAdView = new RFMInterstitialAd(mContext);
}
// Set Ad Request parameters
if (mAdRequest == null) {
mAdRequest = new RFMAdRequest();
}
mAdRequest.setRFMParams(RFM_SERVER_NAME, RFM_PUB_ID, serverParameter);
mAdRequest.setRFMAdAsInterstitial(true);
HashMap<String, String> targetingParamsHM = getTargetingParams();
mAdRequest.setTargetingParams(targetingParamsHM);
// Set Listener
setInterstitialAdViewListener();
// Request Ad
if (!mRFMInterstitialAdView.requestRFMAd(mAdRequest)) {
mCustomEventInterstitialListener.onAdFailedToLoad(AdRequest.ERROR_CODE_INVALID_REQUEST);
}
}
private void setInterstitialAdViewListener() {
if (mRFMInterstitialAdView == null) {
return;
}
mRFMInterstitialAdView.setRFMInterstitialAdListener(new RFMInterstitialAdViewListener() {
@Override
public void onInterstitialAdWillDismiss(RFMAdView rfmAdView) {
Log.v("LOG_TAG", "RFM Ad: Interstitial will dismiss");
}
@Override
public void onInterstitialAdDismissed(RFMAdView rfmAdView) {
Log.v("LOG_TAG", "RFM Ad: Interstitial ad dismissed");
}
@Override
public void onAdRequested(String requestUrl, boolean adRequestSuccess) {
Log.v("LOG_TAG", "RFM Ad: Requesting Url:" + requestUrl);
}
@Override
public void onAdReceived(RFMAdView adView) {
if (mCustomEventInterstitialListener != null) {
mCustomEventInterstitialListener.onAdLoaded();
}
}
@Override
public void onAdFailed(RFMAdView adView) {
if (mCustomEventInterstitialListener != null) {
mCustomEventInterstitialListener.onAdFailedToLoad(AdRequest.ERROR_CODE_NO_FILL);
}
}
@Override
public void onAdStateChangeEvent(RFMAdView adView, RFMAdViewEvent event) {
switch (event) {
case FULL_SCREEN_AD_DISPLAYED:
Log.v("LOG_TAG", "RFM Ad: Full screen ad displayed");
break;
case FULL_SCREEN_AD_DISMISSED:
Log.v("LOG_TAG", "RFM Ad: Full screen ad dismissed");
break;
case AD_CLICKED:
Log.v("LOG_TAG", "RFM Ad: Full screen ad clicked");
if(mCustomEventInterstitialListener != null) {
mCustomEventInterstitialListener.onAdClicked();
}
default:
break;
}
}
@Override
public void onAdResized(RFMAdView adView, int width, int height) {
Log.v("LOG_TAG", "RFM Ad: Resized ");
}
@Override
public void didDisplayAd(RFMAdView adView) {
if (RFMLog.canLogVerbose()) {
Log.v(LOG_TAG, " Into didDisplayAd ");
}
}
@Override
public void didFailedToDisplayAd(RFMAdView adView, String errorMessage) {
Log.v("LOG_TAG", "RFM Ad: Failed to display Ad ");
}
});
}
private HashMap<String, String> getTargetingParams() {
HashMap<String, String> targetingHM = new HashMap<String, String>();
targetingHM.putAll(localTargetingInfoHM);
return targetingHM;
}
@Override
public void showInterstitial() {
mRFMInterstitialAdView.show();
if (mCustomEventInterstitialListener != null)
mCustomEventInterstitialListener.onAdOpened();
}
@Override
public void onDestroy() {
Log.d(LOG_TAG, "RFM : Gracefully clear RFM Ad view ");
try {
if (mRFMInterstitialAdView != null) {
mRFMInterstitialAdView.setRFMInterstitialAdListener(null);
mRFMInterstitialAdView.reset();
mRFMInterstitialAdView = null;
}
} catch (Exception e) {
Log.d(LOG_TAG, "Failed to clean up RFM Adview " + e.getMessage());
}
mCustomEventInterstitialListener = null;
}
@Override
public void onPause() {
}
@Override
public void onResume() {
}
}
<file_sep>/RFMDFPSample/app/src/main/java/com/rfm/admobadaptersample/sample/SampleMainActivity.java
/*
* Copyright (c) 2016. Rubicon Project. All rights reserved
*
*/
package com.rfm.admobadaptersample.sample;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.rfm.admobadaptersample.R;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class SampleMainActivity extends AppCompatActivity {
private String LOG_TAG = "SampleMainActivity";
private AdDataSource mAdDataSource;
private ListView mSampleAdsListView;
private SampleListAdapter mSampleAdsListAdapter;
private long firstAdUnitId = -1;
private static final int READ_INPUT_JSON_PERMISSION_REQUEST = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.sample_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayShowTitleEnabled(false);
TextView toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setText("Admob Adapter");
mAdDataSource = AdDataSource.getInstance(this);
mSampleAdsListView = (ListView) findViewById(R.id.dynamic_list);
mSampleAdsListAdapter = new SampleListAdapter(this);
mSampleAdsListView.setAdapter(mSampleAdsListAdapter);
final SwipeDetector swipeDetector = new SwipeDetector();
mSampleAdsListView.setOnTouchListener(swipeDetector);
mSampleAdsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (swipeDetector.swipeDetected()) {
/* Do not allow swiping the headers and predefined items. */
boolean shouldDelete = true;
if (!mSampleAdsListAdapter.isEnabled(position)) {
shouldDelete = false;
}
AdUnit adUnit = (AdUnit) mSampleAdsListAdapter.getItem(position);
if (!adUnit.isCustom()) {
shouldDelete = false;
}
if (shouldDelete) {
AdUnit _adUnit = (AdUnit) mSampleAdsListAdapter.getItem(position);
deleteAdUnit(_adUnit);
}
} else {
try {
AdUnit adUnit = (AdUnit) mSampleAdsListAdapter.getItem(position);
Intent i = new Intent(getApplicationContext(),
Class.forName(adUnit.getActivityClass().getName()));
i.putExtras(adUnit.toBundle());
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
mSampleAdsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
boolean shouldDelete = true;
if (!mSampleAdsListAdapter.isEnabled(pos)) {
shouldDelete = false;
}
AdUnit adUnit = (AdUnit) mSampleAdsListAdapter.getItem(pos);
if (!adUnit.isCustom()) {
shouldDelete = false;
}
if (shouldDelete) {
AdUnit _rfmAd = (AdUnit) mSampleAdsListAdapter.getItem(pos);
//editAdUnit(_rfmAd.getId());
return true;
}
return false;
}
});
updateListUI();
registerReceiver(mReceiver, new IntentFilter(DatabaseChangedReceiver.ACTION_DATABASE_CHANGED));
setJsonToDBUploader();
}
private DatabaseChangedReceiver mReceiver = new DatabaseChangedReceiver() {
public void onReceive(Context context, Intent intent) {
updateListUI();
}
};
private void addAdUnit(final AdUnit adUnit) {
AdUnit createdAdUnit = mAdDataSource.createAdUnit(adUnit);
if (createdAdUnit != null) {
Log.d(LOG_TAG, "Create new ad unit success!");
}
updateListUI();
}
private void deleteAdUnit(final AdUnit adUnit) {
mAdDataSource.deleteSampleAdUnit(adUnit);
mSampleAdsListAdapter.remove(adUnit);
Utils.snackbar(SampleMainActivity.this, getResources().getString(R.string.item_deleted), true);
updateListUI();
}
protected void showInputDialog() {
LayoutInflater layoutInflater = LayoutInflater.from(SampleMainActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_add_test_case, null);
final EditText testCaseNameEditText = (EditText) promptView.findViewById(R.id.test_case_name_edittext);
final EditText siteIdEditText = (EditText) promptView.findViewById(R.id.site_id_editext);
final Spinner adTypeSpinner = (Spinner) promptView.findViewById(R.id.ad_type_spinner);
final AdUnit.AdType[] adTypes = AdUnit.AdType.values();
final List<String> adTypeStrings = new ArrayList<String>(adTypes.length);
for (final AdUnit.AdType adType : adTypes) {
adTypeStrings.add(adType.getName());
}
adTypeSpinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, android.R.id.text1, adTypeStrings));
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SampleMainActivity.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final String testCaseName = testCaseNameEditText.getText().toString();
if (testCaseName.isEmpty()) {
Utils.snackbar(SampleMainActivity.this, "Test case Name is empty", false);
return;
}
final String siteId = siteIdEditText.getText().toString();
if (testCaseName.isEmpty()) {
Utils.snackbar(SampleMainActivity.this, "SiteId is empty", false);
return;
}
final AdUnit.AdType adType = adTypes[adTypeSpinner.getSelectedItemPosition()];
final AdUnit adUnit = new AdUnit(-1, testCaseName, siteId, adType,
1, 0, AdUnit.LocationType.NORMAL, "6", "0.0", "0.0",
"", 320, 50, true, "", true, "", "", "", 0);
addAdUnit(adUnit);
dialog.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void updateListUI() {
boolean addedUserDefinedHeader = false;
mSampleAdsListAdapter.clear();
mSampleAdsListAdapter.add(new SampleListHeader("PRESET"));
final List<AdUnit> adUnits = mAdDataSource.getAllAdUnits();
firstAdUnitId = adUnits.get(0).getId();
int count = 0;
for (final AdUnit adUnit : adUnits) {
if (adUnit.isCustom() && !addedUserDefinedHeader) {
addedUserDefinedHeader = true;
mSampleAdsListAdapter.add(new SampleListHeader("USER DEFINED"));
}
count = count + 1;
adUnit.setCount(count);
mSampleAdsListAdapter.add(adUnit);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_testcase:
showInputDialog();
return true;
case R.id.action_settings:
Intent sampleSettingsIntent = new Intent(getApplicationContext(), SampleSettings.class);
sampleSettingsIntent.putExtra(AdUnit.ID, firstAdUnitId);
startActivity(sampleSettingsIntent);
return true;
case R.id.action_about:
Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(aboutIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
mAdDataSource.cleanUp();
}
// ---- handle the click of transparent rect to upload data into DB ------
final String INPUT_JSON = "/rubicon/dfpadaptersample/input.json";
private static int clickCount = 0;
private Handler mTimerHandler = new Handler();
private Runnable counterResetRunnable = new Runnable() {
@Override
public void run() {
clickCount = 0;
}
};
private void resetCount(){
mTimerHandler.removeCallbacks(counterResetRunnable);
mTimerHandler.postDelayed(counterResetRunnable, 3000);
}
private void setJsonToDBUploader() {
final View uploadFileToDB = findViewById(R.id.upload_file_to_db);
if (uploadFileToDB != null) {
uploadFileToDB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetCount();
if (clickCount == 10) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getPermissionToReadInputJson();
} else {
uploadJsonToDB();
}
}
clickCount++;
}
});
}
}
private void getPermissionToReadInputJson() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
READ_INPUT_JSON_PERMISSION_REQUEST);
} else {
uploadJsonToDB();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case READ_INPUT_JSON_PERMISSION_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
uploadJsonToDB();
} else {
Utils.snackbar(SampleMainActivity.this, getResources().getString(R.string.json_file_no_permission), false);
}
return;
}
}
}
private void uploadJsonToDB() {
String inputJsonPath = Environment.getExternalStorageDirectory().getPath() + INPUT_JSON;
File file = new File(inputJsonPath);
if (!file.exists()) {
Utils.snackbar(SampleMainActivity.this, getResources().getString(R.string.json_file_not_found), false);
return;
}
String jsonString = JsonToSQLLite.readFileToString(inputJsonPath);
boolean saveStatus = JsonToSQLLite.saveToDB(getApplicationContext(), jsonString);
if (saveStatus) {
Utils.snackbar(SampleMainActivity.this, getResources().getString(R.string.db_upload_success), true);
} else {
Utils.snackbar(SampleMainActivity.this, getResources().getString(R.string.db_upload_failure), false);
}
updateListUI();
}
// -------------------------------------------------------------------
}<file_sep>/RFMDFPSample/settings.gradle
include ':app'
// for development
//include ':app', ':SDKProject'
//project(':SDKProject').projectDir=new File("C:\\Rubi\\sourcecode\\rfm_android_sdk\\Android\\V3\\Libraries\\SDKProject")<file_sep>/RFMDFPSample/app/src/main/java/com/rfm/admobadaptersample/sample/Utils.java
/*
* Copyright (c) 2016. Rubicon Project. All rights reserved
*
*/
package com.rfm.admobadaptersample.sample;
import android.app.Activity;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
public class Utils {
static void snackbar(Activity activity, String msg, boolean positive) {
Snackbar.make(activity.findViewById(android.R.id.content), msg, Snackbar.LENGTH_LONG)
.setActionTextColor(positive?Color.GREEN:Color.RED)
.show();
}
}
<file_sep>/README.md
# Rubicon Project Sample Apps for DFP Adapter Integration
This repository contains sample applications that show how to integrate Rubicon Project's Mobile Ads SDK and DFP Adapters into an Android Application Project when using DFP as a primary ad serving SDK. Please refer to our developer portal (http://dev.rubiconproject.com/docs/Mobile_SDK_for_Android) for detailed integration guide.
You can download our latest SDKs from [this repository](https://github.com/rubicon-project/RFMAdSDK-Android.git) and our DFP Adapters from [this repository](https://github.com/rubicon-project/RFMSDKAdapter-Android-DFP.git)
| c65a06bf1f5038710eba37d256967d4bd7bde741 | [
"Markdown",
"Java",
"Gradle"
] | 8 | Java | rubicon-project/RFMSDKAdapterSamples-Android-DFP | 11cf67429c15c0f4e97b5d20f77094aeb1bdf04a | 9516ebb37ad7927614307c13d932aca902449602 |
refs/heads/master | <file_sep>#include "lib/kernel/list.h"<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "lib/kernel/list.h"
#include "tests/threads/listpop.h"
struct item{
struct list_elem elem;
int priority;
};
#define get_item(ELEM) list_entry(ELEM,struct item, elem)
static void populate(struct list *l, int *a, int n){
struct item *v;
int i;
for (i=0; i<n; i++){
v=malloc(sizeof(struct item));
v->priority = a[i];
list_push_back(l,&(v->elem));
}
}
int compare(const struct list_elem *a, const struct list_elem *b, void * aux){
return get_item(a)->priority<get_item(b)->priority;
}
static void print_sorted(struct list *l){
struct list_elem * it;
list_sort(l, compare, NULL);
for (it=list_begin(l); it!=list_end(l); it=list_next(it))
printf("%d ",get_item(it)->priority);
}
static int test_sorted(struct list *l){
struct list_elem * it = list_begin(l);
int last_p=get_item(it)->priority;
it = list_next(it);
while (it!=list_end(l)){
if (get_item(it)->priority<last_p)
return 0;
last_p=get_item(it)->priority;
it=list_next(it);
}
return 1;
}
void test_list(){
struct list l;
list_init(&l);
populate(&l, ITEMARRAY, ITEMCOUNT);
printf("Sorted array:\n");
print_sorted(&l);
printf("\n");
ASSERT(test_sorted(&l));
}<file_sep>#include "userprog/syscall.h"
#include <stdio.h>
#include <syscall-nr.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "process.h"
#include "threads/vaddr.h"
#include "pagedir.h"
#include "threads/synch.h"
#include "devices/shutdown.h"
#include "devices/input.h"
#include "filesys/file.h"
static void syscall_handler (struct intr_frame *);
struct lock filesys_lock;
void
syscall_init (void)
{
intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
lock_init(&filesys_lock);
}
static bool is_valid_address(const void *addr){
return (addr!=NULL && is_user_vaddr(addr)
&& pagedir_get_page(thread_current()->pagedir,addr)!=NULL);
}
static bool is_valid_buffer(const void *buf, unsigned size){
const uint8_t * addr = buf;
unsigned i;
for (i=0; i<size; i++)
if (!is_valid_address(addr+i))
return 0;
return 1;
}
static void check_stack(void *base_addr, int nr_args){
uint8_t* p =base_addr;
bool ok=1;
int i;
for (i=0; i<4*nr_args; i++)
ok&=is_valid_address(p+i);
if (!ok)
thread_exit();
}
static void halt(void){
shutdown_power_off();
}
static void exit(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,1);
int status_code=*esp;
thread_current()->exit_code = status_code;
thread_exit();
}
static void create(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,2);
char* file = *(char **)esp;
esp++;
unsigned initial_size = *(unsigned *)esp;
if (!is_valid_address(file))
thread_exit();
lock_acquire(&filesys_lock);
f->eax = filesys_create(file, initial_size);
lock_release(&filesys_lock);
}
static void remove(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,1);
char* file = *(char **)esp;
if (!is_valid_address(file))
thread_exit();
lock_acquire(&filesys_lock);
f->eax = filesys_remove(file);
lock_release(&filesys_lock);
}
static void open(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,1);
char* filename = *(char **)esp;
if (!is_valid_address(filename))
thread_exit();
lock_acquire(&filesys_lock);
struct file* file = filesys_open(filename);
lock_release(&filesys_lock);
if (!file){
f->eax = -1;
return;
}
f->eax = add_file(file);
}
static void close(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,1);
fd_t fd = *esp;
struct file* file = get_file_by_fd(fd);
if (file==NULL)
return;
lock_acquire(&filesys_lock);
file_close(file);
lock_release(&filesys_lock);
remove_file(fd);
}
static void write(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,3);
fd_t fd=*esp;
esp++;
void * buf = *(void **)esp;
esp++;
unsigned int size = *(unsigned int *) esp;
if (!is_valid_buffer(buf,size))
thread_exit();
//write to console
if (fd==1){
putbuf(buf,size);
f->eax=size;
}
//else write to file
else {
struct file * file = get_file_by_fd(fd);
if (file==NULL){
f->eax = 0;
return;
}
lock_acquire(&filesys_lock);
f->eax = file_write(file,buf,size);
lock_release(&filesys_lock);
}
}
static void read(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,3);
fd_t fd=*esp;
esp++;
void * buf = *(void **)esp;
esp++;
unsigned int size = *(unsigned int *) esp;
if (size==0){
f->eax = 0;
return;
}
if (!is_valid_buffer(buf,size))
thread_exit();
//read from console
if (fd==0){
char * buffer = buf;
unsigned k=0;
while (k<size)
buffer[k++]=input_getc();
f->eax=size;
}
//else read from file
else {
struct file * file = get_file_by_fd(fd);
if (file==NULL){
f->eax = 0;
return;
}
lock_acquire(&filesys_lock);
f->eax = file_read(file,buf,size);
lock_release(&filesys_lock);
}
}
static void filesize(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,1);
fd_t fd = *esp;
struct file* file = get_file_by_fd(fd);
if (file==NULL)
return;
lock_acquire(&filesys_lock);
f->eax = file_length(file);
lock_release(&filesys_lock);
}
static void seek(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,2);
fd_t fd = *esp;
esp++;
unsigned position = *esp;
struct file* file = get_file_by_fd(fd);
if (file==NULL)
return;
lock_acquire(&filesys_lock);
file_seek(file,position);
lock_release(&filesys_lock);
}
static void tell(struct intr_frame *f){
uint32_t *esp = (uint32_t * )f->esp+1;
check_stack(esp,1);
fd_t fd = *esp;
struct file* file = get_file_by_fd(fd);
if (file==NULL)
return;
lock_acquire(&filesys_lock);
f->eax = file_tell(file);
lock_release(&filesys_lock);
}
static void wait(struct intr_frame *f){
uint32_t *esp = (uint32_t*)f->esp+1;
check_stack(esp,1);
tid_t pid = *esp;
f->eax = process_wait(pid);
}
static void exec(struct intr_frame *f){
uint32_t *esp = (uint32_t*)f->esp+1;
check_stack(esp,1);
char * cmd_line = *(char**)esp;
tid_t pid;
if (!is_valid_address(cmd_line))
pid = -1;
else
pid = process_execute(cmd_line);
f->eax = pid;
}
static void
syscall_handler (struct intr_frame *f)
{
check_stack(f->esp,1);
uint32_t syscall_nr = *(uint32_t *)f->esp;
switch (syscall_nr){
case SYS_HALT:
halt();
break;
case SYS_EXEC:
exec(f);
break;
case SYS_EXIT:
exit(f);
break;
case SYS_CREATE:
create(f);
break;
case SYS_REMOVE:
remove(f);
break;
case SYS_OPEN:
open(f);
break;
case SYS_CLOSE:
close(f);
break;
case SYS_WRITE:
write(f);
break;
case SYS_READ:
read(f);
break;
case SYS_FILESIZE:
filesize(f);
break;
case SYS_SEEK:
seek(f);
break;
case SYS_WAIT:
wait(f);
break;
case SYS_TELL:
tell(f);
break;
default:
printf("not supported system call %d\n",syscall_nr);
thread_exit();
}
}
<file_sep>#define ITEMCOUNT 10
int ITEMARRAY[ITEMCOUNT] = {3,1,4,2,7,6,9,5,8,3};
| 33d44f1ebd3218159f141978477b38bfc7f83283 | [
"C"
] | 4 | C | mminhh/pintos | bf56722468b8a70e888d4a8fb04332a7c5a45c90 | dcd9730f511220e286798cc8eca0e2e6fd397e9d |
refs/heads/master | <file_sep>#pragma once
#include <string>
#include <SFML\Graphics.hpp>
class glTiled;
class glAction
{
protected:
virtual void execute(sf::Sprite& sprite) = 0;
};
namespace actions {
class fadeOut : public glAction
{
void execute(glTiled& tile);
};
class fadeIn : public glAction
{
void execute(glTiled& tile);
};
}<file_sep>#include "glBoard.h"
#include <stdio.h>
#include "glUtils.h"
#include "glSettings.h"
#include <iostream> // std::cout
#include <sstream>
#include <string>
#include <cmath>
// how much time passes between frames
const float DELTA = 1.0f / 60.0f;
void glBoard::Load()
{
for (int a=1;a<SPRITES;a++){
ostringstream ss2;
ss2 << a;
string str = ss2.str();
backgroundTexture[a].loadFromFile(concat(glSettings::ASSETS_PATH, "bg"+str+".png"));
backgroundSprite[a].setTexture(backgroundTexture[a]);
}
progressBarTexture.loadFromFile(concat(glSettings::ASSETS_PATH, "progress-bar-texture.png"));
}
void glBoard::Init(int level)
{
mAngle = 0;
mTileManager.loadMap(level);
}
void glBoard::Update()
{
mAngle += DELTA * 2.f;
if (mAngle > 360.0f) mAngle = 0.0f;
}
glTiledLoader& glBoard::getTileManager()
{
return this->mTileManager;
}
void glBoard::Draw(sf::RenderWindow& graphics,sf::Vector2f pos,sf::Vector2f size,bool left,sf::Vector2f leftHero,sf::Vector2f rightHero)
{
int beginX;
int endX;
if (left) {
beginX=0;
endX=10;
} else{
beginX=10;
endX=20;
};
int tiledSize = 64;
int beginY= floor((pos.y-384)/tiledSize);
int endY= floor(((pos.y-384+size.y))/tiledSize)+1;
int act=0;
bool draw = false; int p,r;
int offset = 0;
offset = (left) ? 0 : -tiledSize*10;
//graphics.setView(graphics.getDefaultView());
for (int a=beginX;a<endX;a++) {
for (int b=beginY;b<endY;b++) {
if (a>=0 && b>=0 && b<100 && a<20) {
act = mTileManager.getValue(b, a);
if (act==INVISIBLE_POSX) {
draw = true;
p=a;
r=b;
} else if(act>=1 && act<=SPRITES && !mTileManager.isActive(b,a)){
backgroundSprite[act].setPosition(a*tiledSize + offset, (b)*tiledSize + (act >= OBJECTS_MIN && act <= OBJECTS_MAX ? 10 * sin(mAngle) - 10 : 0));
backgroundSprite[act].setColor(mTileManager.getColor(b,a));
float opacity = mTileManager.getOpacity(b,a);
if (std::abs(leftHero.y-rightHero.y)<=4*64){
backgroundSprite[act].setColor(sf::Color(255, 255, 255,255));
}
// draw picking progress bar
int pressesAmount = getTileManager().getTile(b, a).amountOfPresses;
if(pressesAmount && pressesAmount < glTiled::MAX_AMOUNT_OF_PRESSES)
{
DrawPressStackProgressBar(graphics, pressesAmount/(float)glTiled::MAX_AMOUNT_OF_PRESSES, a*tiledSize + offset, (b)*tiledSize);
}
if(pressesAmount >= glTiled::MAX_AMOUNT_OF_PRESSES)
{
// set nice transparency effect
backgroundSprite[act].setColor(sf::Color(255, 255, 255, 100));
}
graphics.draw(backgroundSprite[act]);// define a 120x50 rectangle
backgroundSprite[act].setColor(sf::Color(255, 255, 255,255));
} else if ((act==FREE || (act>=OBJECTS_MIN && act<=OBJECTS_MAX)) && mTileManager.isActive(b,a)) {
float opacity = mTileManager.getLowerOpacity(b,a);
if (left)
backgroundSprite[act].setPosition(a*tiledSize, (b)*tiledSize + (act >= OBJECTS_MIN && act <= OBJECTS_MAX ? 5 * sin(mAngle) : 0));
else
backgroundSprite[act].setPosition((a - 10)*tiledSize, (b)*tiledSize + (act >= OBJECTS_MIN && act <= OBJECTS_MAX ? 5 * sin(mAngle) : 0));
backgroundSprite[act].setColor(sf::Color(255* opacity, 255, 255 * opacity, opacity * 255));
graphics.draw(backgroundSprite[act]);
}
/*
if(act>=1 && act<=SPRITES && !mTileManager.isActive(b,a)){
backgroundSprite[act].setPosition(a*tiledSize + offset,(b)*tiledSize);
graphics.draw(backgroundSprite[act]);
int pressesAmount = getTileManager().getTile(b, a).amountOfPresses;
if(pressesAmount && pressesAmount <= glTiled::MAX_AMOUNT_OF_PRESSES)
{
DrawPressStackProgressBar(graphics, pressesAmount/(float)glTiled::MAX_AMOUNT_OF_PRESSES, a*tiledSize + offset, (b)*tiledSize);
}
} else if ((act==FREE || (act>=OBJECTS_MIN && act<=OBJECTS_MAX)) && mTileManager.isActive(b,a)){
float opacity = mTileManager.getLowerOpacity(b,a);
backgroundSprite[act].setPosition(a*tiledSize + offset,(b)*tiledSize);
*/
}
}
}
if (draw) {
// define a 120x50 rectangle
/* sf::RectangleShape rectangle(sf::Vector2f(640, 4*64));
rectangle.setPosition(p*tiledSize,(r-3)*tiledSize);
rectangle.setFillColor(sf::Color(110, 110, 110, 250));
graphics.draw(rectangle);*/
}
}
void glBoard::DrawPressStackProgressBar(sf::RenderWindow& graphics, float progress, float posx, float posy)
{
sf::RectangleShape bar = sf::RectangleShape(sf::Vector2f(6.f, progress*glSettings::TILE_HEIGHT));
bar.setTexture(&progressBarTexture);
bar.setPosition(posx, posy + glSettings::TILE_HEIGHT - progress*glSettings::TILE_HEIGHT);
graphics.draw(bar);
}
void glBoard::ChangeLevel(int level)
{
mTileManager.loadMap(level);
}
<file_sep>//#include "pch.h"
#include "glMainMenu.h"
#include "glUtils.h"
#include "glSettings.h"
glMainMenu::MenuResult glMainMenu::Show(sf::RenderWindow& window, float viewWidth, float viewHeight)
{
mBackgroundMenu.loadFromFile(concat(glSettings::ASSETS_PATH, "titlepage.png"));
mStart.loadFromFile(concat(glSettings::ASSETS_PATH, "start.png"));
mExit.loadFromFile(concat(glSettings::ASSETS_PATH, "exit.png"));
mBackgroundSpriteMenu.setTexture(mBackgroundMenu);
mBackgroundSpriteMenu.setOrigin(mBackgroundMenu.getSize().x, 0);
mBackgroundSpriteMenu.setPosition(viewWidth, 0);
mStartSprite.setTexture(mStart);
mExitSprite.setTexture(mExit);
mStartSprite.setOrigin(mStart.getSize().x/2 , mStart.getSize().y/2);
mExitSprite.setOrigin(mExit.getSize().x/2, mExit.getSize().y/2);
mStartSprite.setPosition(viewWidth/2-410, viewHeight/2 - 60);
mExitSprite.setPosition(viewWidth/2-410, viewHeight/2 + 110);
sf::Vector2f v1(viewWidth/2-500.0f,viewHeight- mActiveSprite1.getLocalBounds().height -25.0f);
mActiveSprite1.setPosition(v1);
sf::Vector2f v2(viewWidth/2+280.0f, viewHeight- mActiveSprite2.getLocalBounds().height -265.0f);
mActiveSprite2.setPosition(v2);
//Play menu item coordinates
MenuItem playButton;
playButton.rect.left = mStartSprite.getPosition().x - mStart.getSize().x/2;
playButton.rect.height = mStart.getSize().y;
playButton.rect.top = mStartSprite.getPosition().y - mStart.getSize().y/2;
playButton.rect.width = mStart.getSize().x;
playButton.action = Play;
//Exit menu item coordinates
MenuItem exitButton;
exitButton.rect.left = mExitSprite.getPosition().x - mExit.getSize().x/2;
exitButton.rect.height = mExit.getSize().y;
exitButton.rect.top = mExitSprite.getPosition().y - mExit.getSize().y/2;
exitButton.rect.width = mExit.getSize().x;
exitButton.action = Exit;
_menuItems.push_back(playButton);
_menuItems.push_back(exitButton);
glMainMenu::MenuResult result;
while(true)
{
/*// inicjalizacja naszzego widoku (view) i jego rozmiarów
float windowHeight = (float)window.getSize().y;
float viewScale = 768.0f/windowHeight;
viewWidth = window.getSize().x*viewScale;
viewHeight = 768;*/
sf::View view(sf::FloatRect(0, 0, viewWidth, viewHeight));
window.setView(view);
window.clear(sf::Color(0,0,0));
window.draw(mBackgroundSpriteMenu);
window.draw(mStartSprite);
window.draw(mExitSprite);
window.draw(mActiveSprite1);
window.draw(mActiveSprite2);
window.display();
result = GetMenuResponse(window,viewWidth,viewHeight);
if(result != Nothing)
return result;
}
}
glMainMenu::MenuResult glMainMenu::HandleClick(int x, int y, sf::RenderWindow& window, float viewWidth, float viewHeight)
{
std::list<MenuItem>::iterator it;
x = x * (viewHeight / window.getSize().y);
y = y * (viewHeight / window.getSize().y);
for ( it = _menuItems.begin(); it != _menuItems.end(); it++)
{
sf::Rect<int> menuItemRect = (*it).rect;
if( menuItemRect.top + menuItemRect.height > y
&& menuItemRect.top < y
&& menuItemRect.left < x
&& menuItemRect.left + menuItemRect.width > x)
{
return (*it).action;
}
}
return Nothing;
}
glMainMenu::MenuResult glMainMenu::GetMenuResponse(sf::RenderWindow& window, float viewWidth, float viewHeight)
{
sf::Event menuEvent;
while(window.pollEvent(menuEvent))
{
if(menuEvent.type == sf::Event::MouseButtonPressed)
{
return HandleClick(menuEvent.mouseButton.x,menuEvent.mouseButton.y,window,viewWidth,viewHeight);
}
if(menuEvent.type == sf::Event::Closed)
{
window.close();
return Exit;
}
else
return Nothing;
}
}
<file_sep>#pragma once
#include "SFML\Window.hpp"
#include "SFML\Graphics.hpp"
#include <list>
class glMainMenu
{
public:
enum MenuResult { Nothing, Exit, Play };
struct MenuItem
{
public:
sf::Rect<int> rect;
MenuResult action;
};
sf::Event event;
MenuResult Show(sf::RenderWindow& window, float viewWidth, float viewHeight);
void Load();
sf::Texture mBackgroundMenu;
sf::Sprite mBackgroundSpriteMenu;
sf::Texture mStart, mExit;
sf::Sprite mStartSprite, mExitSprite;
//heroes
sf::Sprite mActiveSprite1;
sf::Texture mBackFront1;
sf::Sprite mActiveSprite2;
sf::Texture mBackFront2;
private:
MenuResult GetMenuResponse(sf::RenderWindow& window, float viewWidth, float viewHeight);
MenuResult HandleClick(int x, int y,sf::RenderWindow& window, float viewWidth, float viewHeight);
std::list<MenuItem> _menuItems;
};<file_sep>#include "glBullet.h"
#include "glSettings.h"
#include "glUtils.h"
// how much time passes between frames
const float DELTA = 1.0f / 60.0f;
const float glBullet::acceleration = 1500.0f;
void glBullet::Init(int bottomEdge, sf::Texture * texture, sf::Texture * warning)
{
bulletTexture = texture;
bulletSprite.setPosition(20 + rand() % 600 - bulletTexture->getSize().x, bottomEdge + 10);
bulletSprite.setTexture(*bulletTexture);
mVelocity = - (rand() % 600 + 1200); // 60 - 140 px/sec
mDying = false;
mOpacity = 1.0f;
mTimer = 0;
warningTexture = warning;
warningSprite.setTexture(*warningTexture);
mPlayed = false;
}
void glBullet::Update()
{
mTimer += DELTA;
if(!mDying)
{
if (mTimer > 2.2f)
{
float x = bulletSprite.getPosition().x;
float y = bulletSprite.getPosition().y;
bulletSprite.setPosition(x, y + mVelocity * DELTA);
mVelocity += acceleration * DELTA;
}
if (mTimer > 2.0f)
{
if (!mPlayed)
{
mPlayed = true;
musicObject.PlaySound("bullet");
}
}
}
else
{
mOpacity -= DELTA;
if (mOpacity < 0)
mOpacity = 0;
}
}
void glBullet::Draw(sf::RenderWindow& graphics)
{
graphics.draw(bulletSprite);
}
void glBullet::DrawWarning(sf::RenderWindow& graphics, int bottomEdge)
{
warningSprite.setPosition(bulletSprite.getPosition().x - (bulletTexture->getSize().x - warningTexture->getSize().x) + (rand() % 16 - 8), bottomEdge - warningTexture->getSize().y - 30 + (rand() % 16 - 8));
if (mTimer < 2.0f)
graphics.draw(warningSprite);
}<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "glHero.h"
#include "glTiled.h"
class glTiledLoader
{
private:
// private data
bool mBoolean;
int** board;
// size of the currently loaded map
int amountOfRows;
int amountOfColumns;
public:
std::vector<std::vector <int> > vec;
std::vector<std::vector <glTiled> > vecTiled;
glTiledLoader();
~glTiledLoader(){};
void Load();
void Init();
void Draw();
void Update();
void UpdateHighscore(int score);
glTiled& getTile(int row ,int column);
void loadMap(int number);
void getTiledValue(int x,int y);
void callAssociated(int x,int y);
bool isLadder(int x,int y);
bool isActive(int x,int y);
float getOpacity(int x,int y);
bool isWall(int x,int y);
bool isFree(int x,int y);
int getValue(int x,int y);
int getMapWidth();
int getMapHeight();
bool intersectsWithWall(glHero& hero);
bool blockedByObstacleOnRightSide(glHero& hero);
bool blockedByObstacleOnLeftSide(glHero& hero);
bool isBlockableObject(int x, int y);
bool isKilledByLaser(int x, int y);
bool intersectsWithLadder(glHero& hero);
sf::FloatRect getTileBoundingBox(int row, int col, glHero::PLAYER playerId);
void setActive(int x,int y);
float getLowerOpacity(int x,int y);
sf::Color getColor(int x, int y);
void runActionOnAssociated(int x,int y);
void runActionOnAssociatedLasers(int x,int y);
void runActionOnAssociatedLasersShowAgain(int x,int y);
void setInvisibleRoom(int x);
glTiled &searchTiled(int c, int type);
vector<glTiled*> searchTilesAssociatedForAction(int scope, int search_type);
vector<glTiled*> searchTilesAssociatedForActionOrigin(int scope, int search_type);
// returns tile coordinates by position
void getTileCoords(float posX, float posY, glHero::PLAYER playerId, int& tileX, int& tileY);
};<file_sep>#pragma once
#include <SFML/Audio.hpp><file_sep>#pragma once
#include "SFML\Graphics.hpp"
#define SPRITES 10
class glProgressBar
{
private:
sf::Sprite backgroundSprite[SPRITES];
sf::Texture backgroundTexture[SPRITES];
sf::Texture pbTexture;
sf::Sprite pbSprite;
sf::Clock timer;
public:
float lava;
float player1;
float player2;
void Load();
void Init();
void Update(float player1, float player2);
/**
* Draw game on the main window object
*/
void Draw(sf::RenderWindow& graphics);
void DrawLava(sf::RenderWindow& graphics,bool left);
};<file_sep>#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Config.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
#include "glSettings.h"
#include "glUtils.h"
#include "glMainMenu.h"
#include "glGame.h"
#include "glHandleMusic.h"
int main()
{
sf::RenderWindow window(sf::VideoMode(glSettings::WINDOW_WIDTH, glSettings::WINDOW_HEIGHT), "The everlasting race!"/*, sf::Style::Fullscreen*/);
glGame gameObject;
gameObject.Load();
gameObject.Init(window);
/*
// inicjalizacja naszzego widoku (view) i jego rozmiarów
float windowHeight = (float)window.getSize().y;
float viewScale = 768.0f/windowHeight;
viewWidth = window.getSize().x*viewScale;
viewHeight = 768;
sf::View view(sf::FloatRect(0, 0, viewWidth, viewHeight));
window.setView(view);
*/
// uruchom generator liczb losowych
srand((unsigned)time(NULL));
sf::Clock frame_timer;
const float DELTA = 1.0f/60.0f;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::E)
{
gameObject.GetReleasedLeft();
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::RControl)
{
gameObject.GetReleasedRight();
}
if (event.type == sf::Event::Closed)
window.close();
/*else if (event.type == sf::Event::Resized)
{
float width = window.getSize().x;
float height = window.getSize().y;
// Minimum size
if(width < 800)
width = 800;
if(height < 600)
height = 600;
if (width<(5.0f/4.0f)*height)
width=(5.0f/4.0f)*height;
if (width>2*height)
height=1.0f/2.0f*width;
window.setSize(sf::Vector2u(width, height));
*/
else
gameObject.HandleEvent(event);
}
if(frame_timer.getElapsedTime().asSeconds() > DELTA)
{
if(gameObject.Win()){
/*for(int i=0;i < 20./DELTA;++i){
if(frame_timer.getElapsedTime().asMilliseconds() > DELTA){
gameObject.Update();
frame_timer.restart();
}
}*/
gameObject.GameStateWin();
}
else if(gameObject.GameOver()){
/*for(int i=0;i < 20./DELTA;++i){
if(frame_timer.getElapsedTime().asMilliseconds() > DELTA){
gameObject.Update();
frame_timer.restart();
}
}*/
gameObject.GameStateGameOver();
}
else{
gameObject.Update();
frame_timer.restart();
}
}
window.clear();
gameObject.Draw(window);
window.display();
}
return 0;
}<file_sep>#pragma once
#include <SFML/Graphics.hpp>
#include "glHandleMusic.h"
extern glHandleMusic musicObject;
class glBullet
{
public:
sf::Texture *bulletTexture;
sf::Sprite bulletSprite;
sf::Texture *warningTexture;
sf::Sprite warningSprite;
const static float acceleration;
float mVelocity;
float mOpacity;
bool mDying;
float mTimer;
bool mPlayed;
static void Load();
void Init(int bottomEdge, sf::Texture * texture, sf::Texture * warning);
void Update();
void Draw(sf::RenderWindow& graphics);
void DrawWarning(sf::RenderWindow& graphics, int bottomEdge);
};<file_sep>#include "glProgressBar.h"
#include <stdio.h>
#include "glUtils.h"
#include "glSettings.h"
#include <iostream> // std::cout
#include <sstream>
#include <string>
#include <math.h> /* floor */
void glProgressBar::Load()
{
backgroundTexture[0].loadFromFile(concat(glSettings::ASSETS_PATH, "progress-bar.png"));
backgroundSprite[0].setTexture(backgroundTexture[0]);
backgroundTexture[1].loadFromFile(concat(glSettings::ASSETS_PATH, "pb-z1.png"));
backgroundSprite[1].setTexture(backgroundTexture[1]);
backgroundTexture[2].loadFromFile(concat(glSettings::ASSETS_PATH, "pb-z2.png"));
backgroundSprite[2].setTexture(backgroundTexture[2]);
backgroundTexture[3].loadFromFile(concat(glSettings::ASSETS_PATH, "death-1.png"));
backgroundSprite[3].setTexture(backgroundTexture[3]);
backgroundTexture[4].loadFromFile(concat(glSettings::ASSETS_PATH, "death-2.png"));
backgroundSprite[4].setTexture(backgroundTexture[4]);
backgroundTexture[5].loadFromFile(concat(glSettings::ASSETS_PATH, "death-3.png"));
backgroundSprite[5].setTexture(backgroundTexture[5]);
backgroundTexture[6].loadFromFile(concat(glSettings::ASSETS_PATH, "death-4.png"));
backgroundSprite[6].setTexture(backgroundTexture[6]);
pbTexture.loadFromFile(concat(glSettings::ASSETS_PATH, "progress-level.png"));
pbSprite.setTexture(pbTexture);
}
void glProgressBar::Init()
{
lava=6400-50;
player1=6400-24;
player2=6400-24;
timer.restart();
}
void glProgressBar::Update(float play1, float play2)
{
player1=play1;
player2=play2;
}
void glProgressBar::Draw(sf::RenderWindow& graphics)
{
// define a 120x50 rectangle
if(timer.getElapsedTime().asSeconds() > 3){
lava-=0.004+0.0004*timer.getElapsedTime().asSeconds();}
if (lava<0){
lava=0;}
backgroundSprite[0].setPosition(625,0);
graphics.draw(backgroundSprite[0]);
float actual = ((1-(lava/6400))*754);
float actualPlayer1 = ((1-(player1/6400))*754);
float actualPlayer2 = ((1-(player2/6400))*754);
if (lava-player1>180 || lava-player2>180 ){
lava-=0.051;
}else if (lava-player1>300 || lava-player2>300 ){
lava-=0.064;
}else if (lava-player1>400 || lava-player2>400 ){
lava-=0.90;
}else if (lava-player1>500 || lava-player2>500 ){
lava-=0.137;
}else if (lava-player1>600 || lava-player2>600 ){
lava-=0.5;
}
pbSprite.setPosition(626,763-actual);
graphics.draw(pbSprite);
backgroundSprite[1].setPosition(552,763-actualPlayer1);
graphics.draw(backgroundSprite[1]);
backgroundSprite[2].setPosition(660,763-actualPlayer2);
graphics.draw(backgroundSprite[2]);
}
void glProgressBar::DrawLava(sf::RenderWindow& graphics,bool left){
backgroundSprite[3].setScale(sf::Vector2f(1.5f, 1.f));
backgroundSprite[3].setPosition(8*std::sin(0.25*timer.getElapsedTime().asSeconds()),lava+5*std::sin(timer.getElapsedTime().asSeconds()));
graphics.draw(backgroundSprite[3]);
backgroundSprite[4].setColor(sf::Color(255, 255, 255, (0.25*std::sin(4*timer.getElapsedTime().asSeconds()+0.49)+0.75 ) * 255));
backgroundSprite[4].setPosition(3*std::sin(timer.getElapsedTime().asSeconds()+0.75),lava+5*std::sin(timer.getElapsedTime().asSeconds()));
graphics.draw(backgroundSprite[4]);
backgroundSprite[5].setColor(sf::Color(255, 255, 255, (0.25*std::sin(3*timer.getElapsedTime().asSeconds()-0.51)+0.75 ) * 255));
backgroundSprite[5].setPosition(2*std::sin(timer.getElapsedTime().asSeconds()+0.5),lava+5*std::sin(timer.getElapsedTime().asSeconds()));
graphics.draw(backgroundSprite[5]);
backgroundSprite[6].setColor(sf::Color(255, 255, 255, (0.3*std::sin(2*timer.getElapsedTime().asSeconds()+0.51)+0.3 ) * 255));
backgroundSprite[6].setPosition(10*std::sin(0.1*timer.getElapsedTime().asSeconds()-0.5),30+lava+20*std::sin(timer.getElapsedTime().asSeconds()));
graphics.draw(backgroundSprite[6]);
}<file_sep>#include "glTiledLoader.h"
#include "glTiled.h"
#include "glSettings.h"
#include "glHero.h"
#include <assert.h>
#include <iostream>
#include <fstream>
#include <iostream> // std::cout
#include <sstream>
#include <string>
#include <vector>
using namespace std;
glTiledLoader::glTiledLoader()
{
}
glTiled &glTiledLoader::searchTiled(int c, int search_type){
int d=c+6;
c-=6;
if (c<0) c=0;
if (d>=100) d=99;
for (int a=c; a<=d;a++){
for (int b=0; b<vecTiled.at(0).size();b++){
if (vecTiled.at(a).at(b).type == search_type)
return (vecTiled.at(a).at(b));
}
}
}
void glTiledLoader::setInvisibleRoom(int c){
int d=c-3;
for (int a=c; a<=d;a++){
for (int b=0; b<vecTiled.at(0).size()/2;b++){
vecTiled.at(a).at(b).opacity=0;
vecTiled.at(a).at(b).together=true;
vecTiled.at(a).at(b).color=sf::Color(128, 128, 128,255);
}
for (int b=vecTiled.at(0).size()/2; b<vecTiled.at(0).size();b++){
vecTiled.at(a).at(b).opacity=0;
vecTiled.at(a).at(b).together=true;
vecTiled.at(a).at(b).color=sf::Color(128, 128, 128,0);
}
}
}
float glTiledLoader::getOpacity(int x, int y){
return vecTiled.at(x).at(y).opacity;
}
sf::Color glTiledLoader::getColor(int x, int y){
return vecTiled.at(x).at(y).color;
}
vector<glTiled*> glTiledLoader::searchTilesAssociatedForAction(int scope, int search_type)
{
int upperBound = scope + 10;
int lowerBound = scope - 10;
lowerBound = (lowerBound < 0) ? 0 : lowerBound;
upperBound = (upperBound > 99) ? 99 : upperBound;
vector<glTiled*> result;
for (int row = lowerBound; row <= upperBound; row++){
for (int column = 0; column < vecTiled.at(0).size(); column++) {
//cout << vecTiled.at(row).at(column).type << ", ";
if (vecTiled.at(row).at(column).type == search_type)
result.push_back(&vecTiled.at(row).at(column));
}
//cout << endl;
}
return result;
}
vector<glTiled*> glTiledLoader::searchTilesAssociatedForActionOrigin(int scope, int search_type)
{
int upperBound = scope + 10;
int lowerBound = scope - 10;
lowerBound = (lowerBound < 0) ? 0 : lowerBound;
upperBound = (upperBound > 99) ? 99 : upperBound;
vector<glTiled*> result;
for (int row = lowerBound; row <= upperBound; row++){
for (int column = 0; column < vecTiled.at(0).size(); column++) {
//cout << vecTiled.at(row).at(column).type << ", ";
if (vecTiled.at(row).at(column).originalType == search_type)
result.push_back(&vecTiled.at(row).at(column));
}
//cout << endl;
}
return result;
}
void glTiledLoader::loadMap(int number) {
ostringstream ss2;
ss2 << number;
string str = ss2.str();
string line;
int i = 0;
size_t pos = 0;
std::string token;
std::string a ("assets/maps/");
std::string b (".txt");
std::string path;
path = a+str+b;
ifstream myfile (path);
std::stringstream ss;
vecTiled.clear();
vec.clear();
// parsing file
getline(myfile, line);
pos = line.find(",");
std::string rows = line.substr(0, pos);
std::string cols = line.substr(pos+1);
this->amountOfRows = atoi(rows.c_str());
this->amountOfColumns = atoi(cols.c_str());
cout << "Map size: (" << amountOfRows << ", " << amountOfColumns << ")" << endl;
if (myfile.is_open())
{
while ( getline (myfile, line) )
{
std::string s = line;
std::string delimiter = ",";
vec.push_back ( vector<int>() );
vecTiled.push_back(vector<glTiled>() );
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
vec.at(i).push_back( atoi(token.c_str()) );
vecTiled.at(i).push_back(glTiled(atoi(token.c_str()), 0, 0));
s.erase(0, pos + delimiter.length());
}
++i;
}
myfile.close();
for (int a=0; a<vecTiled.size();a++){
for (int b=0; b<vecTiled.at(0).size();b++)
{
int type = vecTiled.at(a).at(b).type;
if (type >= OBJECTS_MIN && type <= OBJECTS_MAX)
{
// search for associated object
vecTiled.at(a).at(b).associated = &searchTiled(a, type+1);
} else if(type == LEVER_LEFT) {
vecTiled.at(a).at(b).actionAssociated = searchTilesAssociatedForAction(a, INVISIBLE_LADDER);
}else if(type == ELEBOX) {
vecTiled.at(a).at(b).actionAssociated = searchTilesAssociatedForAction(a, LASER);
}
if (vecTiled.at(a).at(b).type==INVISIBLE_POSX)
this->setInvisibleRoom(a);
}
}
}else {
cout << "Unable to open file";
}
}
bool glTiledLoader::isActive(int x,int y){
return vecTiled.at(x).at(y).isActive();
}
void glTiledLoader::Update(){
for (int a=0; a<vecTiled.size();a++){
for (int b=0; a<vecTiled.at(0).size();b++){
vecTiled.at(a).at(b).Update();
}
}
}
glTiled& glTiledLoader::getTile(int row , int column)
{
assert (row >= 0 || column >= 0 || row < 100 || column < 20);
return vecTiled.at(row).at(column);
}
void glTiledLoader::setActive(int x,int y){
vecTiled.at(x).at(y).setDefinitelyActive();
}
void glTiledLoader::runActionOnAssociated(int x,int y){
if(vecTiled.at(x).at(y).type == LEVER_LEFT)
// change lever sprite
vecTiled.at(x).at(y).type = LEVER_RIGHT;
else
{
vecTiled.at(x).at(y).runActionOnAssociated();
}
}
void glTiledLoader::runActionOnAssociatedLasers(int x,int y){
if(vecTiled.at(x).at(y).type == LASER)
vecTiled.at(x).at(y).type=0;
vecTiled.at(x).at(y).runActionOnAssociatedLaser();
}
void glTiledLoader::runActionOnAssociatedLasersShowAgain(int x,int y) {
if(vecTiled.at(x).at(y).originalType == LASER)
vecTiled.at(x).at(y).type=LASER;
vecTiled.at(x).at(y).runActionOnAssociatedLaserShow();
}
float glTiledLoader::getLowerOpacity(int x,int y){
float opacity = vecTiled.at(x).at(y).getLowerOpacity();
if (opacity < 0.3){
vecTiled.at(x).at(y).type=0;
}
return opacity;
}
bool glTiledLoader::isLadder(int x,int y){
if (vecTiled.at(x).at(y).type >= LADDER_MIN && vecTiled.at(x).at(y).type <= LADDER_MAX){
return true;
}
return false;
}
bool glTiledLoader::isKilledByLaser(int x, int y)
{
if (vecTiled.at(x).at(y).type==LASER){
return true;
}
return false;
}
bool glTiledLoader::isBlockableObject(int x, int y)
{
if (((vecTiled.at(x).at(y).type >= OBJECTS_MIN && vecTiled.at(x).at(y).type <= OBJECTS_MAX )||(vecTiled.at(x).at(y).type==LASER))&& vecTiled.at(x).at(y).type % 2 == 1){
return true;
}
return false;
}
bool glTiledLoader::isWall(int x,int y){
if (vecTiled.at(x).at(y).type >= GROUND_MIN && vecTiled.at(x).at(y).type <= GROUND_MAX){
return true;
}
return false;
}
bool glTiledLoader::isFree(int x,int y){
if (vecTiled.at(x).at(y).type == FREE){
return true;
}
return false;
}
int glTiledLoader::getValue(int x,int y){
return vecTiled.at(x).at(y).type;
}
int glTiledLoader::getMapWidth()
{
return glSettings::TILE_WIDTH*amountOfColumns;
}
int glTiledLoader::getMapHeight()
{
return glSettings::TILE_HEIGHT*amountOfRows;
}
///////////////
// (0,0)
//
//
//
// (TILE_HEIGHT*ilość, 0) -> HEROES
void glTiledLoader::getTileCoords(float posX, float posY, glHero::PLAYER playerId, int& tileRow, int& tileColumn)
{
tileRow = (int)posY/glSettings::TILE_HEIGHT;
tileColumn = (int)posX/glSettings::TILE_WIDTH;
if(playerId == glHero::PLAYER::SND)
{
tileColumn += 10;
}
}
sf::FloatRect glTiledLoader::getTileBoundingBox(int row, int col, glHero::PLAYER playerId)
{
if(playerId == glHero::PLAYER::FST)
return sf::FloatRect(col*glSettings::TILE_WIDTH, row*glSettings::TILE_HEIGHT, glSettings::TILE_HEIGHT, glSettings::TILE_WIDTH);
else
return sf::FloatRect(col*glSettings::TILE_WIDTH-640, row*glSettings::TILE_HEIGHT, glSettings::TILE_HEIGHT, glSettings::TILE_WIDTH);
}
bool glTiledLoader::intersectsWithWall(glHero& hero)
{
int firstTileRow, firstTileColumn;
int row, column;
bool debug = false;
sf::Sprite sprite = hero.getSpirte();
getTileCoords(sprite.getGlobalBounds().left+sprite.getTextureRect().width/2, sprite.getGlobalBounds().top + sprite.getTextureRect().height/2, hero.playerId, row, column);
if(debug)
{
cout << "Sprite position: (" << sprite.getGlobalBounds().left << ", " << sprite.getGlobalBounds().top << ")" << endl;
cout << "Checking tile area for collision: " << row << ", " << column << " Intersects: " << sprite.getGlobalBounds().intersects(getTileBoundingBox(row, column, hero.playerId))
<< " Is wall: " << isWall(row, column) << endl;
cout << "Tile position: (" << getTileBoundingBox(row, column, hero.playerId).left << ", " << getTileBoundingBox(row, column, hero.playerId).top << ")" << endl;
}
for(int i = -1; i <= 1; ++i)
{
for(int j = -1; j <= 1; ++j)
{
if(row+i < 0 || column+j < 0 || row+i >= amountOfRows || column+j >= amountOfColumns)
continue;
if(sprite.getGlobalBounds().intersects(getTileBoundingBox(row+i, column+j, hero.playerId)) && isWall(row+i, column+j))
{
return true;
}
}
}
return false;
}
bool glTiledLoader::blockedByObstacleOnLeftSide(glHero& hero)
{
int firstTileRow, firstTileColumn;
int row, column;
bool debug = false;
sf::Sprite sprite = hero.getSpirte();
sf::FloatRect spriteBB = sprite.getGlobalBounds();
spriteBB.height -= 5.f;
getTileCoords(sprite.getPosition().x+sprite.getTextureRect().width/2, sprite.getPosition().y + sprite.getTextureRect().height/2, hero.playerId, row, column);
if(debug)
{
cout << "Sprite position: (" << sprite.getGlobalBounds().left << ", " << sprite.getGlobalBounds().top << ")" << endl;
cout << "Checking tile area for collision: " << row << ", " << column << " Intersects: " << sprite.getGlobalBounds().intersects(getTileBoundingBox(row, column, hero.playerId))
<< " Is wall: " << isWall(row, column) << endl;
cout << "Tile position: (" << getTileBoundingBox(row, column, hero.playerId).left << ", " << getTileBoundingBox(row, column, hero.playerId).top << ")" << endl;
}
for(int i = -1; i <= 1; ++i)
{
for(int j = -1; j <= 0; ++j)
{
if(row+i < 0 || column+j < 0 || row+i >= amountOfRows || column+j >= amountOfColumns)
continue;
if(spriteBB.intersects(getTileBoundingBox(row+i, column+j, hero.playerId)) && (isWall(row+i, column+j) || isBlockableObject(row+i, column+j)))
{
return true;
}
}
}
return false;
}
bool glTiledLoader::blockedByObstacleOnRightSide(glHero& hero)
{
int firstTileRow, firstTileColumn;
int row, column;
bool debug = false;
sf::Sprite sprite = hero.getSpirte();
sf::FloatRect spriteBB = sprite.getGlobalBounds();
spriteBB.height -= 5.f;
getTileCoords(sprite.getPosition().x+sprite.getTextureRect().width/2, sprite.getPosition().y + sprite.getTextureRect().height/2, hero.playerId, row, column);
if(debug)
{
cout << "Sprite position: (" << sprite.getGlobalBounds().left << ", " << sprite.getGlobalBounds().top << ")" << endl;
cout << "Checking tile area for collision: " << row << ", " << column << " Intersects: " << sprite.getGlobalBounds().intersects(getTileBoundingBox(row, column, hero.playerId))
<< " Is wall: " << isWall(row, column) << endl;
cout << "Tile position: (" << getTileBoundingBox(row, column, hero.playerId).left << ", " << getTileBoundingBox(row, column, hero.playerId).top << ")" << endl;
}
for(int i = -1; i <= 1; ++i)
{
for(int j = 0; j <= 1; ++j)
{
if(row+i < 0 || column+j < 0 || row+i >= amountOfRows || column+j >= amountOfColumns)
continue;
if(spriteBB.intersects(getTileBoundingBox(row+i, column+j, hero.playerId)) && (isWall(row+i, column+j) || isBlockableObject(row+i, column+j)))
{
return true;
}
}
}
return false;
}
bool glTiledLoader::intersectsWithLadder(glHero& hero)
{
int firstTileRow, firstTileColumn;
int row, column;
bool debug = false;
sf::Sprite sprite = hero.getSpirte();
getTileCoords(sprite.getPosition().x+sprite.getTextureRect().width/2, sprite.getPosition().y + sprite.getTextureRect().height/2, hero.playerId, row, column);
if(debug)
{
cout << "Sprite position: (" << sprite.getPosition().x<< ", " << sprite.getPosition().y << ")" << endl;
cout << "Checking tile area for collision: " << row << ", " << column << " Intersects: " << sprite.getGlobalBounds().intersects(getTileBoundingBox(row, column, hero.playerId))
<< " Is ladder: " << isLadder(row, column) << endl;
cout << "Tile position: (" << getTileBoundingBox(row, column, hero.playerId).left << ", " << getTileBoundingBox(row, column, hero.playerId).top << ")" << endl;
}
if(row < 0 || column < 0 || row >= amountOfRows || column >= amountOfColumns)
return false;
if(sprite.getGlobalBounds().intersects(getTileBoundingBox(row, column, hero.playerId)) && isLadder(row, column))
return true;
return false;
}<file_sep>#include "glAction.h"
namespace actions {
void fadeOut::execute(glTiled& tile)
{
//
}
void fadeIn::execute(glTiled& tile)
{
//
}
}<file_sep>#pragma once
#include <string>
using namespace std;
class glSettings {
public:
static const string ASSETS_PATH;
static const int WINDOW_WIDTH = 1280;
static const int WINDOW_HEIGHT = 768;
static const int TILE_WIDTH = 64;
static const int TILE_HEIGHT = 64;
static const int TILES_IN_ROW = 24;
};
<file_sep>#include "glTiled.h"
#include "glSettings.h"
#include "glTiled.h"
#include "glAction.h"
#include "glUtils.h"
#include <iostream>
#include <fstream>
#include <iostream> // std::cout
#include <sstream>
#include <string>
#include <vector>
using namespace std;
glTiled::glTiled(int type, int row, int column) {
this->row = row;
this->column = column;
this->type = type;
this->active = false;
this->used=false;
this->pressed=false;
this->framesPressed=false;
this->framesActive=false;
this->opacity=1;
this->associated = NULL;
this->together=false;
this->color = sf::Color(255, 255, 255,255);
this->amountOfPresses = 0;
this->readyToExecAssociatedAction = false;
}
float glTiled::getLowerOpacity(){
opacity -= 0.001f;
if (opacity < 0.3){
opacity = 0.3;
this->type =0;
}
return opacity;
}
bool glTiled::isActive()
{
return active;
}
bool glTiled::isPressed()
{
return pressed;
}
bool glTiled::isUsed()
{
return used;
}
void glTiled::Init(sf::RenderWindow& window) {
}
void glTiled::Update() {
if (framesPressed>0){
framesPressed--;
}
if (framesPressed>0 && framesPressed<5){
framesPressed=0;
pressed=false;
}
if (framesActive>0){
framesActive--;
}
if (framesActive>0 && framesActive<5){
framesActive=0;
active=false;
}
}
void glTiled::setPressed(int framesPressed) {
pressed=true;
framesPressed=30+5;
}
void glTiled::runActionOnAssociated() {
if (this->associated != NULL && type>=OBJECTS_MIN && type%2==0)
(*associated).setDefinitelyActive();
for(vector<glTiled*>::iterator tile_it = actionAssociated.begin(); tile_it < actionAssociated.end(); ++tile_it)
{
(*tile_it)->showLadder();
}
}
void glTiled::runActionOnAssociatedLaser() {
if (this->associated != NULL && type>=OBJECTS_MIN && type%2==0)
(*associated).setDefinitelyActive();
for(vector<glTiled*>::iterator tile_it = actionAssociated.begin(); tile_it < actionAssociated.end(); ++tile_it)
{
(*tile_it)->hideLasers();
}
}
void glTiled::runActionOnAssociatedLaserShow() {
this->actionAssociated;
for(vector<glTiled*>::iterator tile_it = actionAssociated.begin(); tile_it < actionAssociated.end(); ++tile_it)
{
(*tile_it)->showLasers();
}
}
void glTiled::press()
{
amountOfPresses++;
if(amountOfPresses >= MAX_AMOUNT_OF_PRESSES)
readyToExecAssociatedAction = true;
}
void glTiled::resetPresses()
{
amountOfPresses = 0;
}
void glTiled::setActive(int framesPressed) {
if (type>=OBJECTS_MIN){
active=true;
framesPressed=30+5;
}
}
void glTiled::showLadder()
{
type = LADDER_INNER;
}
void glTiled::hideLasers()
{
type = 0;
}
void glTiled::showLasers()
{
cout<<"zmin"<<endl;
type = LASER;
}
void glTiled::setDefinitelyActive() {
if (type>=OBJECTS_MIN){
if (type%2!=0){
active=true;
framesPressed=0;
}
this->runActionOnAssociated();
}
}
void glTiled::setUsed() {
used=true;
}
void glTiled::executeAction(glAction& action)
{
// action.execute(this);
}
<file_sep>#include <cstdio>
#include <iostream>
#include "glScore.h"
#include "glUtils.h"
#include "glSettings.h"
using namespace std;
glScore::glScore(void)
{
}
glScore::~glScore(void)
{
}
void glScore::Load()
{
if (!mDigitsImage.loadFromFile(concat(glSettings::ASSETS_PATH, "numbers.png")))
printf("Błąd przy wczytywaniu pliku data/numbers.png");
if (!mScoreImage.loadFromFile(concat(glSettings::ASSETS_PATH, "scoreBgnd.png")))
printf("Błąd przy wczytywaniu pliku data/score.png");
if (!mYears.loadFromFile(concat(glSettings::ASSETS_PATH, "years.png")))
printf("Błąd przy wczytywaniu pliku data/years.png");
mYearsSprite.setTexture(mYears);
if (!mMonths.loadFromFile(concat(glSettings::ASSETS_PATH, "months.png")))
printf("Błąd przy wczytywaniu pliku data/monhts.png");
mMonthsSprite.setTexture(mMonths);
}
void glScore::Init(int cScore)
{
mCurrentScore = cScore;
mScore.setTexture(mScoreImage);
mScore.setOrigin(mScoreImage.getSize().x / 2, mScoreImage.getSize().y / 2);
for(int w = mDigitsImage.getSize().x / 10, h = mDigitsImage.getSize().y, i = 0; i < 10; i++)
{
mDigits[i].setTexture(mDigitsImage);
mDigits[i].setTextureRect(sf::IntRect(i * w, 0, w, h));
}
}
void glScore::Step()
{
//fAngle += ONE_FRAME_DURATION*5.0f;
//if (fAngle > 100.0f) fAngle = 0.0f;
//mScore.SetRotation( 10*sin(fAngle) );
}
void glScore::Draw(sf::RenderWindow& graphics)
{
// drawing the score background
mScore.setPosition(sf::Vector2f(mScoreImage.getSize().x / 2 + 5, 768 - mScoreImage.getSize().y / 2 - 5));
graphics.draw(mScore);
int years = mCurrentScore / 12;
int months = mCurrentScore % 12;
//drawing years and months
std::vector<int> digYears;
int digit;
if (years == 0)
digYears.push_back(0);
else
while (years > 0)
{
digit = years % 10;
digYears.insert(digYears.begin(), digit);
years /= 10;
}
std::vector<int> digMonths;
if (months == 0)
digMonths.push_back(0);
else
while (months > 0)
{
digit = months % 10;
digMonths.insert(digMonths.begin(), digit);
months /= 10;
}
float pos = mScore.getPosition().x - ((digYears.size() + digMonths.size() + 4) * 25) / 2 - 14;
// drawing years
for(unsigned int i = 0; i < digYears.size(); ++i)
{
mDigits[digYears[i]].setPosition(sf::Vector2f(float(pos + (i * (25))), mScore.getPosition().y - 30));
graphics.draw(mDigits[digYears[i]]);
}
pos += 50;
// drawing "y"
mYearsSprite.setPosition(sf::Vector2f(pos, mScore.getPosition().y - 30));
graphics.draw(mYearsSprite);
pos += 50;
// drawing months
for (unsigned int i = 0; i < digMonths.size(); ++i)
{
mDigits[digMonths[i]].setPosition(sf::Vector2f(float(pos + (i * (25))), mScore.getPosition().y - 30));
graphics.draw(mDigits[digMonths[i]]);
}
pos += 50;
// drawing "m"
mMonthsSprite.setPosition(sf::Vector2f(pos, mScore.getPosition().y - 30));
graphics.draw(mMonthsSprite);
}
void glScore::SetCurrentScore(int currentScore)
{
if (currentScore > mCurrentScore)
mCurrentScore = currentScore;
}
int glScore::GetScore()
{
return mCurrentScore;
}<file_sep>Gra stworzona na KrakJam'ie 2015
===================
To zaczynamy :)
<file_sep>#include "glSettings.h"
const string glSettings::ASSETS_PATH = "assets/"; <file_sep>#pragma once
#include "SFML\Graphics.hpp"
#include "SFML\Audio.hpp"
#include <vector>
#define GROUND_MIN 1
#define GROUND_MAX 20
#define LADDER_MIN 21
#define LADDER_INNER 21
#define LADDER_MAX 23
#define OBJECTS_MIN 24
#define OBJECTS_MAX 31
#define LEVER_LEFT 32
#define LEVER_RIGHT 33
#define INVISIBLE_LADDER 34
#define LASER 35
#define ELEBOX 36
#define INVISIBLE_POSX 50
#define INVISIBLE_POSY 51
#define FREE 99
class glAction;
using namespace std;
class glTiled
{
private:
public:
bool active;
bool used;
bool pressed;
bool readyToExecAssociatedAction;
int framesPressed;
int framesActive;
sf::Color color;
int amountOfPresses;
int row, column;
static const int MAX_AMOUNT_OF_PRESSES = 8;
glTiled(int type, int row, int column);
bool together;
glTiled *associated;
vector<glTiled*> actionAssociated;
float opacity;
int type;
int originalType;
void Load();
void Init(sf::RenderWindow& window);
bool isActive();
float getLowerOpacity();
bool isPressed();
bool isUsed();
void Update();
void setPressed();
void setUsed();
void setDefinitelyActive();
void setPressed(int framesPressed);
void setActive(int framesPressed);
void callAssociated();
void runActionOnAssociated();
void runActionOnAssociatedLaser();
void runActionOnAssociatedLaserShow();
void showLadder();
void showLasers();
void hideLasers();
void press();
void resetPresses();
protected:
void executeAction(glAction& action);
};<file_sep>/*
* Useful functions
*/
#pragma once
#include <string>
using namespace std;
const string concat(string fst, string snd);
const char* concat_cstr(string fst, string snd);<file_sep>#pragma once
#include "SFML\Audio.hpp"
class glHandleMusic
{
public:
sf::Music MusicLevel1, MusicMenu, MusicGameOver;
std::vector<std::pair<sf::SoundBuffer,std::string> > Sounds;
std::vector<sf::Sound> Players;
void StopAll();
void HandleMusic();
void PlaySound(std::string name);
};<file_sep>#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include "glHero.h"
#include "glSettings.h"
#include "glUtils.h"
using namespace std;
// PARAMS
// how many frames for particular animations
const int glHero::leftWalkingFrames = 4;
const int glHero::rightWalkingFrames = 5;
const int glHero::climbingFrames = 1;
const float glHero::frameDuration = 0.1f;
const float glHero::climbingSpeed = 180.0f;
const float glHero::walkingSpeed = 220.0f;
const float glHero::fallingSpeed = 250.0f;
// how much time passes between frames
const float DELTA = 1.0f / 60.0f;
void glHero::Load(int _side)
{
walkingFrames = (_side == 0 ? leftWalkingFrames : rightWalkingFrames);
side = _side;
ostringstream oss;
for (int a = 0; a < walkingFrames; a++) {
oss.str(string());
oss.clear();
oss << "hero" << side + 1 << "_left_" << a << ".png";
imageWalkingLeft[a].loadFromFile(concat(glSettings::ASSETS_PATH, oss.str()));
oss.str(string());
oss.clear();
oss << "hero" << side + 1 << "_right_" << a << ".png";
imageWalkingRight[a].loadFromFile(concat(glSettings::ASSETS_PATH, oss.str()));
}
for (int a = 0; a < climbingFrames; a++) {
oss.str(string());
oss.clear();
oss << "hero" << side + 1 << "_up_" << a << ".png";
imageClimbingUp[a].loadFromFile(concat(glSettings::ASSETS_PATH, oss.str()));
oss.str(string());
oss.clear();
oss << "hero" << side + 1 << "_down_" << a << ".png";
imageClimbingDown[a].loadFromFile(concat(glSettings::ASSETS_PATH, oss.str()));
}
}
void glHero::Init(float x, float y, sf::View View, glHero::PLAYER _playerId)
{
position.x = x;
position.y = y;
playerId = _playerId;
currentFrame = 0;
lastEvent = NONE;
playerView = View;
death = false;
opacity = 1.0f;
if (side == 0)
{
sprite.setTexture(imageWalkingRight[0]);
}
if (side == 1)
{
sprite.setTexture(imageWalkingLeft[0]);
}
}
void glHero::Update(event _event)
{
// zapisanie stanu, na potrzeby klasy nadrzednej
lastEvent = _event;
// ruch
if (_event & CLIMBUP)
{
position.y -= climbingSpeed * DELTA;
}
if (_event & CLIMBDOWN)
{
position.y += climbingSpeed * DELTA;
}
if (_event & RIGHT)
{
position.x += walkingSpeed * DELTA;
}
if (_event & LEFT)
{
position.x -= walkingSpeed * DELTA;
}
if (_event & FALL)
{
position.y += fallingSpeed * DELTA;
}
if (_event & NONE)
{
animationTimer = 0;
currentFrame;
}
if (_event & RIGHTBORDER){
position.x = playerView.getSize().x - getWidth();
}
if (_event & LEFTBORDER){
position.x = 0;
}
// animacje
if (_event & CLIMBUP)
{
animationTimer += DELTA;
if (animationTimer > frameDuration)
{
currentFrame++;
animationTimer = 0;
}
if (currentFrame >= climbingFrames)
currentFrame = 0;
sprite.setTexture(imageClimbingUp[currentFrame]);
}
if (_event & CLIMBDOWN)
{
animationTimer += DELTA;
if (animationTimer > frameDuration)
{
currentFrame++;
animationTimer = 0;
}
if (currentFrame >= climbingFrames)
currentFrame = 0;
sprite.setTexture(imageClimbingDown[currentFrame]);
}
if (_event & RIGHT)
{
if (_event & FALL)
{
sprite.setTexture(imageWalkingRight[0]);
}
else
{
animationTimer += DELTA;
if (animationTimer > frameDuration)
{
currentFrame++;
animationTimer = 0;
}
if (currentFrame >= walkingFrames)
currentFrame = 0;
sprite.setTexture(imageWalkingRight[currentFrame]);
}
}
if (_event & LEFT)
{
if (_event & FALL)
{
sprite.setTexture(imageWalkingLeft[0]);
}
else
{
animationTimer += DELTA;
if (animationTimer > frameDuration)
{
currentFrame++;
animationTimer = 0;
}
if (currentFrame >= walkingFrames)
currentFrame = 0;
sprite.setTexture(imageWalkingLeft[currentFrame]);
}
}
// dying
if (death == 1)
{
opacity -= 0.3f * DELTA;
if (opacity < 0)
opacity = 0;
}
}
void glHero::UpdateReverse(event _event)
{
if (_event & FALL)
{
position.y -= fallingSpeed * DELTA;
}
if (_event & RIGHT)
{
position.x -= walkingSpeed * DELTA;
}
if (_event & LEFT)
{
position.x += walkingSpeed * DELTA;
}
if (_event & CLIMBDOWN)
{
position.y -= climbingSpeed * DELTA;
}
}
void glHero::Draw(sf::RenderWindow& graphics)
{
sprite.setColor(sf::Color(255, 255 * opacity, 255 * opacity, opacity * 255));
sprite.setPosition(position + sf::Vector2f(0,4.0f));
graphics.draw(sprite);
sprite.setPosition(position);
}
int glHero::getWidth()
{
return imageWalkingLeft[0].getSize().x;
}
int glHero::getHeight()
{
return imageWalkingLeft[0].getSize().y;
}<file_sep>#include "glGame.h"
#include <stdio.h>
#include "glUtils.h"
#include "glSettings.h"
#include "glTiled.h"
#include <iostream>
#include <stdlib.h>
#include <sstream>
// params
const int glGame::bornAge = 36;
const int glGame::level1Age = 147;
const int glGame::level2Age = 231;
const int glGame::level3Age = 302;
const int glGame::level4Age = 733;
const int glGame::level5Age = 1076;
const float DELTA = 1.0f / 60.0f;
glHandleMusic musicObject;
void glGame::Load()
{
backgroundTexture.loadFromFile(concat(glSettings::ASSETS_PATH, "sky.png"));
backgroundSprite.setTexture(backgroundTexture);
gProgressBar.Load();
heroLeft.Load(0);
heroRight.Load(1);
gBoard.Load();
score.Load();
bulletTexture.loadFromFile(concat(glSettings::ASSETS_PATH, "bullet.png"));
warningTexture.loadFromFile(concat(glSettings::ASSETS_PATH, "warning.png"));
level = 1;
}
void glGame::Init(sf::RenderWindow& window)
{
gProgressBar.Init();
pressTimer=0;
//wczytanie mapy
printf("-----------------------------------------------------\n");
printf("Zaczynamy nowa gre.\n");
printf("-----------------------------------------------------\n");
gBoard.Init(1);
bulletsVecLeft.clear();
bulletsVecRight.clear();
player1View.setSize(sf::Vector2f(window.getSize().x/2.f, window.getSize().y/1.f));
player2View.setSize(sf::Vector2f(window.getSize().x/2.f, window.getSize().y)/1.f);
player1View.setCenter(player1View.getSize().x/2.f, gBoard.getTileManager().getMapHeight()-384);
player2View.setCenter(player2View.getSize().x/2.f, gBoard.getTileManager().getMapHeight()-384);
// player 2 (right side of the screen)
player2View.setViewport(sf::FloatRect(0.5f, 0, 0.5f, 1));
// player 1 (left side of the screen)
player1View.setViewport(sf::FloatRect(0, 0, 0.5f, 1));
heroLeft.Init(100, gBoard.getTileManager().getMapHeight() - 64 - heroLeft.getHeight(), player1View, glHero::PLAYER::FST);
heroRight.Init(500, gBoard.getTileManager().getMapHeight() - 64 - heroRight.getHeight(), player2View, glHero::PLAYER::SND);
playerLeftOnLadder = playerRightOnLadder = false;
gameState = GAME_STATE::MENU;
musicObject.HandleMusic();
isMenu = false;
isPlaying = false;
isGameOver = false;
isWin = false;
bulletsTimerLeft = 0.0f;
bulletsTimerRight = 0.0f;
bulletsBoundLeft = rand() % 15 + 20;
bulletsBoundRight = rand() % 15 + 20;
score.Init(0);
}
bool glGame::Win()
{
bool win = false;
if(heroLeft.position.y < 50 && heroRight.position.y < 50){
win = true;}
return win;
}
void glGame::GetReleasedLeft() {
cout<<"KONIEC"<<endl;
float x = heroLeft.position.x+heroLeft.getWidth()/2;
float y = heroLeft.position.y+heroLeft.getHeight()/2;
int a,b;
gBoard.getTileManager().getTileCoords(x,y,heroLeft.playerId, a, b);
gBoard.getTileManager().runActionOnAssociatedLasersShowAgain(a, b);
x = heroRight.position.x+heroRight.getWidth()/2;
y = heroRight.position.y+heroRight.getHeight()/2;
glTiledLoader tileManager = gBoard.getTileManager();
int row, column;
tileManager.getTileCoords(x, y, heroRight.playerId, row, column);
glTiled& tile = gBoard.getTileManager().getTile(row, column);
if (tile.type==LASER){
heroRight.death=true;
}
}
void glGame::GetReleasedRight(){
cout<<"KONIEC"<<endl;
float x = heroRight.position.x+heroRight.getWidth()/2;
float y = heroRight.position.y+heroRight.getHeight()/2;
int a,b;
gBoard.getTileManager().getTileCoords(x,y,heroRight.playerId, a, b);
gBoard.getTileManager().runActionOnAssociatedLasersShowAgain(a, b);
x = heroLeft.position.x+heroLeft.getWidth()/2;
y = heroLeft.position.y+heroLeft.getHeight()/2;
glTiledLoader tileManager = gBoard.getTileManager();
int row, column;
tileManager.getTileCoords(x, y, heroLeft.playerId, row, column);
glTiled& tile = gBoard.getTileManager().getTile(row, column);
if (tile.type==LASER){
heroLeft.death=true;
}
}
bool glGame::GameOver()
{
bool gameOver = false;
if(heroLeft.death == true && heroRight.death == true){
gameOver = true;}
return gameOver;
}
void glGame::GameStateWin()
{
gameState = GAME_STATE::WIN;
}
void glGame::GameStateGameOver()
{
gameState = GAME_STATE::GAMEOVER;
}
void glGame::Update()
{
glTiledLoader& tileManager = gBoard.getTileManager();
gBoard.Update();
pressTimer+=DELTA;
if (pressTimer>0.4){
pressTimer=0;
}
if (!heroLeft.death)
{
// player 1 movement
if (sf::Keyboard::isKeyPressed(sf::Keyboard::E))
{
if (pressTimer>=0.36){
float x = heroLeft.position.x+heroLeft.getWidth()/2;
float y = heroLeft.position.y+heroLeft.getHeight()/2;
glTiledLoader tileManager = gBoard.getTileManager();
int row, column;
tileManager.getTileCoords(x, y, heroLeft.playerId, row, column);
if (gBoard.getTileManager().getTile(row, column).type==ELEBOX){
gBoard.getTileManager().runActionOnAssociatedLasers(row, column);
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
heroLeft.Update(glHero::LEFT);
if(gBoard.getTileManager().blockedByObstacleOnLeftSide(heroLeft))
heroLeft.UpdateReverse(glHero::LEFT);
playerLeftOnLadder = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && tileManager.intersectsWithLadder(heroLeft) )
{
heroLeft.Update(glHero::CLIMBUP);
playerLeftOnLadder = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
heroLeft.Update(glHero::RIGHT);
if(gBoard.getTileManager().blockedByObstacleOnRightSide(heroLeft))
heroLeft.UpdateReverse(glHero::RIGHT);
playerLeftOnLadder = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && tileManager.intersectsWithLadder(heroLeft))
{
heroLeft.Update(glHero::CLIMBDOWN);
if(gBoard.getTileManager().intersectsWithWall(heroLeft))
heroLeft.UpdateReverse(glHero::CLIMBDOWN);
playerLeftOnLadder = true;
}
if (heroLeft.position.x < 0){
heroLeft.Update(glHero::LEFTBORDER);
}
if (heroLeft.position.x > player1View.getSize().x - heroLeft.getWidth()){
heroLeft.Update(glHero::RIGHTBORDER);
}
if(!playerLeftOnLadder)
{
// gravity
heroLeft.Update(glHero::FALL);
if(gBoard.getTileManager().intersectsWithWall(heroLeft))
heroLeft.UpdateReverse(glHero::FALL);
}
} else
heroLeft.Update(glHero::NONE);
// player 2 movement
if (!heroRight.death)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::RControl))
{
if (pressTimer>=0.36){
float x = heroRight.position.x+heroRight.getWidth()/2;
float y = heroRight.position.y+heroRight.getHeight()/2;
glTiledLoader tileManager = gBoard.getTileManager();
int row, column;
tileManager.getTileCoords(x, y, heroRight.playerId, row, column);
if (gBoard.getTileManager().getTile(row, column).type==ELEBOX){
gBoard.getTileManager().runActionOnAssociatedLasers(row, column);
}
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
heroRight.Update(glHero::LEFT);
if(gBoard.getTileManager().blockedByObstacleOnLeftSide(heroRight))
heroRight.UpdateReverse(glHero::LEFT);
playerRightOnLadder = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && tileManager.intersectsWithLadder(heroRight))
{
heroRight.Update(glHero::CLIMBUP);
playerRightOnLadder = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
heroRight.Update(glHero::RIGHT);
if(gBoard.getTileManager().blockedByObstacleOnRightSide(heroRight))
heroRight.UpdateReverse(glHero::RIGHT);
playerRightOnLadder = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && tileManager.intersectsWithLadder(heroRight))
{
heroRight.Update(glHero::CLIMBDOWN);
if(gBoard.getTileManager().intersectsWithWall(heroRight))
heroRight.UpdateReverse(glHero::CLIMBDOWN);
playerRightOnLadder = true;
}
if (heroRight.position.x < 0){
heroRight.Update(glHero::LEFTBORDER);
}
if (heroRight.position.x > player1View.getSize().x - heroRight.getWidth()){
heroRight.Update(glHero::RIGHTBORDER);
}
if(!playerRightOnLadder)
{
// gravity
heroRight.Update(glHero::FALL);
if(gBoard.getTileManager().intersectsWithWall(heroRight))
heroRight.UpdateReverse(glHero::FALL);
}
} else
heroRight.Update(glHero::NONE);
// updating bullets
for (int i = 0; i < bulletsVecLeft.size(); ++i) {
bulletsVecLeft.at(i).Update();
if (bulletsVecLeft.at(i).mOpacity <= 0)
{
bulletsVecLeft.erase(bulletsVecLeft.begin() + i); --i;
}
}
for (int i = 0; i < bulletsVecRight.size(); ++i) {
bulletsVecRight.at(i).Update();
if (bulletsVecRight.at(i).mOpacity <= 0)
{
bulletsVecRight.erase(bulletsVecRight.begin() + i); --i;
}
}
bulletsTimerLeft += DELTA;
if (bulletsTimerLeft > bulletsBoundLeft)
{
bulletsVecLeft.push_back(glBullet());
bulletsVecLeft.at(bulletsVecLeft.size() - 1).Init(player1View.getCenter().y + 384, &bulletTexture, &warningTexture);
bulletsTimerLeft = 0.0f;
bulletsBoundLeft = rand() % 10 + 5;
}
bulletsTimerRight += DELTA;
if (bulletsTimerRight > bulletsBoundRight)
{
bulletsVecRight.push_back(glBullet());
bulletsVecRight.at(bulletsVecRight.size() - 1).Init(player2View.getCenter().y + 384, &bulletTexture, &warningTexture);
bulletsTimerRight = 0.0f;
bulletsBoundRight = rand() % 10 + 5;
}
CheckColisions();
// progress bar
gProgressBar.Update(heroLeft.position.y,heroRight.position.y);
// updating the camera
float y1 = heroLeft.position.y + heroLeft.getHeight() / 2;
float y2 = heroRight.position.y + heroRight.getHeight() / 2;
if (y1 > gBoard.getTileManager().getMapHeight() - 384)
y1 = gBoard.getTileManager().getMapHeight() - 384;
if (y2 > gBoard.getTileManager().getMapHeight() - 384)
y2 = gBoard.getTileManager().getMapHeight() - 384;
if (y1 < 384)
y1 = 384;
if (y2 < 384)
y2 = 384;
player1View.setCenter(player1View.getCenter().x, y1);
player2View.setCenter(player2View.getCenter().x, y2);
// Death in lava
if(heroRight.position.y + heroRight.getHeight() - 170 > gProgressBar.lava){
heroRight.death = true;}
if(heroLeft.position.y + heroLeft.getHeight() - 170 > gProgressBar.lava){
heroLeft.death = true;}
// updating score
float progress = (float(gBoard.getTileManager().getMapHeight() - min(player1View.getCenter().y, player2View.getCenter().y) - 384) / float(gBoard.getTileManager().getMapHeight() - 768.0f));
switch (level)
{
case 1:
score.SetCurrentScore(bornAge + progress * (level1Age - bornAge));
break;
case 2:
score.SetCurrentScore(level1Age + progress * (level2Age - level1Age));
break;
case 3:
score.SetCurrentScore(level2Age + progress * (level3Age - level2Age));
break;
case 4:
score.SetCurrentScore(level3Age + progress * (level4Age - level3Age));
break;
case 5:
score.SetCurrentScore(level4Age + progress * (level5Age - level4Age));
break;
}
}
void glGame::Draw(sf::RenderWindow& graphics)
{
graphics.setView(graphics.getDefaultView());
double pos = 0;
switch(gameState)
{
case GAME_STATE::MENU:
if(!isMenu){
musicObject.StopAll();
musicObject.MusicMenu.play();
isMenu = true;
}
chosenOption = mainMenu.Show(graphics, graphics.getSize().x, graphics.getSize().y);
switch(chosenOption)
{
case glMainMenu::Exit:
graphics.close();
break;
case glMainMenu::Play:
gameState = GAME_STATE::GAMEPLAY;
break;
}
case GAME_STATE::GAMEPLAY:
if(!isPlaying){
musicObject.StopAll();
musicObject.MusicLevel1.play();
isPlaying = true;
}
graphics.setView(player1View);
// for parallax-scrolling
pos = gBoard.getTileManager().getMapHeight() - backgroundTexture.getSize().y * 6 - 0.8 * (gBoard.getTileManager().getMapHeight() - player1View.getCenter().y - 384.0f);
for (int i = 0; i < 6; ++i)
{
backgroundSprite.setPosition(0, pos + i * backgroundTexture.getSize().y);
graphics.draw(backgroundSprite);
}
gBoard.Draw(graphics, player1View.getCenter(), player1View.getSize(), true,heroLeft.position,heroRight.position);
heroLeft.Draw(graphics);
gProgressBar.DrawLava(graphics, true);
for (int i = 0; i < bulletsVecLeft.size(); ++i) {
bulletsVecLeft.at(i).Draw(graphics);
}
graphics.setView(player2View);
// for parallax-scrolling
pos = gBoard.getTileManager().getMapHeight() - backgroundTexture.getSize().y * 6 - 0.8 * (gBoard.getTileManager().getMapHeight() - player2View.getCenter().y - 384.0f);
for (int i = 0; i < 6; ++i)
{
backgroundSprite.setPosition(0, pos + i * backgroundTexture.getSize().y);
graphics.draw(backgroundSprite);
}
gBoard.Draw(graphics, player2View.getCenter(), player2View.getSize(), false,heroLeft.position,heroRight.position);
heroRight.Draw(graphics);
gProgressBar.DrawLava(graphics, false);
for (int i = 0; i < bulletsVecRight.size(); ++i) {
bulletsVecRight.at(i).Draw(graphics);
}
graphics.setView(graphics.getDefaultView());
gProgressBar.Draw(graphics);
score.Draw(graphics);
graphics.setView(player1View);
for (int i = 0; i < bulletsVecLeft.size(); ++i) {
bulletsVecLeft.at(i).DrawWarning(graphics, player1View.getCenter().y + 384);
}
graphics.setView(player2View);
for (int i = 0; i < bulletsVecRight.size(); ++i) {
bulletsVecRight.at(i).DrawWarning(graphics, player2View.getCenter().y + 384);
}
break;
case GAME_STATE::WIN:
if(!isWin){
musicObject.StopAll();
isWin = true;
}
break;
case GAME_STATE::GAMEOVER:
if(!isGameOver){
musicObject.StopAll();
musicObject.MusicGameOver.play();
isGameOver = true;
}
DrawGameOver(graphics);
break;
}
}
void glGame::DrawGameOver(sf::RenderWindow& graphics)
{
gameOverBackground.loadFromFile(concat(glSettings::ASSETS_PATH, "gameOver.png"));
gameOverBackgroundSprite.setTexture(gameOverBackground);
gameOverBackgroundSprite.setOrigin(gameOverBackground.getSize().x/2., gameOverBackground.getSize().y/2.);
gameOverBackgroundSprite.setPosition(graphics.getSize().x/2., graphics.getSize().y/2.);
sf::View view(sf::FloatRect(0, 0, graphics.getSize().x, graphics.getSize().y));
graphics.setView(view);
graphics.clear(sf::Color(0,0,0));
graphics.draw(gameOverBackgroundSprite);
}
void glGame::HandleEvent(sf::Event event)
{
if(event.type == event.KeyReleased)
{
if(event.key.code == sf::Keyboard::E)
{
float x = heroLeft.position.x+heroLeft.getWidth()/2;
float y = heroLeft.position.y+heroLeft.getHeight()/2;
glTiledLoader tileManager = gBoard.getTileManager();
int row, column;
tileManager.getTileCoords(x, y, heroLeft.playerId, row, column);
glTiled& tile = gBoard.getTileManager().getTile(row, column);
if(tile.type >= OBJECTS_MIN && tile.type!=LASER && tile.type!=ELEBOX)
{
tile.press();
if(tile.readyToExecAssociatedAction)
{
gBoard.getTileManager().runActionOnAssociated(row, column);
} else
{
stringstream ss;
ss << (rand()%4+1);
string str = ss.str();
musicObject.PlaySound("press" + str);
}
}
}
if (event.key.code == sf::Keyboard::RControl)
{
float x = heroRight.position.x+heroRight.getWidth()/2;
float y = heroRight.position.y+heroRight.getHeight()/2;
glTiledLoader tileManager = gBoard.getTileManager();
int row, column;
tileManager.getTileCoords(x, y, heroRight.playerId, row, column);
glTiled& tile = gBoard.getTileManager().getTile(row, column);
if(tile.type >= OBJECTS_MIN)
{
gBoard.getTileManager().runActionOnAssociatedLasers(row, column);
tile.press();
if(tile.readyToExecAssociatedAction)
{
gBoard.getTileManager().runActionOnAssociated(row, column);
} else
{
stringstream ss;
ss << (rand()%4+1);
string str = ss.str();
musicObject.PlaySound("press" + str);
}
}
}
if (event.key.code == sf::Keyboard::Num1)
{
ChangeLevel(1);
}
if (event.key.code == sf::Keyboard::Num2)
{
ChangeLevel(2);
}
}
}
void glGame::CheckColisions()
{
for (int i = 0; i < bulletsVecLeft.size(); ++i)
{
sf::Vector2f bulletPosition = bulletsVecLeft.at(i).bulletSprite.getPosition();
sf::Vector2u bulletSize = bulletTexture.getSize();
if (!bulletsVecLeft.at(i).mDying)
{
if (bulletPosition.x + bulletSize.x > heroLeft.position.x && bulletPosition.x < heroLeft.position.x + heroLeft.getWidth())
if (bulletPosition.y + bulletSize.y > heroLeft.position.y && bulletPosition.y < heroLeft.position.y + heroLeft.getHeight())
{
heroLeft.death = true;
bulletsVecLeft.at(i).mDying = true;
}
}
}
for (int i = 0; i < bulletsVecRight.size(); ++i)
{
sf::Vector2f bulletPosition = bulletsVecRight.at(i).bulletSprite.getPosition();
sf::Vector2u bulletSize = bulletTexture.getSize();
if (!bulletsVecRight.at(i).mDying)
{
if (bulletPosition.x + bulletSize.x > heroRight.position.x && bulletPosition.x < heroRight.position.x + heroRight.getWidth())
if (bulletPosition.y + bulletSize.y > heroRight.position.y && bulletPosition.y < heroRight.position.y + heroRight.getHeight())
{
heroRight.death = true;
bulletsVecRight.at(i).mDying = true;
}
}
}
}
void glGame::ChangeLevel(int level)
{
//wczytanie mapy
printf("-----------------------------------------------------\n");
printf("Nowy level: %d\n", level);
printf("-----------------------------------------------------\n");
gBoard.Init(level);
gProgressBar.Init();
bulletsVecLeft.clear();
bulletsVecRight.clear();
heroLeft.Init(100, gBoard.getTileManager().getMapHeight() - 64 - heroLeft.getHeight(), player1View, glHero::PLAYER::FST);
heroRight.Init(500, gBoard.getTileManager().getMapHeight() - 64 - heroRight.getHeight(), player2View, glHero::PLAYER::SND);
playerLeftOnLadder = playerRightOnLadder = false;
bulletsTimerLeft = 0.0f;
bulletsTimerRight = 0.0f;
bulletsBoundLeft = rand() % 10 + 5;
bulletsBoundRight = rand() % 10 + 5;
}
<file_sep>#pragma once
#include "SFML\Graphics.hpp"
#include "glBoard.h"
#include "glTiledLoader.h"
#define SPRITES 100
class glBoard
{
private:
sf::Sprite backgroundSprite[SPRITES];
sf::Texture backgroundTexture[SPRITES];
sf::Texture progressBarTexture;
glTiledLoader mTileManager;
float mAngle;
public:
void Load();
void Update();
void Init(int level);
void ChangeLevel(int level);
/**
* Draw game on the main window object
*/
void Draw(sf::RenderWindow& graphics, sf::Vector2f pos,sf::Vector2f size, bool left,sf::Vector2f herol,sf::Vector2f heror);
void DrawPressStackProgressBar(sf::RenderWindow& graphics, float progress, float posx, float posy);
glTiledLoader& getTileManager();
};<file_sep>#pragma once
#include "SFML\Graphics.hpp"
class glScore
{
int mCurrentScore;
sf::Texture mDigitsImage;
sf::Texture mScoreImage;
sf::Texture mYears;
sf::Texture mMonths;
sf::Sprite mDigits[10];
sf::Sprite mScore;
sf::Sprite mYearsSprite;
sf::Sprite mMonthsSprite;
float leftBorder;
float topPos;
float fAngle; // kat
public:
glScore(void);
~glScore(void);
void Load();
void Init(int cScore);
void Step();
void Draw(sf::RenderWindow& graphics);
void SetCurrentScore(int currentScore);
int GetScore();
};
<file_sep>#include "glHandleMusic.h"
#include <iostream>
using namespace std;
void glHandleMusic::HandleMusic()
{
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"press1"));
if (!Sounds.back().first.loadFromFile("assets/music/press1.ogg"))
cout << "Error while loading sounds" << endl;
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"press2"));
if (!Sounds.back().first.loadFromFile("assets/music/press2.ogg"))
cout << "Error while loading sounds" << endl;
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"press3"));
if (!Sounds.back().first.loadFromFile("assets/music/press3.ogg"))
cout << "Error while loading sounds" << endl;
Sounds.push_back(std::pair<sf::SoundBuffer, std::string>(sf::SoundBuffer(), "press4"));
if (!Sounds.back().first.loadFromFile("assets/music/press4.ogg"))
cout << "Error while loading sounds" << endl;
Sounds.push_back(std::pair<sf::SoundBuffer, std::string>(sf::SoundBuffer(), "bullet"));
if (!Sounds.back().first.loadFromFile("assets/music/bullet.ogg"))
cout << "Error while loading sounds" << endl;
/*Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"FallEgg_1"));
if (!Sounds.back().first.loadFromFile("data/music/FallEgg_1.ogg")) return false;
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"CatchEgg_0"));
if (!Sounds.back().first.loadFromFile("data/music/CatchEgg_0.ogg")) return false;
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"CatchEgg_1"));
if (!Sounds.back().first.loadFromFile("data/music/CatchEgg_1.ogg")) return false;
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"Fox"));
if (!Sounds.back().first.loadFromFile("data/music/fox.ogg")) return false;
Sounds.push_back(std::pair<sf::SoundBuffer,std::string>(sf::SoundBuffer(),"Door"));
if (!Sounds.back().first.loadFromFile("data/music/Door.ogg")) return false;*/
MusicLevel1.openFromFile("assets/music/level1.ogg");
MusicMenu.openFromFile("assets/music/menu.ogg");
MusicGameOver.openFromFile("assets/music/gameOver.ogg");
MusicLevel1.setLoop(true);
MusicMenu.setLoop(true);
Players.resize(Sounds.size());
}
void glHandleMusic::PlaySound(std::string name)
{
int i;
std::vector<std::pair<sf::SoundBuffer,std::string> >::iterator it;
for (i = 0; i < Sounds.size(); ++i)
if (Sounds[i].second == name)
break;
Players[i].setBuffer(Sounds[i].first);
Players[i].play();
}
void glHandleMusic::StopAll()
{
MusicLevel1.stop();
MusicMenu.stop();
MusicGameOver.stop();
}<file_sep>#pragma once
#include "SFML\Graphics.hpp"
class glTiled
{
private:
public:
int posX;
int posY;
bool isActive;
int type;
void Load();
void Init(sf::RenderWindow& window);
};<file_sep>#include "glUtils.h"
using namespace std;
const string concat(string fst, string snd)
{
return (fst + snd);
}
const char* concat_cstr(string fst, string snd)
{
return (fst + snd).c_str();
}<file_sep>#pragma once
#include "SFML\Graphics.hpp"
#include "glMainMenu.h"
#include "glHero.h"
#include "glTiledLoader.h"
#include "glBoard.h"
#include "glHandleMusic.h"
#include "glProgressBar.h"
#include "glBullet.h"
#include "glScore.h"
#define GRAVITY 10.f
class glGame
{
private:
sf::Sprite backgroundSprite;
sf::Sprite gameOverBackgroundSprite;
sf::Texture backgroundTexture;
sf::Texture gameOverBackground;
sf::Texture bulletTexture;
sf::Texture warningTexture;
glBoard gBoard;
glProgressBar gProgressBar;
sf::View player1View;
sf::View player2View;
glMainMenu mainMenu;
glMainMenu::MenuResult chosenOption;
glScore score;
bool playerLeftOnLadder;
bool playerRightOnLadder;
glHero heroLeft;
glHero heroRight;
std::vector<glBullet> bulletsVecLeft;
std::vector<glBullet> bulletsVecRight;
float bulletsTimerLeft;
float bulletsTimerRight;
float pressTimer;
float bulletsBoundLeft;
float bulletsBoundRight;
enum GAME_STATE {MENU, GAMEPLAY, GAMEOVER, WIN} gameState;
bool isMenu, isPlaying, isGameOver, isWin;
void DrawGameOver(sf::RenderWindow& graphics);
int level;
const static int bornAge;
const static int level1Age;
const static int level2Age;
const static int level3Age;
const static int level4Age;
const static int level5Age;
public:
void ShowScores();
void ShowDemo();
void Load();
void Init(sf::RenderWindow& window);
void Update();
void CheckCollisionBorder();
bool Win();
void ChangeLevel(int level);
bool GameOver();
void GetReleasedLeft();
void GetReleasedRight();
void GameStateWin();
void GameStateGameOver();
void CheckColisions();
/**
* Draw game on the main window object
*/
void Draw(sf::RenderWindow& graphics);
/**
* Handle concrete event
*/
void HandleEvent(sf::Event event);
};<file_sep>#pragma once
#include <SFML/Graphics.hpp>
class glHero
{
private:
// animations
sf::Texture imageWalkingLeft[7];
sf::Texture imageWalkingRight[7];
sf::Texture imageClimbingDown[7];
sf::Texture imageClimbingUp[7];
sf::View playerView;
sf::Sprite sprite;
int currentFrame;
float animationTimer;
// properties
int walkingFrames;
static const int leftWalkingFrames;
static const int rightWalkingFrames;
static const int climbingFrames;
static const float frameDuration;
static const float climbingSpeed;
static const float walkingSpeed;
static const float fallingSpeed;
public:
enum event {
CLIMBUP = 1,
CLIMBDOWN = 2,
RIGHT = 4,
LEFT = 8,
FALL = 16,
NONE = 32,
RIGHTBORDER = 64,
LEFTBORDER = 128
};
enum PLAYER {
FST,
SND
};
bool death;
event lastEvent;
PLAYER playerId;
int side;
sf::Vector2f position;
float opacity;
int getWidth();
int getHeight();
sf::Sprite& getSpirte() {return sprite;}
void Load(int _side);
void Init(float x, float y, sf::View View, glHero::PLAYER _playerId);
void Update(event _event);
void UpdateReverse(event _event);
void Draw(sf::RenderWindow& graphics);
};
| 630b304fbcabb57d199ebd6f6e3f2b159f88229c | [
"Markdown",
"C",
"C++"
] | 30 | C++ | sevikon/krakjam2015 | 7a4d04c42c4c6feeedea4781cd987fe268a5ea49 | 9a744fd64a715b5f31da6e60f5a5aeb4891889e6 |
refs/heads/master | <repo_name>mallikarjunveepuru/WebChat<file_sep>/src/main/resources/reg.properties
reg.login=login
reg.name=name
reg.password=<PASSWORD>
reg.address=address
reg.submit=submit<file_sep>/src/main/java/com/github/mykhalechko/webchat/dto/ChatUserDto.java
package com.github.mykhalechko.webchat.dto;
import org.springframework.hateoas.ResourceSupport;
public class ChatUserDto extends ResourceSupport {
// private String name;
private String login;
private String password;
private String isAdmin;
public String getIsAdmin() {
return isAdmin;
}
// private String isAdmin;
//
// public String getIsAdmin() {
// return isAdmin;
// }
//
// public String getName() {
// return name;
// }
public String getLogin() {
return login;
}
public String getPassword() {
return <PASSWORD>;
}
@Override
public String toString() {
return getLogin();
}
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/service/RedisConnect.java
package com.github.mykhalechko.webchat.service;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import javax.annotation.Resource;
@Component
public class RedisConnect {
@Resource
private Environment env;
private Jedis jedis;
public Jedis getJedis() {
if (jedis == null) {
jedis = new Jedis(env.getRequiredProperty("redis.url"));
}
return jedis;
}
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/util/WebSocketConfig.java
package com.github.mykhalechko.webchat.util;
import com.github.mykhalechko.webchat.controller.MySocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import javax.annotation.Resource;
@Configuration
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Resource
private Environment env;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(handler(), env.getRequiredProperty("socket.url"))
.withSockJS();
}
@Bean
public WebSocketHandler handler() {
return new MySocketHandler();
}
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/service/LoginServiceImpl.java
package com.github.mykhalechko.webchat.service;
import com.github.mykhalechko.webchat.dto.ChatUserDto;
import com.github.mykhalechko.webchat.repository.ChatUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private ChatUserRepository chatUserRepository;
@Override
public boolean verifyLogin(ChatUserDto chatUserDto) {
System.out.println("Bef");
if (chatUserRepository.isUserExist(chatUserDto)) {
System.out.println("Af");
return true;
}
return false;
}
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/service/LoginService.java
package com.github.mykhalechko.webchat.service;
import com.github.mykhalechko.webchat.dto.ChatUserDto;
public interface LoginService {
public boolean verifyLogin(ChatUserDto chatUserDto);
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/entity/ChatUser.java
package com.github.mykhalechko.webchat.entity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name = "chatusers")
public class ChatUser {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "userId", length = 6, nullable = false)
private Long userId;
@Column(name = "name", length = 30, nullable = false)
private String name;
@Column(name = "login", length = 30, nullable = false, unique = true)
private String login;
@Column(name = "password", length = 30, nullable = false)
private String password;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "role_id")
private Role role;
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Long getUserIdId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
<file_sep>/src/test/java/com/github/mykhalechko/webchat/service/LoginServiceImpl.java
package com.github.mykhalechko.webchat.service;
import com.github.mykhalechko.webchat.dto.ChatUserDto;
import com.github.mykhalechko.webchat.repository.ChatUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements LoginService {
static {
System.out.println("TestLoginServiceImpl");
}
@Autowired
private ChatUserRepository chatUserRepository;
@Override
public boolean verifyLogin(ChatUserDto chatUserDto) {
return true;
}
}<file_sep>/src/main/java/com/github/mykhalechko/webchat/controller/ChatController.java
package com.github.mykhalechko.webchat.controller;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@Controller
public class ChatController {
@Resource
private Environment env;
@RequestMapping(value = "/chat", method = RequestMethod.GET)
public ModelAndView chatAccess(HttpSession session) {
ModelAndView modelAndView = new ModelAndView();
System.out.println("login " + session.getAttribute("login"));
if (session.getAttribute("login") != null) {
System.out.println("login121212 " + session.getAttribute("login"));
modelAndView.addObject("user", session.getAttribute("login"));
modelAndView.addObject("socketUrl", env.getRequiredProperty("socket.url"));
modelAndView.setViewName("chat");
} else {
modelAndView.setViewName("error");
}
return modelAndView;
}
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/service/RegistrationServiceImpl.java
package com.github.mykhalechko.webchat.service;
import com.github.mykhalechko.webchat.entity.ChatUser;
import com.github.mykhalechko.webchat.repository.ChatUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
@Service
public class RegistrationServiceImpl implements RegistrationService {
@Autowired
private ChatUserRepository chatUserRepository;
@Override
public ModelAndView getRegister() {
ChatUser user = new ChatUser();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", user);
modelAndView.setViewName("registration");
return modelAndView;
}
@Override
public boolean create(ChatUser user) {
try {
chatUserRepository.saveAndFlush(user);
return true;
} catch (Exception e) {
return false;
}
}
}
<file_sep>/src/main/java/com/github/mykhalechko/webchat/entity/BlackList.java
package com.github.mykhalechko.webchat.entity;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
@Entity
@Table(name = "blacklist")
public class BlackList {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id", length = 6, nullable = false)
private Long id;
@OneToOne
@JoinColumn(name = "banned_user_id", nullable = false)
private ChatUser bannedUser;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public ChatUser getBannedUser() {
return bannedUser;
}
public void setBannedUser(ChatUser bannedUser) {
this.bannedUser = bannedUser;
}
}
<file_sep>/src/test/java/com/github/mykhalechko/webchat/controller/LoginControllerTest.java
package com.github.mykhalechko.webchat.controller;
import com.github.mykhalechko.webchat.util.ApplicationConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MockServletContext.class, AnnotationConfigWebContextLoader.class, ApplicationConfig.class})
@WebAppConfiguration
public class LoginControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(context).dispatchOptions(true).build();
}
@Test
public void getLogin() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/login"))
.andExpect(status().isOk())
.andExpect(model()
.attribute("urlpath", "/getLoginLink"));
}
@Test
public void verifyLogin() throws Exception {
String jsonStr = "{ \"login\": \"1\", \"password\": \"1\" }";
mockMvc.perform(MockMvcRequestBuilders.post("/verifyLogin")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(jsonStr))
.andExpect(jsonPath("$.links[0].href", is("http://localhost/chat")));
}
}
<file_sep>/README.md
# WebChat
#####Training project
- Maven
- Spring Framework
- MVC
- Data JPA
- WebSocket
- HATEOAS
- PostgreSQL
- Redis
- JavaScript
- SockJS
- AngularJS
- jQuery
##### Deploy to Tomcat without IDE
add to **apache-tomcat\conf\tomcat-users.xml**
```xml
<tomcat-users>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<user username="admin" password="<PASSWORD>" roles="manager-gui,manager-script" />
</tomcat-users>
```
and **apache-maven\conf\settings.xml**
```xml
<servers>
<server>
<id>TomcatServer</id>
<username>admin</username>
<password><PASSWORD></<PASSWORD>>
</server>
</servers>
```
use **mvn tomcat7:deploy** OR **mvn tomcat7:redeploy**
Tomcat manager should be running or properly setup, before you can use it with maven.
**Good Luck!** | 69ef19abf2a90993fc7d6595eb11fa2277d5934b | [
"Markdown",
"Java",
"INI"
] | 13 | INI | mallikarjunveepuru/WebChat | 0b8105d5e7ff8035e5db3ccb26ee6e299d8e288a | 0dc8305c61766d0c8ce3b36de4ddfaa654949d60 |
refs/heads/main | <file_sep>$('.service_item_part').slick({
dots: false,
infinite: true,
speed: 300,
slidesToShow: 3,
slidesToScroll: 1,
prevArrow: '<i class="fas fa-long-arrow-alt-left prevarrow"></i>',
nextArrow: '<i class="fas fa-long-arrow-alt-right nextarrow"></i>',
});
// ========================
var containerEl = document.querySelector('.portfolio-item-part');
var mixer = mixitup(containerEl);
// testimonial slider ===============
$('.testimonial-item-part').slick({
dots: false,
infinite: true,
speed: 300,
slidesToShow: 2,
slidesToScroll: 1,
prevArrow: '<i class="fas fa-long-arrow-alt-left prevarrow"></i>',
nextArrow: '<i class="fas fa-long-arrow-alt-right nextarrow"></i>',
}); | f47f93cc35ec7d2d13fa9ca5ebad25410931ce93 | [
"JavaScript"
] | 1 | JavaScript | Rafibd500/portfolio | 7eda7f42ad672407044dc16c0c8ee82bf20ad8d8 | 2b2f039819d9653366221c3d05c0c1086d272bc6 |
refs/heads/master | <repo_name>pwahlbom/CrazyMath<file_sep>/CrazyMath/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CrazyMath
{
public class MathClass
{
public int doSomething(int number1, int number2)
{
//divide
return number1 / number2;
}
public int doSomething(int number1, int number2, int number3)
{
//add
return number1 + number2 + number3;
}
public int doSomething(int number1, int number2, int number3, int number4)
{
//multiply
return number1 * number2 * number3 * number4;
}
public int doSomething(params int[] numbers)
{
var intTotal = 0;
foreach (var number in numbers)
{
intTotal = intTotal + number;
}
return intTotal;
}
}
class Program
{
static void Main(string[] args)
{
var clsNum1 = new MathClass();
var MySum1 = clsNum1.doSomething(6,2);
var clsNum2 = new MathClass();
var MySum2 = clsNum2.doSomething(3,3,3);
var clsNum3 = new MathClass();
var MySum3 = clsNum3.doSomething(2,2,2,2);
Console.WriteLine(MySum1);
Console.WriteLine(MySum2);
Console.WriteLine(MySum3);
Console.ReadLine();
}
}
}
| 18b7bc4da7492a866c098507306607ae2e62dd84 | [
"C#"
] | 1 | C# | pwahlbom/CrazyMath | b1f8336dd0aad68c4b13f7fd763bba3a17def4dc | 8c3172dd405742c5925c4c37569cabbaadafc7ee |
refs/heads/master | <file_sep>package test;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
public class Swipedemo extends TestScritpt{
public static void main(String[] args) throws MalformedURLException {
AndroidDriver<AndroidElement> driver=capabilities();
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.findElementByXPath("//android.widget.Button[@text = 'Existing User? SIGN IN']").click();
driver.findElementByXPath("//android.widget.EditText[@text = 'Email/Mobile no.']").click();
driver.findElementByClassName("android.widget.EditText").sendKeys("<PASSWORD>");
driver.findElementById("com.flipkart.android:id/et_password").sendKeys("<PASSWORD>");
driver.findElementByXPath("//android.widget.Button[@text = 'SIGN IN']").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
System.out.println(driver.findElementById("com.flipkart.android:id/flyout_parent_title").getText());
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"My Account\")").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//driver.findElementByXPath("//android.widget.Button[@text = 'Existing User? SIGN IN']").click();
TouchAction t =new TouchAction(driver);
t.press(driver.findElementByXPath("//*[@content-desc='My Orders']")).waitAction(2000).moveTo(driver.findElementByXPath("//*[@content-desc='My Reviews']")).release().perform();
//
//System.out.println(driver.findElementById("com.flipkart.android:id/flyout_parent_title").getText());
//driver.findElementByXPath("//*[@content-desc = 'Logout of this app']").click();
}
}
<file_sep>package test;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
public class Working_Code extends TestScritpt{
public static void main(String[] args) throws MalformedURLException{
AndroidDriver<AndroidElement> driver=capabilities();
// login
driver.findElementByXPath("//android.widget.Button[@text = 'Existing User? SIGN IN']").click();
driver.findElementByXPath("//android.widget.EditText[@text = 'Email/Mobile no.']").click();
driver.findElementByClassName("android.widget.EditText").sendKeys("<PASSWORD>");
driver.findElementById("com.flipkart.android:id/et_password").sendKeys("<PASSWORD>");
driver.findElementByXPath("//android.widget.Button[@text = 'SIGN IN']").click();
// electronics_mobile_
driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
//driver.findElementByClassName("//android.widget.ImageButton").click();
driver.findElementById("com.flipkart.android:id/flyout_parent_title").click();
driver.findElementByAndroidUIAutomator("text(\"Mobiles\")").click();
driver.findElementById("com.flipkart.android:id/firstCreativeCard").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
driver.findElementByClassName("android.widget.ImageButton").click();
driver.findElementByClassName("android.widget.ImageButton").click();
// offerZone
driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"Offer Zone\")").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
// myreward
driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"My Rewards\")").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
}
}
<file_sep>package test;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
public class Login extends TestScritpt{
public static void main (String[] args) throws MalformedURLException{
String Status;
//AndroidDriver<AndroidElement> driver=capabilities();
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
LoginCheck obj= new LoginCheck();
Status = obj.invalidLogin();
Status = obj.validLogin();
Status = obj.when_I_Click_on_productNavigation();
Status = obj.when_I_Click_on_myCart();
Status = obj.when_I_Click_on_myWhishlist();
Status = obj.when_I_Click_on_myOrders();
Status = obj.when_I_Click_on_myAccount();
Status = obj.when_I_Click_on_myRewards();
Status = obj.when_I_Click_on_myNotifications();
Status = obj.when_I_Click_on_myOrders();
Status = obj.when_I_Click_on_helpCentre();
Status = obj.when_I_Click_on_giftCard();
Status = obj.when_I_Click_on_offerZone();
System.out.println("Test Result.."+Status);
//obj.validLogin();
}
}
<file_sep>package test;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import junit.framework.Assert;
public class LoginCheck{
LoginCheck() throws MalformedURLException{
//AndroidDriver<AndroidElement> driver;
}
AndroidDriver<AndroidElement> driver=TestScritpt.capabilities();
String invalidLogin(){
String Status, value;
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.Button[@text = 'Existing User? SIGN IN']").click();
driver.findElementByXPath("//android.widget.EditText[@text = 'Email/Mobile no.']").click();
driver.findElementByClassName("android.widget.EditText").sendKeys("<PASSWORD>");
driver.findElementById("com.flipkart.android:id/et_password").sendKeys("123");
driver.findElementByXPath("//android.widget.Button[@text = 'SIGN IN']").click();
driver.findElementByXPath("//android.widget.TextView[@text = 'Account does not exist']").getText();
value = driver.findElementByXPath("//android.widget.TextView[@text = 'Account does not exist']").getText();
if(value.equals("Account does not exist")) {
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Error Message.."+value);
return Status;
}
String validLogin(){
String Status;
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//driver.findElementByXPath("//android.widget.Button[@text = 'New to Flipkart? SIGNUP']").click();
driver.findElementByXPath("//android.widget.Button[@text = 'Existing User? SIGN IN']").click();
driver.findElementByXPath("//android.widget.EditText[@text = 'Email/Mobile no.']").click();
driver.findElementByClassName("android.widget.EditText").sendKeys("9496616082");
driver.findElementById("com.flipkart.android:id/et_password").sendKeys("<PASSWORD>");
driver.findElementByXPath("//android.widget.Button[@text = 'SIGN IN']").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.findElementByAndroidUIAutomator("text(\"My Account\")").click();
//System.out.println(driver.findElementByXPath("//android.view.View[@content-desc = 'Nivya']").getText());
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByXPath("//android.view.View[@content-desc = 'editprofile']").click();
String name=driver.findElementById("first_name").getText();
driver.findElementByXPath("//android.widget.Button[@content-desc = 'SUBMIT']").click();
if(name.equals("Nivya")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Login Person"+name);
return Status;
}
String when_I_Click_on_productNavigation()
{
String Pvalue, Status;
//driver.findElementByXPath("//android.widget.ImageButton[@resource-id = 'com.flipkart.android:id/btn_skip']").click();
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.findElementByXPath("//android.widget.ImageButton[@content-desc = 'Open Drawer']").click();
//driver.findElementById("com.flipkart.android:id/logo_icon").click();
//driver.findElementByClassName("//android.widget.ImageButton").click();
driver.findElementById("com.flipkart.android:id/flyout_parent_title").click();
driver.findElementByAndroidUIAutomator("text(\"Mobiles\")").click();
Pvalue = driver.findElementByXPath("//android.widget.TextView[@text = 'Mobiles Destination']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.ImageButton[@content-desc = 'Back Button']").click();
driver.findElementByClassName("android.widget.ImageButton").click();
driver.findElementByClassName("android.widget.ImageButton").click();
//driver.findElementByClassName("android.widget.ImageButton").click();
if(Pvalue.equals("Mobiles Destination")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Pvalue);
return Status;
}
String when_I_Click_on_offerZone(){
String OFvalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.findElementByAndroidUIAutomator("text(\"My Cart\")").click();
OFvalue = driver.findElementByXPath("//android.widget.TextView[@text = 'Offer Zone']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(OFvalue.equals("Offer Zone")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+OFvalue);
return Status;
}
String when_I_Click_on_myNotifications(){
String Nvalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.findElementByAndroidUIAutomator("text(\"Notifications\")").click();
Nvalue = driver.findElementByXPath("//android.widget.TextView[@text = 'Notifications']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Nvalue.equals("Notifications")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Nvalue);
return Status;
}
String when_I_Click_on_myRewards(){
String Rvalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.findElementByAndroidUIAutomator("text(\"My Rewards\")").click();
Rvalue = driver.findElementByXPath("//android.widget.TextView[@text = 'My Rewards']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Rvalue.equals("My Rewards")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Rvalue);
return Status;
}
String when_I_Click_on_myCart(){
String Cvalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.findElementByAndroidUIAutomator("text(\"My Cart\")").click();
Cvalue = driver.findElementByXPath("//android.widget.TextView[@text = 'My Cart']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Cvalue.equals("My Cart")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Cvalue);
return Status;
}
String when_I_Click_on_myWhishlist(){
String Wvalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
//driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"My Wishlist\")").click();
Wvalue = driver.findElementByXPath("//android.widget.TextView[@text = 'Wishlist']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Wvalue.equals("Wishlist")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Wvalue);
return Status;
}
String when_I_Click_on_myOrders(){
String Ovalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"My Orders\")").click();
Ovalue = driver.findElementByXPath("//android.widget.TextView[@text = 'My Orders']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Ovalue.equals("My Orders")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Ovalue);
return Status;
}
String when_I_Click_on_myAccount(){
String Avalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"My Account\")").click();
Avalue = driver.findElementByXPath("//android.widget.TextView[@text = 'My Account']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Avalue.equals("My Account")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Avalue);
return Status;
}
String when_I_Click_on_giftCard(){
String Avalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"Gift Card\")").click();
Avalue = driver.findElementByXPath("//android.widget.TextView[@text = 'Gift Card']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Avalue.equals("Gift Card")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Avalue);
return Status;
}
String when_I_Click_on_helpCentre(){
String Avalue, Status;
//driver.findElementById("com.flipkart.android:id/btn_skip").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementById("com.flipkart.android:id/logo_icon").click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByAndroidUIAutomator("text(\"Help Centre\")").click();
Avalue = driver.findElementByXPath("//android.widget.TextView[@text = 'Help Centre']").getText();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElementByClassName("android.widget.ImageButton").click();
if(Avalue.equals("Help Centre")){
Status = "pass";
}else{
Status = "fail";
}
System.out.println("Messsage"+Avalue);
return Status;
}
}
| 43bfde76a22c92b128ae15044ca598b62c521ad3 | [
"Java"
] | 4 | Java | nivyavarghese99/Mob | 905cee3bd5051ccfdbfb1e8ccaf5bc414c3bba31 | 615aa1b810277daaf15e268eb2eb8c44e4ec679c |
refs/heads/master | <file_sep># Project Overview
An artificial intelligence Tic Tac Toe with Min-Max algorithm.
# Software Used
- Visual Studio 2019
- Photoshop
<br/>This is a group project. Group Members:
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
<file_sep>#include "graphics.h"
#include <windows.h>
#include <mmsystem.h>
#include <iostream>
#include <vector>
#include <time.h>
#include <thread>
using namespace std;
int cpu_move_to_row=1, cpu_move_to_col=1;
const int no_of_page = 4;
const string WindowName = "TicTacToe...";
const string MainBackgroundImageName = "images/EntryBG.jpg";
bool isExit = false;
const int width = 780;
const int height = 780;
//total grid will be 9
const int total_row = 3, total_col = 3;
class Point {
public: int x, y; Point(int _x=0, int _y=0) :x(_x), y(_y) {}
};
class Grid {
public: Point topLeft, bottomRight; char occupiedType;
Grid(int x1 = 0, int y1 = 0, int x2 = 0, int y2 = 0) :topLeft(Point(x1, y1)), bottomRight(Point(x2, y2)) {occupiedType = '*'; }
Grid(Point TL, Point BR) : topLeft(TL), bottomRight(BR) { occupiedType = '*'; }
int getWidth() { return abs(topLeft.x - bottomRight.x); }
int getHeight() { return abs(topLeft.y - bottomRight.y); }
};
Grid grid[total_row][total_col];
void drawGrid(int width, int height, int margin)
{
//draw 3 vertical line
setcolor(WHITE);
setlinestyle(0, 0, 3);
int row_width = (width - margin * 2) / 3;
int col_width = (height - margin * 2) / 3;
//draw 4 horizontal line
line(margin, margin, width - margin, margin);
line(margin, margin + row_width, width - margin, margin + row_width);
line(margin, margin + row_width * 2, width - margin, margin + row_width * 2);
line(margin, height - margin, width - margin, height - margin);
//draw 4 vertical line
line(margin, margin, margin, height - margin);
line(margin + col_width, margin, margin + col_width, height - margin);
line(margin + col_width * 2, margin, margin + col_width * 2, height - margin);
line(width - margin, margin, width - margin, height - margin);
for (int i = 0; i < total_row; i++)
for (int j = 0; j < total_col; j++)
grid[i][j] = Grid(margin + j * col_width, margin + i * row_width, margin + (j+1) * col_width, margin + (i+1) * row_width);
}
#pragma region Full Condition
int isFull()// grid is full
{
for (int i=0; i<total_row; i++)
for (int j=0; j<total_col; j++)
if (grid[i][j].occupiedType!='X')
if(grid[i][j].occupiedType != 'O')
return 0;
return 1;
}
#pragma endregion
#pragma region WinningCondition
int me_won()
{
//horizontal win condition
if (grid[0][0].occupiedType == 'O' && grid[0][1].occupiedType == 'O' && grid[0][2].occupiedType == 'O')
return 1;
if (grid[1][0].occupiedType == 'O' && grid[1][1].occupiedType == 'O' && grid[1][2].occupiedType == 'O')
return 1;
if (grid[2][0].occupiedType == 'O' && grid[2][1].occupiedType == 'O' && grid[2][2].occupiedType == 'O')
return 1;
//vertical win condition
if (grid[0][0].occupiedType == 'O' && grid[1][0].occupiedType == 'O' && grid[2][0].occupiedType == 'O')
return 1;
if (grid[0][1].occupiedType == 'O' && grid[1][1].occupiedType == 'O' && grid[2][1].occupiedType == 'O')
return 1;
if (grid[0][2].occupiedType == 'O' && grid[1][2].occupiedType == 'O' && grid[2][2].occupiedType == 'O')
return 1;
//sliding win condition
if (grid[0][0].occupiedType == 'O' && grid[1][1].occupiedType == 'O' && grid[2][2].occupiedType == 'O')
return 1;
if (grid[0][2].occupiedType == 'O' && grid[1][1].occupiedType == 'O' && grid[2][0].occupiedType == 'O')
return 1;
return 0;
}
int cpu_won()
{
//horizontal win condition
if (grid[0][0].occupiedType == 'X' && grid[0][1].occupiedType == 'X' && grid[0][2].occupiedType == 'X')
return 1;
if (grid[1][0].occupiedType == 'X' && grid[1][1].occupiedType == 'X' && grid[1][2].occupiedType == 'X')
return 1;
if (grid[2][0].occupiedType == 'X' && grid[2][1].occupiedType == 'X' && grid[2][2].occupiedType == 'X')
return 1;
//vertical win condition
if (grid[0][0].occupiedType == 'X' && grid[1][0].occupiedType == 'X' && grid[2][0].occupiedType == 'X')
return 1;
if (grid[0][1].occupiedType == 'X' && grid[1][1].occupiedType == 'X' && grid[2][1].occupiedType == 'X')
return 1;
if (grid[0][2].occupiedType == 'X' && grid[1][2].occupiedType == 'X' && grid[2][2].occupiedType == 'X')
return 1;
//sliding win condition
if (grid[0][0].occupiedType == 'X' && grid[1][1].occupiedType == 'X' && grid[2][2].occupiedType == 'X')
return 1;
if (grid[0][2].occupiedType == 'X' && grid[1][1].occupiedType == 'X' && grid[2][0].occupiedType == 'X')
return 1;
return 0;
}
#pragma endregion
//here is the minimax for computer brain
int minimax(bool flag)// The minimax function
{
int max_val = -1000, min_val = 1000; //-100 is our assumed infinite max value, 100 is our assumed infinite min value
int i, j, value = 1;
if (cpu_won() == 1)
{
return 10;
}
else if (me_won() == 1)
{
return -10;
}
else if (isFull() == 1)
{
return 0;
}
int score[total_row][total_col] = { {1,1,1}, {1,1,1}, {1,1,1} };//if score[i]=1 then it is empty
for (i = 0; i < total_row; i++)
for (j=0; j<total_col; j++)
{
if (grid[i][j].occupiedType == '*')
{
if (min_val > max_val) // reverse of pruning condition
{
if (flag == true)
{
grid[i][j].occupiedType = 'X';
value = minimax(false);
}
else
{
grid[i][j].occupiedType = 'O';
value = minimax(true);
}
grid[i][j].occupiedType = '*';
score[j][i] = value;
}
}
}
if (flag == true)
{
max_val = -1000;
for (int i = 0; i < total_row; i++)
for (int j = 0; j < total_col; j++)
{
if (score[j][i] > max_val && score[j][i] != 1)
{
max_val = score[j][i];
cpu_move_to_row = i;
cpu_move_to_col = j;
}
}
return max_val;
}
if (flag == false)
{
min_val = 1000;
for (i=0; i<total_row; i++)
for (j = 0; j < total_col; j++)
{
if (score[j][i] < min_val && score[j][i] != 1)
{
min_val = score[j][i];
cpu_move_to_row = i;
cpu_move_to_col = j;
}
}
return min_val;
}
}
class Player{
public:
bool hasMoved;
Player() { hasMoved = false; }
void Control()
{
int x, y;
getmouseclick(WM_LBUTTONDOWN, x, y);
int crop_image_to_offset = 5; //we need to reduce the image size becoz it hide our lines.
for (int i = 0; i < total_row; i++) {
for (int j = 0; j < total_col; j++)
{
//first, check for a valid grid
if (grid[i][j].occupiedType == '*') {
if (x >= grid[i][j].topLeft.x
&& x <= grid[i][j].bottomRight.x
&& y >= grid[i][j].topLeft.y
&& y <= grid[i][j].bottomRight.y
)
{
cout << endl << endl;
cout << "\nYou press grid [" << i << "][" << j << "]\n";
readimagefile("images/O.jpg", grid[i][j].topLeft.x + crop_image_to_offset
, grid[i][j].topLeft.y + crop_image_to_offset
, grid[i][j].bottomRight.x - crop_image_to_offset
, grid[i][j].bottomRight.y - crop_image_to_offset);
grid[i][j].occupiedType = 'O';
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
hasMoved = true;
return;
}
}
else
{
hasMoved = false;
}
}
}
}
};
class Computer {
public:
Computer() { }
void Control()
{
int crop_image_to_offset = 5;
cout<<"\nMinimax: "<<minimax(true);
if (grid[cpu_move_to_row][cpu_move_to_col].occupiedType == '*')
{
grid[cpu_move_to_row][cpu_move_to_col].occupiedType = 'X';
readimagefile("images/X.jpg", grid[cpu_move_to_row][cpu_move_to_col].topLeft.x + crop_image_to_offset
, grid[cpu_move_to_row][cpu_move_to_col].topLeft.y + crop_image_to_offset
, grid[cpu_move_to_row][cpu_move_to_col].bottomRight.x - crop_image_to_offset
, grid[cpu_move_to_row][cpu_move_to_col].bottomRight.y - crop_image_to_offset);
cout << "\nCPU select grid[" << cpu_move_to_row << "][" << cpu_move_to_col << "]";
PlaySound("sounds/CPUSelect.wav", NULL, SND_FILENAME);
}
}
};
class PageController {
private:
bool isMeFirst;
int currPageIndex;
public:
PageController()
{
currPageIndex = 0;
srand(time(NULL));
cpu_move_to_row = rand() % total_row;
cpu_move_to_col = rand() % total_col;
isMeFirst = false;
}
void switchPage()
{
currPageIndex = (currPageIndex + 1) % no_of_page;
}
void displayCurrentPage()
{
cout << "Displaying page: " << currPageIndex<<endl;
DisplayPage(currPageIndex);
}
void DisplayPage(int index)
{
switch (index)
{
case 0:
{
EntryPageScene(width, height);
break;
}
case 1:
{
SelectFirstPageScene(width, height);
break;
}
case 2:
{
PlayPageScene(width, height);
break;
}
case 3:
ResultPageScene(width, height);
break;
}
}
void EntryPageScene(int width, int height)
{
int marginX = 100;
readimagefile(MainBackgroundImageName.c_str(), 0, 0, width, height / 2);
readimagefile("images/playBtn.jpg", width / 2 - marginX, height / 12*7, width / 2 + marginX, height / 12 *8);
readimagefile("images/exitBtn.jpg", width / 2 - marginX, height / 12*10 , width / 2 + marginX, height / 12*11);
setmousequeuestatus(WM_LBUTTONDOWN);
//while (!ismouseclick(WM_LBUTTONDOWN)) { /*wait for press*/}
while (1)
{
int x, y;
getmouseclick(WM_LBUTTONDOWN, x, y);
if (x >= width / 2 - marginX
&& x <= width / 2 + marginX
&& y >= height / 12 * 7
&& y <= height / 12 * 8)
{
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
cleardevice();
switchPage();
break;
}
if (x >= width / 2 - marginX
&& x <= width / 2 + marginX
&& y >= height / 12 * 10
&& y <= height / 12 * 11)
{
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
cleardevice();
closegraph();
isExit = true;
break;
}
}
}
void SelectFirstPageScene(int width, int height)
{
mciSendString("play sounds/bgm.wav", NULL, 0, 0);
int buttonWidth = 200;
readimagefile("images/WhoFirstImg.jpg", width / 2 - buttonWidth, (1 / 12.0) * height, width / 2 + buttonWidth, (3 / 12.0) * height);
readimagefile("images/computerBtn.jpg", width / 2 - buttonWidth, (5 / 12.0) * height, width / 2 + buttonWidth, (7 / 12.0) * height);
readimagefile("images/meBtn.jpg", width / 2 - buttonWidth, (8 / 12.0) * height, width / 2 + buttonWidth, (10 / 12.0) * height);
while (1)
{
int x, y;
getmouseclick(WM_LBUTTONDOWN, x, y);
if (x >= width / 2 - buttonWidth
&& x <= width / 2 + buttonWidth
&& y >= (5 / 12.0) * height
&& y <= (7 / 12.0) * height)
{
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
cleardevice();
switchPage();
isMeFirst = false;
break;
}
if (x >= width / 2 - buttonWidth
&& x <= width / 2 + buttonWidth
&& y >= (8 / 12.0) * height
&& y <= (10 / 12.0) * height)
{
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
cleardevice();
switchPage();
isMeFirst = true;
break;
}
}
}
void PlayPageScene(int width, int height)
{
drawGrid(width, height, 100);
int font_size = 1;
settextstyle(10, HORIZ_DIR, font_size);
char cpu_say[] = "CPU: Don't click so fast, let me think...";
outtextxy(20, height-60, cpu_say);
delay(1000);
char me_reply[] = "Me: okay...";
outtextxy(20, height - 40, me_reply);
Player me;
Computer enemy;
int isMyTurn = false;
cout << "\n\nMe first? " << ((isMeFirst) ? "\nYa, me first\n\n" : "\nNo, cpu first\n\n")<<endl;
cout << "----------Game Start---------\n\n";
if (isMeFirst)
{
while (1)
{
me.Control();
if (me.hasMoved)
{
isMyTurn = false;
break;
}
}
}
//looping the game until sb win
while (1)
{
//computer turn
if (!isMyTurn)
{
enemy.Control();
isMyTurn = true;
}
if (cpu_won() || isFull())
{
cout << "\nLoading Result...\n\n";
int font_size = 3;
settextstyle(10, HORIZ_DIR, 3);
setcolor(WHITE);
outtextxy((width - 100) / 2 - 17 * 3, 0, "\nLoading Result...");
delay(1000);
cleardevice();
switchPage();
break;
}
if (isMyTurn)//here is our gameplay
{
me.Control();
if (me.hasMoved)
{
me.hasMoved = false;
isMyTurn = false;
}
}
if (me_won()||cpu_won()||isFull())
{
settextstyle(10, HORIZ_DIR, 3);
setcolor(WHITE);
outtextxy((width-100)/2-17*3, 0, "\nLoading Result...");
delay(1000);
cleardevice();
switchPage();
break;
}
}
}
void ResultPageScene(int width, int height)
{
int buttonWidth = 120;
mciSendString("close sounds/bgm.wav", NULL, 0, 0);
readimagefile("images/restartBtn.jpg", width / 2 - buttonWidth, (5 / 12.0) * height, width / 2 + buttonWidth, (7 / 12.0) * height);
readimagefile("images/exitBtn.jpg", width / 2 - buttonWidth, (8 / 12.0) * height, width / 2 + buttonWidth, (10 / 12.0) * height);
if (me_won() == 1)
{
cout << "\n\n---------Result---------\nMe Win!\n\n";
readimagefile("images/youWinImg.jpg", 50, (1 / 12.0) * height, width - 50, (3 / 12.0) * height);
PlaySound("sounds/Win.wav", NULL, SND_FILENAME);
}
else if (cpu_won() == 1)
{
cout << "\n\n---------Result---------\nCPU Win!\n\n";
readimagefile("images/youLoseImg.jpg", 50, (1 / 12.0) * height, width - 50, (3 / 12.0) * height);
PlaySound("sounds/Lose.wav", NULL, SND_FILENAME);
}
else if (isFull() == 1)
{
cout << "\n\n---------Result---------\nDraw!\n\n";
readimagefile("images/drawImg.jpg", 50, (1 / 12.0) * height, width - 50, (3 / 12.0) * height);
PlaySound("sounds/Draw.wav", NULL, SND_FILENAME);
}
while (1)
{
int x, y;
getmouseclick(WM_LBUTTONDOWN, x, y);
if (x >= width / 2 - buttonWidth
&& x <= width / 2 + buttonWidth
&& y >= (5 / 12.0) * height
&& y <= (7 / 12.0) * height)
{
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
cleardevice();
currPageIndex = 1;
system("cls");
break;
}
if (x >= width / 2 - buttonWidth
&& x <= width / 2 + buttonWidth
&& y >= (8 / 12.0) * height
&& y <= (10 / 12.0) * height)
{
PlaySound("sounds/Button.wav", NULL, SND_FILENAME);
cleardevice();
closegraph();
isExit = true;
break;
}
}
}
};
int main()
{
int winPosX = (getmaxwidth() - width) / 2;
int winPosY = (getmaxheight() - height) / 2;
//centre our window at the middle
initwindow(width, height, WindowName.c_str(), winPosX, winPosY);
PageController c;
while (!isExit)
{
c.displayCurrentPage();
}
return 0;
}
| a4a5b2fa1d209f9ac91c28eeaba9a95930b82ca2 | [
"Markdown",
"C++"
] | 2 | Markdown | tanseejou/AI-Tic-Tac-Toe | 284583ee59f793c4586b402445bbb79d9fd1e648 | 85d4e6f24275e0de8cef49e86cdeb78c36bd68e0 |
refs/heads/main | <repo_name>FBSeletronica/Franzininho-Projetos<file_sep>/Input/Button_Counter_Franzininho_WiFi/main/main.c
/*
Autor : <NAME>
Data 31/03/21
Exemplo de Input
Nesse exemplo ao pressionar irá iniciar uma contagem indefinida e será mostrado
os valores de contagem no terminal. Foi adotado a topologia utilizando resistor de pullup
interno da placa Franzininho Wi-Fi
*/
/* Inclusão arquivos de cabeçalho*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_log.h"
/* Definições do Pino*/
#define BTN 15
void app_main(void){ // Main
/* INPUT*/
gpio_pad_select_gpio(BTN);
gpio_set_direction(BTN,GPIO_MODE_INPUT);
/* Habilita pullup*/
gpio_pullup_en(BTN);
gpio_pulldown_dis(BTN);
/* Mensagem de inicialização*/
ESP_LOGI("[INFO]", "INICIANDO CONTADOR FRANZININHO");
/* Habilita pulldown*/
//gpio_pulldown_en(BTN);
//gpio_pullup_dis(BTN);
unsigned int counter = 0; // Variavel para receber o incremento após ser pressionar o botão
bool last_state_btn = 0; // Variável para auxiliar do botão
while (1) { // Loop
bool state_btn = gpio_get_level(BTN); // Leitura do botão
if(!state_btn && !last_state_btn) {last_state_btn = 1;} // Se botão pressionado seta variável last_state_btn
else if(state_btn && last_state_btn) { /* Botão pressionado e last_state_btn em 1, realiza a contagem
e mostra no terminal o valor da contagem*/
counter ++;
ESP_LOGI("Contador ", " %d", counter);
last_state_btn = 0; // Reseta a variável
}
vTaskDelay(1); // Delay 1 ms
}// endLoop
}// endMain<file_sep>/README.md
# Franzininho Projetos
## Seja Bem-Vindo
Nesse repositório apresento exemplos de projetos para o iniciante dar seu primeiros passos com a placa Franzininho WiFi. Sinta-se a vontade em contribuir e dar seu feedback, estamos em desenvolvimento e toda ajuda é necessária ;)
## Exemplos Básicos
1. Input
2. Output (Falta implementar)
3. Analog-Digital Convert (Falta implementar)
4. I2C (Falta implementar)
5. SPI (Falta implementar)
6. Bluetooth Low Energy ((Falta implementar))
* Nota: Os exemplos listados utlizando o editor de texto Visual Code Studio (VS Code) junto a extensão da Espressif para interagir com a IDF
## Referência
- Sobre o projeto Franzininho : https://franzininho.com.br/
- Extensão IDF : https://www.youtube.com/watch?v=rxMg_zxO0q0&t=1s
- Documentação API : https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/index.html
- Documentação ESP32 : https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/index.html
<file_sep>/Input/Button_Exem_Franzininho_WiFi/main/main.c
/* Exemplo de Botão
Nesse exemplo ao pressionar botão táctil o LED_ONBOARD é acionado e mostra no terminal. */
/* Inclusão arquivos de cabeçalho*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "sdkconfig.h"
/* Definições de Pinos*/
#define BTN 15
#define LED_ONBOARD 2
#define HIGH 1
#define LOW 0
void app_main(void){ // Main
/* OUTPUT*/
gpio_pad_select_gpio(LED_ONBOARD);
gpio_set_direction(LED_ONBOARD,GPIO_MODE_OUTPUT);
/* INPUT*/
gpio_pad_select_gpio(BTN);
gpio_set_direction(BTN,GPIO_MODE_INPUT);
/* Habilita pulldown*/
//gpio_pulldown_en(BTN);
//gpio_pullup_dis(BTN);
/* Habilita pullup*/
gpio_pullup_en(BTN);
gpio_pulldown_dis(BTN)
int last_state_btn = 0;
while (1) { // Loop
int state_btn = gpio_get_level(BTN); // Leitura do botão
if(!state_btn && !last_state_btn) {
gpio_set_level(LED_ONBOARD,HIGH);// Se botão for zero então ... liga LED
ESP_LOGI("[INFO]", "LED LIGADO");// Mostra informação no monitor "LED LIGADO"
last_state_btn = 1;
}
else if(state_btn && last_state_btn){
gpio_set_level(LED_ONBOARD,LOW);// Senão... desliga LED
ESP_LOGI("[INFO]", "LED DESLIGADO"); // Mostra informação no monitor "LED DESLIGADO"
last_state_btn = 0;
}
vTaskDelay(1); // Delay 1 ms
}// endLoop
}// endMain | 938200ea4c5c9a1a22a32a4635eaa2b768584a11 | [
"Markdown",
"C"
] | 3 | C | FBSeletronica/Franzininho-Projetos | 5549c091aeba591866635705bf48cab421569d43 | deef15472f06d3e20b7369e058b648207833b21b |
refs/heads/master | <file_sep>import pandas as pd
import email
from bs4 import BeautifulSoup as bs
from html2text import html2text as h2t
import base64
import re
import nltk
from nltk import wordpunct_tokenize
from nltk.corpus import stopwords
import spacy
from spacy import displacy
from collections import Counter
import en_core_web_sm
nlp = en_core_web_sm.load()
from pprint import pprint
import json
import datetime as dt
from datetime import timedelta as td
import os
import collections
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
from bs4 import BeautifulSoup as bs
from tqdm._tqdm_notebook import tqdm_notebook as tqdm
import dask.dataframe as dd
from dateutil.tz import tzutc
import Functions as Fn
#from nltk.internals import find_jars_within_path
#st = StanfordNERTagger('stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz','stanford-ner-2018-10-16/stanford-ner.jar',encoding='utf-8')
#jar = 'stanford-ner-2018-10-16/stanford-ner.jar'
#model = 'stanford-ner-2018-10-16/classifiers/english.all.3class.distsim.crf.ser.gz'
#ner_tagger = StanfordNERTagger(model, jar, encoding='utf8')
def decodeBase64(encodedStr):
#print(encodedStr)
if(encodedStr[:10] == '=?UTF-8?B?' and encodedStr[-2:] == '?='): #only base64 encoded string
encodedStr = encodedStr[10:-2] #remove start and last 2
decodedBytes = base64.b64decode(encodedStr)
decodedStr = str(decodedBytes, "utf-8")
return decodedStr
else: #also some text after the encoded string
return encodedStr
def splitAndDecode (fullStr):#recognise parts of fullStr as base64 stuff that needs to be decoded
#print("Let's split this mess! This it what it looks like now:\n" + fullStr)#
splits = fullStr.split()
returnStr = ''
for split in splits:
returnStr += decodeBase64(split) + ' '
returnStr = returnStr[:-1]
#print("Pfew, done. This is the new string:\n" + returnStr)
return returnStr
def getbody(msg):
body = None
#Walk through the parts of the email to find the text body.
if msg.is_multipart():
for part in msg.walk():
# If part is multipart, walk through the subparts.
if part.is_multipart():
for subpart in part.walk():
if subpart.get_content_type() == 'text/plain':
# Get the subpart payload (i.e the message body)
body = subpart.get_payload(decode=True)
#charset = subpart.get_charset()
# Part isn't multipart so get the email body
elif part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True)
#charset = part.get_charset()
# If this isn't a multi-part message then get the payload (i.e the message body)
elif msg.get_content_type() == 'text/plain':
body = msg.get_payload(decode=True)
# No checking done to match the charset with the correct part.
for charset in getcharsets(msg):
try:
body = body.decode(charset)
except UnicodeDecodeError:
handleerror("UnicodeDecodeError: encountered.",msg,charset)
except AttributeError:
handleerror("AttributeError: encountered" ,msg,charset)
return body
def getcharsets(msg):
charsets = set({})
for c in msg.get_charsets():
if c is not None:
charsets.update([c])
return charsets
def handleerror(errmsg, emailmsg,cs):
print()
print(errmsg)
print("This error occurred while decoding with ",cs," charset.")
print("These charsets were found in the one email.",getcharsets(emailmsg))
print("This is the subject:",emailmsg['subject'])
print("This is the sender:",emailmsg['From'])
def return_payload(row):
if row['email_raw_object'].is_multipart():
partlist = []
for part in row['email_raw_object'].get_payload():
partlist.append(part.get_payload())
return partlist
else:
return [row['email_raw_object'].get_payload()]
def html_to_text(row):
part = html_iterator(row['body_raw'])
return part
def make_readable(row):
content = row['body_text']
non_readable_text = Fn.ListToString(content, " ")
readable_text = non_readable_text.replace(' =', '').replace('= ', '')
readable_text = readable_text.replace('=0A=', '').replace('0A=', '')
readable_text = readable_text.replace('=A0', ' ').replace('=C2', '')
#Line below removes line breaks.
#readable_text = readable_text.replace('\n', '')
return readable_text
def html_iterator(html):
for i, elem in enumerate(html):
#print(str(i)+': '+str(type(elem)))
if isinstance(elem, str):
try:
html[i] = h2t(html[i])
except:
html[i] = html[i]
elif isinstance(elem, list):
html[i] = html_iterator(elem)
elif isinstance(elem, email.message.Message):
msg = elem.as_string()
html[i] = html_iterator([msg])
else: print('-----ERROR-----: '+str(type(elem)))
return html
def text_to_words(row):
content = row['body_text']
new_list = list(text_iterator(content))
word_list=[]
for part in new_list:
words = re.split('\W+|_', part)
lower_words = [word.lower() for word in words]
word_list.append(lower_words)
flat_list = list(text_iterator(word_list))
return flat_list
def readable_text_to_words(row):
content = row['body_readable']
content = Fn.StringToList(content)
new_list = list(text_iterator(content))
word_list=[]
for part in new_list:
words = re.split(' ', part)
lower_words = [word for word in words]
word_list.append(lower_words)
flat_list = list(text_iterator(word_list))
flat_list = list(filter(("").__ne__, flat_list))
return flat_list
def text_iterator(text):
for elem in text:
if isinstance(elem, collections.abc.Iterable) and not isinstance(elem, (str,bytes)):
yield from text_iterator(elem)
else:
yield elem
def detect_language(row):
'''words = []
for x in row['body_words']:
for y in x:
words.append(y)'''
words = row['body_words']
languages_ratios = {}
for language in stopwords.fileids():
stopwords_set = set(stopwords.words(language))
words_set = set(words)
common_elements = words_set.intersection(stopwords_set)
languages_ratios[language] = len(common_elements)
most_rated_lang = max(languages_ratios, key=languages_ratios.get)
return most_rated_lang
def mail_list(row):
lst = []
full_lst = []
mail_regex = '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}' #regex to recognise email address
title_regex = '[A-Za-z-]+:' #regex to recognise header such as 'From:'
mail_reg_2 = "\n[A-Za-z-]+:\n <"+mail_regex #regex to recognise pairs where header and mail address are seperated by a newline
sender = re.findall(mail_regex, row['sender_email']) #list of mail address in sender_email column (most likely 1 address)
exclude = ['apwg', 'phishing', 'ecrimex'] #list of words mostly included in the mail addresses to which the phishing mails are sent to report
exclude = exclude + sender
mail_filter = lambda s: not any(x in s for x in exclude) #filter that removes mail addresses containing the to be excluded mail addresses
html_regex = '<[A-Za-z-]+>[A-Za-z-]+:[\s]?<\/[A-Za-z-]+>[^<]*<[^>]*>[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}<\/[A-Za-z-]+>'
mailto_regex = 'mailto:[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}'
title_filter = lambda s: not any(x==s for x in ['http:', 'mailto:'])
for column in [row['email_raw_headers'],row['email_raw_body']]: #check for mail addresses in both the header and the body
diff_lines = re.findall(mail_reg_2, column)
correct_addresses = filter(mail_filter, diff_lines) #filter out the excluded mail addresses
for mail in correct_addresses:
_, head, m = mail.split('\n')
full_lst.append((head, m.lower()[2:]))
for line in column.split('\n'): #check for each line in the mail
if line.startswith("<html>"): #for pieces of html code, the extraction of mail addresses needs to be done differently
html_parts = re.findall(html_regex, line)
for html in html_parts:
mailto = re.findall(mailto_regex, html)
for m in mailto:
html = html.replace(m, '')
head = re.findall(title_regex, html)
mail = re.findall(mail_regex, html)
mail_l = [x.lower() for x in mail]
tuples = []
if len(mail_l)==0:
pass
elif len(head)==len(mail_l):
for i in range(len(head)):
tuples.append((head[i],mail_l[i]))
for tup in tuples:
for x in exclude:
if x in tup[1]:
tuples.remove(tup)
break
else:
correct_addresses = filter(mail_filter, mail_l) #filter out the excluded mail addresses
mail = []
for address in correct_addresses:
mail.append(address)
if len(mail)!=0:
if len(head)==0:
tuples.append(("Unknown:", mail))
elif len(head)==1:
tuples.append((head[0], mail))
else:
title = 'Unknown:'+', '.join(head)
for m in mail:
tuples.append((title, m))
if len(tuples)>0:
for tup in tuples:
full_lst.append(tup)
else:
addresses = re.findall(mail_regex, line) #in plain text, search for mail addresses on each line
addresses_l = [x.lower() for x in addresses] #make all characters lowercase for comparison with exclusion list
correct_addresses = filter(mail_filter, addresses_l) #filter out the excluded mail addresses
mail = []
for address in correct_addresses: #for each correct address:
#lst.append(address) #save the address to a list
line = line.replace(address, '') #and remove it from the text line
mail.append(address)
title_line_lst = re.findall(title_regex, line) #look for header in the line with the address
real_titles = filter(title_filter, title_line_lst) #remove http: & mailto: from list
head = []
for title in real_titles:
head.append(title)
if len(mail)==0: pass
elif len(mail)==len(head):
for i in range(len(head)):
full_lst.append((head[i],mail[i]))
elif len(head)==0:
for address in mail:
full_lst.append(("Unknown:", address))
else:
title = 'Unknown:'+', '.join(head)
for m in mail:
full_lst.append((title, m))
full_set = set(full_lst)
remove_set = set([])
if len(full_set)>1:
for s in full_set:
if s[0]=="Unknown:":
b = False
new_set = full_set.copy()
new_set.remove(s)
for f in new_set:
if f[1]==s[1]:
#print(s)
#print(full_set)
remove_set.add(s)
break
for r in remove_set:
if r in full_set:
full_set.remove(r)
mail_list = []
for f in full_set:
mail_list.append(f)
return mail_list
def remove_nest(lst, new_lst):
for l in lst:
if type(l) == list:
remove_nest(l, new_lst)
else:
new_lst.append(l)
return new_lst
def ner_tagger(row):
entities = []
flat = []
flat_list = remove_nest(row['body_raw'], flat)
html = ' '.join(flat_list)
style_regex = '<style[^>]*>[^<]*</style>'
tag_regex = '<[^>]*>'
style = re.findall(style_regex, html)
for s in style:
html = html.replace(s, '')
tags = re.findall(tag_regex, html)
for t in tags:
html = html.replace(t, '')
soup = bs(html)
text = soup.get_text()
tokenized_text = word_tokenize(text)
classified_text = st.tag(tokenized_text)
for tup in classified_text:
if tup[1]!='O':
entities.append(tup)
return entities
def create_columns(phishdf):
print('change date-type')
phishdfs = phishdf.copy() #phisdf structured
print('create and extract mail object')
phishdfs['email_raw_total'] = phishdfs['email_raw_headers']+phishdfs['email_raw_body']
phishdfs['email_raw_object'] = phishdfs.email_raw_total.apply(lambda x: email.message_from_string(x))
phishdfs['from'] = phishdfs.email_raw_object.apply(lambda x: x['from'])
phishdfs['to'] = phishdfs.email_raw_object.apply(lambda x: x['to'])
phishdfs['subject'] = phishdfs.email_raw_object.apply(lambda x: x['subject'])
phishdfs['date'] = phishdfs.email_raw_object.apply(lambda x: x['date'])
phishdfs['content-type'] = phishdfs.email_raw_object.apply(lambda x: x['content-type'])
phishdfs['return-path'] = phishdfs.email_raw_object.apply(lambda x: x['return-path'])
phishdfs['local_time'] = phishdfs.date.apply(lambda x: x.split()[-2])
print('payload')
phishdfs['body_raw'] = phishdfs.apply(return_payload, axis=1)
print('html to text')
phishdfs['body_text'] = phishdfs.apply(html_to_text, axis=1)
#Added by me:
print('Text to readable Text')
phishdfs['body_readable'] = phishdfs.apply(make_readable, axis = 1)
print('text to word list')
phishdfs['body_words'] = phishdfs.apply(text_to_words, axis=1)
#added by me
print("text to readable word list")
phishdfs['readable_words'] = phishdfs.apply(readable_text_to_words, axis = 1)
print('detect language')
phishdfs['language'] = phishdfs.apply(detect_language, axis=1)
'''
#Replace are base64 encoded splits in str fields with the decoded version.
for col in list(phishdfs):
if(isinstance(phishdfs.loc[1,col], str)):
for i in phishdfs.index:
phishdfs.loc[i,col] = splitAndDecode(phishdfs.loc[i,col])
'''
#tqdm.pandas(desc='detect email addresses')
phishdfs['addresses'] = phishdfs.apply(mail_list, axis=1)#, meta=('addresses', object))
#tqdm.pandas(desc='detect names')
#phishdfs['names'] = phishdfs.progress_apply(ner_tagger, axis=1)#, meta=('names', object)) #er zijn nu wat html to text dingen overbodig
return phishdfs
def split_df(phishdfs):
#checking the errored emails
errphishdfs = phishdfs[phishdfs['body_text']=='0']
errphishdfsc = errphishdfs.drop(columns=['body_raw', 'body_text', 'body_words', 'language'])
goodphishdfs = phishdfs[phishdfs['body_text']!='0']
accepted_languages = ['english', 'dutch', 'german', 'french']
goodphishdfsl = goodphishdfs[goodphishdfs['language'].isin(accepted_languages)]
# small_phishdfs = goodphishdfsl#.drop(['email_raw_total', 'email_raw_body', 'email_raw_headers', 'body_words'], axis=1)#[['id', 'date_sent', 'date_received', 'date','from', 'to', 'return-path', 'content-type', 'subject', 'email_raw_total', 'body_raw', 'body_text', 'body_words', 'language', 'addresses']].copy()
#small_phishdfs['names'] = small_phishdfs.apply(detect_names, axis=1)
wrong_lang = goodphishdfs[~goodphishdfs['language'].isin(accepted_languages)]
return errphishdfsc, goodphishdfsl, wrong_lang
<file_sep>#Set a value in a DataFrame
def WriteToDataFrame(Input, Df_Row, Df_Column, Df_Name):
Df_Name.loc[Df_Row, str(Df_Column)] = str(Input)
#Get a value in a DataFrame
def GetFromDataFrame(Df_Row, Df_Column, Df_Name):
Output = Df_Name.loc[Df_Row, str(Df_Column)]
return Output
#Cut a DataFrame and return it
def CutDataFrame(DataFrame_Name, Startrow, Endrow):
Sliced_DataFrame = DataFrame_Name[Startrow: Endrow]
return Sliced_DataFrame
def GetColumnFromDataFrame(DataFrame, Column):
df = DataFrame
Selected_Column = df[[Column]]
return Selected_Column
#Get number of rows
def Get_DataFrame_RowCount(DataFrame_Name):
return DataFrame_Name.shape[0]
#Get number of columns
def Get_DataFrame_ColCount(DataFrame_Name):
return DataFrame_Name.shape[1]
<file_sep>from preprocessing.csvsplit import train_test_split<file_sep>from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import AdaBoostClassifier
def train_svm(X_train, y_train, C = 1, kernel = "rbf", gamma = "scale"):
clf = svm.SVC(C = C, kernel = kernel, gamma = gamma)
clf.fit(X_train, y_train.ravel())
return clf
def train_rf(X_train, y_train, n_estimators = 1000, max_depth = 200):
clf = RandomForestClassifier(
n_estimators = n_estimators,
max_depth = max_depth
)
clf.fit(X_train, y_train.ravel())
return clf
def train_mlp(
X_train, y_train,
solver = "lbfgs",
alpha = 0.3,
hidden_layer_sizes = (500,20),
random_state = 0
):
clf = MLPClassifier(
solver = solver,
alpha = alpha,
hidden_layer_sizes = hidden_layer_sizes,
random_state = random_state
)
clf.fit(X_train, y_train.ravel())
return clf
def train_logreg(X_train, y_train, penalty = "l2", solver = "lbfgs", C = 1):
clf = LogisticRegression(penalty = penalty, solver = solver, C = C)
clf.fit(X_train, y_train.ravel())
return clf
def train_adaboost(X_train, y_train, n_estimators = 50, learning_rate = 0.05):
clf = AdaBoostClassifier(
n_estimators = n_estimators,
learning_rate = learning_rate)
clf.fit(X_train, y_train.ravel())
return clf<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Jul 25 15:00:17 2020
@author: <NAME>
"""
import pandas as pd
data = pd.read_fwf('glove.840B.300d.txt', sep=" ", header=None, engine = "python")
words = []
for i in range(len(data)):
string = data[0][i]
split_string = string.split(" ")
word = split_string[0]
words.append(word)
df_words = pd.DataFrame(data = {"Words": words})
df_words.to_csv("glove.840B.300d_words.csv", sep = ",", index = False)<file_sep>import pandas as pd #Pandas library for DataFrames
import os
import re
#Declaring debugging / setting variables
Directory_Labelled_Emails = "D:/Bachelor_Thesis/Labelled_Email_Files/"
os.chdir(Directory_Labelled_Emails)
List_Mail_Files = os.listdir()
#Create DataFrame Df_Data, which will contain all data in the labelled mails file.
Df_Data = pd.DataFrame()
for filename in List_Mail_Files:
with open(Directory_Labelled_Emails + filename, encoding = "utf-8") as File_To_Load:
Df_Raw_File_Data = pd.read_csv(File_To_Load)
A = Df_Raw_File_Data.loc[Df_Raw_File_Data["IsPhishing"] == 0]
B = Df_Raw_File_Data.loc[Df_Raw_File_Data["IsPhishing"] == 1]
Df_Data = Df_Data.append(A)
Df_Data = Df_Data.append(B)
del Df_Raw_File_Data
Df_Data = Df_Data.loc[:, Df_Data.columns.intersection(["IsPhishing", "body_text"])]
#Write to CSV
for i in range(len(Df_Data)):
rawtxt = Df_Data.iloc[i, 1]
txt = re.sub(r'\\n', '', rawtxt)
Df_Data.iloc[i, 1] = txt
Df_Data.to_csv("D:/editedmails.csv", index = False)<file_sep>#GLOBAL
SEEDS = list(range(0,10))
TO_AUGMENT = True
AUGMENTATION_PERCENTAGE = [1.01, 1.03, 1.035, 1.04, 1.045, 1.05]
AUGMENTATION_FREQUENCY = 20
TO_CLASSIFY = True
TO_CSV = True
#SUPPORT VECTOR MACHINE
TRAIN_SVM = False
SVM_C = [0.15, 0.75, 1, 1.1]
SVM_KERNEL = ["linear", "rbf"]
SVM_GAMMA = ["scale"]
svm_combined = [(C, kernel, gamma) for C in SVM_C for kernel in SVM_KERNEL for gamma in SVM_GAMMA]
#RANDOM FORESTS
TRAIN_RANDOM_FOREST = False
RF_ESTIMATORS = [100, 250, 500]
RF_MAX_DEPTH = [10, 50, 100, 200]
rf_combined = [(n_estimators, max_depth) for n_estimators in RF_ESTIMATORS for max_depth in RF_MAX_DEPTH]
#MULTILAYER PERCEPTRON
TRAIN_MLP = True
MLP_SOLVER = ["lbfgs"] #, "sgd", "adam"]
MLP_ALPHA = [0.1, 0.25, 0.5]
MLP_HIDDEN_LAYERS = [20, 40, 60, (50,5), (50,10), (100, 10), (100, 20), (250, 10)]
MLP_RANDOM_STATE = [0]
mlp_combined = [(solver, alpha, layers, state) for solver in MLP_SOLVER for alpha in MLP_ALPHA for layers in MLP_HIDDEN_LAYERS for state in MLP_RANDOM_STATE]
#LOGISTIC REGRESSION
TRAIN_LOGREG = False
LOGREG_PENALTY = ["l2"]
LOGREG_SOLVER = ["lbfgs"]
LOGREG_C = [0.4, 0.5, 0.75, 1]
logreg_combined = [(penalty, solver, C) for penalty in LOGREG_PENALTY for solver in LOGREG_SOLVER for C in LOGREG_C]
#ADAPTIVE BOOSTING
TRAIN_ADABOOST = False
ADA_ESTIMATORS = [1, 5, 10, 20, 30, 40, 50, 75, 100]
ADA_LEARNING_RATE = [0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05, 0.075, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.25, 1.5, 1.75, 2]
ada_combined = [(n_estimators, learning_rate) for n_estimators in ADA_ESTIMATORS for learning_rate in ADA_LEARNING_RATE]<file_sep># Import
import base64 #Used for encoding/decoding of base64 strings
from nltk.parse import CoreNLPParser
import html2text as h2t
import re as regex
from collections import Counter
import chardet
import random
import DataFrameFunctions as DfFun #Import DataFrameFunctions
import email
def ListToString(List, Delimiter = " "):
if isinstance(List, list):
return Delimiter.join(str(v) for v in List )
else:
return List
def StringToList(List, Delimiter = " "):
if isinstance(List, str):
return List.split(Delimiter)
else:
return List
# Decoding functions
#Base 64 ("=?utf-8?b?" && "?=")
def decodeBase64(encodedStr):
if(encodedStr[:10].lower() == '=?utf-8?b?' and encodedStr[-2:] == '?='): #only base64 encoded strings
encodedStr = encodedStr[10:-2] #Removes first 10 and last 2 characters
decodedBytes = base64.b64decode(encodedStr) #Decoding to base 64
decodedStr = str(decodedBytes, "utf-8") #UTF-8 string
return decodedStr #returns decoded string
else:
return encodedStr #returns encoded string
#The NER Tagger (part of CoreNLP) can be started by running Start_Server.bat in 'D:\Bachelor_Thesis\Email_Extraction\CoreNLP\stanford-corenlp-4.0.0'
def NER(word):
ner_tagger = CoreNLPParser(url='http://localhost:9000', tagtype='ner')
Linguistic_Element_Type = ner_tagger.tag(word.split())
return Linguistic_Element_Type
def HTML_To_Text(HTML):
Plain_Text = h2t.html2text(HTML)
#The current version of the html2text module is broken. using config.py
return Plain_Text
#Fetch Email Address
def Retreive_Email_Addresses(Email_String):
regex_Email_Address = '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}' #regex to recognise email address
Email = regex.findall(regex_Email_Address, str(Email_String))
Email_No_Dupes = RemoveDuplicates(Email)
return Email_No_Dupes
#Fetch links in text
def Retreive_URLs(String):
regex_URL = '[A-Za-z0-9._%+-]+\.[A-Za-z0-9.-]+\.[A-Za-z/=()@.0-9_?&]{2,400}'
URL = regex.findall(regex_URL, str(String))
URL_No_Dupes = RemoveDuplicates(URL)
return URL_No_Dupes
#Remove Email Address, return username (everything that is left)
def Get_Email_Username(Email_String, Email_Address):
List_Sender_Email = StringToList(Email_String)
#Remove duplicates using function below
if List_Sender_Email[-1] == Email_Address: #check if last element is email address
del List_Sender_Email[-1]
return List_Sender_Email
def RemoveDuplicates(List_Unfiltered):
DuplicatesRemoved = list(Counter(List_Unfiltered))
return DuplicatesRemoved
def DetectEncoding(String):
if isinstance(String, str):
ByteArray = bytearray()
ByteArray.extend(map(ord, String))
Encoding = chardet.detect(ByteArray)
return Encoding
def Extract_HTML(String):
StartIndex = String.lower().find("<html")
print(StartIndex)
EndIndex = String.lower().find("</html>")
print(EndIndex)
if StartIndex == EndIndex:
return String
else:
return String[StartIndex: EndIndex + 7]
def Get_Relevant_Aspects(String):
HTML_String = Extract_HTML(String)
if HTML_String != String:
HTML_String = HTML_To_Text(HTML_String)
return HTML_String
else:
return String
def Print_Email(DataFrame_Row, DataFrame_Name):
print("Email details: ")
print("Sender: " + DataFrame_Name.loc[DataFrame_Row, "Sender_Email_Username"] + ": " + DataFrame_Name.loc[DataFrame_Row, "Sender_Email_Address"])
print("Attachments: " + str(DataFrame_Name.loc[DataFrame_Row, "email_has_attachments"]))
print("Subject: " + str(DataFrame_Name.loc[DataFrame_Row, "email_subject"]))
print("Raw body: ")
TextList = DataFrame_Name.loc[DataFrame_Row, "readable_words"]
TextString = ListToString(TextList)
for line in TextString.splitlines():
print(line)
#print(DetectEncoding(TextString))
def Get_Data_Not_Seen(DataFrame_Name):
UpperBound = DfFun.Get_DataFrame_RowCount(DataFrame_Name)
RowToTake = random.randint(0, UpperBound - 1)
if DataFrame_Name.loc[RowToTake, "Seen_Before"] == "1":
return Get_Data_Not_Seen(DataFrame_Name)
else:
return RowToTake
def GetEmailBody(MailString):
MailMessage = email.message_from_string(MailString)
Body = ""
if MailMessage.is_multipart():
for part in MailMessage.walk():
ctype = part.get_content_type()
if ctype == 'text/plain':
Body = part.get_payload(decode=True)
else:
Body = MailMessage.get_payload(decode=True)
return Body
def ReturnMail(MailString):
MailMessage = email.message_from_string(MailString)
body = ""
if MailMessage.is_multipart():
print("Is Multipart")
else:
print("is not Multipart")
<file_sep>import pandas as pd
import os
def main():
cwd = os.getcwd().replace('\\', '/')
directories = [
"ada",
"logreg",
"mlp",
"rf",
"svm"
]
for dir in directories:
df = pd.DataFrame()
os.chdir("{}/experimentresults/{}/".format(cwd, dir))
csv_files = os.listdir()
for csv in csv_files:
data = pd.read_csv("{}/experimentresults/{}/{}".format(cwd, dir, csv))
data["augmentation"] = csv
df = df.append(data)
df.to_csv("{}/experimentresults/{}/all_experiments.csv".format(cwd, dir), index = False)
df.to_excel("{}/experimentresults/{}/all_experiments.xlsx".format(cwd, dir), index = False)
if __name__ == "__main__":
main()<file_sep>import pandas as pd
import os
current_dir = os.getcwd().replace('\\', '/')
def load_data(
current_dir = current_dir,
training_data = "part_1.csv",
testing_data = "part_2.csv"
):
Directory_Labelled_Emails = current_dir
df_train = pd.read_csv(
Directory_Labelled_Emails
+ training_data
)
df_test = pd.read_csv(
Directory_Labelled_Emails
+ testing_data
)
X_train = df_train.iloc[:, 1:302]
y_train = df_train.iloc[:, 0]
X_test = df_test.iloc[:, 1:302]
y_test = df_test.iloc[:, 0]
return X_train, y_train, X_test, y_test<file_sep>import pandas as pd
import os
def main():
cwd = os.getcwd().replace('\\', '/')
directories = [
"ada",
"logreg",
"mlp",
"rf",
"svm"
]
for dir in directories:
df = pd.DataFrame()
os.chdir("{}/{}/".format(cwd, dir))
csv_files = os.listdir()
print(csv_files)
AUGMENTATION = ["1.01", "1.015", "1.02", "1.025", "1.03", "1.035", "1.04", "1.045", "1.05"]
data = pd.DataFrame()
for augmentation in AUGMENTATION:
intermediate_data = pd.DataFrame()
for seed in range(0, 10):
if "seed{}_augmentation{}.csv".format(seed, augmentation) in csv_files:
df = pd.read_csv("{}/{}/seed{}_augmentation{}.csv".format(cwd, dir, seed, augmentation))
df["seed"] = seed
df["augmentation"] = augmentation
intermediate_data = pd.concat([intermediate_data, df], axis = 1)
data = pd.concat([data, intermediate_data], axis = 0)
data.to_excel("{}/{}/all_experiments.xlsx".format(cwd, dir), index = False)
if __name__ == "__main__":
main()<file_sep>from augmentation.augmentation import augment<file_sep>import numpy as np
import pandas as pd
def augment(
file_directory,
filename,
randomization_factor,
augmentation_frequency,
writing_directory
):
df = pd.read_csv(
file_directory + filename,
index_col = None
)
np_data = df.to_numpy(copy = True)
np_augmented = np.copy(np_data)
np_ones = np.ones(len(np_data))
for _ in range(0, augmentation_frequency):
np_random = np.random.normal(
1,
randomization_factor - 1,
(len(np_data), 300)
)
np_random = np.insert(
np_random,
0,
np_ones,
axis = 1
)
output = np.multiply(np_data, np_random)
np_augmented = np.insert(np_augmented, 0, output, axis = 0)
pd.DataFrame(np_augmented).to_csv(
writing_directory
+ filename,
index = False
)<file_sep>from classification.performancemetrics import evaluate
from classification.loaddata import load_data
from classification.algorithms import train_svm, train_rf, train_mlp, train_logreg, train_adaboost<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 09:27:28 2020
@author: <NAME>
"""
import pandas as pd #Pandas library for DataFrames
import math
def CutDataFrame(DataFrame_Name, Startrow, Endrow):
Sliced_DataFrame = DataFrame_Name[Startrow: Endrow]
return Sliced_DataFrame
Directory_Phishing_Mails = "D:/Bachelor_Thesis/APWG Phishing Emails/APWG Phishing Emails/"
Df_Large_File_Data = pd.DataFrame() #Empty dataframe where our data will be stored.
FILESIZE = 1000 #Amount of rows in a new file.
List_Mail_Files = [
"phish_month_8_2018",
"phish_month_9_2018",
"phish_month_10_2018",
"phish_month_11_2018",
"phish_month_12_2018",
"phish_month_1_2019",
"phish_month_2_2019",
"phish_month_3_2019"
]
for filename in List_Mail_Files:
with open(Directory_Phishing_Mails + filename + ".json") as file_to_load:
Df_Raw_File_Data = pd.read_json(file_to_load)
length = len(Df_Raw_File_Data)
file_amount = math.ceil(length/FILESIZE)
for index in range(0, file_amount):
Sliced_DataFrame = CutDataFrame(Df_Raw_File_Data, index * FILESIZE, (index + 1) * FILESIZE)
Sliced_DataFrame.to_csv("D:/Bachelor_Thesis/Sliced_Email_Files/" + filename + "_" + str((index + 1)) + ".csv")
del Df_Raw_File_Data<file_sep>from timeit import default_timer as timer
import pandas as pd
import numpy as np
from vectorizer import Vectorize
def get_shape(np_array):
return np_array.shape[0]
start1 = timer()
df_data = pd.read_csv("D:/Bachelor_Thesis/GitHub/BachelorThesis/Organized/testfiles/preprocessed_mails.csv")[["body_readable", "IsPhishing"]]
np_vectorized_emails = np.empty([0,301])
for index in range(0, len(df_data)):
start_timer2 = timer()
print(index)
body = df_data.loc[index, "body_readable"]
label = df_data.loc[index, "IsPhishing"]
weighted_vector = Vectorize(body).weighted_avg_vector
weighted_vector_and_label = np.insert(weighted_vector, 0, label, axis = 0)
insert_at = get_shape(np_vectorized_emails)
np_vectorized_emails = np.insert(
np_vectorized_emails,
insert_at,
weighted_vector_and_label,
axis = 0
)
end_timer2 = timer()
print("Time is " + str(end_timer2 - start_timer2))
end1 = timer()
print("Time is " + str(end1 - start1))
pd.DataFrame(np_vectorized_emails).to_csv("D:/Bachelor_Thesis/GitHub/BachelorThesis/Organized/testfiles/vectorized_mails.csv")<file_sep>import nltk
import pandas as pd
import string
#nltk.download()
from nltk import word_tokenize
from nltk.corpus import stopwords
stop_words = set(stopwords.words("english"))
filename = "D:/editedmails.csv"
words_file = "D:/Bachelor_Thesis/GitHub/BachelorThesis/Organized/preprocessing/glove.840B.300d_words.csv"
df_data = pd.read_csv(filename)[["IsPhishing", "body_text"]]
df_words = pd.read_csv(words_file)
all_words = df_words["Words"].tolist()
df_processed = pd.DataFrame(columns = ["IsPhishing", "body_readable"])
for index in range(len(df_data)):
text = df_data.loc[index][1]
tokens = word_tokenize(text)
tokens = [w.lower() for w in tokens]
table = str.maketrans("", "", string.punctuation)
stripped = [w.translate(table) for w in tokens]
words = [word for word in stripped if word.isalpha()]
words_no_stop = [w for w in words if not w in stop_words]
words_only_legit = [w for w in words_no_stop if w in all_words]
separator = " "
value = separator.join(words_only_legit)
df_processed.loc[index, "IsPhishing"] = df_data.loc[index, "IsPhishing"]
df_processed.loc[index, "body_readable"] = value
df_processed.to_csv("D:/Bachelor_Thesis/GitHub/BachelorThesis/Organized/testfiles/preprocessed_mails.csv", index = False)<file_sep>from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import pandas as pd
import csv
import warnings
warnings.filterwarnings("ignore")
GLOVE_DIRECTORY = "C:/Users/<NAME>/Documents/TBK/Year_3/Module 12/"
words = pd.read_table(
GLOVE_DIRECTORY + "glove.840B.300d.txt",
sep=" ",
index_col=0,
header=None,
quoting=csv.QUOTE_NONE
)
MEMOIZE = True
#function for getting the vector of a word. Uses Memoization.
vec_cache = {}
def vec(w):
if w in vec_cache:
return vec_cache[w]
try:
word_vector = words.loc[w].as_matrix()
if MEMOIZE:
vec_cache[w] = word_vector
return word_vector
except:
pass
#Definition of class BagOfWords
class BagOfWords:
"""
BagOfWords converts a string to a bag of words. Attributes: matrix, tokens
"""
def __init__(self, string):
vectorizer = CountVectorizer()
self.words_one_hot = vectorizer.fit_transform(string.split(" ")).toarray()
self.tokens = vectorizer.get_feature_names()
#Definition of class Vectorize.
class Vectorize:
"""
This class vectorizes strings.
"""
def __init__(self, string):
self.string = str(string)
words_one_hot = BagOfWords(self.string).words_one_hot
self.word_counts = np.sum(words_one_hot, axis = 0)
self.tokens = BagOfWords(self.string).tokens
self.all_vectors = np.empty([0,301])
self.vectorize()
self.get_weighted_average_vector()
return
def vectorize(self):
for index in range(0, len(self.tokens)):
word = self.tokens[index]
word_count = self.word_counts[index]
wordvec = vec(word)
if wordvec is not None:
wordvec = np.insert(wordvec, 0, word_count, axis = 0)
self.all_vectors = np.insert(
self.all_vectors,
self.all_vectors.shape[0],
wordvec,
axis = 0
)
return
def get_weighted_average_vector(self):
total_words = np.sum(self.all_vectors, axis = 0)[0]
totals_vector = np.zeros(300)
for i in range(0, self.all_vectors.shape[0]):
word_count = self.all_vectors[i][0]
totals_vector = totals_vector + word_count * self.all_vectors[i][1:301]
output = totals_vector / total_words
self.weighted_avg_vector = output
return<file_sep>from vectorization.vectorizer import Vectorize<file_sep>#GLOBAL
SEEDS = [0]
TO_AUGMENT = True
AUGMENTATION_PERCENTAGE = [1.005, 1.01, 1.015, 1.02, 1.025, 1.03, 1.035, 1.04, 1.045, 1.05]
AUGMENTATION_FREQUENCY = 20
TO_CLASSIFY = True
TO_CSV = True
#SUPPORT VECTOR MACHINE
TRAIN_SVM = True
SVM_C = [0.01, 0.02, 0.03, 0.04, 0.05, 0.1, 0.15, 0.2, 0.25, 0.5, 0.75, 1, 1.1, 1.2, 1.25, 1.3, 1.4, 1.5, 1.75, 2, 2.5, 3, 4, 5, 7.5, 10]
SVM_KERNEL = ["linear", "rbf"]
SVM_GAMMA = ["scale"]
svm_combined = [(C, kernel, gamma) for C in SVM_C for kernel in SVM_KERNEL for gamma in SVM_GAMMA]
#RANDOM FORESTS
TRAIN_RANDOM_FOREST = True
RF_ESTIMATORS = [100, 250, 500]
RF_MAX_DEPTH = [10, 50, 100, 200]
rf_combined = [(n_estimators, max_depth) for n_estimators in RF_ESTIMATORS for max_depth in RF_MAX_DEPTH]
#MULTILAYER PERCEPTRON
TRAIN_MLP = True
MLP_SOLVER = ["lbfgs"] #, "sgd", "adam"]
MLP_ALPHA = [0.1, 0.25, 0.5]
layer_1 = [50, 100, 250, 500]
layer_2 = [5, 10, 20, 50]
combination_constructor = [(one, two) for one in layer_1 for two in layer_2]
MLP_HIDDEN_LAYERS = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 250, 300, 350, 400, 450, 500]
for one, two in combination_constructor:
MLP_HIDDEN_LAYERS.append((one, two))
MLP_RANDOM_STATE = [0]
mlp_combined = [(solver, alpha, layers, state) for solver in MLP_SOLVER for alpha in MLP_ALPHA for layers in MLP_HIDDEN_LAYERS for state in MLP_RANDOM_STATE]
#LOGISTIC REGRESSION
TRAIN_LOGREG = True
LOGREG_PENALTY = ["l2"]
LOGREG_SOLVER = ["lbfgs"]
LOGREG_C = [0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.75, 1]
logreg_combined = [(penalty, solver, C) for penalty in LOGREG_PENALTY for solver in LOGREG_SOLVER for C in LOGREG_C]
#ADAPTIVE BOOSTING
TRAIN_ADABOOST = True
ADA_ESTIMATORS = [1, 5, 10, 20, 30, 40, 50, 75, 100]
ADA_LEARNING_RATE = [0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05, 0.075, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.25, 1.5, 1.75, 2]
ada_combined = [(n_estimators, learning_rate) for n_estimators in ADA_ESTIMATORS for learning_rate in ADA_LEARNING_RATE]<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jun 9 09:27:28 2020
@author: <NAME>
"""
import pandas as pd #Pandas library for DataFrames
from datetime import datetime #Get current date and time, this is later used to create new files automatically.
import Functions as Fn #Import Functions from Functions.py
import DataFrameFunctions as DfFun #Import DataFrameFunctions
import ErikMichelle as EM
import os
#Declaring debugging / setting variables
#Directory_Phishing_Mails = "D:/Bachelor_Thesis/Sliced_Email_Files/" #Directory where CSV files are stored.
Df_Raw_Data = pd.DataFrame() #Empty dataframe where our data will be stored.
#List_Mail_Files = [
# "phish_month_1_2019_1"
# ]
Directory_Sliced_Emails = "D:/Bachelor_Thesis/Sliced_Email_Files/"
os.chdir(Directory_Sliced_Emails)
List_Mail_Files = os.listdir()
#Load files and add contents to Pandas Dataframe "Df_Raw_Data".
#for Filename in List_Mail_Files:
Filename = List_Mail_Files[21]
with open(Directory_Sliced_Emails + Filename, encoding = "utf-8") as File_To_Load:
Df_Raw_Data = pd.read_csv(File_To_Load)
#List of all headers for our data.
List_Data_Headers = [
"id",
"date_sent",
"date_received",
"date_reported",
"links",
"sender_email",
"recipient_email",
"email_subject",
"email_raw_headers",
"email_raw_body",
"email_has_attachments",
"modified"
]
#List for all headers where the data has the format "timestamp". Datatype is np.int64
List_Data_Dates = [
"date_sent",
"date_received",
"date_reported"
]
#List of all columns that need to be added.
List_Columns_For_Features = [
"IsPhishing",
"Error",
"Seen_Before",
"Sender_Email_Address",
"URLs_in_email"
]
#This is where we modify the DataFrame and preprocess our data for labelling.
#Loop over all rows
for Index in range(0, len(Df_Raw_Data)):
#Set feature columns with blank value.
for feature in List_Columns_For_Features:
DfFun.WriteToDataFrame("", Index, feature, Df_Raw_Data)
#Loop over all Columns
for Header in List_Data_Headers:
#Get data of a single sample.
Data = DfFun.GetFromDataFrame(Index, Header, Df_Raw_Data)
#If the value is a date, convert to dd/mm/yyyy format.
if Header in List_Data_Dates: #Checks if Data is in format Timestamp by comparing Headers.
if Data > 0: #Timestamp has to be positive. This is not the case in the raw data, this needs to be addressed.
Data = pd.datetime.fromtimestamp(Data) #Convert Timestamp to DateTime format using Pandas.
DfFun.WriteToDataFrame(Data, Index, Header, Df_Raw_Data) #Write Data to the DataFrame.
#If the value is a sender email, retrieve the email and username. In case these are not found, leave them blank.
elif Header == "sender_email": #Checks if entry may contain email address.
Email_Address = Fn.Retreive_Email_Addresses(Data)
if len(Email_Address) == 0:
Email_Address = [""]
#Write Email Address to Sender_Email_Address
DfFun.WriteToDataFrame(Email_Address[-1], Index, "Sender_Email_Address", Df_Raw_Data)
#Write Username to the field Sender_Email_Username
Email_Username = Fn.Get_Email_Username(Data, Fn.ListToString(Email_Address[-1]))
if len(Email_Username) != 0:
Email_Username = Fn.ListToString(Email_Username, " ")
DfFun.WriteToDataFrame(Email_Username, Index, "Sender_Email_Username", Df_Raw_Data)
else:
DfFun.WriteToDataFrame("", Index, "Sender_Email_Username", Df_Raw_Data)
Df_Filtered_Data_Full = EM.create_columns(Df_Raw_Data)
for Index in range(0, len(Df_Filtered_Data_Full)):
Data = DfFun.GetFromDataFrame(Index, "body_readable", Df_Filtered_Data_Full)
URL_List = Fn.Retreive_URLs(Data)
URL_String = Fn.ListToString(URL_List, " ")
DfFun.WriteToDataFrame(URL_String, Index, "URLs_in_Email", Df_Filtered_Data_Full)
#This is where we start labelling the Emails.
#Printing Emails
Get_Next = True
Items_Left = DfFun.Get_DataFrame_RowCount(Df_Filtered_Data_Full)
while Get_Next and Items_Left != 0:
CurrentRow = Fn.Get_Data_Not_Seen(Df_Filtered_Data_Full)
for _ in range(0, 100):
print("")
Fn.Print_Email(CurrentRow, Df_Filtered_Data_Full)
print("Is this a Phishing Email? [True (1)/False(0)/Skip(s)/Exit(e)]: ")
Phishing_Value = input()
if Phishing_Value == "e":
Get_Next = bool(False)
elif Phishing_Value == "0" or Phishing_Value == "1":
Df_Filtered_Data_Full.loc[CurrentRow, "IsPhishing"] = Phishing_Value
else:
Df_Filtered_Data_Full.loc[CurrentRow, "Error"] = Phishing_Value
Df_Filtered_Data_Full.loc[CurrentRow, "Seen_Before"] = "1"
Items_Left -= 1
#Dropping columns
#Note that email_raw_object MUST be dropped in order to write to CSV. This is due to the entry being of type (email.message.Message)
Columns_To_Drop = [ "email_raw_object"
]
#This is a list of all columns
"""
Columns_To_Drop = ["id",
"links",
"date_sent",
"date_received",
"date_reported",
"email_subject",
"modified",
"IsPhishing",
"Error",
"Seen_Before",
"Sender_Email_Address",
"Sender_Email_Username",
"date",
"return-path",
"local_time",
"body_words",
"sender_email",
"recipient_email",
"email_raw_headers",
"email_raw_body",
"email_has_attachments",
"email_raw_total",
"email_raw_object",
"from",
"to",
"subject",
"content-type",
"body_raw",
"body_text",
"addresses"]
"""
Df_Filtered_Data_Dropped = Df_Filtered_Data_Full.drop(columns = Columns_To_Drop)
#Write to CSV
#print("Write to CSV? [True/False]: ")
#Comment in line below gives option not to write to CSV. As Datetime is now included, though, this defaults to True.
To_Csv = True #bool(input())
if To_Csv:
Current_Date_And_Time = datetime.now()
Current_Date_And_Time_String = Current_Date_And_Time.strftime("%d_%m_%Y_%H_%M_%S")
Df_Filtered_Data_Dropped.to_csv("D:/Bachelor_Thesis/Labelled_Email_Files/_" + Filename + "_" + Current_Date_And_Time_String + "Parts_Labelled.csv")<file_sep>import pandas as pd
import math
import os
current_dir = os.getcwd().replace('\\', '/')
def train_test_split(
filename = "nan_removed.csv",
test_size = 0.2,
random_state = 0,
part1_name = "part_1.csv",
part2_name = "part_2.csv",
subdir = "/testfiles/"
):
df = pd.read_csv(current_dir + subdir + filename)
df = df.sample(frac=1, random_state = random_state).reset_index(drop=True)
row_count = len(df)
split_at = math.floor(row_count * (1 - test_size))
part_1 = df[0 : split_at]
part_2 = df[split_at :]
part_1.to_csv(current_dir + subdir + part1_name, index = False)
part_2.to_csv(current_dir + subdir + part2_name, index = False)
return<file_sep>import pandas as pd
is_excel = False
file_dir = "D:/Bachelor_Thesis/GitHub/BachelorThesis/Organized/testfiles/"
filename = "vectorized_mails.csv"
df = pd.DataFrame()
if is_excel:
df = pd.read_excel(file_dir + filename + ".xlsx")
else:
df = pd.read_csv(file_dir + filename)
try:
df = df.drop(columns = "Unnamed: 0")
df = df.drop(columns = "ID")
except:
pass
nan_columns = df.isnull().any(axis=1)
rows_list = []
for i in range(0, len(df)):
if nan_columns.loc[i]:
rows_list.append(i)
new_df = df.drop(rows_list)
new_df.to_csv(file_dir + "nan_removed.csv", index = False) <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 10:11:47 2020
@author: <NAME>
"""
from sklearn import metrics
def evaluate(y_test, y_pred):
accuracy = metrics.accuracy_score(y_test, y_pred)
precision = metrics.precision_score(y_test, y_pred)
recall = metrics.recall_score(y_test, y_pred)
f1_score = metrics.f1_score(y_test, y_pred)
roc_auc_score = metrics.roc_auc_score(y_test, y_pred)
return accuracy, precision, recall, f1_score, roc_auc_score<file_sep>import os
import pandas as pd
from timeit import default_timer as timer
from augmentation import augment
from classification import train_svm, train_rf, train_mlp, train_logreg, train_adaboost, evaluate, load_data
from preprocessing import train_test_split
from experiments import SEEDS, TO_AUGMENT, AUGMENTATION_PERCENTAGE, AUGMENTATION_FREQUENCY, \
TO_CLASSIFY, TO_CSV, \
TRAIN_SVM, svm_combined, \
TRAIN_RANDOM_FOREST, rf_combined, \
TRAIN_MLP, mlp_combined, \
TRAIN_LOGREG, logreg_combined, \
TRAIN_ADABOOST, ada_combined
import warnings
warnings.filterwarnings("ignore")
current_dir = os.getcwd().replace('\\', '/')
metrics_list = ["accuracy", "precision", "recall", "f1_score", "roc_auc_score"]
def write_to_df(df, entries, y_test, y_pred):
accuracy, precision, recall, f1_score, roc_auc_score = evaluate(y_test, y_pred)
columns = metrics_list
row = df.shape[0]
for item in columns:
df.loc[row, item] = locals()[item]
for item in entries:
df.loc[row, item] = entries[item]
return
def main(seed, AUGMENTATION_PERCENTAGE = 1):
pd_svm = pd.DataFrame(columns = ["C", "kernel", "gamma"] + metrics_list)
pd_rf = pd.DataFrame(columns = ["n_estimators", "max_depth"] + metrics_list)
pd_mlp = pd.DataFrame(columns = ["solver", "alpha", "layers", "state"] + metrics_list)
pd_logreg = pd.DataFrame(columns = ["penalty", "solver", "C"] + metrics_list)
pd_ada = pd.DataFrame(columns = ["n_estimators", "learning_rate"] + metrics_list)
train_test_split(random_state = seed)
if TO_AUGMENT:
augment(current_dir + "/testfiles/",
"part_1.csv",
AUGMENTATION_PERCENTAGE,
AUGMENTATION_FREQUENCY,
current_dir + "/testfiles/"
)
if TO_CLASSIFY:
#Load data
(X_train, y_train, X_test, y_test) = load_data(current_dir = current_dir + "/testfiles/")
if TRAIN_SVM:
for C, kernel, gamma in svm_combined:
clf = train_svm(X_train, y_train, C, kernel, gamma)
y_pred = clf.predict(X_test)
accuracy = evaluate(y_test, y_pred)[0]
print("SVM: Seed: {}, Augmentation: {}.".format(seed, augmentation_percentage))
entries = {}
entries["C"] = C
entries["kernel"] = kernel
entries["gamma"] = gamma
write_to_df(pd_svm, entries, y_test, y_pred)
if TRAIN_RANDOM_FOREST:
for n_estimators, max_depth in rf_combined:
clf = train_rf(X_train, y_train, n_estimators, max_depth)
y_pred = clf.predict(X_test)
accuracy = evaluate(y_test, y_pred)[0]
print("Random Forests: Seed: {}, n_estimators: {}, max_depth: {}, accuracy: {}.".format(seed, n_estimators, max_depth, accuracy))
entries = {}
entries["n_estimators"] = n_estimators
entries["max_depth"] = max_depth
write_to_df(pd_rf, entries, y_test, y_pred)
if TRAIN_MLP:
for solver, alpha, layers, state in mlp_combined:
clf = train_mlp(X_train, y_train, solver, alpha, layers, state)
y_pred = clf.predict(X_test)
accuracy = evaluate(y_test, y_pred)[0]
print("MultiLayer Perceptron: Seed: {}, solver: {}, alpha: {}, layers: {}, state: {}, accuracy: {}.".format(seed, solver, alpha, layers, state, accuracy))
entries = {}
entries["solver"] = solver
entries["alpha"] = alpha
entries["layers"] = layers
entries["state"] = state
write_to_df(pd_mlp, entries, y_test, y_pred)
if TRAIN_LOGREG:
for penalty, solver, C in logreg_combined:
clf = train_logreg(X_train, y_train, penalty = penalty, solver = solver, C = C)
y_pred = clf.predict(X_test)
accuracy = evaluate(y_test, y_pred)[0]
print("Logistic Regression: Seed: {}, penalty: {}, solver: {}, C: {}, accuracy: {}.".format(seed, penalty, solver, C, accuracy))
entries = {}
entries["penalty"] = penalty
entries["solver"] = solver
entries["C"] = C
write_to_df(pd_logreg, entries, y_test, y_pred)
if TRAIN_ADABOOST:
for n_estimators, learning_rate in ada_combined:
clf = train_adaboost(X_train, y_train, n_estimators = n_estimators, learning_rate = learning_rate)
y_pred = clf.predict(X_test)
accuracy = evaluate(y_test, y_pred)[0]
print("Adaptive Boosting: Seed: {}, n_estimators: {}, learning_rate: {}, accuracy: {}.".format(seed, n_estimators, learning_rate, accuracy))
entries = {}
entries["n_estimators"] = n_estimators
entries["learning_rate"] = learning_rate
write_to_df(pd_ada, entries, y_test, y_pred)
if TO_CSV:
if TRAIN_SVM:
pd_svm.to_csv("{}/experimentresults/svm/seed{}_augmentation{}.csv".format(current_dir, seed, augmentation_percentage), index = False)
#pd_svm.to_excel("{}/experimentresults/svm/seed{}.xlsx".format(current_dir, seed), index = False)
if TRAIN_RANDOM_FOREST:
pd_rf.to_csv("{}/experimentresults/rf/seed{}_augmentation{}.csv".format(current_dir, seed, augmentation_percentage), index = False)
#pd_rf.to_excel("{}/experimentresults/rf/seed{}.xlsx".format(current_dir, seed), index = False)
if TRAIN_MLP:
pd_mlp.to_csv("{}/experimentresults/mlp/seed{}_augmentation{}.csv".format(current_dir, seed, augmentation_percentage), index = False)
#pd_mlp.to_excel("{}/experimentresults/mlp/seed{}.xlsx".format(current_dir, seed), index = False)
if TRAIN_LOGREG:
pd_logreg.to_csv("{}/experimentresults/logreg/seed{}_augmentation{}.csv".format(current_dir, seed, augmentation_percentage), index = False)
#pd_logreg.to_excel("{}/experimentresults/logreg/seed{}.xlsx".format(current_dir, seed), index = False)
if TRAIN_ADABOOST:
pd_ada.to_csv("{}/experimentresults/ada/seed{}_augmentation{}.csv".format(current_dir, seed, augmentation_percentage), index = False)
#pd_ada.to_excel("{}/experimentresults/ada/seed{}.xlsx".format(current_dir, seed), index = False)
if __name__ == "__main__":
if TO_AUGMENT == False:
for seed in SEEDS:
main(seed)
else:
for augmentation_percentage in AUGMENTATION_PERCENTAGE:
for seed in SEEDS:
main(seed, AUGMENTATION_PERCENTAGE = augmentation_percentage)
print("Program finished. Runtime was {} seconds.".format(timer())) | a24add6699bf00152998b3448960501ec0bfb963 | [
"Python"
] | 25 | Python | KylianRijnbergen/BachelorThesis | bf65a0e648f1cc38145bd64dac78a4a322c927fe | 06ab9aecd56e2e063b5cf056775eed77e75d1d6a |
refs/heads/master | <file_sep>package uk.ac.cam.queens.w3.util;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: jh
* Date: 12/3/13
* Time: 7:45 PM
* To change this template use File | Settings | File Templates.
*/
public class Order {
private int customerId;
private int productId;
private Date transactionTime;
private String countryCode;
public Order(int customerId, int productId, Date transactionTime, String countryCode) {
this.customerId = customerId;
this.productId = productId;
this.transactionTime = transactionTime;
this.countryCode = countryCode;
}
public int getCustomerId() {return customerId;}
public int getProductId() {
return productId;
}
public Date getTransactionTime() {
return transactionTime;
}
public String getCountryCode() {
return countryCode;
}
}
<file_sep>package uk.ac.cam.queens.w3.predictors;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Adam on 17/12/13.
*/
public interface PredictionMaker {
public void train(HashMap<String,Double> params);
public ArrayList<Integer> getRecommendations (int customerId);
}
<file_sep>package uk.ac.cam.queens.w3.predictors;
import uk.ac.cam.queens.w3.*;
import uk.ac.cam.queens.w3.util.Customer;
import uk.ac.cam.queens.w3.util.Order;
import uk.ac.cam.queens.w3.util.Product;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;
/**
* Created with IntelliJ IDEA.
* User: jh
* Date: 12/5/13
* Time: 11:00 PM
* To change this template use File | Settings | File Templates.
*/
public abstract class Predictor implements PredictionMaker {
DataLoader mDataLoader;
private Double baselineExpDecay = 5 * 10E-11;
public Predictor (DataLoader dataLoader) {
mDataLoader = dataLoader;
preTrain();
}
public void preTrain (){
}
public void train(HashMap<String,Double> params){
if (params.get("baselineExpDecay") != null)
baselineExpDecay = params.get("baselineExpDecay");
}
private static ArrayList<Product> cachedBaseline;
public ArrayList<Product> initialiseBaseline(){
// calculate cache
if (cachedBaseline == null){
ArrayList<Product> products = mDataLoader.getProducts();
for (Customer customer : mDataLoader.getCustomers())
for (Order order : customer.getOrders()){
long t = mDataLoader.getLatestTimeInTrainingSet().getTime() - order.getTransactionTime().getTime();
products.get(order.getProductId()).incrementWeightedCount(Math.exp(-1*t*baselineExpDecay));
}
// rescale so all weightedCounts are between 0 and 1
// find maximum weighted count
double maxWeightedCount = 0;
for (int i = 0; i<products.size(); i++)
maxWeightedCount = Math.max(maxWeightedCount,products.get(i).getWeightedCount());
// normalize
for (int i = 0; i<products.size(); i++)
products.get(i).setWeightedCount(products.get(i).getWeightedCount()/maxWeightedCount);
cachedBaseline = products;
}
// copy cache
ArrayList<Product> products = new ArrayList<Product>();
for (Product product : cachedBaseline)
products.add(product.getProductId(),product.copy());
return products;
}
public abstract ArrayList<Integer> getRecommendations (int customerId);
}
<file_sep>package uk.ac.cam.queens.w3;
import uk.ac.cam.queens.w3.predictors.FlexiPredictor;
import uk.ac.cam.queens.w3.util.DataWriter;
import uk.ac.cam.queens.w3.util.Evaluator;
import uk.ac.cam.queens.w3.util.TestCase;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: jh
* Date: 12/3/13
* Time: 7:28 PM
* To change this template use File | Settings | File Templates.
*/
public class MultiTest {
static NewDataLoader mDataLoader;
static DataWriter mDataWriter;
public static void main (String[] args){
ArrayList<TestCase> testCustomers;
// run test on part of training set or actual test file (test.csv)
final boolean runOnRealTestSet = false;
// load data
try {
//SortedDataLoader newDataLoader = new SortedDataLoader(2000000);
mDataWriter = new DataWriter();
mDataLoader = new NewDataLoader(30000); // load data (NumberOfTrainingRows)
if (!runOnRealTestSet)
testCustomers = mDataLoader.getTestCustomers();
else
testCustomers = mDataLoader.getRealTestCustomersFromFile();
} catch (IOException e){
System.err.println("Could not load datafile");
e.printStackTrace();
return;
}
// create instance of predictor
FlexiPredictor predictor = new FlexiPredictor(mDataLoader);
for (int x = 10; x <= 15 ; x+=1)
{
double param1 = Math.pow(2, x);
System.out.println("Parameter values " + param1) ;
predictor.resetParameters(param1);
predictor.train(null);
System.out.println("Running over test cases, of which there are " + testCustomers.size());
double totalScore = 0;
for (TestCase testCase : testCustomers){
// System.out.println("Calculating recommendation for user: " + testCase.getCustomerId());
ArrayList<Integer> recommendations = predictor.getRecommendations(testCase.getCustomerId());
if (runOnRealTestSet){
String outputLine = "";
for (Integer rec : recommendations){
outputLine += rec.toString() + ",";
}
// remove trailing comma
outputLine = outputLine.substring(0,outputLine.length()-1);
outputLine += "\n";
mDataWriter.write(outputLine);
}
double score = Evaluator.rateRecommendations(recommendations, testCase.getProducts());
totalScore += score;
// System.out.println("The answer was" + testCase.getProductId());
// System.out.println("Result: " + score);
// System.out.println();
}
totalScore = totalScore / testCustomers.size();
System.out.println("Average score: " + totalScore);
}
mDataWriter.close();
}
}
<file_sep>package uk.ac.cam.queens.w3;
import uk.ac.cam.queens.w3.util.Customer;
import uk.ac.cam.queens.w3.util.Order;
import uk.ac.cam.queens.w3.util.Product;
import uk.ac.cam.queens.w3.util.TestCase;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.lang.System.*;
/**
* Created by Adam on 02/01/14.
*/
public class NewDataLoader {
private final static String trainFile = "train.csv";
private final static String testFile = "test.csv";
private final static String dataPath = "data/";
// private final static int noRecords = 2224535;
private final static int noRecords = 31000;
private final static int maxCustomerId = 337405;
private final static int maxProductId = 505;
private List<Order> records = new Vector<Order>();
private List<Product> products = new ArrayList<Product>();
private Customer[] customers = null;
private int[] customerCount = new int[maxCustomerId+1];
private ArrayList<TestCase> testCustomers = new ArrayList<TestCase>();
private int trainRows;
private Date latestTime = new Date();
public NewDataLoader(int trainRows) throws IOException
{
this.trainRows = trainRows;
for (int i = 0; i <= maxProductId; ++i)
{
products.add(new Product(i));
}
System.out.println("Loading data");
LoadDataFile();
System.out.println("Sorting the data by date");
sortByDate(records);
System.out.println("Initialising test customers");
initialiseTestCustomers();
System.out.println("Data loaded");
}
public void LoadDataFile() throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(dataPath+trainFile));
SimpleDateFormat dataParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String line;
List<String> splitLine;
int customer;
int product;
Date date;
// skip first line:
// Customer_Id,(No column name),Order_Created,Product_Id
reader.readLine();
int linesRead = 0;
while ((line = reader.readLine()) != null && linesRead < noRecords)
{
splitLine = Arrays.asList(line.split("\\s*,\\s*"));
try {
date = dataParser.parse(splitLine.get(2));
date.setTime(date.getTime()-dataParser.parse("2012-04-01 00:00:00.000").getTime());
if (date.after(latestTime)) latestTime = date;
} catch (ParseException e){
err.println("Failed to parse date");
e.printStackTrace();
return;
}
customer = Integer.parseInt(splitLine.get(0));
product = Integer.parseInt(splitLine.get(1));
products.get(product).incrementCount();
++customerCount[product]; // pourquoi?
records.add(new Order(customer, product, date, splitLine.get(3)));
++linesRead;
if (linesRead % 250000 == 0)
out.println("Read " + linesRead + " lines");
}
}
// Implement some SQL-like features
public void sortByDate(List<Order> array) {Collections.sort(array, new Comparator<Order>() {
@Override
public int compare(Order o1, Order o2) {
return (o1.getTransactionTime().getTime() - o2.getTransactionTime().getTime()) > 0 ? 1 : -1;
}
});}
public Customer[] getCustomers()
{
if (customers == null)
{
customers = new Customer[maxCustomerId+1];
for (Order order: records.subList(0, trainRows))
{
int customer = order.getCustomerId();
if (customers[customer] == null)
customers[customer] = new Customer(customer, new Vector<Order>());
customers[customer].getOrders().add(order);
// customers[customer].getOrders().add(new Order(customer,
// order.getProductId(), order.getTransactionTime(), order.getCountryCode()));
}
}
return customers;
}
public List<Order> getRecords() {return records;}
public List<Order> getTraining() { return records.subList(0, trainRows); }
public List<Product> getProducts() { return products; }
public static int getNoRecords() { return noRecords; }
public static int getMaxCustomerId() { return maxCustomerId; }
public static int getMaxProductId() { return maxProductId; }
public int getTrainRows() { return trainRows; }
public Date getLatestTime() { return latestTime; }
public void initialiseTestCustomers()
{
// Use DataLoader class!
//for (int j = trainRows; j<noRecords; ++j)
//testCustomers.add(new TestCase(records.get(j).getCustomerId(), records.get(j).getProductId()));
}
public ArrayList<TestCase> getTestCustomers() {
return testCustomers;
}
public ArrayList<TestCase> getRealTestCustomersFromFile () throws IOException {
BufferedReader br = new BufferedReader(new FileReader(dataPath+testFile));
String line;
int linesRead = 0;
ArrayList<TestCase> realTestCustomers = new ArrayList<TestCase>();
// read test data
while ((line = br.readLine()) != null) {
// process the line.
int customerId = Integer.parseInt(line);
realTestCustomers.add(new TestCase(customerId,null));
linesRead++;;
}
br.close();
System.out.println("Read " + linesRead + " lines from test.csv");
return realTestCustomers;
}
}
<file_sep>package uk.ac.cam.queens.w3.util;
import java.util.Vector;
/**
* Created with IntelliJ IDEA.
* User: jh
* Date: 12/3/13
* Time: 7:44 PM
* To change this template use File | Settings | File Templates.
*/
public class Customer {
private int customerId;
Vector<Order> ordersPlaced;
public Customer(int customerId, Vector<Order> ordersPlaced) {
this.customerId = customerId;
this.ordersPlaced = ordersPlaced;
}
public int getCustomerId (){
return customerId;
}
public Vector<Order> getOrders (){
return ordersPlaced;
}
}
<file_sep>package uk.ac.cam.queens.w3.util;
import java.util.Comparator;
/**
* Created with IntelliJ IDEA.
* User: jh
* Date: 12/3/13
* Time: 8:50 PM
* To change this template use File | Settings | File Templates.
*/
public class Product {
private int productId;
private int count;
private double weightedCount;
public Product(int productId) {
this.productId = productId;
this.count = 0;
this.weightedCount = 0;
}
// copy constructor
public Product (Product product){
this.productId = product.productId;
this.count = product.count;
this.weightedCount = product.weightedCount;
}
public int getProductId() {
return productId;
}
public double getCount() {
return count;
}
public double getWeightedCount() {
return weightedCount;
}
public void incrementWeightedCount(double weightedCount) {
this.weightedCount += weightedCount;
}
public void incrementCount() {
this.count++;
}
public static class WeightedCountComparator implements Comparator<Product> {
@Override
public int compare(Product o1, Product o2) {
return (o1.getWeightedCount() < o2.getWeightedCount() ? 1 : (o1.getWeightedCount() == o2.getWeightedCount() ? 0 : -1));
}
}
public void setWeightedCount(double weightedCount) {
this.weightedCount = weightedCount;
}
public Product copy (){
Product product = new Product(this.productId);
product.count = this.count;
product.setWeightedCount(this.getWeightedCount());
return product;
}
}
<file_sep>package uk.ac.cam.queens.w3;
import uk.ac.cam.queens.w3.util.Product;
import uk.ac.cam.queens.w3.util.TestCase;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static java.lang.System.*;
/**
* Created by Adam on 02/01/14.
*/
public class SortedDataLoader {
private final static String trainFile = "train.csv";
private final static String testFile = "test.csv";
private final static String dataPath = "data/";
private final static int noRecords = 2224535;
private final static int maxCustomerId = 337405;
private final static int maxProductId = 505;
private int[][] records = new int[noRecords][4];
private ArrayList<Product> products = new ArrayList<Product>();
private int[] customerCount = new int[maxCustomerId+1];
private ArrayList<TestCase> testCustomers = new ArrayList<TestCase>();
private int trainRows;
private static int noCols = 3;
// Indices for the record array
private static int CUSTOMER = 0;
private static int PRODUCT = 1;
private static int DATE = 2;
private int latestTime = 0;
public SortedDataLoader(int trainRows) throws IOException
{
this.trainRows = trainRows;
for (int i = 0; i <= maxProductId; ++i)
{
products.add(new Product(i));
}
System.out.println("Loading data");
LoadDataFile();
System.out.println("Sorting the data by date");
sortBy(records, DATE);
System.out.println("Initialising test customers");
initialiseTestCustomers();
System.out.println("Data loaded");
}
public void LoadDataFile() throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(dataPath+trainFile));
SimpleDateFormat dataParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String line;
List<String> splitLine;
int customer;
int product;
Date date;
int countryCode;
// skip first line:
// Customer_Id,(No column name),Order_Created,Product_Id
reader.readLine();
int linesRead = 0;
while ((line = reader.readLine()) != null && linesRead < noRecords)
{
splitLine = Arrays.asList(line.split("\\s*,\\s*"));
try {
date = dataParser.parse(splitLine.get(2));
date.setTime(date.getTime()-dataParser.parse("2012-04-01 00:00:00.000").getTime());
} catch (ParseException e){
err.println("Failed to parse date");
e.printStackTrace();
return;
}
customer = Integer.parseInt(splitLine.get(0));
product = Integer.parseInt(splitLine.get(1));
records[linesRead][CUSTOMER]= customer;
records[linesRead][PRODUCT] = product;
products.get(product).incrementCount();
++customerCount[product];
// Record time in seconds and a slightly dangerous cast to int
if (date.getTime()/1000 > Integer.MAX_VALUE)
{
out.println("Bad cast - Adam you shouldn't be doing that");
return;
}
records[linesRead][DATE] = (int) (date.getTime()/1000);
latestTime = records[linesRead][DATE] > latestTime ? records[linesRead][DATE] : latestTime;
++linesRead;
if (linesRead % 500000 == 0)
out.println("Read " + linesRead + " lines");
}
}
// Implement some SQL-like features
public void sortBy(int[][] array, final int column, int start, int end)
{
// Valid col index?
assert (0<= column && column < noCols);
// Sort records
Arrays.sort(array, start, end, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[column] - o2[column];
}
});
}
public void sortBy(int[][] array, final int column)
{
sortBy(array, column, 0, array.length);
}
public void sortBy(int[][] array, final int column1, final int column2, int start, int end)
/*
Sort columns by column1, then sub-sort by column2
*/
{
// Valid col indices?
assert (0<= column1 && column1 < noCols && 0 <= column2 && column2 < noCols);
// Sort records
Arrays.sort(array, start, end, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
// Compare by column 1 first, and only then by column 2
return o1[column1] - o2[column1] == 0? o1[column2] - o2[column2] : o1[column1] - o1[column1];
}
});
}
public void sortBy(int[][] array, final int column1, final int column2)
{
sortBy(array, column1, column2, 0, array.length);
}
public int count(int[][] array, int column, int value, int start, int end)
{
// Valid col indices?
assert (0<= column && column < noCols);
int count = 0;
for (int c = start; c < end; ++c)
{
if (array[c][column] == value)
++count;
}
return count;
}
public int count(int[][] array, int column1, int value1, int column2, int value2, int start, int end)
{
// Valid col indices?
assert (0<= column1 && column1 < noCols && 0 <= column2 && column2 < noCols);
int count = 0;
for (int c = start; c < end; ++c)
{
if (array[c][column1] == value1 && array[c][column2] == value2)
++count;
}
return count;
}
public int[][] select(int[][] array, int column, int value, int start, int end)
{
int n = count(array, column, value, start, end);
int[][] toReturn = new int[n][noCols];
int insertion = 0;
for (int i = start; i < end; ++i)
{
if (array[i][column] == value)
{
System.arraycopy(array[i], 0, toReturn[insertion], 0, noCols);
insertion++;
}
}
return toReturn;
}
public int[][] select(int[][] array, int column1, int value1, int column2, int value2, int start, int end)
{
int n = count(array, column1, value1, column2, value2, start, end);
int[][] toReturn = new int[n][noCols];
int insertion = 0;
for (int i = start; i < end; ++i)
{
if (array[i][column1] == value1 && array[i][column2] == value2)
{
System.arraycopy(array[i], 0, toReturn[insertion], 0, noCols);
insertion++;
}
}
return toReturn;
}
public int[][] getRecords()
{
return records;
}
public int[][] getRecords(int start, int end)
{
return Arrays.copyOfRange(records, start, end);
}
public int[][] getTraining()
{
sortBy(records, DATE);
return Arrays.copyOfRange(records, 0, trainRows);
}
public static int getNoRecords() {
return noRecords;
}
public static int getMaxCustomerId() {
return maxCustomerId;
}
public static int getMaxProductId() {
return maxProductId;
}
public int getTrainRows() {
return trainRows;
}
public static int getCUSTOMER() {
return CUSTOMER;
}
public static int getPRODUCT() {
return PRODUCT;
}
public static int getDATE() {
return DATE;
}
public int getLatestTime()
{
return latestTime;
}
public void initialiseTestCustomers()
{
// Use DataLoader class!
//for (int j = trainRows; j<noRecords; ++j)
//testCustomers.add(new TestCase(records[j][CUSTOMER], records[j][PRODUCT]));
}
public ArrayList<TestCase> getTestCustomers() {
return testCustomers;
}
public ArrayList<TestCase> getRealTestCustomersFromFile () throws IOException {
BufferedReader br = new BufferedReader(new FileReader(dataPath+testFile));
String line;
int linesRead = 0;
ArrayList<TestCase> realTestCustomers = new ArrayList<TestCase>();
// read test data
while ((line = br.readLine()) != null) {
// process the line.
int customerId = Integer.parseInt(line);
realTestCustomers.add(new TestCase(customerId,null));
linesRead++;;
}
br.close();
System.out.println("Read " + linesRead + " lines from test.csv");
return realTestCustomers;
}
public ArrayList<Product> getProducts() {
return products;
}
}
<file_sep>package uk.ac.cam.queens.w3;
import uk.ac.cam.queens.w3.predictors.PredictionMaker;
import uk.ac.cam.queens.w3.predictors.Predictor;
import uk.ac.cam.queens.w3.predictors.ProductIntersectionPredictor;
import uk.ac.cam.queens.w3.util.DataWriter;
import uk.ac.cam.queens.w3.util.Evaluator;
import uk.ac.cam.queens.w3.util.TestCase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* User: jh
* Date: 12/3/13
* Time: 7:28 PM
* To change this template use File | Settings | File Templates.
*/
public class HutChallenge {
static DataLoader mDataLoader;
static DataWriter mDataWriter;
public static void main (String[] args){
ArrayList<TestCase> testCustomers;
// run test on part of training set or actual test file (test.csv)
final boolean runOnRealTestSet = false;
// load data
try {
//SortedDataLoader newDataLoader = new SortedDataLoader(2000000);
mDataWriter = new DataWriter();
mDataLoader = new DataLoader(2000000,100000); // load data (NumberOfTrainingRows,NumberOfTestRows)
if (!runOnRealTestSet)
testCustomers = mDataLoader.getTestCustomers();
else
testCustomers = mDataLoader.getRealTestCustomersFromFile();
} catch (IOException e){
System.err.println("Could not load datafile");
e.printStackTrace();
return;
}
// create instance of predictor
PredictionMaker predictor = new ProductIntersectionPredictor(mDataLoader);
HashMap<String,Double> params = new HashMap<String,Double>();
params.put("baselineExpDecay", 5 * 10E-11 );
predictor.train(params);
double totalScore = 0;
for (TestCase testCase : testCustomers){
System.out.println("Calculating recommendation for user: " + testCase.getCustomerId());
ArrayList<Integer> recommendations = predictor.getRecommendations(testCase.getCustomerId());
if (runOnRealTestSet){
String outputLine = "";
for (Integer rec : recommendations){
outputLine += rec.toString() + ",";
}
// remove trailing comma
outputLine = outputLine.substring(0,outputLine.length()-1);
outputLine += "\n";
mDataWriter.write(outputLine);
} else {
double score = Evaluator.rateRecommendations(recommendations,testCase.getProducts());
totalScore += score;
System.out.println("Result: " + score);
System.out.println();
}
}
totalScore = totalScore / testCustomers.size();
System.out.println("Average score: " + totalScore);
mDataWriter.close();
}
}
| c49fadd34b36da5b74a0315388dfcc5d79f849bf | [
"Java"
] | 9 | Java | ae-foster/hutgroup | 9b818f638f57f850534309d35a759bbfe7befe12 | 9cd47be5eb2eab1ebe3cc9fe4f3c3e162fa944b2 |
refs/heads/master | <file_sep>Django==1.8
SQLAlchemy==0.9.7
Werkzeug==0.9.4
cov-core==1.15.0
coverage==3.7.1
importlib==1.0.3
passlib==1.6.2
pexpect==3.3
py==1.4.26
pytest==2.6.2
pytest-cov==1.8.0
requests==2.4.1
schema==0.3.1
wsgiref==0.1.2
<file_sep>"""
Package for haasplugin.
"""
<file_sep>"""
Definition of urls for haasplugin.
"""
from django.conf.urls import patterns, include, url
from haasplugin.views import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'haasplugin.views.home', name='home'),
# url(r'^haasplugin/', include('haasplugin.haasplugin.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'(?:.*?/)?(?P<path>(images)/.+)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT }),
url(r'^projects/(?P<name>.+)/attach_node', allocate_node),
url(r'^projects/(?P<name>.+)/assign_headnode', allocate_node),
url(r'^projects/(?P<name>.+)/detach_node', detach_node),
url(r'^projects/(?P<name>.+)/detach_headnode', detach_node),
url(r'^projects/(?P<name>.+)/hnic_add', hnic_add),
url(r'^project_create', project_create),
url(r'^project_delete', project_delete),
url(r'^projects/(?P<project>.+)/headnodes/(?P<name>.+)/headnode_delete', headnode_delete),
url(r'^projects/(?P<project>.+)/headnodes/(?P<name>.+)/start', headnode_start),
url(r'^projects/(?P<project>.+)/headnodes/(?P<name>.+)/stop', headnode_stop),
url(r'^headnode_delete', headnode_delete),
url(r'^headnode_create', headnode_create),
url(r'^headnodes/(?P<name>.+)/headnode_delete_hnic/(?P<hnic>.+)', headnode_delete_hnic),
url(r'^headnodes/(?P<name>.+)/hnic_add', hnic_add),
url(r'^headnodes/(?P<name>.+)', headnode_details),
url(r'^node_create', node_create),
url(r'^node_delete', node_delete),
url(r'^network_create', network_create),
url(r'^network_delete', network_delete),
url(r'^network_project_create', network_project_create),
url(r'^projects/(?P<name>.+)', project_details),
url(r'^nodes/(?P<name>.+)/node_register_nic', node_register_nic),
url(r'^nodes/(?P<name>.+)/node_delete_nic/(?P<nic>.+)', node_delete_nic),
url(r'^nodes/(?P<name>.+)/power_cycle', node_powercycle),
url(r'^nodes/(?P<name>.+)', node_details),
#url(r'^networks/(?P<name>.+)', network_details), #change project_details to network_details here and create it in views.py
url(r'^projects/', projects),
url(r'^nodes/', nodes),
url(r'^networks/', networks),
url(r'^$', projects),
)
<file_sep>moc-gui-plugins
Plugin architecture for The Mass Open Cloud GUI
===============================================
#Run the HaaS Server
Go to the HaaS directory
$cd ~/haas
The first time you start working in the repository, set up a clean test environment:
$virtualenv .venv
Next, each time you start working, enter the environment:
$source .venv/bin/activate
Then, proceed with installing the HaaS and its dependencies into the virtual environment:
$pip install -e .
Run the server with
$haas serve
Then, run the networks server in a new terminal:
Go to the HaaS directory
$cd ~/haas
enter the environment:
$source .venv/bin/activate
start the networks with
$haas serve_networks
------------------------------------------------------
#Run the HaaS UI Server
Go to the moc-gui-plugins directory
$cd ~/MOCUI
Start the Moc UI's virtual environment
$source mocui/bin/activate
Go to the moc-gui-plugins directory
$cd ~/MOCUI/moc-gui-plugins
Start the Haas Plugin server locally
$python manage.py runserver 9000
------------------------------------------------------
#Run the MOC UI
Go to the moc-gui-plugins directory
$cd ~/MOCUI
Start the Moc UI's virtual environment
$source mocui/bin/activate
Go into the UI directory
$cd ~/MOCUI/ui
Go to the moc-gui-plugins directory
./runserver.sh
Run the UI
open browser and point it to localhost:8000
Register as a new user
Go to the HaaS tab on the navigation bar
------------------------------------------------------
<file_sep>{% extends "base.html" %}
{% block content %}
<h1>{{headnode.name}}<small>
<!--<a href="/nodes/{{node.name}}/power_cycle" class="btn btn-primary btn-sm">Power cycle</a>-->
</small></h1>
{% if headnode.dirty %}
<a href ="/projects/{{headnode.project}}/headnodes/{{headnode.name}}/start" class="btn btn-primary btn-sm">Start Headnode</a>
{%else%}
<a href ="/projects/{{headnode.project}}/headnodes/{{headnode.name}}/stop" class="btn btn-danger btn-sm">Stop Headnode</a>
{% endif %}
<div class="row">
<div class="col-md-6">
<hr />
<h3>HNICS</h3>
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr class ="info">
<th class ="info">
HNIC name
</th>
<th>
Actions
</th>
</tr>
</thead>
{% for hnic in headnode.hnics%}
<tr class="active">
<td>{{hnic}}</td>
<td>
<a href="{{headnode.name}}/headnode_delete_hnic/{{hnic}}" class="btn btn-danger btn-sm">Delete</a>
</td>
</tr>
{% endfor %}
</table>
<div class="btn-group" role="group" aria-label="...">
<a href="../../projects/{{headnode.project}}" class="btn btn-default btn-sm">
<i class="glyphicon glyphicon-arrow-left"></i> Back</a>
{% include 'createModal.html' with createModal=createModal%}
{% if headnode.hnics %}
<a href="#" data-toggle="modal"
data-target="#basicModalWarn{{network.label}}" class="btn btn-danger btn-sm"><i class="glyphicon glyphicon-trash"></i> Delete</a>
<div class="modal fade" id="basicModalWarn{{network.label}}" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 class="modal-title" id="myModalLabel">{{headnode.name}}</h3>
</div>
<div class="modal-body">
This headnode cannot be deleted. Please make sure that this headnode has no hnics allocated to it.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{% else %}
{% include "deleteModal.html" with deleteModal=deleteForm %}
{% endif %}
</div>
</div>
</div>
{% endblock %}
<file_sep>from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse, HttpResponseRedirect
from haasplugin.forms import *
from django.conf import settings
import requests
import json
# projects related functions
############################
def projects(request):
"""
List keystone projects available to the user;
attempt to login with credentials
"""
r = requests.get(settings.HAAS_URL + '/projects')
projects = r.json()
createProjectForm = CreateProjectForm()
createProjectForm.action = "/project_create"
createModal = {'header':'Create New Project', 'form':createProjectForm}
context = {'projects': projects, 'createModal':createModal}
return render(request, 'projects.html', {'context': context})
def project_details(request, name):
"""
Get specified project details
"""
project_nodes = requests.get(settings.HAAS_URL + '/project/' + name + '/nodes')
project_nodes = project_nodes.json()
nodes = []
for proj_node in project_nodes:
node = requests.get(settings.HAAS_URL + '/node/' +proj_node)
node = node.json()
nodes.append(node)
networks = requests.get(settings.HAAS_URL + '/project/' + name + '/networks')
networks = networks.json()
project_headnodes = requests.get(settings.HAAS_URL + '/project/' + name + '/headnodes')
project_headnodes = project_headnodes.json()
headnodes = []
for proj_hnode in project_headnodes:
hnode_details = requests.get(settings.HAAS_URL + '/headnode/' + proj_hnode)
hnode_details = hnode_details.json()
headnodes.append(hnode_details)
project = {'name':name, 'project_nodes':project_nodes, 'networks':networks, 'headnodes':project_headnodes}
headnodeForm = HeadnodeForm()
createModal = {'header':'Create New Headnode', 'form':headnodeForm}
networkForm = CreateProjectNetworkForm()
networkForm.action = '/network_project_create'
createNetworkModal = {'header':'Create New Network', 'form':networkForm}
deleteForm = DeleteProjectForm()
deleteForm.action = '/project_delete'
deleteModal = {'header':name, 'form': deleteForm}
return render(request, 'projectDetails.html', {'project': project, 'nodes': nodes, 'hnodes': headnodes, 'deleteForm': deleteModal, 'createHeadnodeModal':createModal, 'createNetworkModal':createNetworkModal})
def project_create(request):
"""
Creates the project with specified name
"""
if request.method == "POST":
form = CreateProjectForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
r = requests.put(settings.HAAS_URL + '/project/' + name)
if(r.status_code == 200):
return redirect('haasplugin.views.projects')
else:
return render(request, 'error.html', {'status': r.status_code})
return render(request, 'error.html', {'status': 'Ahh..'})
def project_delete(request):
"""
Deletes the project with specified name
"""
if request.method == "POST":
form = DeleteProjectForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
r = requests.delete(settings.HAAS_URL + '/project/' + name)
if(r.status_code == 200):
return redirect('haasplugin.views.projects')
else:
return render(request, 'error.html', {'status': r.status_code })
return render(request, 'error.html', {'status': 'Ahh..'})
# headnode related functions
#############################
def headnode(request):
"""
Show the headnode of a project
"""
headnode = [{'name':'headNode1'}]
return render(request, headnode)
def headnode_create(request):
"""
Create the headnode of a project
"""
name = ""
base_img = ""
project = ""
if request.method == "POST":
form = HeadnodeForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
base_img = form.cleaned_data['base_img']
project = form.cleaned_data['project']
context = {'project':project, 'base_img':base_img}
r = requests.put(settings.HAAS_URL + '/headnode/' + name, data = json.dumps(context))
if(r.status_code == 200):
return redirect('haasplugin.views.project_details', project)
else:
return render(request, 'error.html', {'status': r.status_code})
return render(request, 'error.html', {'status': 'Ahh..'})
def headnode_details(request, name):
"""
Show the specified headnode details
"""
headnode = requests.get(settings.HAAS_URL + '/headnode/' + name)
headnode = headnode.json()
addHNICForm = AddHNICForm()
addHNICForm.action = '/headnodes/'+name+'/hnic_add'
createModal = {'header': 'Add New HNIC', 'form': addHNICForm, 'btnText':'Register HNIC'}
deleteHeadnode = DeleteHeadnodeForm(initial={'project': headnode['project']})
deleteHeadnode.action = '/headnode_delete'
deleteModal = {'header':name, 'form':deleteHeadnode}
return render(request, 'headnodeDetails.html', {'headnode': headnode, 'createModal': createModal, 'deleteForm':deleteModal})
def headnode_delete_hnic(request, name, hnic):
"""
Delete the specified hnic from given headnode
"""
r = requests.delete(settings.HAAS_URL + '/headnode/'+name+'/hnic/'+hnic)
if r.status_code == 200:
return redirect('haasplugin.views.headnode_details', name)
else:
return render(request, 'error.html', {'status': r.status_code })
def hnic_add(request, name):
"""
Adds the specified hnic to headnode
"""
if request.method == "POST":
form = AddHNICForm(request.POST)
if form.is_valid():
hnic = form.cleaned_data["hnic"]
r = requests.put(settings.HAAS_URL + '/headnode/'+ name +'/hnic/' + hnic)
if(r.status_code == 200):
return redirect('haasplugin.views.headnode_details', name)
else:
return render(request, 'error.html', {'status': r})
return render(request, 'error.html', {'status': 'Ahh..'})
def headnode_delete(request):
"""
Deletes the headnode
"""
if request.method == 'POST':
form = DeleteHeadnodeForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
project = form.cleaned_data["project"]
r = requests.delete(settings.HAAS_URL + '/headnode/' + name)
if(r.status_code == 200):
return redirect('haasplugin.views.project_details', project)
else:
return render(request, 'error.html', {'status': r.status_code })
return render(request, 'error.html', {'status': 'Invalid form'})
return render(request, 'error.html', {'status': 'Ahh..'})
def headnode_start(request, project, name):
r = requests.post(settings.HAAS_URL + '/headnode/' + name + '/start')
if(r.status_code == 200):
return redirect('haasplugin.views.headnode_details', name)
else:
return render(request, 'error.html', {'status': r.status_code })
return render(request, 'error.html', {'status': 'Ahh..'})
def headnode_stop(request, project, name):
r = requests.post(settings.HAAS_URL + '/headnode/' + name + '/stop')
if(r.status_code == 200):
return redirect('haasplugin.views.headnode_details', name)
else:
return render(request, 'error.html', {'status': r.status_code })
return render(request, 'error.html', {'status': 'Ahh..'})
# node related functions
#################################
def allocate_node(request, name):
"""
Attaches the specified node to the project
"""
node_name = ""
if request.method == 'POST':
form = AllocateNodeForm(request.POST)
if form.is_valid():
node_name = form.cleaned_data['node_name']
payload = {'node':node_name}
r = requests.post(settings.HAAS_URL + '/project/' + name + '/connect_node', data = json.dumps(payload))
if r.status_code == 200:
return redirect('haasplugin.views.project_details', name)
else:
return render(request, 'error.html', {'status': 'form is not valid' })
project = {'name':name}
nodes = requests.get(settings.HAAS_URL + '/free_nodes')
nodes = nodes.json()
context = {'project' : project, 'nodes':nodes}
return render(request, 'allocateNode.html', {'context': context, 'nnode': node_name})
def detach_node(request, name):
"""
Detaches the node from the specified project
"""
if request.method == 'POST':
form = DetachNodeForm(request.POST)
if form.is_valid():
node_name = form.cleaned_data['node_name']
payload = {'node':node_name}
r = requests.post(settings.HAAS_URL + '/project/' + name + '/detach_node', data = json.dumps(payload))
if r.status_code == 200:
return redirect('haasplugin.views.project_details', name)
else:
return render(request, 'error.html', {'status': r.status_code})
else:
return render(request, 'error.html', {'status': "form's not valid" })
return redirect('haasplugin.views.project_details', name)
def node_details(request, name):
"""
Show node details: Name, Availabiltiy, Associated NICs
"""
node = requests.get(settings.HAAS_URL + '/node/' + name)
node = node.json()
deleteNode = DeleteNodeForm()
deleteNode.action = '/node_delete'
deleteForm = {'header': name, 'form':deleteNode}
registerNic = RegisterNodeNicForm()
registerNic.action = '/nodes/' +name+ '/node_register_nic'
return render(request, 'nodeDetails.html', {'node': node, 'deleteForm':deleteForm, 'registerNic':registerNic})
def node_powercycle(request, name):
"""
Power cycles the node
"""
if request.method == 'POST':
requests.post(settings.HAAS_URL + '/node/' + name + '/power_cycle')
return redirect('haasplugin.views.node_details', name)
payload = {'node':name}
r = requests.post(settings.HAAS_URL + '/node/' + name + '/power_cycle')
return redirect('haasplugin.views.node_details', name)
def node_register_nic(request, name):
"""
Register nic to the node
"""
if request.method == 'POST':
form = RegisterNodeNicForm(request.POST)
if form.is_valid():
nic = form.cleaned_data['nic']
macaddr = form.cleaned_data['macaddr']
payload = {'macaddr':macaddr}
r = requests.put(settings.HAAS_URL + '/node/' + name + '/nic/' + nic, data = json.dumps(payload))
if r.status_code == 200:
return redirect('haasplugin.views.node_details', name)
else:
return render(request, 'error.html', {'status': r.status_code })
else:
return render(request, 'error.html', {'status': "form's not valid" })
def node_delete_nic(request, name, nic):
"""
Deletes the nic from the node
"""
r = requests.delete(settings.HAAS_URL + '/node/' + name + '/nic/' + nic)
if r.status_code == 200:
return redirect('haasplugin.views.node_details', name)
else:
return render(request, 'error.html', {'status': r.status_code })
def nodes(request):
"""
List all nodes available to the user;
"""
r = requests.get(settings.HAAS_URL + '/nodes')
all_nodes = r.json()
nodes = []
for proj_node in all_nodes:
node = requests.get(settings.HAAS_URL + '/node/' +proj_node)
node = node.json()
nodes.append(node)
createNodeForm = CreateNodeForm()
createNodeForm.action = '/node_create'
createModal = {'header':'Create New Node', 'form':createNodeForm}
context = {'all_nodes':all_nodes,'nodes':nodes, 'createModal':createModal}
return render(request, 'nodes.html', {'context': context})
def node_create(request):
"""
Creates the node
"""
if request.method == "POST":
form = CreateNodeForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
ipmi_host = form.cleaned_data["ipmi_host"]
ipmi_user = form.cleaned_data["ipmi_user"]
ipmi_pass = form.cleaned_data["ipmi_pass"]
payload = {'ipmi_host' : ipmi_host, 'ipmi_user' : ipmi_user, 'ipmi_pass' : ipmi_pass}
r = requests.put(settings.HAAS_URL + '/node/' + name, data = json.dumps(payload))
if(r.status_code == 200):
return redirect('haasplugin.views.nodes')
else:
return render(request, 'error.html', {'status': r.status_code})
return render(request, 'error.html', {'status': 'Ahh..'})
def node_delete(request):
"""
Deletes the node
"""
if request.method == "POST":
form = DeleteNodeForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
r = requests.delete(settings.HAAS_URL + '/node/' + name)
if(r.status_code == 200):
return redirect('haasplugin.views.nodes')
else:
return render(request, 'error.html', {'status': r.status_code })
# networks related functions
##############################
def network_create(request):
"""
Creates the network
"""
if request.method == "POST":
form = CreateNetworkForm(request.POST)
if form.is_valid():
network = form.cleaned_data["network"]
creator = "admin"
access = ""
net_id = ""
payload = {'creator' : creator, 'access' : access, 'net_id' : net_id}
r = requests.put(settings.HAAS_URL + '/network/' + network, data = json.dumps(payload))
if(r.status_code == 200):
return redirect('haasplugin.views.networks')
else:
return render(request, 'error.html', {'status': r.status_code})
return render(request, 'error.html', {'status': 'Ahh..'})
def network_project_create(request):
"""
Creates a projects private network
"""
if request.method == "POST":
form = CreateProjectNetworkForm(request.POST)
if form.is_valid():
network = form.cleaned_data["network"]
creator = "admin"
access = form.cleaned_data["access"]
net_id = ""
payload = {'creator' : creator, 'access' : access, 'net_id' : net_id}
r = requests.put(settings.HAAS_URL + '/network/' + network, data = json.dumps(payload))
if(r.status_code == 200):
return redirect('haasplugin.views.project_details', access)
else:
return render(request, 'error.html', {'status': r.status_code})
return render(request, 'error.html', {'status': 'Ahh..'})
def networks(request):
"""
List all networks
"""
r = requests.get(settings.HAAS_URL + '/networks')
networks = r.json()
createNetwork = CreateNetworkForm()
createNetwork.action = "/network_create"
createModal = {'header':'Create New Network', 'form':createNetwork}
deleteForm = DeleteNetworkForm()
deleteForm.action = '/network_delete'
context = {'networks':networks, 'createModal': createModal, 'deleteForm':deleteForm }
return render(request, 'networks.html', {'context': context})
def network_delete(request):
"""
Deletes the network with specified name
"""
if request.method == "POST":
form = DeleteNetworkForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
r = requests.delete(settings.HAAS_URL + '/network/' + name)
if(r.status_code == 200):
return redirect('haasplugin.views.networks')
else:
return render(request, 'error.html', {'status': r.status_code })
return render(request, 'error.html', {'status': 'Ahh..'})
<file_sep>#Summary of meeting 2/11/2015
----------
##To-do
- Create the UI Design Prototype (Sketch) with pen and paper
- templates
- start the Django project
##Actions
- Create new
- Query
- Delete
## Architecture
- project - lowest level
- network
- node - dependent network
- headnode - dependent network
<file_sep>{% extends "base.html" %}
{% block content %}
<div class="col-md-8">
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr class = "info">
<th>Node Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for node in context.all_nodes %}
<tr class = "active">
<td>{% block node%}
{% for element in context.nodes %}
{% if element.name == node %}
{% include "node.html" %}
{% endif %}
{% endfor%}
{% endblock %}
</td>
<td> <a href="/nodes/{{node}}" class="btn btn-success btn-sm">
<span class = "glyphicon glyphicon-cog" aria-hidden = "true"> </span>
Manage</a></td>
</tr>
{% endfor%}
</tbody>
</table>
</div>
<div class="col-md-10">
{% include 'createModal.html' with createModal=context.createModal %}
</div>
<script type="text/javascript">
window.onload=function () {
$('#node').addClass('active');
};
</script>
{% endblock %}
<file_sep>from django import forms
class CreateProjectForm(forms.Form):
"""description of class"""
name = forms.CharField(label='Project name', widget=forms.TextInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class DeleteProjectForm(forms.Form):
"""description of class"""
name = forms.CharField(label='Delete Project')
action = '/projects/delete'
back_text = ''
submit = ''
class CreateNodeForm(forms.Form):
"""description of class"""
name = forms.CharField(label='Node name', widget=forms.TextInput(attrs={'required':'required'}))
ipmi_host = forms.CharField(label='IPMI host', widget=forms.TextInput(attrs={'required':'required'}))
ipmi_user = forms.CharField(label='IPMI user', widget=forms.TextInput(attrs={'required':'required'}))
ipmi_pass = forms.CharField(label='IPMI pass', widget=forms.PasswordInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class DeleteNodeForm(forms.Form):
"""description of class"""
name = forms.CharField(label='Delete Node', widget=forms.TextInput(attrs={'required':'required'}))
action = ''
back_text = ''
submit = ''
class RegisterNodeNicForm(forms.Form):
"""description of class"""
nic = forms.CharField(label='NIC name', widget=forms.TextInput(attrs={'required':'required'}))
macaddr = forms.CharField(label='Mac Address', widget=forms.TextInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class AllocateNodeForm(forms.Form):
node_name = forms.CharField(widget=forms.HiddenInput())
action = ''
submit = ''
back_text = ''
class DetachNodeForm(forms.Form):
node_name = forms.CharField(widget=forms.HiddenInput())
submit = "Detach"
class HeadnodeForm(forms.Form):
name = forms.CharField(label='Headnode Name', widget=forms.TextInput(attrs={'required':'required'}))
base_img = forms.CharField(label='Base Image', widget=forms.TextInput(attrs={'required':'required'}))
project = forms.CharField(label='Project', widget=forms.TextInput(attrs={'required':'required'}))
action = '/headnode_create/'
back_link = '/projects/details/'
back_text = ''
submit = ''
class AddHNICForm(forms.Form):
"""description of class"""
hnic = forms.CharField(label='HNIC Name', widget=forms.TextInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class CreateNetworkForm(forms.Form):
"""description of class"""
network = forms.CharField(label='Network name', widget=forms.TextInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class CreateProjectNetworkForm(forms.Form):
"""description of class"""
network = forms.CharField(label='Network name', widget=forms.TextInput(attrs={'required':'required'}))
access = forms.CharField(label='Project', widget=forms.TextInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class DeleteHeadnodeForm(forms.Form):
name = forms.CharField(label='Headnode', widget=forms.TextInput(attrs={'required':'required'}))
project = forms.CharField(label='',widget=forms.HiddenInput(attrs={'required':'required'}))
action = ''
back_link = ''
back_text = ''
submit = ''
class DeleteNetworkForm(forms.Form):
name = forms.CharField(label='Delete Network')
action = '/networks/delete'
back_text = ''
submit = ''
<file_sep># moc-gui-plugins
Plugin architecture for The Mass Open Cloud GUI
Note: There is an alternate setup in the file "Alternate-setup-for-Mac.md
". But this generic setup should work for Linux based systems.
##Install and Run a HaaS Server
<b>1. Clone the HaaS repo:</b>
$git clone https://github.com/CCI-MOC/haas
<b>2. Install HaaS:</b>
$cd haas
$sudo python setup.py install
<b>3. Create a system user called "haas_user": </b>
$sudo useradd haas_user -d /var/lib/haas -m -r
<b>4. Create a HaaS configuration file:</b>
haas.cfgcontains settings for both the CLI client and the server.
Copy one of the haas.cfg* files in examples/ into:
a. haas main directory
b. /etc
<b>5. Create a symlink to the haas cfg in the HaaS user's home directory:</b>
$sudo ln -s /etc/haas.cfg /var/lib/haas/
<b>6. Intialize the HaaS Database:</b>
$haas init_db
<b>7. Run the HaaS server by following the instructions [here]:</b>
https://github.com/CCI-MOC/haas/blob/master/HACKING.rst
##Install and Run HaaS UI
<b>1. Clone Haas UI into the folder of your choice: </b>
$git clone https://github.com/BU-EC500-SP15/moc-gui-plugins
<b>2. Create a new virtual environment using virtualenv</b>
$virtualenv venv
You may replace 'venv' with a name of your choice, but remember to do so for the entire tutorial.
<b>3. Enter this virtual environment using</b>
$source venv/bin/activate
The path is different if you named the virtualenv differently.
<b>4. While the venv is active and in the .git directory for moc-gui-plugins, install necessary libraries</b>
$pip install -r requirements.txt
<b>5. Start the Haas Plugin server locally</b>
$python manage.py runserver 9000
We recommend using python version 2.7. You run this on any port except 5000 (HaaS server port) or 8000 (MOC UI port).
## Setup and Run the MOC UI
<b>1. Clone the MOC UI repo </b>
$git clone https://github.com/BU-EC500-SP15/ui.git
<b>2. Start a Django Project </b>
a. create python virtual enviornment using "$virtualenv [env-name]"
b. source environment using $"source [env-name]/bin/activate"
c.install requirements using "$pip install -r requirements.txt"
d. create database with "$./syncdb.sh"
e. create folder to hold session ids with "$mkdir session"
f. run server with "$./runserver.sh"
<b> 3. Run the UI </b>
a. open browser and point it to localhost:8000
b. Register as a new user
<b> For more details, refer to the MOC UI page: https://github.com/CCI-MOC/ui.git </b>
<file_sep># moc-gui-plugins
Plugin Architecture for the Mass Open Cloud GUI, Alternate Setup
##Install and Run a HaaS Server
<b>1. Open terminal (1) and clone the HaaS repo:</b>
$git clone https://github.com/CCI-MOC/haas.git
<b>2. Create a HaaS configuration file:</b>
haas.cfg contains settings for both the CLI client and the server. Copy haas.cfg.dev-no-hardware file in examples/ into:
a. haas main directory (the super directory of /examples/)
b. rename the file to haas.cfg
<b>3. Create a new virtual environment using virtualenv</b>
This setup requires having the virtual environment directory inside of the haas directory.
<pre>
$cd haas
$virtualenv venv
</pre>
You may replace 'venv' with a name of your choice for [env-name], but remember to use the same virtual environment for the entire setup.
<b>3. Enter this virtual environment using:</b>
<pre>
$source venv/bin/activate
</pre>
The path is different if you named the virtualenv differently.
<b>4. Install necessary files</b>
<pre>
$pip install -e .
</pre>
<b>5. Intialize the HaaS Database:</b>
<pre>
$haas init_db
</pre>
Open a new terminal (2). Go back to the haas directory and reactivate the virtual environment.
<b>5. Run the HaaS Server</b>
<pre>
$haas serve
</pre>
Open another new terminal (3). Go back to the haas directory and reactivate the virtual environment.
<b>6. Run the HaaS Server Networks</b>
<pre>
$haas serve_networks
</pre>
The HaaS server should be up and running, and ready to interface with REST calls from the HaaS UI.
##Install and Run HaaS UI
<b>1. Open a new terminal (4).
<b>2. Clone Haas UI into the directory of your choice, but preferably in the same location as haas: </b>
<pre>
$git clone https://github.com/BU-EC500-SP15/moc-gui-plugins.git
</pre>
<b>3. Reactivate the virtual environment in this terminal. Then go back to the moc-gui-plugins directory.
</b>
<b>4. Install Django </b>
<pre>
$pip install django
</pre>
<b>5. Start the Haas Plugin server locally</b>
<pre>
$python manage.py runserver 9000
</pre>
We recommend using python version 2.7. Technically, you can run this on any port except 5000, which is reserved for HaaS server, and 8000, which is reserved for the MOC UI Django project by default.
<b>6. Errors </b>
At this point, if you get errors it might be because there are additional functional HaaS APIs added for the HaaS UI but they're not currently implemented in HaaS.
To fix this, go to the moc-gui-plugins directory. Go to "for new haas", and copy the two files: api.py, cli.py. Go to the haas directory. Go into the second haas directory. Copy these files into this directory. This operation updates the HaaS API and CLI.
These files are not actually updated while the HaaS server is running. Stop them, then deactivate the virtual environment (with $deactivate). Restart the virtual environment and get the server and server-networks running again.
## Setup and Run the MOC UI
<b>1. Clone the MOC UI repo </b>
a. open a new terminal (5)
b. git clone https://github.com/BU-EC500-SP15/ui.git
<b>2. Start a Django Project </b>
a. activate the virtual environment again for this terminal
b. go back to the ui/ directory
c. install requirements using "$pip install -r requirements.txt"
d. create database with "./syncdb.sh"
e. create folder to hold session ids with "mkdir session"
f. run server with "./runserver.sh"
<b> 3. Run the UI </b>
Note: These steps may not be necessary.
a. open browser and point it to localhost:8000
b. Register as a new user
<b> For more details, refer to the MOC UI page: https://github.com/CCI-MOC/ui</b>
| ce1dba3908ec13d41d518a4380e2d5513659f7f6 | [
"Markdown",
"Python",
"Text",
"HTML"
] | 11 | Text | BU-EC500-SP15/moc-gui-plugins | f056b002ba20474b0b7441554341628eedb02bed | 976d55556d5c640ff65b4459564ccec95ff457b0 |
refs/heads/master | <file_sep>'use strict';
var container = require('elephas-container');
var app = container.get('app', app);
exports.get = function(uri, func) {
return app.get(uri, func);
};
exports.post = function(uri, func) {
return app.post(uri, func);
};
exports.put = function(uri, func) {
return app.put(uri, func);
};
exports.delete = function(uri, func) {
return app.delete(uri, func);
};
| 1fdd2232de0d8d0ac1c874eae0d742ae93393f53 | [
"JavaScript"
] | 1 | JavaScript | ingtk/elephas-web | f4d153082604a2e414cdb180f5bd947bed022a76 | 607e047252c5cae5e98863de594bc1c7e2cb8887 |
refs/heads/master | <file_sep>import React, {Component} from 'react';
import "./bootstrap.css";
// var list = [1, 2, 3, 4];
// var list2 = list.map(function(v, i){
// return v*v
// })
// console.log(list2)
// var color = (...)? "red" : "blue";
// console.log( eval("3 + 4 * 5") )
class TicTacToe extends Component {
constructor(props) {
super(props);
this.state = {
currentPlayer: "X",
board: ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
}
}
handleClick(btnIndex) {
var cp = this.state.currentPlayer;
var b = this.state.board;
if (b[btnIndex] === "-") {
b[btnIndex] = cp;
if (cp === "X") {
cp = "O";
} else {
cp = "X";
}
this.setState({
board: b,
currentPlayer: cp
});
this.analyze();
}
}
analyze() {
console.log("ANALYZE")
var b = this.state.board;
if (b[0]===b[1] && b[1]===b[2] && b[1] !== "-")
{
alert(b[1] + " has won")
}
else if (b[3] === b[4] && b[4] === b[5] && b[4] !== "-") {
alert(b[1] + " has won")
}
else if (b[6] === b[7] && b[7] === b[8] && b[8] !== "-") {
alert(b[1] + " has won")
}
else if (b[0] === b[3] && b[3] === b[6] && b[0] !== "-") {
alert(b[1] + " has won")
}
else if (b[1] === b[4] && b[4] === b[7] && b[1] !== "-") {
alert(b[1] + " has won")
}
else if (b[2] === b[5] && b[5] === b[8] && b[8] !== "-") {
alert(b[1] + " has won")
}
else if (b[0] === b[4] && b[4] === b[8] && b[8] !== "-") {
alert(b[1] + " has won")
}
else if(b[2] === b[4] && b[4] === b[6] && b[2] !== "-") {
alert(b[1] + " has won")
}
else if (b[0] !== "-" && b[1] !== "-" && b[2] !== "-" && b[3] !== "-" && b[4] !== "-" && b[5] !== "-" && b[6] !== "-" && b[7] !== "-" && b[8] !== "-")
{
alert("DRAW")
}
// TODO More conditions
}
render(){
return(
<div class = "container">
<h2 class = "text-center mt-4 text-primary">TicTacToe</h2>
{
this.state.board.map(function(v, i) {
return (
<span key={i}>
{
(i % 3 === 0) ? <br /> : null
}
<button style={{width:50}} class = "btn btn-dark m-1 " onClick={() => { this.handleClick(i) }}>
{v}
</button>
</span>
);
}, this)
}
</div>
)
}
}
export default TicTacToe;
<file_sep>import React from 'react';
import { render } from 'react-dom';
import TicTacToe from './TicTacToe';
import "./bootstrap.css";
const App = () => (
<div class = "container">
<h2 class = "display-4 text-center bg-danger text-light py-4">My App</h2>
<TicTacToe/>
</div>
);
render(<App />, document.getElementById('root'));
| a9336ff840514d0cd0ae9dd340d8d2b18e746723 | [
"JavaScript"
] | 2 | JavaScript | rahul14314/TicTacToe | ec2f714ee13ec07225cf77d37e5b2c06a5f070aa | 41e1b76efff6e31e8a3507711d472fb91c001980 |
refs/heads/master | <repo_name>sanchit-ahuja/Hashcode-2020<file_sep>/hashcode_e.cpp
#include<bits/stdc++.h>
#include<fstream>
using namespace std;
vector<int> scores;
bool comparePairs(const int a, const int b)
{
return scores[a] > scores[b];
}
int main () {
ifstream file;
ofstream ofile;
file.open("f_libraries_of_the_world.txt");
ofile.open("hashcode_f_sol.txt");
int books, libs, days;
int score;
file>>books>>libs>>days;
for (int k=0; k<books; k++) {
file>>score;
scores.push_back(score);
}
multimap<double, vector<vector<int> >, greater<int> > m;
multimap<double, vector<vector<int> >, greater<int> >::iterator it;
pair<double, vector<vector<int> > > p;
int a, b, c, d, i = 0;
cout<<"\n\n-- Reading from file --\n\n";
while (file>>a) {
file>>b;
file>>c;
p = make_pair((double)(pow(a,0.5)*c)/(double)(b), vector<vector<int> >(2, vector<int>(0,0)));
p.second[0].push_back(a);
p.second[0].push_back(b);
p.second[0].push_back(c);
p.second[0].push_back(i);
for (int k=0; k<a; k++) {
file>>d;
p.second[1].push_back(d);
}
sort(p.second[1].begin(), p.second[1].end(), comparePairs);
m.insert(p);
i++;
}
cout<<"\n\n-- Read from file -- \n\n";
int day = 0;
int count = 0;
map<int, int> s;
for (it = m.begin(); it != m.end(); it++) {
day += (*it).second[0][1];
if (day>=days)
break;
count++;
vector<int> v;
for (int j=0; j<(*it).second[0][0]; j++) {
if (s.find((*it).second[1][j]) == s.end()) {
v.push_back((*it).second[1][j]);
s.insert(make_pair((*it).second[1][j], 0));
}
}
ofile<<(*it).second[0][3]<<" "<<v.size()<<endl;
for (int j=0; j<v.size(); j++)
ofile<<v[j]<<" ";
ofile<<endl;
}
cout<<count<<endl;
file.close();
ofile.close();
return 0;
}<file_sep>/README.md
# Hashcode-2020
This repository contains our team Rand0mCoders implementation of Hashcode 2020 problem.
### Team Members
1. [<NAME>](https://github.com/sarthak-sehgal)
2. [<NAME>](https://github.com/AbhinavTuli)
3. [<NAME>](https://github.com/sanchit-ahuja)
4. [<NAME>](https://github.com/adhyay2000)
The solution for B and C input files have been implemented in Python and for E and F in C++.
This was our first attempt at HashCode. We were able to bag an international rank of 1161 out of 10000+ teams and a rank of 121 in India amongst 3000+ teams.
<file_sep>/first.py
from collections import defaultdict,OrderedDict
def readfile(filename):
library_dict = {}
with open(filename,'r') as f:
data = f.readlines()
# print(type(data[0]))
B,L,D = data[0].split()
for i in range(1,int(len(data)/2)):
temp_arr = [int(i) for i in data[2*i].split()]
c = temp_arr[1]
val_books = [int(i) for i in data[2*i+1].split()]
library_dict[i-1] = [c,val_books]
# print((library_dict))
return library_dict
def sol_a(library_dict):
# sorted_dict = {k: v for k, v in sorted(library_dict.items(), key=lambda item: item[1][0])}
sorted_dict = sorted(library_dict.items(),key = lambda x: x[1][0])
# print(sorted_dict[i][0])
libraries = []
# libraries = [i[0] for i in sorted_dict]
# days = [i[1][0] for i in sorted_dict]
# print(libraries)
total = 0
for i in sorted_dict:
total += i[1][0]
if total >= 1000:
break
libraries.append(i[0])
with open("ans.txt",'w') as f:
f.write('90' + '\n')
# f.write(libraries_str)
for i in libraries:
# print((library_dict[i][1]))
f.write(str(i) + ' '+ str(len(library_dict[i][1]))+ '\n')
temp_arr_2 = [str(j) for j in library_dict[i][1]]
temp_str = ' '.join(temp_arr_2)
f.write(temp_str + '\n')
def sol_b(library_dict):
data_book = {}
val_arrs = []
with open('c_incunabula.txt') as f:
data = f.readlines()
# val_arrs = [int(i) for i in data[0].split()]
temp_arr = [int(i) for i in data[1].split()]
for i in range(len(temp_arr)):
data_book[i] = temp_arr[i]
# B,L,D = val_arrs
library_dict = readfile('c_incunabula.txt')
score_save = {}
for i in range(len(library_dict)):
temp_val = library_dict[i][1]
total = 0
for j in temp_val:
total += data_book[j]
score_save[i] = [(total)**4/((library_dict[i][0]))**5]
sorted_dict = sorted(score_save.items(),key = lambda x: x[1],reverse = True)
sorted_dict = OrderedDict(sorted_dict)
# print(type(sorted_dict))
total_days = 0
with open('ans2.txt','w') as f:
f.write('10000'+ '\n')
for key,val in sorted_dict.items():
f.write(str(key) + ' ' + str(len(library_dict[key][1]))+ '\n')
temp_arr_2 = [str(j) for j in library_dict[key][1]]
temp_str = ' '.join(temp_arr_2)
f.write(temp_str + '\n')
if __name__ == "__main__":
library_dict = readfile("c_incunabula.txt")
score_save = sol_b(library_dict)
| f1d67d5bc367ee33b46c278d6918270f5247d119 | [
"Markdown",
"Python",
"C++"
] | 3 | C++ | sanchit-ahuja/Hashcode-2020 | 244fb81e763751547f5ef277841816489ad7d275 | 08d323f9f9188897a1f71fdd74877f1b1d9975d4 |
refs/heads/master | <file_sep>package main
import (
"fmt"
"sync"
"time"
)
type Thing struct {
Ch chan bool
l int
*sync.Mutex
}
func NewThing() *Thing {
return &Thing{Ch: make(chan bool)}
}
func (t *Thing) Wait() {
t.l++
<-t.Ch
}
func (t *Thing) Broadcast() {
for i := 0; i < t.l; i++ {
t.Ch <- false
}
t.l = 0
}
func DoA(a int, c *Thing) {
fmt.Println("Waitin on ", a)
c.Wait()
fmt.Println("Ok, doing ", a)
time.Sleep(time.Second)
fmt.Println("Ok, finished ", a)
}
func Runner(c *Thing) {
c.Broadcast()
}
func main() {
c := NewThing()
go DoA(1, c)
go DoA(2, c)
go DoA(3, c)
time.Sleep(time.Second)
go Runner(c)
time.Sleep(time.Second * 5)
fmt.Println("Here")
}
<file_sep>"# temp-subscribe"
| 2f62a136bd29d3b685303fb206aa34988ea41ebf | [
"Markdown",
"Go"
] | 2 | Go | xcodder/temp-subscribe | a0df0ca8aa74d932d72dbb3b40c49bfd96fe3d55 | 94fda5bac3d9e04c998b719faf5618f4788c8621 |
refs/heads/master | <repo_name>sindriing/schelling-segregation<file_sep>/schelling.py
# <NAME>
# 11/03/2020
import argparse
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
def get_neighbours(x, y, g):
return g[x - 1 : x + 2, y - 1 : y + 2]
def get_neighbours_location(x, y):
return [
(i, j)
for i in range(x - 1, x + 2)
for j in range(y - 1, y + 2)
if grid[i, j] != 0
]
def happy(x, y, g):
return happy_val(x, y, g) >= PREJUDICE
def happy_val(x, y, g):
me = g[x, y]
surrounding = get_neighbours(x, y, g)
assert surrounding.shape == (3, 3)
goodNeighbours = 0
for agent in surrounding.flatten():
if me == agent:
goodNeighbours += 1
elif agent == 0:
goodNeighbours += 0.5
return goodNeighbours
def switcheroo(x, y, grid):
mehappy = happy(x, y, grid)
unhappies = []
happies = []
for i, j in get_neighbours_location(x, y):
if i == x and j == y:
continue
elif not happy(i, j, grid) and not mehappy and grid[x, y] != grid[i, j]:
unhappies.append((i, j))
elif (
happy(i, j, grid)
and not mehappy
and grid[x, y] != grid[i, j]
and grid[i, j] != 0
):
if 9 - happy_val(i, j, grid) >= happy_val(x, y, grid):
happies.append((i, j))
if len(unhappies) != 0: # Try to swap with some other unhappy agent
nx, ny = random.choice(unhappies)
elif len(happies) != 0: # Swap with a happy agent if it doesn't make me worse off
nx, ny = random.choice(happies)
else:
return (-1, -1)
grid[x, y], grid[nx, ny] = grid[nx, ny], grid[x, y]
return nx, ny
def add_frame(arr, ims):
temp = plt.imshow(
arr[1:-1, 1:-1], animated=True, vmin=0.70, vmax=args.players + 0.1
)
ims.append([temp])
def parse_arguments():
parser = argparse.ArgumentParser(description="Schellings Segregation Model")
parser.add_argument(
"mode",
choices=["gif", "image", "live"],
help="should the program save the simulation as a gif, save the final result as a png or show the simulation on screen?",
)
parser.add_argument(
"-n",
"--name",
default="schelling" + datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S"),
help="name for the created gif",
)
parser.add_argument(
"-s", "--size", type=int, default=50, help="Size of the simulation. Default:50"
)
parser.add_argument(
"-g",
"--groups",
type=int,
default=2,
choices=[2, 3, 4],
help="number of different groups in the model. default:2",
)
parser.add_argument(
"-d",
"--prejudice",
type=int,
default=4,
choices=[1, 2, 3, 4, 5, 6, 7],
help="How many similar neighbours the agents want to be happy: default:4",
)
parser.add_argument(
"-i",
"--iterations",
type=int,
default=8,
help="number of simulation iterations performed. default:8",
)
parser.add_argument(
"-m",
"--moves_per_frame",
type=int,
default=0,
help="number of moves per saved image in the gif. default:size/10+1",
)
parser.add_argument(
"-v",
"--verbose",
type=bool,
default=True,
help="Display additional information during runtime. default:True",
)
args = parser.parse_args()
if args.moves_per_frame == 0:
args.moves_per_frame = args.size // 10 + 1
if args.iterations <= 0:
print("Iterations must be positive")
if args.moves_per_frame <= 0:
print("moves_per_frame must be positive")
args.prejudice += 1 # adjustmets because prejudice checks count the agent itself
return args
if __name__ == "__main__":
args = parse_arguments()
SIZE = args.size
PREJUDICE = args.prejudice
# Initialisation
fig = plt.figure(figsize=[SIZE / 10, SIZE / 10])
plt.axis("off")
fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
imgrid = []
start = np.random.randint(low=1, high=args.players + 1, size=(SIZE, SIZE))
grid = np.zeros((SIZE + 2, SIZE + 2))
grid[1:-1, 1:-1] = start
switchCount = 0
# Keeping track of active agents speeds up processing
active = [(i, j) for i in range(1, SIZE) for j in range(1, SIZE)]
random.shuffle(active)
active = set(active)
nextActive = set()
for iteration in range(args.iterations):
if args.verbose:
print("Iteration", iteration)
for x, y in active:
# do switches
if not happy(x, y, grid):
nx, ny = switcheroo(x, y, grid)
if (nx, ny) != (-1, -1):
nextActive.update(get_neighbours_location(x, y))
nextActive.update(get_neighbours_location(nx, ny))
if args.mode == "gif" and switchCount % args.moves_per_frame == 0:
add_frame(grid, imgrid)
switchCount += 1
active = nextActive
nextActive = set()
if args.verbose:
print("Number of active agents: ", len(active))
if args.verbose:
print(f"Total number of switches: {switchCount}")
# Saving
if args.mode == "image":
plt.imshow(grid[1:-1, 1:-1], vmin=0.75, vmax=args.players + 0.1)
plt.savefig(f"images/{args.name}.png", bbox_inches="tight")
if args.mode == "gif":
print(f"Number of frames in gif: {len(imgrid)}")
ani = animation.ArtistAnimation(
fig, imgrid, interval=100, blit=False, repeat_delay=5000
)
ani.save(f"gifs/{args.name}.gif", writer="pillow", fps=60)
if args.mode == "live":
plt.show()
<file_sep>/README.md
# schelling-segregation
A model for simulating Schelling's model of ethnic residential segregation and generating gifs or images from the resulting simulation. The model can generate gifs of the whole simulation or just an image of the final result.
## Demo
### A schelling simulation with the default settings

### The final image of a three group simulation on a 100x100 grid
<img src="images/p3s100.png" alt="Your image title" width="550"/>
## Basic
python schelling.py gif
python schelling.py image
## Advanced
To see the full list of current parameters, details and defaults run:
`python3 schelling.py -h`\
Example of advanced run:\
`python3 schelling.py image --groups 3 --size 90 --prejudice 4 --iterations 20 --moves-per-frame 8`
| a2490e85287aa2c965a0126319b1329ef8e57bc6 | [
"Markdown",
"Python"
] | 2 | Python | sindriing/schelling-segregation | df3cc593edbb5bee2578f20cf6fad9ac1c4d6126 | 0deb9eebfbd0e961d266a06fa3db99679530451d |
refs/heads/master | <repo_name>aashishogale/regex-exp<file_sep>/registration.sh
#! /bin/bash
read -p "Enter first name" fname
fnamepat="^[A-Z][a-z][a-z]+$";
if [[ $fname =~ $fnamepat ]]
then
echo "Valid first name";
else
echo "Invalid first name";
fi
read -p "Enter Last name" lname
lnamepat="^[A-Z][a-z][a-z]+$";
if [[ $lname =~ $lnamepat ]]
then
echo "Valid last name";
else
echo "Invalid last name";
fi
read -p "Enter Email id" email
emailpat="^abc([\.-]?)[a-z0-9]*@[a-z]+\.[a-z]+(\.[a-z])*$";
if [[ $email =~ $emailpat ]]
then
echo "Valid email address";
else
echo "Invalid email address";
fi
read -p "Enter Mobile number" mob
mobpat="^[0-9]{2}[[:space:]][0-9]{10}$";
if [[ $mob =~ $mobpat ]]
then
echo "Valid mobile number";
else
echo "Invalid mobile number";
fi
read -p "Enter password" pass
passpat1="^([a-zA-Z0-9@#!]){8}$";
passpat2="^([a-z0-9@#!]*)[A-Z]+([a-z0-9@#!]*)$";
passpat3="^[a-zA-Z@#!]*[0-9]+[a-zA-Z@#!]*$";
passpat4="^([a-zA-Z0-9]*)[^a-zA-Z_0-9\s]([a-zA-Z0-9]*)$";
if [[ $pass =~ $passpat1 ]]
then
if [[ $pass =~ $passpat2 ]]
then
if [[ $pass =~ $passpat3 ]]
then
if [[ $pass =~ $passpat4 ]]
then
echo "Perfect password"
else
echo "Please enter at least one special char";
fi
else
echo "Please enter at least one digit";
fi
else
echo "Please enter at least one caps letter";
fi
else
echo "Your password should be of 8 length";
fi
<file_sep>/userRegistrationRegex.sh
#!/bin/bash
echo "---------Welcome to User Registration-----------"
function validateFirstName(){
namepattern="^[A-Z]([a-z]{2}+)+$"
if [[ $1 =~ $namepattern ]]
then
echo "Valid Name"
else
echo "Invalid Name"
fi
}
function validateEmail(){
emailpattern="\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b"
if [[ $1 =~ $emailpattern ]]
then
echo "Valid email address"
else
echo "Invalid email address"
fi
}
function validateMobile(){
read -p "Mobile : " mobile
mobpattern="^[0-9]{2}[[:space:]][0-9]{10}$"
if [[ $mobile =~ $mobpattern ]]
then
echo "Valid mobile number"
else
echo "Invalid mobile number"
fi
}
function validatePassword(){
passpattern1="^([a-zA-Z0-9@#!]){8,}$"
passpattern2="^([a-z0-9@#!]*)[A-Z]+([a-z0-9@#!]*)$"
passpattern3="^[a-zA-Z@#!]*[0-9]+[a-zA-Z@#!]*$"
passpattern4="^([a-zA-Z0-9]*)[^a-zA-Z_0-9\s]([a-zA-Z0-9]*)$"
if [[ $1 =~ $passpattern1 ]]
then
if [[ $1 =~ $passpattern2 ]]
then
if [[ $1 =~ $passpattern3 ]]
then
if [[ $1 =~ $passpattern4 ]]
then
echo "Success : Valid Password"
else
echo "Error : At least one special character required"
fi
else
echo "Error : At least one digit mandatory"
fi
else
echo "Error : At least one caps letter required"
fi
else
echo "Error : Password must be of 8 length"
fi
}
read -p "First Name : " fname
validateFirstName $fname
read -p "Last Name : " lname
validateFirstName $lname
read -p "Email : " email
validateEmail $email
validateMobile
read -p "Password : " password
validatePassword $password
echo "----------------------------------"
<<SampleEmail
-------Valid Emails----------
<EMAIL>,
<EMAIL>,
<EMAIL>
<EMAIL>,
<EMAIL>,
<EMAIL>
<EMAIL>,
<EMAIL>
<EMAIL>
------Invalid Emails (TLD - Top Level Domains)--------------
abc – must contains “@” symbol
<EMAIL> – tld can not start with dot “.”
<EMAIL>.a – “.a” is not a valid tld, last tld must contains at least two characters
<EMAIL> – tld can not start with dot “.”
<EMAIL> – tld can not start with dot “.”
.<EMAIL> – email’s 1st character can not start with “.”
<EMAIL> – email’s is only allow character, digit, underscore and dash
<EMAIL> – email’s tld is only allow character and digit
<EMAIL> – double dots “.” are not allow
<EMAIL> – email’s last character can not end with dot “.”
<EMAIL> – double “@” is not allow
<EMAIL>.1a -email’s tld which has two characters can not contains digit
<EMAIL> - cannont have multiple email’s tld
SampleEmail
| 65980370589ff9ca1fe81862665c7fa5c9e723cc | [
"Shell"
] | 2 | Shell | aashishogale/regex-exp | 6fd55f59b8c7a97baa88fe3e60803de15d81aab9 | 32a868cde71fcc01bd6e88da93d2c08d68baabe9 |
refs/heads/master | <repo_name>shintech/next-express<file_sep>/layouts/Main/index.js
/* /layouts/Main/index.js
*/
import Head from 'next/head'
import Wrapper from './Wrapper'
import Nav from '../../components/Nav'
import Footer from '../../components/Footer'
import { withRouter } from 'next/router'
const Main = ({ children, domain = 'domain', title = 'Main Layout', router }) =>
<Wrapper>
<Head>
<title>{ title }</title>
<link rel='icon' type='image/png' href='/public/images/favicon.png' />
</Head>
<header>
<Nav pathname={router.asPath} />
</header>
<main>
{ children }
</main>
<Footer>
<img src='/public/images/react.svg' width='25px' height='25px' />
<a href='#'>
<i className='far fa-copyright' />
shintech.ninja
</a>
</Footer>
</Wrapper>
export default withRouter(Main)
<file_sep>/actions/home.js
import C from '../store/constants'
export default {
initialize: function (id) {
return async dispatch => {
dispatch({
type: C.INITIALIZE
})
}
}
}
<file_sep>/store/constants.js
const constants = {
INITIALIZE: 'INITIALIZE'
}
export default constants
<file_sep>/server/index.js
const express = require('express')
const bodyParser = require('body-parser')
const next = require('next')
const path = require('path')
const compression = require('compression')
const morgan = require('morgan')
const nextRoutes = require('../routes')
const getRouter = require('./router')
const environment = process.env['NODE_ENV']
const port = process.env['PORT'] || 8000
const host = process.env['HOST'] || 'localhost'
const logger = require('./logger')({ environment })
const dev = environment !== 'production'
const app = next({ dev })
const handler = nextRoutes.getRequestHandler(app)
app.prepare()
.then(() => {
const server = express()
const api = getRouter({ logger })
if (environment === 'development') server.use(morgan('dev'))
server.use('/public', express.static(path.join(__dirname, '../public')))
.use(bodyParser.urlencoded({ extended: true }))
.use(bodyParser.json())
.use(compression())
.use('/api', api)
.use(handler)
.listen(port, host)
.on('listening', () => {
logger.info(`listening on port ${port}...`)
})
.on('error', (err) => {
throw (err)
})
})
<file_sep>/store/state.js
export default {
home: {
loading: true
}
}
<file_sep>/components/Nav/index.js
/* /components/Nav/index.js
*/
import Link from 'next/link'
import Wrapper from './Wrapper'
function toggleResponsive () {
var x = document.getElementById('topNav')
console.log(x.classList)
if (x.classList.contains('responsive')) {
x.classList.remove('responsive')
} else {
x.classList.add('responsive')
}
}
const Nav = ({ pathname }) =>
<Wrapper>
<nav id='topNav' className='topnav'>
<Link prefetch href='/'><a className={!pathname || pathname === '/' || pathname === '' ? 'active' : null}>home</a></Link>
<Link prefetch href='#'><a className={pathname === '/sandbox' ? 'active sandbox' : 'sandbox'}>menu</a></Link>
<a href='javascript:void(0);' className='icon' onClick={() => { toggleResponsive() }}>
<i className='fa fa-bars' />
</a>
</nav>
</Wrapper>
export default Nav
<file_sep>/readme.md
## shintech/next
### Installation
.yarn install
### Usage
#### Development
npm run dev
#### Production
docker-compose build && docker-compose up -d
### TODO
- [ ] authentication
- [ ] work on loading component
- [ ] try to make loading animation for d3 graphs
- [ ] write some tests
- [ ] upload and process files
- [ ] download files
- [ ] more graph
- [ ] error and success handling for file upload
- [ ] find a different solution for fonts
- [x] convert Section component into Layout
- [x] add success and failure actions for fetch
- [ ] handle error in fetch action
- [x] modal to display detailed info
- [ ] animated transition for modal
- [ ] button to switch between top and side navigation
- [ ] override options on components
- [ ] add styling to contents of Section
- [ ] add styling to contents of Modal
- [ ] add some more layouts
- [ ] make better compnent for adding tasks
- [ ] add grid layout to sandbox
- [ ] make modal movable
- [ ] add griddle to sandbox
- [ ] some fake numerical data
- [x] style footer
- [x] make navbar collapse
<file_sep>/reducers/home.js
/* /reducers/posts.js
*/
import C from '../store/constants'
const posts = (state = {}, action) => {
switch (action.type) {
case C.INITIALIZE:
return {
loading: !state.loading
}
default:
return state
}
}
export default posts
| 0cb099b2401ee45d03a8fd4211026fc3044c07ab | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | shintech/next-express | 03d3c6fb4f54bc8aa83ccc94a3f872cdcdeb1357 | f647a57c2500c725605b1ff898fc5e3ddf37170d |
refs/heads/master | <repo_name>JuliRataiko/Course_project<file_sep>/kursach/kursach/ImageProcessing/Steganography.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kursach.ImageProcessing
{
public class Steganography
{
public BitArray ByteToBit(byte src)
{
BitArray bitArray = new BitArray(8);
bool st = false;
for (int i = 0; i < 8; i++)
{
if ((src >> i & 1) == 1)
{
st = true;
}
else st = false;
bitArray[i] = st;
}
return bitArray;
}
public byte BitToByte(BitArray scr)
{
byte num = 0;
for (int i = 0; i < scr.Count; i++)
if (scr[i] == true)
num += (byte)Math.Pow(2, i);
return num;
}
public bool isEncryption(Bitmap scr)
{
byte[] rez = new byte[1];
Color color = scr.GetPixel(0, 0);
BitArray colorArray = ByteToBit(color.R); //получаем байт цвета и преобразуем в массив бит
BitArray messageArray = ByteToBit(color.R); ;//инициализируем результирующий массив бит
messageArray[0] = colorArray[0];
messageArray[1] = colorArray[1];
colorArray = ByteToBit(color.G);//получаем байт цвета и преобразуем в массив бит
messageArray[2] = colorArray[0];
messageArray[3] = colorArray[1];
messageArray[4] = colorArray[2];
colorArray = ByteToBit(color.B);//получаем байт цвета и преобразуем в массив бит
messageArray[5] = colorArray[0];
messageArray[6] = colorArray[1];
messageArray[7] = colorArray[2];
rez[0] = BitToByte(messageArray); //получаем байт символа, записанного в 1 пикселе
string m = Encoding.GetEncoding(1251).GetString(rez);
if (m == "/")
{
return true;
}
else return false;
}
public void WriteCountText(int count, Bitmap src)
{
byte[] CountSymbols = Encoding.GetEncoding(1251).GetBytes(count.ToString());
for (int i = 0; i < CountSymbols.Length; i++)
{
BitArray bitCount = ByteToBit(CountSymbols[i]); //биты количества символов
Color pColor = src.GetPixel(0, i + 1); //1, 2, 3 пикселы
BitArray bitsCurColor = ByteToBit(pColor.R); //бит цветов текущего пикселя
bitsCurColor[0] = bitCount[0];
bitsCurColor[1] = bitCount[1];
byte nR = BitToByte(bitsCurColor); //новый бит цвета пиксея
bitsCurColor = ByteToBit(pColor.G);//бит бит цветов текущего пикселя
bitsCurColor[0] = bitCount[2];
bitsCurColor[1] = bitCount[3];
bitsCurColor[2] = bitCount[4];
byte nG = BitToByte(bitsCurColor);//новый цвет пиксея
bitsCurColor = ByteToBit(pColor.B);//бит бит цветов текущего пикселя
bitsCurColor[0] = bitCount[5];
bitsCurColor[1] = bitCount[6];
bitsCurColor[2] = bitCount[7];
byte nB = BitToByte(bitsCurColor);//новый цвет пиксея
Color nColor = Color.FromArgb(nR, nG, nB); //новый цвет из полученных битов
src.SetPixel(0, i + 1, nColor); //записали полученный цвет в картинку
}
}
public int ReadCountText(Bitmap src)
{
byte[] rez = new byte[3]; //массив на 3 элемента, т.е. максимум 999 символов шифруется
for (int i = 0; i < 3; i++)
{
Color color = src.GetPixel(0, i + 1); //цвет 1, 2, 3 пикселей
BitArray colorArray = ByteToBit(color.R); //биты цвета
BitArray bitCount = ByteToBit(color.R); ; //инициализация результирующего массива бит
bitCount[0] = colorArray[0];
bitCount[1] = colorArray[1];
colorArray = ByteToBit(color.G);
bitCount[2] = colorArray[0];
bitCount[3] = colorArray[1];
bitCount[4] = colorArray[2];
colorArray = ByteToBit(color.B);
bitCount[5] = colorArray[0];
bitCount[6] = colorArray[1];
bitCount[7] = colorArray[2];
rez[i] = BitToByte(bitCount);
}
string m = Encoding.GetEncoding(1251).GetString(rez);
return Convert.ToInt32(m, 10);
}
}
}
<file_sep>/kursach/kursach/ImageProcessing/BitmapProcessor.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Color = System.Drawing.Color;
namespace kursach.ImageProcessing
{
public static class BitmapProcessor
{
private static int ClampColor(double value)
{
return value > 255.0 ? 255 : value < 0.0 ? 0 : (int)value;
}
private static int ClampColor(int value)
{
return value > 255 ? 255 : value < 0 ? 0 : value;
}
private static double ChangePixel(byte data, double c)
{
const float oneOver255 = 1.0f / 255.0f;
return ((data * oneOver255 - 0.5) * c + 0.5) * 255;
}
public static BitmapSource ConvertToGrayscale(this BitmapSource source)
{
var newFormatedBitmapSource = new FormatConvertedBitmap();
newFormatedBitmapSource.BeginInit();
newFormatedBitmapSource.Source = source;
newFormatedBitmapSource.DestinationFormat = PixelFormats.Gray32Float;
newFormatedBitmapSource.EndInit();
return newFormatedBitmapSource;
}
public static unsafe BitmapSource ConvertToGrayscale(this Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
byte* scan0 = (byte*)bData.Scan0.ToPointer();
for (int i = 0; i < bData.Height; ++i)
for (int j = 0; j < bData.Width; ++j)
{
byte* data = scan0 + i * bData.Stride + j * 4;
byte avg = (byte)((*data + *(data + 1) + *(data + 2)) / 3);
*data = *(data + 1) = *(data + 2) = avg;
}
bmp.UnlockBits(bData);
return new Bitmap(bmp).ToBitmapImage();
}
public static unsafe BitmapImage ReverseImage(this Bitmap source)
{
for (var y = 0; y <= source.Height - 1; y++)
{
for (var x = 0; x <= source.Width - 1; x++)
{
var inv = source.GetPixel(x, y);
inv = Color.FromArgb(255, 255 - inv.R, 255 - inv.G, 255 - inv.B);
source.SetPixel(x, y, inv);
}
}
return source.ToBitmapImage();
}
public static Bitmap ToBitmap(this BitmapSource source)
{
var bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
var data = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite,
bmp.PixelFormat);
source.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data);
return bmp;
}
public static BitmapImage ToBitmapImage(this Bitmap bitmap)
{
var bitmapImage = new BitmapImage();
using (var memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
return bitmapImage;
}
public static BitmapImage ToBitmapImage(this BitmapSource source)
{
using (var memoryStream = new MemoryStream())
{
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
encoder.Save(memoryStream);
memoryStream.Position = 0;
var bImg = new BitmapImage();
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();
memoryStream.Close();
return bImg;
}
}
public static unsafe BitmapImage ChangeSepia(this Bitmap bmp)
{
var bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var scan0 = (byte*)bData.Scan0.ToPointer();
for (var i = 0; i < bData.Height; ++i)
for (var j = 0; j < bData.Width; ++j)
{
var data = scan0 + i * bData.Stride + j * 3;
var tone = (byte)(0.299 * (*(data + 2)) + 0.587 * (*(data + 1)) + 0.114 * (*data));
*(data + 2) = (byte)((tone > 206) ? 255 : tone + 49);
*(data + 1) = (byte)((tone < 14) ? 0 : tone - 14);
*(data + 0) = (byte)((tone < 56) ? 0 : tone - 56);
}
bmp.UnlockBits(bData);
return new Bitmap(bmp).ToBitmapImage();
}
public static unsafe BitmapImage ChangeBrightness(this BitmapSource source, int newBrightness)
{
var bmp = source.ToBitmap();
var bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
var scan0 = (byte*)bData.Scan0.ToPointer();
for (var i = 0; i < bData.Height; ++i)
for (var j = 0; j < bData.Width; ++j)
{
var data = scan0 + i * bData.Stride + j * 4;
*data = (byte)ClampColor(*data + newBrightness);
*(data + 1) = (byte)ClampColor(*(data + 1) + newBrightness);
*(data + 2) = (byte)ClampColor(*(data + 2) + newBrightness);
}
bmp.UnlockBits(bData);
return bmp.ToBitmapImage();
}
public static unsafe BitmapImage ChangeContrast(this BitmapSource source, int contrastValue)
{
var bmp = source.ToBitmap();
if (contrastValue < -100 || contrastValue > 100) return source.ToBitmapImage();
var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var scan0 = (byte*)bmpData.Scan0.ToPointer();
var contrast = (100.0 + contrastValue) / 100.0;
contrast *= contrast;
for (var i = 0; i < bmpData.Height; ++i)
for (var j = 0; j < bmpData.Width; ++j)
{
var data = scan0 + i * bmpData.Stride + j * 3;
data[0] = (byte)ClampColor(ChangePixel(data[0], contrast));
data[1] = (byte)ClampColor(ChangePixel(data[1], contrast));
data[2] = (byte)ClampColor(ChangePixel(data[2], contrast));
}
bmp.UnlockBits(bmpData);
return bmp.ToBitmapImage();
}
public static unsafe BitmapImage ChangeColorBalance(this BitmapSource source, int red, int green, int blue)
{
var bmp = source.ToBitmap();
var bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
var scan0 = (byte*)bData.Scan0.ToPointer();
for (var i = 0; i < bData.Height; ++i)
for (var j = 0; j < bData.Width; ++j)
{
var data = scan0 + i * bData.Stride + j * 4;
*data = (byte)ClampColor(*data + blue);
*(data + 1) = (byte)ClampColor(*(data + 1) + green);
*(data + 2) = (byte)ClampColor(*(data + 2) + red);
}
bmp.UnlockBits(bData);
return bmp.ToBitmapImage();
}
public static BitmapSource EncodeText(this Bitmap bPic, string text)
{
var steganography = new Steganography();
byte[] bytes = Encoding.ASCII.GetBytes(text);
int CountText = bytes.Length;
if (CountText > ((bPic.Width * bPic.Height)) - 4)
{
return bPic.ToBitmapImage();
}
if (steganography.isEncryption(bPic))
{
return bPic.ToBitmapImage();
}
byte[] Symbol = Encoding.GetEncoding(1251).GetBytes("/");
BitArray ArrBeginSymbol = steganography.ByteToBit(Symbol[0]);
Color curColor = bPic.GetPixel(0, 0);
BitArray tempArray = steganography.ByteToBit(curColor.R);
tempArray[0] = ArrBeginSymbol[0];
tempArray[1] = ArrBeginSymbol[1];
byte nR = steganography.BitToByte(tempArray);
tempArray = steganography.ByteToBit(curColor.G);
tempArray[0] = ArrBeginSymbol[2];
tempArray[1] = ArrBeginSymbol[3];
tempArray[2] = ArrBeginSymbol[4];
byte nG = steganography.BitToByte(tempArray);
tempArray = steganography.ByteToBit(curColor.B);
tempArray[0] = ArrBeginSymbol[5];
tempArray[1] = ArrBeginSymbol[6];
tempArray[2] = ArrBeginSymbol[7];
byte nB = steganography.BitToByte(tempArray);
Color nColor = Color.FromArgb(nR, nG, nB);
bPic.SetPixel(0, 0, nColor);
steganography.WriteCountText(CountText, bPic);
int index = 0;
bool st = false;
for (int i = 4; i < bPic.Width; i++)
{
for (int j = 0; j < bPic.Height; j++)
{
Color pixelColor = bPic.GetPixel(i, j);
if (index == bytes.Length)
{
st = true;
break;
}
BitArray colorArray = steganography.ByteToBit(pixelColor.R);
BitArray messageArray = steganography.ByteToBit(bytes[index]);
colorArray[0] = messageArray[0];
colorArray[1] = messageArray[1];
byte newR = steganography.BitToByte(colorArray);
colorArray = steganography.ByteToBit(pixelColor.G);
colorArray[0] = messageArray[2];
colorArray[1] = messageArray[3];
colorArray[2] = messageArray[4];
byte newG = steganography.BitToByte(colorArray);
colorArray = steganography.ByteToBit(pixelColor.B);
colorArray[0] = messageArray[5];
colorArray[1] = messageArray[6];
colorArray[2] = messageArray[7];
byte newB = steganography.BitToByte(colorArray);
Color newColor = Color.FromArgb(newR, newG, newB);
bPic.SetPixel(i, j, newColor);
index++;
}
if (st)
{
break;
}
}
return bPic.ToBitmapImage();
}
public static string DecodeText(this BitmapSource source)
{
var bPic = source.ToBitmap();
var steganography = new Steganography();
if (!steganography.isEncryption(bPic))
{
return string.Empty;
}
int countSymbol = steganography.ReadCountText(bPic);
byte[] message = new byte[countSymbol];
int index = 0;
bool st = false;
for (int i = 4; i < bPic.Width; i++)
{
for (int j = 0; j < bPic.Height; j++)
{
Color pixelColor = bPic.GetPixel(i, j);
if (index == message.Length)
{
st = true;
break;
}
BitArray colorArray = steganography.ByteToBit(pixelColor.R);
BitArray messageArray = steganography.ByteToBit(pixelColor.R); ;
messageArray[0] = colorArray[0];
messageArray[1] = colorArray[1];
colorArray = steganography.ByteToBit(pixelColor.G);
messageArray[2] = colorArray[0];
messageArray[3] = colorArray[1];
messageArray[4] = colorArray[2];
colorArray = steganography.ByteToBit(pixelColor.B);
messageArray[5] = colorArray[0];
messageArray[6] = colorArray[1];
messageArray[7] = colorArray[2];
message[index] = steganography.BitToByte(messageArray);
index++;
}
if (st)
{
break;
}
}
return Encoding.GetEncoding(1251).GetString(message);
}
public static unsafe BitmapImage NormalizeIllumination(this Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
var scan0 = (byte*)bData.Scan0.ToPointer(); //Pointer to first byte of image
int r = 0, g = 0, b = 0, avg = 0;
for (int i = 0; i < bData.Height; ++i)
for (int j = 0; j < bData.Width; ++j)
{
byte* data = scan0 + i * bData.Stride + j * 3;
r += *(data + 2);
g += *(data + 1);
b += *data;
}
r /= bData.Height * bData.Width;
g /= bData.Height * bData.Width;
b /= bData.Height * bData.Width;
avg = ((r + g + b) / 3);
for (int i = 0; i < bData.Height; ++i)
for (int j = 0; j < bData.Width; ++j)
{
byte* data = scan0 + i * bData.Stride + j * 3;
*(data + 2) = (byte)(*(data + 2) * avg / r);
*(data + 1) = (byte)(*(data + 1) * avg / g);
*data = (byte)(*(data) * avg / b);
}
bmp.UnlockBits(bData);
return new Bitmap(bmp).ToBitmapImage();
}
public static BitmapImage ApplyBlur(this Bitmap sourceBitmap)
{
BitmapData sourceData = sourceBitmap.LockBits(new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
double factor = 1.0 / 81.0;
int bias = 0;
var filterMatrix = new double[,]
{ { 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1},
{ 1, 1, 1, 1, 1, 1, 1, 1, 1}, };
byte[] pixelBuffer = new byte[sourceData.Stride * sourceData.Height];
byte[] resultBuffer = new byte[sourceData.Stride * sourceData.Height];
Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length);
sourceBitmap.UnlockBits(sourceData);
double blue = 0.0;
double green = 0.0;
double red = 0.0;
int filterWidth = filterMatrix.GetLength(1);
int filterHeight = filterMatrix.GetLength(0);
int filterOffset = (filterWidth - 1) / 2;
int calcOffset = 0;
int byteOffset = 0;
for (int offsetY = filterOffset; offsetY <
sourceBitmap.Height - filterOffset; offsetY++)
{
for (int offsetX = filterOffset; offsetX <
sourceBitmap.Width - filterOffset; offsetX++)
{
blue = 0;
green = 0;
red = 0;
byteOffset = offsetY * sourceData.Stride + offsetX * 4;
for (int filterY = -filterOffset; filterY <= filterOffset; filterY++)
{
for (int filterX = -filterOffset; filterX <= filterOffset; filterX++)
{
calcOffset = byteOffset + (filterX * 4) + (filterY * sourceData.Stride);
blue += (double)(pixelBuffer[calcOffset]) * filterMatrix[filterY + filterOffset, filterX + filterOffset];
green += (double)(pixelBuffer[calcOffset + 1]) * filterMatrix[filterY + filterOffset, filterX + filterOffset];
red += (double)(pixelBuffer[calcOffset + 2]) * filterMatrix[filterY + filterOffset, filterX + filterOffset];
}
}
blue = factor * blue + bias;
green = factor * green + bias;
red = factor * red + bias;
blue = (blue > 255 ? 255 :
(blue < 0 ? 0 :
blue));
green = (green > 255 ? 255 :
(green < 0 ? 0 :
green));
red = (red > 255 ? 255 :
(red < 0 ? 0 :
red));
resultBuffer[byteOffset] = (byte)(blue);
resultBuffer[byteOffset + 1] = (byte)(green);
resultBuffer[byteOffset + 2] = (byte)(red);
resultBuffer[byteOffset + 3] = 255;
}
}
Bitmap resultBitmap = new Bitmap(sourceBitmap.Width, sourceBitmap.Height);
BitmapData resultData = resultBitmap.LockBits(new Rectangle(0, 0, resultBitmap.Width, resultBitmap.Height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Marshal.Copy(resultBuffer, 0, resultData.Scan0, resultBuffer.Length);
resultBitmap.UnlockBits(resultData);
return new Bitmap(resultBitmap).ToBitmapImage();
}
public static BitmapImage Sharpen(this Bitmap image)
{
Bitmap sharpenImage = new Bitmap(image.Width, image.Height);
int filterWidth = 3;
int filterHeight = 3;
int w = image.Width;
int h = image.Height;
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
Color imageColor = image.GetPixel(x, y);
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + w) % w;
int imageY = (y - filterHeight / 2 + filterY + h) % h;
imageColor = image.GetPixel(imageX, imageY);
red += imageColor.R * filter[filterX, filterY];
green += imageColor.G * filter[filterX, filterY];
blue += imageColor.B * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
sharpenImage.SetPixel(i, j, result[i, j]);
}
}
return sharpenImage.ToBitmapImage();
}
}
}
<file_sep>/kursach/kursach/Models/ImageDetails.cs
using System;
public class ImageDetails
{
/// <summary>
/// A name for the image, not the file name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// A description for the image.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Full path such as c:\path\to\image.png
/// </summary>
public string Path { get; set; }
/// <summary>
/// The image file name such as image.png
/// </summary>
public string FileName { get; set; }
/// <summary>
/// The file name extension: bmp, gif, jpg, png, tiff, etc...
/// </summary>
public string Extension { get; set; }
/// <summary>
/// The image height
/// </summary>
public int Height { get; set; }
/// <summary>
/// The image width.
/// </summary>
public int Width { get; set; }
/// <summary>
/// Overrided Equals method.
/// </summary>
/// <param name="other">Other object.</param>
/// <returns>The result.</returns>
public bool Equals(ImageDetails other)
{
return this.Name == other.Name &&
this.Description == other.Description &&
this.Path == other.Path &&
this.FileName == other.FileName &&
this.Extension == other.Extension &&
this.Height == other.Height &&
this.Width == other.Width;
}
}
| 878d16a3399c3d73ff915a508b4c6bc8bf4e6b38 | [
"C#"
] | 3 | C# | JuliRataiko/Course_project | 4dc621a32543ec2d10bf95b7ef757b1d257571c2 | 136f831e15b1297a8cf97b6824571ad3778863f9 |
refs/heads/master | <file_sep>using System;
namespace Game.Data
{
public class Point : IEquatable<Point>
{
public double x;
public double y;
public Point(Point other)
: this(other.x, other.y)
{
}
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return $"{x},{y}";
}
public double QDistanceTo(Point other) => (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y);
public double DistanceTo(Point other) => Math.Sqrt(QDistanceTo(other));
public void Limit(double radius)
{
if (x < radius) x = radius;
if (x > Constants.WORLD_WIDTH - radius) x = Constants.WORLD_WIDTH - radius;
if (y < radius) y = radius;
if (y > 1000) y = 1000;
}
public void MoveTo(Point other, double dist)
{
var d = DistanceTo(other);
if (d < Constants.EPSILON)
return;
var dx = other.x - x;
var dy = other.y - y;
var coef = dist / d;
Move((int) (x + dx * coef), (int) (y + dy * coef));
}
// Move the point to x and y
public void Move(int x, int y)
{
this.x = x;
this.y = y;
}
public bool Equals(Point other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return x.Equals(other.x) && y.Equals(other.y);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Point) obj);
}
public override int GetHashCode()
{
unchecked
{
return (x.GetHashCode() * 397) ^ y.GetHashCode();
}
}
public static bool operator ==(Point left, Point right)
{
return Equals(left, right);
}
public static bool operator !=(Point left, Point right)
{
return !Equals(left, right);
}
}
}<file_sep>namespace Game.Data
{
public class BuildAction : IGameAction
{
private readonly int siteId;
private readonly StructureType structureType;
private readonly UnitType unitType;
public BuildAction(int siteId, StructureType structureType, UnitType unitType = UnitType.None)
{
this.siteId = siteId;
this.structureType = structureType;
this.unitType = unitType;
}
public override string ToString()
{
if (structureType == StructureType.Barracks)
return $"BUILD {siteId} {structureType.ToString().ToUpper()}-{unitType.ToString().ToUpper()}";
return $"BUILD {siteId} {structureType.ToString().ToUpper()}";
}
}
}<file_sep>using System.Linq;
namespace Game.Data
{
public class TrainAction : IGameAction
{
private readonly int[] siteIds;
public TrainAction(params int[] siteIds)
{
this.siteIds = siteIds;
}
public override string ToString()
{
return "TRAIN" + (siteIds.Any() ? $" {string.Join(" ", siteIds)}" : "");
}
}
}<file_sep>namespace Game.Data
{
public class MoveAction : IGameAction
{
private readonly int x;
private readonly int y;
public MoveAction(Point target)
: this((int)target.x, (int)target.y)
{
}
public MoveAction(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return $"MOVE {x} {y}";
}
}
}<file_sep>using System;
using System.Collections.Generic;
using Game.Helpers;
namespace Game.Data
{
public class State
{
public Countdown countdown;
public Random random;
public int turn;
public int gold;
public int touchedSite;
public readonly Dictionary<int, Structure> structures = new Dictionary<int, Structure>();
public readonly Queen[] queens = new Queen[2];
public readonly List<Unit>[] units = { new List<Unit>(), new List<Unit>() };
}
}<file_sep>namespace Game.Data
{
public class Queen : Point
{
public int health;
public Queen(int x, int y, int health) : base(x, y)
{
this.health = health;
}
}
}<file_sep>namespace Game.Data
{
public class Site : Point
{
public readonly int radius;
public Site(int x, int y, int radius) : base(x, y)
{
this.radius = radius;
}
}
}<file_sep>using System;
using Game.Data;
namespace Game
{
public class Desision
{
public IGameAction queenAction = new WaitAction();
public TrainAction trainAction = new TrainAction();
public void Write()
{
Console.Out.WriteLine(queenAction);
Console.Out.WriteLine(trainAction);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Game.Data;
namespace Game
{
public class Strategy
{
private readonly InitData data;
private List<KeyValuePair<int, Site>> nearestSites;
private int runPoint;
private Point startPos;
private HashSet<int> noGold = new HashSet<int>();
private KeyValuePair<int, Site> targetSite;
public Strategy(InitData data)
{
this.data = data;
}
public Desision Decide(State state)
{
if (startPos == null)
{
startPos = new Point(state.queens[0]);
nearestSites = data.sites.OrderBy(x => startPos.QDistanceTo(x.Value)).ToList();
}
noGold.UnionWith(state.structures.Where(x => x.Value.gold == 0).Select(x => x.Key));
targetSite = nearestSites.FirstOrDefault(s =>
state.structures[s.Key].owner == -1 ||
state.structures[s.Key].owner == 1 &&
state.structures[s.Key].structureType != StructureType.Tower);
return new Desision
{
queenAction = ChooseQueenAction(state),
trainAction = ChooseTrainAction(state)
};
}
private TrainAction ChooseTrainAction(State state)
{
var sitesCanTrainGiants = data.sites
.Where(x => state.structures[x.Key].owner == 0
&& state.structures[x.Key].structureType == StructureType.Barracks
&& state.structures[x.Key].BarracksTrainTurnsLeft == 0
&& state.structures[x.Key].BarracksCreepType == UnitType.Giant)
.OrderBy(x => x.Value.QDistanceTo(state.queens[1]))
.ToList();
var sitesCanTrainArchers = data.sites
.Where(x => state.structures[x.Key].owner == 0
&& state.structures[x.Key].structureType == StructureType.Barracks
&& state.structures[x.Key].BarracksTrainTurnsLeft == 0
&& state.structures[x.Key].BarracksCreepType == UnitType.Archer)
.OrderBy(x => x.Value.QDistanceTo(state.queens[1]))
.ToList();
var sitesCanTrainKnights = data.sites
.Where(x => state.structures[x.Key].owner == 0
&& state.structures[x.Key].structureType == StructureType.Barracks
&& state.structures[x.Key].BarracksTrainTurnsLeft == 0
&& state.structures[x.Key].BarracksCreepType == UnitType.Knight)
.OrderBy(x => x.Value.QDistanceTo(state.queens[1]))
.ToList();
var gold = state.gold;
var sitesToTrain = new List<int>();
if (state.units[0].All(u => u.type != UnitType.Knight) && sitesCanTrainKnights.Any())
{
if (gold < 80)
return new TrainAction(sitesToTrain.ToArray());
gold -= 80;
sitesToTrain.Add(sitesCanTrainKnights.First().Key);
sitesCanTrainKnights.RemoveAt(0);
}
//if (state.structures.Any(s => s.Value.owner == 1 && s.Value.structureType == StructureType.Tower)
// && state.units[0].All(u => u.type != UnitType.Giant) && sitesCanTrainGiants.Any())
//{
// if (gold < 140)
// return new TrainAction(sitesToTrain.ToArray());
// gold -= 140;
// sitesToTrain.Add(sitesCanTrainGiants.First().Key);
//}
if (state.units[0].All(u => u.type != UnitType.Archer) && sitesCanTrainArchers.Any())
{
if (gold < 100)
return new TrainAction(sitesToTrain.ToArray());
gold -= 100;
sitesToTrain.Add(sitesCanTrainArchers.First().Key);
}
foreach (var s in sitesCanTrainKnights)
if (gold >= 80)
{
gold -= 80;
sitesToTrain.Add(s.Key);
}
return new TrainAction(sitesToTrain.ToArray());
}
private IGameAction ChooseQueenAction(State state)
{
if (TryEscape(state, out var gameAction))
return gameAction;
if (TryUpgradeMines(state, out gameAction))
return gameAction;
if (TryBuildBasic(state, out gameAction))
return gameAction;
if (TryUpgradeTowers(state, out gameAction))
return gameAction;
if (TryBuildAdvanced(state, out gameAction))
return gameAction;
if (TryUpgradeTowers2(state, out gameAction))
return gameAction;
return new WaitAction();
}
private bool TryBuildAdvanced(State state, out IGameAction buildAction)
{
buildAction = null;
var targetSites = nearestSites.Where(s =>
state.structures[s.Key].owner == -1 ||
state.structures[s.Key].owner == 1 &&
state.structures[s.Key].structureType != StructureType.Tower)
.ToList();
var freeSites = targetSites
.TakeWhile(x => !state.structures
.Any(s => s.Value.owner == 1
&& s.Value.structureType == StructureType.Tower
&& data.sites[s.Key].DistanceTo(x.Value) <= s.Value.TowerAttackRadius))
.ToList();
if (!freeSites.Any())
return false;
if (state.structures.Count(s =>
s.Value.owner == 0 && s.Value.structureType == StructureType.Barracks &&
s.Value.BarracksCreepType == UnitType.Archer) < 1)
{
buildAction = new BuildAction(targetSite.Key, StructureType.Barracks, UnitType.Archer);
return true;
}
var freeSitesWithGold = freeSites.Where(x => !noGold.Contains(x.Key) && (state.structures[x.Key].gold == -1 || state.structures[x.Key].gold > 0)).ToList();
if (state.structures.Count(s =>
s.Value.owner == 0 && s.Value.structureType == StructureType.Mine) < 5
&& freeSitesWithGold.Any())
{
buildAction = new BuildAction(freeSitesWithGold.First().Key, StructureType.Mine);
return true;
}
return false;
}
private bool TryBuildBasic(State state, out IGameAction buildAction)
{
buildAction = null;
var targetSites = nearestSites.Where(s =>
state.structures[s.Key].owner == -1 ||
state.structures[s.Key].owner == 1 &&
state.structures[s.Key].structureType != StructureType.Tower)
.ToList();
var freeSites = targetSites
.TakeWhile(x => !state.structures
.Any(s => s.Value.owner == 1
&& s.Value.structureType == StructureType.Tower
&& data.sites[s.Key].DistanceTo(x.Value) <= s.Value.TowerAttackRadius))
.ToList();
if (!freeSites.Any())
return false;
var freeSitesWithGold = freeSites.Where(x => !noGold.Contains(x.Key) && (state.structures[x.Key].gold == -1 || state.structures[x.Key].gold > 0)).ToList();
if (state.structures.Count(s =>
s.Value.owner == 0 && s.Value.structureType == StructureType.Mine) < 3
&& freeSitesWithGold.Any())
{
buildAction = new BuildAction(freeSitesWithGold.First().Key, StructureType.Mine);
return true;
}
if (state.structures.Count(s =>
s.Value.owner == 0 && s.Value.structureType == StructureType.Barracks &&
s.Value.BarracksCreepType == UnitType.Knight) < 1)
{
buildAction = new BuildAction(targetSite.Key, StructureType.Barracks, UnitType.Knight);
return true;
}
if (state.structures.Count(s =>
s.Value.owner == 0 && s.Value.structureType == StructureType.Tower) < 2)
{
buildAction = new BuildAction(targetSite.Key, StructureType.Tower);
return true;
}
return false;
}
private bool TryUpgradeMines(State state, out IGameAction buildAction)
{
var candidates = new HashSet<int>(state.structures
.Where(s => s.Value.owner == 0 && s.Value.structureType == StructureType.Mine &&
s.Value.MineIncome < s.Value.maxMineSize)
.Select(s => s.Key));
if (!candidates.Any())
{
buildAction = null;
return false;
}
buildAction = new BuildAction(nearestSites.First(s => candidates.Contains(s.Key)).Key, StructureType.Mine);
return true;
}
private bool TryUpgradeTowers(State state, out IGameAction buildAction)
{
var candidates = new HashSet<int>(state.structures
.Where(s => s.Value.owner == 0 && s.Value.structureType == StructureType.Tower &&
s.Value.TowerAttackRadius <= 150)
.Select(s => s.Key));
if (!candidates.Any())
{
buildAction = null;
return false;
}
buildAction = new BuildAction(nearestSites.First(s => candidates.Contains(s.Key)).Key, StructureType.Tower);
return true;
}
private bool TryUpgradeTowers2(State state, out IGameAction buildAction)
{
var candidates = new HashSet<int>(state.structures
.Where(s => s.Value.owner == 0 && s.Value.structureType == StructureType.Tower)
.OrderBy(s => s.Value.TowerAttackRadius)
.Select(s => s.Key));
if (!candidates.Any())
{
buildAction = null;
return false;
}
buildAction = new BuildAction(candidates.First(), StructureType.Tower);
return true;
}
private bool TryEscape(State state, out IGameAction gameAction)
{
if (state.units[1].Any(u => u.DistanceTo(state.queens[0]) <= 350))
{
var towerCandidate = data.sites
.OrderBy(s => s.Value.DistanceTo(state.queens[0]))
.FirstOrDefault(s => state.structures[s.Key].owner == -1 && s.Value.DistanceTo(state.queens[0]) <= 200);
if (towerCandidate.Value != null)
{
gameAction = new BuildAction(
towerCandidate.Key,
StructureType.Tower);
return true;
}
if (state.structures.Any(s => s.Value.owner == 0 && s.Value.structureType == StructureType.Tower))
{
var runTower = nearestSites.First(x =>
state.structures[x.Key].owner == 0 &&
state.structures[x.Key].structureType == StructureType.Tower);
var runStructure = state.structures[runTower.Key];
var runPoints = new[]
{
new Point(runTower.Value.x - runStructure.TowerAttackRadius * 2.5 / 3, runTower.Value.y),
new Point(runTower.Value.x, runTower.Value.y - runStructure.TowerAttackRadius * 2.5 / 3),
new Point(runTower.Value.x + runStructure.TowerAttackRadius * 2.5 / 3, runTower.Value.y),
new Point(runTower.Value.x, runTower.Value.y + runStructure.TowerAttackRadius * 2.5 / 3)
};
foreach (var point in runPoints)
{
point.Limit(Constants.QUEEN_RADIUS);
while (data.sites.Any(s =>
s.Key != runTower.Key && s.Value.DistanceTo(point) < s.Value.radius + Constants.QUEEN_RADIUS))
point.MoveTo(runTower.Value, 10);
}
if (state.units[1].Any(u => u.DistanceTo(state.queens[0]) <= 200))
{
if (state.queens[0].DistanceTo(runPoints[runPoint]) < Constants.QUEEN_RADIUS)
{
runPoint = (runPoint + 1) % runPoints.Length;
Console.Error.WriteLine($"RunPoint={runPoint}");
}
gameAction = new MoveAction(runPoints[runPoint]);
return true;
}
runPoint = Array.IndexOf(runPoints,
runPoints.OrderByDescending(p => state.units[1].Max(u => u.DistanceTo(p))).First());
Console.Error.WriteLine($"RunPoint={runPoint}");
gameAction = new BuildAction(
runTower.Key,
StructureType.Tower);
return true;
}
{
gameAction = new BuildAction(targetSite.Key, StructureType.Tower);
return true;
}
}
gameAction = null;
return false;
}
}
}<file_sep>using System.Collections.Generic;
namespace Game.Data
{
public class InitData
{
public readonly Dictionary<int, Site> sites = new Dictionary<int, Site>();
}
}<file_sep>namespace Game.Data
{
public class Unit : Point
{
public readonly UnitType type;
public int health;
public Unit(int x, int y, int unitType, int health) : base(x, y)
{
type = (UnitType) unitType;
this.health = health;
}
}
}<file_sep>namespace Game.Data
{
public class Structure
{
public readonly StructureType structureType;
public readonly int owner;
public readonly int param1;
public readonly int param2;
public readonly int gold;
public readonly int maxMineSize;
public Structure(int structureType, int owner, int param1, int param2, int gold, int maxMineSize)
{
this.structureType = (StructureType) structureType;
this.owner = owner;
this.param1 = param1;
this.param2 = param2;
this.gold = gold;
this.maxMineSize = maxMineSize;
}
public int MineIncome => param1;
public int TowerHP => param1;
public int BarracksTrainTurnsLeft => param1;
public int TowerAttackRadius => param2;
public UnitType BarracksCreepType => (UnitType) param2;
}
}<file_sep>namespace Game.Data
{
public enum StructureType
{
None = -1,
Mine = 0,
Tower = 1,
Barracks = 2
}
}<file_sep>namespace Game.Data
{
public interface IGameAction
{
}
}<file_sep>using System;
using System.Linq;
using Game.Helpers;
namespace Game.Data
{
public class StateReader
{
private string lastLine;
private readonly bool logToError = true;
private readonly Func<string> readLine;
private readonly Func<int> getSeed;
public StateReader(string input)
{
var lines = input.Split('|');
var seedLine = lines.SingleOrDefault(l => l.StartsWith("seed:"));
if (seedLine != null)
{
var seed = int.Parse(seedLine.Substring("seed:".Length));
getSeed = () => seed;
lines = lines.Where(l => !l.StartsWith("seed:")).ToArray();
}
var index = 0;
logToError = false;
readLine = () => index < lines.Length ? lines[index++] : null;
}
public StateReader(Func<string> consoleReadLine)
{
readLine = () =>
{
lastLine = consoleReadLine();
if (logToError)
Console.Error.Write(lastLine + "|");
return lastLine;
};
getSeed = () =>
{
var seed = Guid.NewGuid().GetHashCode();
if (logToError)
Console.Error.Write($"seed:{seed}|");
return seed;
};
}
public InitData ReadInitData()
{
var result = new InitData();
string[] inputs;
int numSites = int.Parse(readLine());
for (int i = 0; i < numSites; i++)
{
inputs = readLine().Split(' ');
int siteId = int.Parse(inputs[0]);
int x = int.Parse(inputs[1]);
int y = int.Parse(inputs[2]);
int radius = int.Parse(inputs[3]);
result.sites.Add(siteId, new Site(x, y, radius));
}
if (logToError)
Console.Error.WriteLine();
return result;
}
public State ReadState(InitData data)
{
try
{
var state = new State();
var inputs = readLine().Split(' ');
state.gold = int.Parse(inputs[0]);
state.touchedSite = int.Parse(inputs[1]); // -1 if none
for (int i = 0; i < data.sites.Count; i++)
{
inputs = readLine().Split(' ');
int siteId = int.Parse(inputs[0]);
int mineGold = int.Parse(inputs[1]); // used in future leagues
int maxMineSize = int.Parse(inputs[2]); // used in future leagues
int structureType = int.Parse(inputs[3]); // -1 = No structure, 2 = Barracks
int owner = int.Parse(inputs[4]); // -1 = No structure, 0 = Friendly, 1 = Enemy
int param1 = int.Parse(inputs[5]);
int param2 = int.Parse(inputs[6]);
state.structures.Add(siteId, new Structure(structureType, owner, param1, param2, mineGold, maxMineSize));
}
int numUnits = int.Parse(readLine());
for (int i = 0; i < numUnits; i++)
{
inputs = readLine().Split(' ');
int x = int.Parse(inputs[0]);
int y = int.Parse(inputs[1]);
int owner = int.Parse(inputs[2]);
int unitType = int.Parse(inputs[3]); // -1 = QUEEN, 0 = KNIGHT, 1 = ARCHER
int health = int.Parse(inputs[4]);
if (unitType == -1)
state.queens[owner] = new Queen(x, y, health);
else
state.units[owner].Add(new Unit(x, y, unitType, health));
}
state.random = new Random(getSeed());
state.countdown = new Countdown(90);
if (logToError)
Console.Error.WriteLine();
return state;
}
catch (Exception e)
{
throw new FormatException($"Line [{lastLine}]", e);
}
}
}
}<file_sep>using System.Diagnostics;
namespace Game.Helpers
{
public class Countdown
{
private readonly int milliseconds;
private readonly Stopwatch stopwatch = Stopwatch.StartNew();
public Countdown(int milliseconds)
{
this.milliseconds = milliseconds;
}
public long ElapsedMilliseconds => stopwatch.ElapsedMilliseconds;
public bool IsExpired() => stopwatch.ElapsedMilliseconds > milliseconds;
}
}<file_sep>namespace Game.Data
{
public class WaitAction : IGameAction
{
public override string ToString()
{
return "WAIT";
}
}
}<file_sep>using System;
using Game.Data;
namespace Game
{
public static class Constants
{
public const double EPSILON = 1e-6;
public const int QUEEN_RADIUS = 30;
public const int WORLD_WIDTH = 1920;
public const int WORLD_HEIGHT = 1000;
}
public unsafe class EntryPoint
{
private static void Main(string[] args)
{
var reader = new StateReader(Console.ReadLine);
var data = reader.ReadInitData();
var strategy = new Strategy(data);
// game loop
var turn = 0;
while (true)
{
var state = reader.ReadState(data);
state.turn = turn;
Console.Error.WriteLine($"Turn: {turn}");
var action = strategy.Decide(state);
Console.Error.WriteLine($"time: {state.countdown.ElapsedMilliseconds}");
turn++;
action.Write();
}
}
}
}<file_sep>namespace Game.Data
{
public enum UnitType
{
None = -1,
Knight = 0,
Archer = 1,
Giant = 2
}
} | 05399f7f86a1eb3f5f36dc6a894d4495c0565a7e | [
"C#"
] | 19 | C# | spaceorc/codingame2018-code-royale | c54b04aa19d2291b0a304281df84d452a30749ff | c19cef7fdf71877b638f8d33efab0ab9e2c9fe31 |
refs/heads/master | <file_sep># JavaPractice_TrafficLights
因為C做不到我想要的,一怒之下嘗試用Java寫出紅綠燈,但還是沒達到我的需求
<file_sep>import java.util.Scanner;
public class reciprocal_while
{
@SuppressWarnings("unused")
public reciprocal_while()
{
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int i,z,x;
int a; /*厚縊计*/
int s; /*縊计*/
printf("\n厚縊计:");
a =scanner.nextInt(); /*块厚縊计 */
printf("縊计:");
s =scanner.nextInt(); /*块縊计*/
int l=1;/*礚癹伴*/
while(l==1)
{
for( i=a;i>3;i--)
{
printf("厚縊 :");
System.out.println(i);
sleep tom = new sleep();
}
for( z=i;z>0;z--)
{
printf("独縊 :");
System.out.println(z);
sleep tom = new sleep();
}
for( x=s;x>=0;x--)
{
printf("縊 :");
System.out.println(x);
sleep tom = new sleep();
}
}
}
public static void printf(String name) /*陪ボゅ*/
{
System.out.print(name);
}
}
<file_sep> /*µ{¦¡µu¼È¼È°±*/
public class sleep
{
public sleep()
{
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
| 8b6cbe4fd5adf501dbfdff06dd88537d74ed0440 | [
"Markdown",
"Java"
] | 3 | Markdown | MrKevinLeeTW/JavaPractice_TrafficLights | 16d299fe154c39ec9a598d046f7bb2640360511c | c705a3379b8f47ce5ba253bc1d6e4538407b84d1 |
refs/heads/master | <file_sep>suppressPackageStartupMessages(library(sf))
library(lwgeom)
p = st_sfc(st_point(c(7,52)), st_point(c(8,53)), crs = 4326)
st_geod_azimuth(p)
<file_sep>/**********************************************************************
*
* PostGIS - Spatial Types for PostgreSQL
* http://postgis.net
*
* PostGIS 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.
*
* PostGIS 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 PostGIS. If not, see <http://www.gnu.org/licenses/>.
*
**********************************************************************
*
* Copyright 2015-2016 <NAME> <<EMAIL>>
*
**********************************************************************/
#include <string.h>
#include "liblwgeom.h"
#include "liblwgeom_internal.h"
#include "lwgeom_log.h"
#include "lwgeom_geos.h"
#include "lwunionfind.h"
static const int STRTREE_NODE_CAPACITY = 10;
/* Utility struct used to accumulate items in GEOSSTRtree_query callback */
struct QueryContext
{
void** items_found;
uint32_t items_found_size;
uint32_t num_items_found;
};
/* Utility struct to keep GEOSSTRtree and associated structures to be freed after use */
struct STRTree
{
GEOSSTRtree* tree;
GEOSGeometry** envelopes;
uint32_t* geom_ids;
uint32_t num_geoms;
};
static struct STRTree make_strtree(void** geoms, uint32_t num_geoms, char is_lwgeom);
static void destroy_strtree(struct STRTree * tree);
static int union_intersecting_pairs(GEOSGeometry** geoms, uint32_t num_geoms, UNIONFIND* uf);
static int combine_geometries(UNIONFIND* uf, void** geoms, uint32_t num_geoms, void*** clustersGeoms, uint32_t* num_clusters, char is_lwgeom);
/* Make a minimal GEOSGeometry* whose Envelope covers the same 2D extent as
* the supplied GBOX. This is faster and uses less memory than building a
* five-point polygon with GBOX2GEOS.
*/
static GEOSGeometry*
geos_envelope_surrogate(const LWGEOM* g)
{
if (lwgeom_is_empty(g))
return GEOSGeom_createEmptyPolygon();
if (lwgeom_get_type(g) == POINTTYPE) {
const POINT2D* pt = getPoint2d_cp(lwgeom_as_lwpoint(g)->point, 0);
return make_geos_point(pt->x, pt->y);
} else {
const GBOX* box = lwgeom_get_bbox(g);
if (!box)
return NULL;
return make_geos_segment(box->xmin, box->ymin, box->xmax, box->ymax);
}
}
/** Make a GEOSSTRtree that stores a pointer to a variable containing
* the array index of the input geoms */
static struct STRTree
make_strtree(void** geoms, uint32_t num_geoms, char is_lwgeom)
{
struct STRTree tree;
tree.tree = GEOSSTRtree_create(STRTREE_NODE_CAPACITY);
if (tree.tree == NULL)
{
return tree;
}
tree.geom_ids = lwalloc(num_geoms * sizeof(uint32_t));
tree.num_geoms = num_geoms;
if (is_lwgeom)
{
uint32_t i;
tree.envelopes = lwalloc(num_geoms * sizeof(GEOSGeometry*));
for (i = 0; i < num_geoms; i++)
{
tree.geom_ids[i] = i;
tree.envelopes[i] = geos_envelope_surrogate(geoms[i]);
GEOSSTRtree_insert(tree.tree, tree.envelopes[i], &(tree.geom_ids[i]));
}
}
else
{
uint32_t i;
tree.envelopes = NULL;
for (i = 0; i < num_geoms; i++)
{
tree.geom_ids[i] = i;
GEOSSTRtree_insert(tree.tree, geoms[i], &(tree.geom_ids[i]));
}
}
return tree;
}
/** Clean up STRTree after use */
static void
destroy_strtree(struct STRTree * tree)
{
size_t i;
GEOSSTRtree_destroy(tree->tree);
if (tree->envelopes)
{
for (i = 0; i < tree->num_geoms; i++)
{
GEOSGeom_destroy(tree->envelopes[i]);
}
lwfree(tree->envelopes);
}
lwfree(tree->geom_ids);
}
static void
query_accumulate(void* item, void* userdata)
{
struct QueryContext *cxt = userdata;
if (!cxt->items_found)
{
cxt->items_found_size = 8;
cxt->items_found = lwalloc(cxt->items_found_size * sizeof(void*));
}
if (cxt->num_items_found >= cxt->items_found_size)
{
cxt->items_found_size = 2 * cxt->items_found_size;
cxt->items_found = lwrealloc(cxt->items_found, cxt->items_found_size * sizeof(void*));
}
cxt->items_found[cxt->num_items_found++] = item;
}
/* Identify intersecting geometries and mark them as being in the same set */
static int
union_intersecting_pairs(GEOSGeometry** geoms, uint32_t num_geoms, UNIONFIND* uf)
{
uint32_t p, i;
struct STRTree tree;
struct QueryContext cxt =
{
.items_found = NULL,
.num_items_found = 0,
.items_found_size = 0
};
int success = LW_SUCCESS;
if (num_geoms <= 1)
return LW_SUCCESS;
tree = make_strtree((void**) geoms, num_geoms, LW_FALSE);
if (tree.tree == NULL)
{
destroy_strtree(&tree);
return LW_FAILURE;
}
for (p = 0; p < num_geoms; p++)
{
const GEOSPreparedGeometry* prep = NULL;
if (GEOSisEmpty(geoms[p]))
continue;
cxt.num_items_found = 0;
GEOSSTRtree_query(tree.tree, geoms[p], &query_accumulate, &cxt);
for (i = 0; i < cxt.num_items_found; i++)
{
uint32_t q = *((uint32_t*) cxt.items_found[i]);
if (p != q && UF_find(uf, p) != UF_find(uf, q))
{
int geos_type = GEOSGeomTypeId(geoms[p]);
int geos_result;
/* Don't build prepared a geometry around a Point or MultiPoint -
* there are some problems in the implementation, and it's not clear
* there would be a performance benefit in any case. (See #3433)
*/
if (geos_type != GEOS_POINT && geos_type != GEOS_MULTIPOINT)
{
/* Lazy initialize prepared geometry */
if (prep == NULL)
{
prep = GEOSPrepare(geoms[p]);
}
geos_result = GEOSPreparedIntersects(prep, geoms[q]);
}
else
{
geos_result = GEOSIntersects(geoms[p], geoms[q]);
}
if (geos_result > 1)
{
success = LW_FAILURE;
break;
}
else if (geos_result)
{
UF_union(uf, p, q);
}
}
}
if (prep)
GEOSPreparedGeom_destroy(prep);
if (!success)
break;
}
if (cxt.items_found)
lwfree(cxt.items_found);
destroy_strtree(&tree);
return success;
}
/** Takes an array of GEOSGeometry* and constructs an array of GEOSGeometry*, where each element in the constructed
* array is a GeometryCollection representing a set of interconnected geometries. Caller is responsible for
* freeing the input array, but not for destroying the GEOSGeometry* items inside it. */
int
cluster_intersecting(GEOSGeometry** geoms, uint32_t num_geoms, GEOSGeometry*** clusterGeoms, uint32_t* num_clusters)
{
int cluster_success;
UNIONFIND* uf = UF_create(num_geoms);
if (union_intersecting_pairs(geoms, num_geoms, uf) == LW_FAILURE)
{
UF_destroy(uf);
return LW_FAILURE;
}
cluster_success = combine_geometries(uf, (void**) geoms, num_geoms, (void***) clusterGeoms, num_clusters, 0);
UF_destroy(uf);
return cluster_success;
}
static int
dbscan_update_context(GEOSSTRtree* tree, struct QueryContext* cxt, LWGEOM** geoms, uint32_t p, double eps)
{
cxt->num_items_found = 0;
GEOSGeometry* query_envelope;
if (geoms[p]->type == POINTTYPE)
{
const POINT2D* pt = getPoint2d_cp(lwgeom_as_lwpoint(geoms[p])->point, 0);
query_envelope = make_geos_segment( pt->x - eps, pt->y - eps, pt->x + eps, pt->y + eps );
} else {
const GBOX* box = lwgeom_get_bbox(geoms[p]);
query_envelope = make_geos_segment( box->xmin - eps, box->ymin - eps, box->xmax + eps, box->ymax + eps );
}
if (!query_envelope)
return LW_FAILURE;
GEOSSTRtree_query(tree, query_envelope, &query_accumulate, cxt);
GEOSGeom_destroy(query_envelope);
return LW_SUCCESS;
}
/* Union p's cluster with q's cluster, if q is not a border point of another cluster.
* Applicable to DBSCAN with minpoints > 1.
*/
static void
union_if_available(UNIONFIND* uf, uint32_t p, uint32_t q, char* is_in_core, char* in_a_cluster)
{
if (in_a_cluster[q])
{
/* Can we merge p's cluster with q's cluster? We can do this only
* if both p and q are considered _core_ points of their respective
* clusters.
*/
if (is_in_core[q])
{
UF_union(uf, p, q);
}
}
else
{
UF_union(uf, p, q);
in_a_cluster[q] = LW_TRUE;
}
}
/* An optimized DBSCAN union for the case where min_points == 1.
* If min_points == 1, then we don't care how many neighbors we find; we can union clusters
* on the fly, as as we go through the distance calculations. This potentially allows us
* to avoid some distance computations altogether.
*/
static int
union_dbscan_minpoints_1(LWGEOM** geoms, uint32_t num_geoms, UNIONFIND* uf, double eps, char** in_a_cluster_ret)
{
uint32_t p, i;
struct STRTree tree;
struct QueryContext cxt =
{
.items_found = NULL,
.num_items_found = 0,
.items_found_size = 0
};
int success = LW_SUCCESS;
if (in_a_cluster_ret)
{
char* in_a_cluster = lwalloc(num_geoms * sizeof(char));
for (i = 0; i < num_geoms; i++)
in_a_cluster[i] = LW_TRUE;
*in_a_cluster_ret = in_a_cluster;
}
if (num_geoms <= 1)
return LW_SUCCESS;
tree = make_strtree((void**) geoms, num_geoms, LW_TRUE);
if (tree.tree == NULL)
{
destroy_strtree(&tree);
return LW_FAILURE;
}
for (p = 0; p < num_geoms; p++)
{
if (lwgeom_is_empty(geoms[p]))
continue;
dbscan_update_context(tree.tree, &cxt, geoms, p, eps);
for (i = 0; i < cxt.num_items_found; i++)
{
uint32_t q = *((uint32_t*) cxt.items_found[i]);
if (UF_find(uf, p) != UF_find(uf, q))
{
double mindist = lwgeom_mindistance2d_tolerance(geoms[p], geoms[q], eps);
if (mindist == FLT_MAX)
{
success = LW_FAILURE;
break;
}
if (mindist <= eps)
UF_union(uf, p, q);
}
}
}
if (cxt.items_found)
lwfree(cxt.items_found);
destroy_strtree(&tree);
return success;
}
static int
union_dbscan_general(LWGEOM** geoms, uint32_t num_geoms, UNIONFIND* uf, double eps, uint32_t min_points, char** in_a_cluster_ret)
{
uint32_t p, i;
struct STRTree tree;
struct QueryContext cxt =
{
.items_found = NULL,
.num_items_found = 0,
.items_found_size = 0
};
int success = LW_SUCCESS;
uint32_t* neighbors;
char* in_a_cluster;
char* is_in_core;
in_a_cluster = lwalloc(num_geoms * sizeof(char));
memset(in_a_cluster, 0, num_geoms * sizeof(char));
if (in_a_cluster_ret)
*in_a_cluster_ret = in_a_cluster;
/* Bail if we don't even have enough inputs to make a cluster. */
if (num_geoms <= min_points)
{
if (!in_a_cluster_ret)
lwfree(in_a_cluster);
return LW_SUCCESS;
}
tree = make_strtree((void**) geoms, num_geoms, LW_TRUE);
if (tree.tree == NULL)
{
destroy_strtree(&tree);
return LW_FAILURE;
}
is_in_core = lwalloc(num_geoms * sizeof(char));
memset(is_in_core, 0, num_geoms * sizeof(char));
neighbors = lwalloc(min_points * sizeof(uint32_t));
for (p = 0; p < num_geoms; p++)
{
uint32_t num_neighbors = 0;
if (lwgeom_is_empty(geoms[p]))
continue;
dbscan_update_context(tree.tree, &cxt, geoms, p, eps);
/* We didn't find enough points to do anything, even if they are all within eps. */
if (cxt.num_items_found < min_points)
continue;
for (i = 0; i < cxt.num_items_found; i++)
{
uint32_t q = *((uint32_t*) cxt.items_found[i]);
if (num_neighbors >= min_points)
{
/* If we've already identified p as a core point, and it's already
* in the same cluster in q, then there's nothing to learn by
* computing the distance.
*/
if (UF_find(uf, p) == UF_find(uf, q))
continue;
/* Similarly, if q is already identifed as a border point of another
* cluster, there's no point figuring out what the distance is.
*/
if (in_a_cluster[q] && !is_in_core[q])
continue;
}
double mindist = lwgeom_mindistance2d_tolerance(geoms[p], geoms[q], eps);
if (mindist == FLT_MAX)
{
success = LW_FAILURE;
break;
}
if (mindist <= eps)
{
/* If we haven't hit min_points yet, we don't know if we can union p and q.
* Just set q aside for now.
*/
if (num_neighbors < min_points)
{
neighbors[num_neighbors++] = q;
/* If we just hit min_points, we can now union all of the neighbor geometries
* we've been saving.
*/
if (num_neighbors == min_points)
{
uint32_t j;
is_in_core[p] = LW_TRUE;
in_a_cluster[p] = LW_TRUE;
for (j = 0; j < num_neighbors; j++)
{
union_if_available(uf, p, neighbors[j], is_in_core, in_a_cluster);
}
}
}
else
{
/* If we're above min_points, no need to store our neighbors, just go ahead
* and union them now. This may allow us to cut out some distance
* computations.
*/
union_if_available(uf, p, q, is_in_core, in_a_cluster);
}
}
}
if (!success)
break;
}
lwfree(neighbors);
lwfree(is_in_core);
/* Free in_a_cluster if we're not giving it to our caller */
if (!in_a_cluster_ret)
lwfree(in_a_cluster);
if (cxt.items_found)
lwfree(cxt.items_found);
destroy_strtree(&tree);
return success;
}
int union_dbscan(LWGEOM** geoms, uint32_t num_geoms, UNIONFIND* uf, double eps, uint32_t min_points, char** in_a_cluster_ret)
{
if (min_points <= 1)
return union_dbscan_minpoints_1(geoms, num_geoms, uf, eps, in_a_cluster_ret);
else
return union_dbscan_general(geoms, num_geoms, uf, eps, min_points, in_a_cluster_ret);
}
/** Takes an array of LWGEOM* and constructs an array of LWGEOM*, where each element in the constructed array is a
* GeometryCollection representing a set of geometries separated by no more than the specified tolerance. Caller is
* responsible for freeing the input array, but not the LWGEOM* items inside it. */
int
cluster_within_distance(LWGEOM** geoms, uint32_t num_geoms, double tolerance, LWGEOM*** clusterGeoms, uint32_t* num_clusters)
{
int cluster_success;
UNIONFIND* uf = UF_create(num_geoms);
if (union_dbscan(geoms, num_geoms, uf, tolerance, 1, NULL) == LW_FAILURE)
{
UF_destroy(uf);
return LW_FAILURE;
}
cluster_success = combine_geometries(uf, (void**) geoms, num_geoms, (void***) clusterGeoms, num_clusters, 1);
UF_destroy(uf);
return cluster_success;
}
/** Uses a UNIONFIND to identify the set with which each input geometry is associated, and groups the geometries into
* GeometryCollections. Supplied geometry array may be of either LWGEOM* or GEOSGeometry*; is_lwgeom is used to
* identify which. Caller is responsible for freeing input geometry array but not the items contained within it. */
static int
combine_geometries(UNIONFIND* uf, void** geoms, uint32_t num_geoms, void*** clusterGeoms, uint32_t* num_clusters, char is_lwgeom)
{
size_t i, j, k;
/* Combine components of each cluster into their own GeometryCollection */
*num_clusters = uf->num_clusters;
*clusterGeoms = lwalloc(*num_clusters * sizeof(void*));
void** geoms_in_cluster = lwalloc(num_geoms * sizeof(void*));
uint32_t* ordered_components = UF_ordered_by_cluster(uf);
for (i = 0, j = 0, k = 0; i < num_geoms; i++)
{
geoms_in_cluster[j++] = geoms[ordered_components[i]];
/* Is this the last geometry in the component? */
if ((i == num_geoms - 1) ||
(UF_find(uf, ordered_components[i]) != UF_find(uf, ordered_components[i+1])))
{
if (k >= uf->num_clusters) {
/* Should not get here - it means that we have more clusters than uf->num_clusters thinks we should. */
return LW_FAILURE;
}
if (is_lwgeom)
{
LWGEOM** components = lwalloc(j * sizeof(LWGEOM*));
memcpy(components, geoms_in_cluster, j * sizeof(LWGEOM*));
(*clusterGeoms)[k++] = lwcollection_construct(COLLECTIONTYPE, components[0]->srid, NULL, j, (LWGEOM**) components);
}
else
{
(*clusterGeoms)[k++] = GEOSGeom_createCollection(GEOS_GEOMETRYCOLLECTION, (GEOSGeometry**) geoms_in_cluster, j);
}
j = 0;
}
}
lwfree(geoms_in_cluster);
lwfree(ordered_components);
return LW_SUCCESS;
}
<file_sep>suppressPackageStartupMessages(library(sf))
library(sp)
suppressPackageStartupMessages(library(units))
library(geosphere)
x = st_sfc(
st_point(c(0,0)),
st_point(c(1,0)),
st_point(c(2,0)),
st_point(c(3,0)),
crs = 4326
)
y = st_sfc(
st_point(c(0,10)),
st_point(c(1,0)),
st_point(c(2,0)),
st_point(c(3,0)),
st_point(c(4,0)),
crs = 4326
)
st_crs(y) = 4326
st_crs(x) = 4326
d.sf = st_distance(x, y)
d.sp = spDists(as(x, "Spatial"), as(y, "Spatial")) # equiv to geosphere::distMeeus
d.sf - set_units(d.sp, km)
# compare to geosphere::distVincentyEllispoid:
dv = matrix(NA_real_, 4, 5)
dv[1,] = distVincentyEllipsoid(as(x, "Spatial")[1], as(y, "Spatial"))
dv[2,] = distVincentyEllipsoid(as(x, "Spatial")[2], as(y, "Spatial"))
dv[3,] = distVincentyEllipsoid(as(x, "Spatial")[3], as(y, "Spatial"))
dv[4,] = distVincentyEllipsoid(as(x, "Spatial")[4], as(y, "Spatial"))
d.sf - set_units(dv, m) # difference in micrometer range:
<file_sep>suppressPackageStartupMessages(library(lwgeom))
suppressPackageStartupMessages(library(sf))
demo(nc, ask = FALSE)
nc = st_transform(nc, 3857)
st_perimeter(nc)[1:5]
st_perimeter_2d(nc)[1:5]
| 5da70e4e1a85f6d87ee7eed23565d7ab915dde40 | [
"C",
"R"
] | 4 | R | RafaMariano/lwgeom | 6338a27f77b841939c9cfdad39665d00bb63329c | 64d5900b7316008bf2d7b39047246199151d5e66 |
refs/heads/master | <repo_name>TheNewTimeGamer/JavaGeneralPurposeServer<file_sep>/src/newtime/net/gps/ServerBindings.java
package newtime.net.gps;
import java.io.IOException;
import org.graalvm.polyglot.Context;
import newtime.net.http.HttpServer;
import newtime.net.tcp.TcpServer;
public class ServerBindings {
private Context mainContext;
public ServerBindings(Context mainContext) {
this.mainContext = mainContext;
}
public HttpServer createHttpServer(int port) {
HttpServer httpServer = null;
try {
httpServer = new HttpServer(this.mainContext, port);
} catch (IOException e) {
e.printStackTrace();
}
return httpServer;
}
public TcpServer createTcpServer(int port) {
TcpServer tcpServer = null;
try {
tcpServer = new TcpServer(this.mainContext, port);
} catch (IOException e) {
e.printStackTrace();
}
return tcpServer;
}
}<file_sep>/autoexec.js
console.log("launching server..")
const httpServer = server.createHttpServer(80);
httpServer.registerRoute("/", "home");
httpServer.open();
console.log("Server open!");<file_sep>/src/newtime/net/http/response/BadRequestHttpResponse.java
package newtime.net.http.response;
public class BadRequestHttpResponse extends HttpResponse {
public BadRequestHttpResponse() {
this.status = "400 Bad Request";
this.body = "400 Bad Request".getBytes();
this.header.put("Content-Length", ""+this.body.length);
}
}
<file_sep>/src/newtime/net/http/response/HttpResponse.java
package newtime.net.http.response;
import java.util.Map;
import newtime.net.http.request.HttpRequest;
public class HttpResponse extends HttpRequest {
public String status = "200 OK";
public HttpResponse() {
super();
}
public HttpResponse(String status) {
super();
this.status = status;
}
public HttpResponse(String status, String message) {
super();
this.status = status;
this.body = message.getBytes();
this.header.put("Content-Length", ""+body.length);
}
public HttpResponse(byte[] buffer) throws Exception {
super(buffer);
}
public HttpResponse(HttpRequest request) {
super();
this.method = request.method;
this.action = request.action;
this.protocol = request.protocol;
this.header = request.header;
this.get = request.get;
this.post = request.post;
this.body = request.body;
}
protected String getProtocolAsString() {
String protocol = this.protocol + " " + this.status + "\r\n";
return protocol;
}
}
<file_sep>/src/newtime/net/websocket/WebSocketWorker.java
package newtime.net.websocket;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import newtime.net.http.request.HttpRequest;
import newtime.net.http.response.HttpResponse;
import newtime.net.http.response.HttpResponseBadRequest;
import newtime.net.http.response.HttpResponseSwitchingProtocols;
public class WebSocketWorker {
WebSocketWorker(){
}
//
protected HttpResponse Handshake(byte[] data) {
System.out.println("Incoming get request");
HttpRequest request = HttpRequest.build(data);
boolean correctHandshake = true;
// if(request == null) {
// response = new HttpResponseBadRequest();
// correctHandshake = false;
// }
// Checking if the request is a correct websocket handshake. See rfc6455 4.2.1 for more details
String protocol[] = request.protocol.split("/");
if(protocol[0] != "HTTP" && Double.parseDouble(protocol[1]) < 1.1 ) {
correctHandshake = false;
}
else if(request.header.get("Host") == null || request.header.get("Host").equals("")) {
correctHandshake = false;
}
else if(request.header.get("Origin") == null || request.header.get("Origin").equals("")) {
correctHandshake = false;
}
else if(!request.header.get("Upgrade").equals("websocket")) {
correctHandshake = false;
}
else if(!request.header.get("Sec-WebSocket-Version").equals("13")) {
// OPTIONAL TODO: Send a 426 Upgrade Required response.
// With a |Sec-WebSocket-Version| header field indicating the version(s) the server is capable of understanding.
// See: RFC 6455 4.2.2
correctHandshake = false;
}
else if(request.header.get("Sec-WebSocket-Key") == null || request.header.get("Sec-WebSocket-Key") == null) {
correctHandshake = false;
}
//Optional parts 8 and 9 from rfc6455 4.2.1 are not checked for now.
// If the handshake is correct up to this point, we can check and decode the base 64 key, then create the response key.
String responseKey = null;
if(correctHandshake == true) {
String key = request.header.get("Sec-WebSocket-Key");
key = key.trim();
key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
try {
responseKey = Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest(key.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
correctHandshake = false;
e.printStackTrace();
}
}
if(correctHandshake == true) {
System.out.println("true");
return new HttpResponseSwitchingProtocols(responseKey);
// the protocol has been switched to the websocket protocol.
} else {
System.out.println("False");
return new HttpResponseBadRequest();
}
}
}
<file_sep>/src/newtime/util/FileManager.java
package newtime.util;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileManager {
// TODO: Look at return for storeHtmlResource
public static byte[] getFileContent(String path) {
return getFileContent(new File(path));
}
public static byte[] getFileContent(File file) {
byte[] buffer = null;
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
buffer = new byte[in.available()];
in.read(buffer);
in.close();
}catch(IOException e) {
System.err.println("Can't open file: \"" + file.getAbsolutePath() + "\"");
}
return buffer;
}
}
<file_sep>/src/newtime/net/tcp/kernel/Kernel.java
package newtime.net.tcp.kernel;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import newtime.net.tcp.TcpServer;
public class Kernel implements Runnable {
private BufferedReader in;
private TcpServer server;
private Thread thread;
private boolean running = true;
protected ArrayList<Command> commands = new ArrayList<Command>();
public Kernel(TcpServer server) {
addCommands();
this.in = new BufferedReader(new InputStreamReader(System.in));
this.server = server;
this.thread = new Thread(this);
this.thread.start();
}
public void run() {
showWatermark();
while(running) {
try {
tick();
} catch (IOException e) {
e.printStackTrace();
}
}
server.close();
}
protected void addCommands() {
commands.add(new CommandHelp());
}
private void showWatermark() {
System.out.println("Java General Purpose Server.");
System.out.println("Use the \"help\" command to show a list of commands.");
}
private void tick() throws IOException {
String line = this.in.readLine();
String[] args = {line};
if(line.contains(" ")) {
args = line.split(" ");
}
String output = executeCommand(args);
if(output == null) {
System.out.println("Could not find command \"" + args[0] + "\"");
}else {
System.out.println(output);
}
}
private String executeCommand(String[] args) {
String output = null;
for(int i = 0; i < commands.size(); i++) {
if(commands.get(i).name.equals(args[0])) {
output = commands.get(i).execute(this, args);
break;
}
}
return output;
}
}
<file_sep>/src/newtime/net/http/response/InternalServerErrorHttpResponse.java
package newtime.net.http.response;
public class InternalServerErrorHttpResponse extends HttpResponse {
public InternalServerErrorHttpResponse() {
this.status = "501 Method Not Implemented";
this.body = "501 Method Not Implemented".getBytes();
this.header.put("Content-Length", ""+this.body.length);
}
}
<file_sep>/src/newtime/util/format/Hex.java
package newtime.util.format;
public class Hex {
// %02X :
// '0' - The result will be zero-padded.
// '2' - Width of format.
// 'X' - The result is formatted as a hexadecimal integer, upper-case.
public static String fromByteArray(byte[] buffer) {
StringBuilder builder = new StringBuilder();
for(byte b : buffer) {
builder.append(String.format("%02X", b));
}
return builder.toString();
}
}
<file_sep>/src/newtime/net/tcp/TcpServer.java
package newtime.net.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import org.graalvm.polyglot.Context;
public class TcpServer implements Runnable {
protected ServerSocket server;
protected Thread thread;
protected boolean listening = true;
protected Context mainContext;
public TcpServer(Context mainContext, int port) throws IOException {
this.server = new ServerSocket(port);
this.mainContext = mainContext;
}
public void run() {
while(listening) {
try {
listen();
} catch (IOException e) {
e.printStackTrace();
}
}
close();
}
protected void listen() throws IOException {
Socket socket = server.accept();
if(socket != null) {
onConnection(socket);
}
}
public void open() {
this.thread = new Thread(this);
this.thread.start();
}
public void close() {
this.listening = false;
this.closeServer();
try {
this.thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private boolean closeServer() {
try {
this.server.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public TcpConnection onConnection(Socket socket) {
TcpConnection connection = null;
try {
connection = new TcpConnection(this, socket);
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
}
| 7d1f5597dbbb8c6642f4da8f02d13fa711dad14c | [
"JavaScript",
"Java"
] | 10 | Java | TheNewTimeGamer/JavaGeneralPurposeServer | 2765ba023e8946c8f39c9bef20d438b707c67c53 | d46da25dc6d9dbc7890920e10ceca2e85c8aeece |
refs/heads/master | <file_sep>#iconfont
####项目简介
1. 使用gulp和gulp-iconfont将svg文件编译生成以下四种文件:
```
-iconfont.eot
-iconfont.svg
-iconfont.ttf
-iconfont.woff
```
2. 使用gulp-iconfont-css编译模板css生成字体图标的使用样式
```
src/css/_icons.css //模板css
build/css/_icons.css //实际使用css
```
3. 使用gulp-template编译模板html生成字体图标的使用示例
```
src/example/index.html //模板html
build/example/index.html //示例html
```
####Quick Start
安装依赖包:
$ npm install
安装gulp:
$ npm install --g gulp
编译iconfont,并生成css:
$ gulp iconfont
运行example:
$ gulp example
readme生成HTML:
$ Ctrl+Shift+p -> preview -> save to html -> markdown
####项目结构
* `build` 存放着编译后的文件(eot、svg、ttf、woff等).
* `src` 存放待编译资源(svg图标,模板css/html).
* `.gitignore` git忽略列表.
* `gulpfile.js` gulp命令入口文件.
* `package.json` npm 配置文件.
####相关资源
* [gulp](https://github.com/gulpjs/gulp)
* [gulp-iconfont](https://github.com/nfroidure/gulp-iconfont)
* [gulp-iconfont-css](https://github.com/backflip/gulp-iconfont-css)
* [gulp-template](https://www.npmjs.com/package/gulp-template)
* [es6 node green](http://node.green/)
<file_sep>// var gulp = require('gulp');
// var iconfont = require('gulp-iconfont');
// var runTimestamp = Math.round(Date.now()/1000);
// gulp.task('Iconfont', function(){
// return gulp.src(['assets/icons/*.svg'])
// .pipe(iconfont({
// fontName: 'myfont', // required
// prependUnicode: true, // recommended option
// formats: ['ttf', 'eot', 'woff'], // default, 'woff2' and 'svg' are available
// timestamp: runTimestamp, // recommended to get consistent builds when watching files
// }))
// .on('glyphs', function(glyphs, options) {
// // CSS templating, e.g.
// console.log(glyphs, options);
// })
// .pipe(gulp.dest('www/fonts/'));
// });
// var async = require('async');
// var gulp = require('gulp');
// var iconfont = require('gulp-iconfont');
// var consolidate = require('gulp-consolidate');
// gulp.task('Iconfont', function(done){
// var iconStream = gulp.src(['assets/icons/*.svg'])
// .pipe(iconfont({ fontName: 'myfont' }));
// async.parallel([
// function handleGlyphs (cb) {
// iconStream.on('glyphs', function(glyphs, options) {
// gulp.src('templates/myfont.css')
// .pipe(consolidate('lodash', {
// glyphs: glyphs,
// fontName: 'myfont',
// fontPath: '../fonts/',
// className: 's'
// }))
// .pipe(gulp.dest('www/css/'))
// .on('finish', cb);
// });
// },
// function handleFonts (cb) {
// iconStream
// .pipe(gulp.dest('www/fonts/'))
// .on('finish', cb);
// }
// ], done);
// });
var gulp = require('gulp');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');
var clean = require("gulp-clean");
var taskListing = require("gulp-task-listing");
var template = require("gulp-template");
var fs = require("fs");
var icons = fs.readdirSync("src/icons");
icons = icons.map(function(icon){
return icon.replace(/\.\w+$/, '');
});
var fontName = 'iconfont';
gulp.task('iconfont', ['clean'], function(){
gulp.src('src/icons/*.svg')
.pipe(iconfontCss({
fontName: fontName,
path: 'src/templates/_icons.css',
targetPath: '../../build/css/_icons.css',
fontPath: '../fonts/'
}))
.pipe(iconfont({
fontName: fontName,
formats: ['svg', 'ttf', 'eot', 'woff', 'woff2'],
normalize: true
}))
.pipe(gulp.dest('build/fonts/'));
});
gulp.task('example', function(){
gulp.src('src/example/index.html')
.pipe(template({icons: icons}))
.pipe(gulp.dest("./build/example"));
});
gulp.task('clean', function(){
gulp.src("./build", {read: false}).pipe(clean());
});
gulp.task('help', taskListing);
gulp.task('default',['help']); | 2cd189959ea8990b25b9b4c681ecf0ece2bb8356 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | yangdaidi/iconfont | 6a1e3a1b53f0398896df4c5ab7f10d340a9bbe28 | a395ef27fe591d1753770fe831a4f9cc14f714e4 |
refs/heads/master | <file_sep>package com.kwk.bbs.member.api;
public interface MemberService {
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kwk</groupId>
<artifactId>bbs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<java.src.version>1.6</java.src.version>
<java.target.version>1.6</java.target.version>
<project.encoding>UTF-8</project.encoding>
<servlet.version>2.4</servlet.version>
<spring.version>2.5.6</spring.version>
</properties>
<dependencies>
<!-- begining of spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- end of spring framework -->
<!-- begin of jsp servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<!-- end of jsp servlet -->
<!-- begin log-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<!-- end struts2-->
<!-- begin utils-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<!-- end utils-->
<!-- begining of db -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- end of db -->
<!-- begining of test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.4.12</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.4.12</version>
</dependency>
<!-- end of test -->
</dependencies>
</project>
<file_sep>package com.kwk.bbs.member;
public class MemberServiceTest {
}
| 44df3e94e989bf10375e55cfb89fcf7a914c6b98 | [
"Java",
"Maven POM"
] | 3 | Java | caoyanwei/bbs | 69f2b5a1cd15476552372bda31307f86216dbdab | b92c4edcf7f44500803ce9b705c89f530f5d17ee |
refs/heads/master | <file_sep> var x = Math.floor(Math.random()*100520); // generating otp
var count =0;
// generated otp display
function otp() {
document.getElementById("demo-c").innerHTML = x;
document.getElementById("demo-c").style.background="#111";
document.getElementById("demo-c").style.color="#fff";
}
// crate dynamic buton for personal detial
function myFunction() {
var y = document.getElementById("x").value;
if (y==x) {
let div = document.createElement('div');
div.id = 'content';
div.innerHTML = '<button type="reset" value="Reset" data-toggle="collapse" data-target="#xgen" id="xgenc"></button>';
document.getElementById("fm").appendChild(div);
document.getElementById("xgenc").innerHTML = "Enter Personl Detail";
// document.getElementById("xgenc").classList.add("btn")
document.getElementById("xgenc").classList.add("btn-primary");
document.getElementById("xgenc").classList.add("btn");
}
else{ // handlingwrong
count++;
alert("wrong-otp");
document.getElementById("demo-c").innerHTML = x;
}
console.log(count);
if(count>=3)
{
alert("please reload the page");
myFunction();
}
else{
}
}
<file_sep># New-work
this is form page with html css and js
| 3312ae99fa1ca6804f273241d1dea6e4ffa5f2ec | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | raahul09/New-work | d42754fe954e5adf7efe8b71a369c9485c415e43 | a2c1031fe0ceeaa31daf0c22ea02a963f4f6dd9b |
refs/heads/main | <file_sep>package javaCamp3;
public class StudentManager extends UserManager {
public void AddCourse(Student student) {
System.out.println(student.getCourses() + " isimli kurs eklendi");
}
}<file_sep>package javaCamp3;
public class Instructor extends User{
private String instructorCourses;
public Instructor() {
}
public Instructor(String instructorCourses) {
this.instructorCourses = instructorCourses;
}
public String getInstructorCourses() {
return instructorCourses;
}
public void setInstructorCourses(String instructorCourses) {
this.instructorCourses = instructorCourses;
}
}
| 24e6c1dec25c3fa228fae1d22f9a23fe2e73fd41 | [
"Java"
] | 2 | Java | kevsertirink/JavaWork3 | 251ca958f4bc63143ce8c54de7eb474e1789fed1 | cff07190b4d2d03eb89b046b63cebeff265ebbac |
refs/heads/master | <repo_name>ajaylnt2/Angularjsapp<file_sep>/WebAPI/Controller/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebAPI.Controller
{
[Authorize]
public class HomeController : ApiController
{
[HttpGet]
public IHttpActionResult TestAuthorize()
{
return Ok();
}
}
}
| 4aa419fab6bba741e36f19a40f75c835207fa7e4 | [
"C#"
] | 1 | C# | ajaylnt2/Angularjsapp | 5f911e7c32442315098ec58478af5cd5c0da4332 | 750d6f8f3c403ae7699e169763745046bdf9fcd8 |
refs/heads/master | <repo_name>siamcomdeveloper/nodeJS<file_sep>/routes/blogs.js
/*
* GET blogs listing.
*/
//list = select All
exports.list = function(req, res){
req.getConnection(function(err,connection){
connection.query('SELECT * FROM blogs',function(err,rows) {
if(err)
console.log("Error Selecting : %s ",err );
res.render('showlist',{page_title:"All blogs",data:rows});
});
});
};
exports.add = function(req, res){
res.render('showformadd',{page_title:"Create blogs"});
};
exports.edit = function(req, res){
var id = req.params.id;
req.getConnection(function(err,connection){
connection.query('SELECT * FROM blogs WHERE id = ?',[id],function(err,rows)
{
if(err)
console.log("Error Selecting : %s ",err );
res.render('showformedit',{page_title:"Edit blogs",data:rows[0]});
});
});
};
/*Add blog = Create & Insert the blog*/
exports.save = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
req.getConnection(function (err, connection) {
var data = {
topic : input.topic,
content : input.content,
user_id : 9
};
var query = connection.query("INSERT INTO blogs set ? ",data, function(err, rows)
{
if (err)
console.log("Error inserting : %s ",err );
res.redirect('/blogs');
});
// console.log(query.sql); get raw query
});
};
/*Edit = Edit & Update edited blog*/
exports.save_edit = function(req,res){
var input = JSON.parse(JSON.stringify(req.body));
var id = req.body.id;
req.getConnection(function (err, connection) {
var data = {
topic : input.topic,
content : input.content
};
connection.query("UPDATE blogs set ? WHERE id = ? ",[data,id], function(err, rows)
{
if (err)
console.log("Error Updating : %s ",err );
res.redirect('/blogs');
});
});
};
exports.delete_blog = function(req,res){
var id = req.params.id;
req.getConnection(function (err, connection) {
connection.query("DELETE FROM blogs WHERE id = ? ",[id], function(err, rows)
{
if(err)
console.log("Error deleting : %s ",err );
res.redirect('/blogs');
});
});
};
<file_sep>/Readme.txt
CRUD app with Node js, express js, Bootstrap, EJS, MySQL
http://192.168.3.11:8080/blogs | 5e958996b3d3972382df34f4d093a0f101a69646 | [
"JavaScript",
"Text"
] | 2 | JavaScript | siamcomdeveloper/nodeJS | 5a4ccebee172d8bd524da7097a470762f102d695 | 07cc850bcb1b508ca2132154b9cb805e8efcbe66 |
refs/heads/master | <file_sep>#include <iostream>
#include <vector>
// Contains the knight board datastructure and graph representation
#include <KnightBoard/KnightBoard.h>
// The definition of the 32x32 knight board
#include <fullKnightBoard.h>
using namespace std;
int main() {
/////////////
// Level 4 //
/////////////
// Levels 1-3 are covered in the provided unit tests in test/KnightBoard/KnightBoardTest.cpp
// KnightBoard (optionally) takes a char array that defines the map.
// The full Cruise knight board is defined in fullKnightBoard.h
KnightBoard *kn = new KnightBoard(board, 32);
// Coordinates are provided as pairs of ints, the first value is the row, second is the column.
pair<int,int> begin(0,0);
pair<int,int> end(0,31);
// The knight board is represented as a graph, where Squares are the nodes, and valid knight's
// moves are the edges. The shortest path is found using dijkstra's algorithm. A* would be a
// a better alternative, but dijkstra is fine for small boards. Furthermore, the teleports
// would throw off A*'s hueristics.
vector<Square *> path = kn->findShortestPath(begin, end);
// Asserts that each step in the sequence is valid.
kn->validSequence(path, true);
/////////////
// Level 5 //
/////////////
// The longest path will work eventually, but the problem is brute-forced.
// If I had more time, I'd look into tree pruning, or some way or reformulatng
// the problem. It's a hard problem, not much in the way of optimal substructure.
KnightBoard *kn_level5 = new KnightBoard(4);
pair<int,int> begin_level5(0,0);
pair<int,int> end_level5(3,3);
vector<Square *> path_level5 = kn_level5->findLongestPath(begin_level5, end_level5);
return kn_level5->validSequence(path_level5, true);
return 0;
}
<file_sep>#set(ALL_HEADERS KnightBoard/KnightBoard.h)
set(KNIGHT_BOARD_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/KnightBoard/KnightBoard.h PARENT_SCOPE)
set(ALL_HEADERS ${ALL_HEADERS} ${KNIGHT_BOARD_HEADERS} PARENT_SCOPE)
set(SQUARE_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/Square/Square.h PARENT_SCOPE)
set(ALL_HEADERS ${ALL_HEADERS} ${SQUARE_HEADERS} PARENT_SCOPE)
set(ALL_HEADERS ${ALL_HEADERS} ${CMAKE_CURRENT_SOURCE_DIR}/fullKnightBoard.h PARENT_SCOPE)<file_sep>//
// Created by wcmarsha on 9/14/2015.
//
#include <iostream>
#include <stdexcept>
#include <stdlib.h>
#include <algorithm>
#include <limits.h>
#include <set>
#include "KnightBoard/KnightBoard.h"
using std::cout;
using std::endl;
using std::set;
// Common code for constructors.
void KnightBoard::init(char *_board, unsigned int size) {
this->size = size;
this->teleports.first = NULL;
this->teleports.second = NULL;
this->constructEmptyBoard(size);
for(unsigned int col = 0; col < size; col++){
for(unsigned int row = 0; row < size; row++){
Square *sq = new Square(row, col, _board[size*row + col], this);
if(_board[size*row + col] == 'T'){
teleports.first == NULL ? teleports.first = sq : teleports.second = sq;
}
this->setSquare(row, col, sq);
}
}
setAdjacents();
determineAllConnections();
}
KnightBoard::KnightBoard(unsigned int size) {
char * kboard = (char *)malloc(size*size);
for(int i = 0; i < size*size; i++){
kboard[i] = '.';
}
init(kboard, size);
}
KnightBoard::KnightBoard(char *board, unsigned int size) {
this->init(board, size);
}
bool KnightBoard::validSequence(vector<std::pair<unsigned int, unsigned int> > sequence, bool printBoards) {
vector<Square *> squareSequence;
for(auto step : sequence){
squareSequence.push_back(getSquare(step));
}
return validSequence(squareSequence, printBoards);
}
bool KnightBoard::validSequence(vector<Square *> squareSequence, bool printBoards) {
Square *prev = NULL;
for(auto square : squareSequence){
if(!(NULL == prev)){
if(!prev->isConnected(square)){
return false;
}
}
square->containsKnight = true;
if(printBoards)
this->printBoard();
square->containsKnight = false;
prev = square;
}
return true;
}
Square *KnightBoard::getSquare(unsigned int row, unsigned int col) {
if(row >= this->size || row < 0 || col >= this->size || col < 0){
return NULL;
}
return this->board->at(size*row + col);
}
Square *KnightBoard::getSquare(pair<unsigned int, unsigned int> position) {
return this->board->at(size*position.first + position.second);
}
void KnightBoard::setSquare(unsigned int row, unsigned int col, Square *sq) {
if(row >= size || row < 0 || col >= size || col < 0){
throw new std::out_of_range("Arguments to setSquare() were out of range");
}
this->board->at(size*row + col) = sq;
}
void KnightBoard::constructEmptyBoard(unsigned int size) {
vector<Square *> * _board = new vector<Square *>(size*size);
this->board = _board;
}
void KnightBoard::setAdjacents() {
for(unsigned int i = 0; i < this->size; i++){
for(unsigned int j = 0; j < this->size; j++) {
Square *sq = this->getSquare(i, j);
sq->setUp(this->getSquare(i-1, j));
sq->setRight(this->getSquare(i, j+1));
sq->setDown(this->getSquare(i+1, j));
sq->setLeft(this->getSquare(i, j-1));
}
}
}
void KnightBoard::printBoard() {
for (unsigned int i = 0; i < size; i++) {
for (unsigned int j = 0; j < size; j++) {
if(this->getSquare(i,j)->containsKnight)
cout<<"K ";
else
cout << this->getSquare(i, j)->symbol<<" ";
}
cout << endl;
}
cout << endl;
}
void KnightBoard::determineAllConnections() {
for(auto square : *(this->board)){
square->determineConnections();
}
}
Square *KnightBoard::getOtherTeleport(Square *sq) {
if(teleports.first == sq)
return teleports.second;
else
return teleports.first;
}
vector<Square *> KnightBoard::findShortestPath(pair<unsigned int, unsigned int> start,
pair<unsigned int, unsigned int> end) {
typedef pair< Square *, pair<Square *, int> *> future_connection_t;
typedef pair<Square *, int> connection_t;
Square *sqStart = this->getSquare(start);
Square *sqEnd = this->getSquare(end);
sqStart->path_weight=0;
set<Square *> *visited = new set<Square *>();
set<future_connection_t *> *unvisited = new set<future_connection_t *>();
visited->insert(sqStart);
for(int i = 0; i < sqStart->connections.size(); i++){
unvisited->insert(new future_connection_t(sqStart, &(sqStart->connections[i])));
}
// Perform dijkstra's algorithm iteratively.
while(unvisited->size() > 0){
// Get lightest connection
int min_weight = INT_MAX;
future_connection_t *lightest = NULL;
for(auto unvisit : *unvisited){
Square *internal = unvisit->first;
Square *external = unvisit->second->first;
int weight = unvisit->second->second;
int path_weight = unvisit->first->path_weight;
if(path_weight + weight < min_weight){
min_weight = path_weight + weight;
lightest = unvisit;
}
}
lightest->second->first->path_weight = lightest->first->path_weight + lightest->second->second;
lightest->second->first->backEdge = lightest->first;
visited->insert(lightest->second->first);
// Erase connections from unvisited for which a lighter path has been found
vector<future_connection_t *> toErase;
for(auto unvisit : *unvisited){
if(unvisit->second->first == lightest->second->first){
toErase.push_back(unvisit);
}
}
for(auto eraseMe : toErase){
unvisited->erase(eraseMe);
}
for(int i = 0; i < lightest->second->first->connections.size(); i++){
connection_t *conn = &lightest->second->first->connections[i];
if(visited->count(conn->first) == 0)
unvisited->insert(new future_connection_t(lightest->second->first, conn));
}
// Return the path after backtracking.
if(lightest->second->first == sqEnd){
vector<Square *> *lightestPath = new vector<Square *>();
lightestPath->push_back(lightest->second->first);
Square *_backEdge = lightest->first;
while(_backEdge != NULL){
lightestPath->insert(lightestPath->begin(), _backEdge);
_backEdge = _backEdge->backEdge;
}
for(auto visit : *visited){
visit -> backEdge = (NULL);
visit -> path_weight = (INT_MAX);
}
delete visited;
delete unvisited;
return *lightestPath;
}
}
return std::vector<Square *>();
}
vector<Square *> KnightBoard::findLongestPath(pair<unsigned int, unsigned int> start,
pair<unsigned int, unsigned int> end) {
typedef pair< Square *, pair<Square *, int> *> future_connection_t;
typedef pair<Square *, int> connection_t;
Square *sqStart = this->getSquare(start);
Square *sqEnd = this->getSquare(end);
sqStart->path_weight=0;
vector<Square *> *curPath = new vector<Square *>();
vector<Square *> *longestPath = new vector<Square *>();
curPath->push_back(sqStart);
int largestWeight = 0;
longestPathHelper(curPath, longestPath, sqStart, &largestWeight, sqEnd);
return *longestPath;
}
void KnightBoard::longestPathHelper(vector<Square *> *currentPath, vector<Square *> *longestPath, Square *head,
int *largestWeight, Square *sqEnd){
if(head == sqEnd){
if(head->path_weight > *largestWeight){
longestPath->clear();
for(auto step : *currentPath){
longestPath->push_back(step);
}
*largestWeight=head->path_weight;
}
return;
}
for(auto conn : head->connections){
Square * newHead = conn.first;
bool skip_over = false;
for(auto step : *currentPath){
if(step == newHead)
skip_over = true;
}
if(skip_over)
continue;
currentPath->push_back(newHead);
newHead->path_weight = head->path_weight + conn.second;
longestPathHelper(currentPath, longestPath, newHead, largestWeight, sqEnd);
currentPath->erase(find(currentPath->begin(), currentPath->end(), newHead));
}
}
vector<Square *> KnightBoard::findShortestPath(unsigned int s_row, unsigned int s_col, unsigned int e_row,
unsigned int e_col) {
pair<unsigned int,unsigned int> start(s_row,s_col), end(e_row,e_col);
return findShortestPath(start, end);
}
vector<Square *> KnightBoard::findLongestPath(unsigned int s_row, unsigned int s_col, unsigned int e_row,
unsigned int e_col) {
pair<unsigned int,unsigned int> start(s_row,s_col), end(e_row,e_col);
return findLongestPath(start, end);
}
map<char,int> KnightBoard::symbolWeights = {
{'.', 1},
{'B', INT_MAX},
{'W', 2},
{'R', INT_MAX},
{'L', 5},
{'T', 1}
};
<file_sep>//
// Created by wcmarsha on 9/14/2015.
//
#ifndef CRUISE_KNIGHTBOARD_H
#define CRUISE_KNIGHTBOARD_H
#include <vector>
#include <map>
#include <string>
#include <utility>
#include "Square/Square.h"
using std::pair;
using std::vector;
using std::map;
using std::string;
// Needs to be forward declared due to cyclic dependency
class Square;
class KnightBoard {
public:
/**
* Constructs a sizexsize board board of '.' squares.
*/
KnightBoard(unsigned int size);
/**
* Reads in a graph as a 2-D grid, where 'size' represents the side length of the board. E.g,
* for a 7x7 board, size = 7. The board should be heap-allocated, as a reference is maintained,
* and going out of scope would free its memory.
*/
KnightBoard(char *board, unsigned int size);
/*
* Determines whether the given sequence corresponds to valid knight moves.
*/
bool validSequence(vector<std::pair<unsigned int, unsigned int> > sequence, bool printBoards);
bool validSequence(vector<Square *> sequence, bool printBoards);
/**
* Gets the square at the given position.
* position.first is the row, position.second is the column
*/
Square *getSquare(pair<unsigned int, unsigned int> position);
Square *getSquare(unsigned int row, unsigned int col);
/**
* Sets the square at the supplied coordinates to the given square reference.
*/
void setSquare(unsigned int row, unsigned int col, Square * sq);
/**
* Prints the board, including its symbols and the location of the knight.
*/
void printBoard();
/**
* Given a pointer to one teleport square, return a pointer to the other.
* Assumes that there are only two.
*/
Square *getOtherTeleport(Square *sq);
/**
* Finds the shortest path between the two squares specified by the supplies coordinates.
*/
vector<Square *> findShortestPath(pair<unsigned int, unsigned int> start, pair<unsigned int, unsigned int> end);
vector<Square *> findShortestPath(unsigned int s_row, unsigned int s_col, unsigned int e_row, unsigned int e_col);
/**
* Finds the longest path between the two squares specified by the supplies coordinates.
* Eventually, anyway.
*/
vector<Square *> findLongestPath(pair<unsigned int, unsigned int> start, pair<unsigned int, unsigned int> end);
vector<Square *> findLongestPath(unsigned int s_row, unsigned int s_col, unsigned int e_row, unsigned int e_col);
/**
* A map of the weights for the given symbols.
*/
static map<char, int> symbolWeights;
private:
void init(char *board, unsigned int size);
void longestPathHelper(vector<Square *> *currentPath, vector<Square *> *longestPath, Square *head,
int *largestWeight, Square *sqEnd);
void constructEmptyBoard(unsigned int size);
void setAdjacents();
void determineAllConnections();
pair<Square *, Square *> teleports;
char **charBoard;
vector<Square *> *board;
unsigned int size;
};
#endif //CRUISE_KNIGHTBOARD_H
<file_sep>//
// Created by wcmarsha on 9/14/2015.
//
#include <iostream>
#include <vector>
#include <assert.h>
#include <KnightBoard/KnightBoard.h>
using std::vector;
using std::cout;
using std::endl;
namespace CruiseTests {
int adjacentTest(){
int boardSize = 7;
KnightBoard *kn = new KnightBoard(boardSize);
for(int i = 0; i < boardSize; i++){
for(int j = 0; j < boardSize; j++){
Square * s = kn->getSquare(i, j);
vector<Square *> adjacents;
adjacents.push_back(s->getAdjacent("up"));
adjacents.push_back(s->getAdjacent("right"));
adjacents.push_back(s->getAdjacent("down"));
adjacents.push_back(s->getAdjacent("left"));
for(auto adj : adjacents){
if(NULL != adj) {
assert(s->isAdjacent(adj));
assert(adj->isAdjacent(s));
}
}
}
}
return 0;
}
int connectionsTest(){
vector<int> numConns = {4, 6, 8, 8, 8, 6, 4,
6, 8, 12, 12, 12, 8, 6,
8, 12, 16, 16, 16, 12, 8,
8, 12, 16, 16, 16, 12, 8,
8, 12, 16, 16, 16, 12, 8,
6, 8, 12, 12, 12, 8, 6,
4, 6, 8, 8, 8, 6, 4};
int boardSize = 7;
KnightBoard *kn = new KnightBoard(boardSize);
for(int i = 0; i < boardSize; i++){
for(int j = 0; j < boardSize; j++){
Square *s = kn->getSquare(i,j);
int squareConns = s->connections.size();
int expectedConns = numConns[boardSize * i + j];
assert(squareConns == expectedConns);
}
}
return 0;
}
/////////////
// Level 1 //
/////////////
// An example of how a sequence of moves can be validated
bool validSequenceTest(){
int boardSize = 7;
KnightBoard *kn = new KnightBoard(boardSize);
vector<pair<unsigned int, unsigned int> > seq1;
seq1.push_back(*new pair<unsigned int, unsigned int>(0,0));
seq1.push_back(*new pair<unsigned int, unsigned int>(1,2));
seq1.push_back(*new pair<unsigned int, unsigned int>(2,0));
seq1.push_back(*new pair<unsigned int, unsigned int>(3,2));
seq1.push_back(*new pair<unsigned int, unsigned int>(5,3));
return kn->validSequence(seq1, false);
}
bool invalidSequenceTest(){
int boardSize = 7;
KnightBoard *kn = new KnightBoard(boardSize);
vector<pair<unsigned int, unsigned int> > seq1;
seq1.push_back(*new pair<unsigned int, unsigned int>(0,0));
seq1.push_back(*new pair<unsigned int, unsigned int>(1,2));
seq1.push_back(*new pair<unsigned int, unsigned int>(2,0));
seq1.push_back(*new pair<unsigned int, unsigned int>(3,3));
seq1.push_back(*new pair<unsigned int, unsigned int>(5,3));
return kn->validSequence(seq1, false);
}
/////////////////
// Level 2 & 3 //
/////////////////
// An example of how the shortest path can be found between two specified coordinates
bool shortestPathTest(){
int boardSize = 7;
KnightBoard *kn = new KnightBoard(boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(6,6);
vector<Square *> path = kn->findShortestPath(begin, end);
return kn->validSequence(path, false);
}
bool longestPathTest(){
int boardSize = 4;
KnightBoard *kn = new KnightBoard(boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(3,3);
vector<Square *> path = kn->findLongestPath(begin, end);
return kn->validSequence(path, false);
}
bool shortestPathBarrierTest(){
char board[] = {
'.','.','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','.','.','.','.','.','.',
};
int boardSize = 7;
KnightBoard *kn = new KnightBoard(board, boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(0,6);
vector<Square *> path = kn->findShortestPath(begin, end);
return kn->validSequence(path, false);
}
bool shortestPathTeleportTest(){
char board[] = {
'.','.','.','.','.','.','.',
'.','.','.','.','.','.','.',
'.','T','.','.','.','.','.',
'.','.','.','.','.','.','.',
'.','.','.','.','.','T','.',
'.','.','.','.','.','.','.',
'.','.','.','.','.','.','.',
};
int boardSize = 7;
KnightBoard *kn = new KnightBoard(board, boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(6,6);
vector<Square *> path = kn->findShortestPath(begin, end);
return kn->validSequence(path, false);
}
bool shortestPathWaterTest(){
char board[] = {
'.','.','.','.','.','.','.',
'.','.','.','.','.','.','.',
'.','W','.','.','.','.','.',
'W','W','W','.','.','.','.',
'W','W','W','.','.','.','.',
'W','W','.','.','.','.','.',
'.','.','.','.','.','.','.',
};
int boardSize = 7;
KnightBoard *kn = new KnightBoard(board, boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(6,0);
vector<Square *> path = kn->findShortestPath(begin, end);
return kn->validSequence(path, false);
}
bool shortestPathLavaTest(){
char board[] = {
'.','.','.','.','.','.','.',
'.','.','L','.','.','.','.',
'.','W','.','.','.','.','.',
'W','W','W','L','.','.','.',
'W','W','W','.','.','.','.',
'W','W','.','.','.','.','.',
'.','.','.','.','.','.','.',
};
int boardSize = 7;
KnightBoard *kn = new KnightBoard(board, boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(6,0);
vector<Square *> path = kn->findShortestPath(begin, end);
return kn->validSequence(path, false);
}
bool shortestPathRocksTest(){
char board[] = {
'.','.','.','.','R','.','.',
'.','.','R','.','R','.','.',
'.','.','R','.','R','.','.',
'.','.','R','.','.','.','.',
'.','.','R','.','.','.','.',
'.','.','.','.','R','R','.',
'.','.','.','.','.','.','.',
};
int boardSize = 7;
KnightBoard *kn = new KnightBoard(board, boardSize);
pair<int,int> begin(0,0);
pair<int,int> end(6,6);
vector<Square *> path = kn->findShortestPath(begin, end);
return kn->validSequence(path, false);
}
}
int main() {
assert(CruiseTests::adjacentTest() == 0);
assert(CruiseTests::connectionsTest() == 0);
assert(CruiseTests::validSequenceTest() == true);
assert(CruiseTests::invalidSequenceTest() == false);
assert(CruiseTests::shortestPathTest() == true);
assert(CruiseTests::longestPathTest() == true);
assert(CruiseTests::shortestPathBarrierTest() == true);
assert(CruiseTests::shortestPathTeleportTest() == true);
assert(CruiseTests::shortestPathWaterTest() == true);
assert(CruiseTests::shortestPathLavaTest() == true);
assert(CruiseTests::shortestPathRocksTest() == true);
}
<file_sep>cmake_minimum_required(VERSION 2.8)
project(cruise)
enable_testing()
#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include_directories("include")
add_subdirectory(include)
add_subdirectory(src)
# Handle testing
add_subdirectory(test)
# Build and link main executable
set(SOURCE_FILES main.cpp ${ALL_HEADERS})
add_executable(cruise ${SOURCE_FILES})
target_link_libraries(cruise KnightBoard Square)
<file_sep>add_library(KnightBoard STATIC src/KnightBoard.cpp ${KNIGHT_BOARD_HEADERS} ${SQUARE_HEADERS})
<file_sep>//
// Created by wcmarsha on 9/14/2015.
//
#ifndef CRUISE_SQUARE_H
#define CRUISE_SQUARE_H
#include <utility>
#include <vector>
#include <map>
#include <string>
#include "KnightBoard/KnightBoard.h"
using std::vector;
using std::pair;
using std::map;
using std::string;
// Needs to be forward declared due to cyclic dependency
class KnightBoard;
class Square {
public:
Square(int row, int column, char symbol, KnightBoard *board);
Square(pair<int, int> position, char symbol, KnightBoard *board);
/**
* Returns true if the other square, sq, is a valid knight's move away
* from *this. Can only be invoked after KnightBoard::init() is called.
*/
bool isConnected(Square *sq);
/**
* Returns true if the other square, sq, is immediately adjacent
* to *this. Can only be invoked after KnightBoard::init() is called.
*/
bool isAdjacent(Square *sq);
KnightBoard * getBoard();
/**
* Returns the square that is immediately "up", "down", "left", or "right"
* on the board.
*/
Square * getAdjacent(string direction);
Square * setUp(Square *sq);
Square * setRight(Square *sq);
Square * setDown(Square *sq);
Square * setLeft(Square *sq);
/**
* Retrieves the position of the piece in the board.
*/
pair<int, int> getPosition();
/**
* Traverses the graph, and figures out which other squares are a valid
* knight's move away.
*/
void determineConnections();
// The symbol of the square on the map
char symbol;
// True, if the square currently contains the knight. Used for printing.
bool containsKnight;
// Each element of this vector contains a valid knight's move from this square.
// pair.first is the connected square
// pair.second is the weight of the connection
vector<pair<Square *, int> > connections;
// Used for traversing backwards with dijkstra's algorithm.
Square *backEdge;
// The weight of the path thus far.
int path_weight;
private:
vector<Square *> getDirectionalPath(vector<string> knightMove);
KnightBoard *board;
vector<Square *> adjacents;
map<string, Square *> adjacentMap;
pair<int, int> position;
static vector<vector<string> > moves;
};
#endif //CRUISE_SQUARE_H
<file_sep># Cruise KnightBoard
A solution to Cruise's Kight's Board problem.
## Usage
The KnightBoard object contains all the key datastructures and methods. To begin, you must supply the KnightBoard with the size
of the board, and a char array containing the board information. If the board only consists of the '.' character, then only the
board size needs to be supplied. For example:
``` c++
char board[] = {
'.','.','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','T','.','B','.','.','.',
'.','.','.','B','.','.','.',
'.','.','.','B','.','T','.',
'.','.','.','B,'.','.','.',
'.','.','.','B','.','.','.',
};
KnightBoard *kn = new KnightBoard(7); // Constructs a 7x7 board containing only '.'
KnightBoard *kn2 = new KnightBoard(board, 7); // Constructs a 7x7 board containing the map
pair<int,int> begin(0,0); // Start
pair<int,int> end(6,6); // End
vector<Square *> path = kn->findShortestPath(begin, end); // Path through the first board
vector<Square *> path2 = kn->findShortestPath(begin, end); // Path through the second board
kn->validSequence(path, false);
kn->validSequence(path2, false);
```
## Compiling/Running
To compile and run the project, first clone the repository somewhere on your filesystem. It requires CMake >= 2.8, and
gcc/g++ >= 2.8 (that I've tested with. It might work with 4.7).
``` bash
$ git clone https://github.com/wheelium-m/cruiseKnightBoard.git
$ cd cruiseKnightBoard
```
Make a build folder, and generate the makefiles.
``` bash
$ mkdir build && cd build
$ cmake .. && make
```
To run the main program, simply type
``` bash
$ ./cruise
```
To run the tests, type
``` bash
$ ctest
```
## Approach
### Levels 1-4
The board is treated as a graph, where valid knight moves correspond to edges. The board is preprocessed to find all valid
moves that can be made from a particular square, and then traversed using dijkstra's algorithm to find the shortest path.
As is mentioned in the comments, A* might be a better approach for very large boards, but for only a 32x32 dijkstra was
sufficient. Furthermore, the presence of teleporters might throw off A*'s hueristic distance hueristic.
### Level 5
Since the graph is not a DAG, it was hard (NP hard, anyway :) ) to find an efficient solution. It's very possible that there
was some sort of tree-pruning I missed, but I didn't have time to implement anything other than a brute force solution.
## Implementation Time
The breakdown for my work hours is approximately as follows:
* Getting cmake configuring ---------------- 1hr.
* Implementing the graph/board ----------- 5hrs
* Implementing dijkstra's -------------------- 3hrs
* Implementing longest path ---------------- 2 hrs
* Adding tests/commenting ------------------ 1.5 hrs
TOTAL 12.5 hrs
Although I consider myself a C++/Python/Linux style programmer, I am currently working with a Java/Windows development stack, so
it took somewhat longer to implement this than I feel it otherwise would. For this project, I used Jetbrains CLion on Windows
for the brunt of the development, and switched to Emacs/Ubuntu towards the end.
If you would like to see projects on my other gitHub account, you can find them here: https://github.com/wmarshall484
I am currently contributing to IBMStreams, a realtime datastreaming framework.
Thanks for reviewing this! Please let me know if you have any questions.
<file_sep>add_executable(KnightBoardTest KnightBoard/KnightBoardTest.cpp ${ALL_HEADERS})
target_link_libraries(KnightBoardTest KnightBoard Square)
add_test(KnightBoardTestTarget KnightBoardTest 0)<file_sep>add_subdirectory(KnightBoard)
add_subdirectory(Square)<file_sep>add_library(Square STATIC src/Square.cpp ${KNIGHT_BOARD_HEADERS} ${SQUARE_HEADERS})
<file_sep>//
// Created by wcmarsha on 9/14/2015.
//
#include <limits.h>
#include "Square/Square.h"
Square::Square(int row, int column, char symbol, KnightBoard *board)
:adjacents(4), containsKnight(false), backEdge(NULL), path_weight(INT_MAX) {
this->position.first = row;
this->position.second = column;
this->symbol = symbol;
this->board = board;
}
Square::Square(pair<int, int> position, char symbol, KnightBoard *board)
:adjacents(4), containsKnight(false), backEdge(NULL), path_weight(INT_MAX) {
this->position.first = position.first;
this->position.second = position.second;
this->symbol = symbol;
this->board = board;
}
bool Square::isConnected(Square *sq) {
for (auto connection : connections) {
if (connection.first == sq) {
return true;
}
}
return false;
}
bool Square::isAdjacent(Square *sq) {
for (auto adjacent : adjacents) {
if (adjacent == sq) {
return true;
}
}
return false;
}
KnightBoard *Square::getBoard() {
return this->board;
}
Square *Square::setUp(Square *sq) {
this->adjacents[0] = sq;
this->adjacentMap["up"] = sq;
}
Square *Square::setRight(Square *sq) {
this->adjacents[1] = sq;
this->adjacentMap["right"] = sq;
}
Square *Square::setDown(Square *sq) {
this->adjacents[2] = sq;
this->adjacentMap["down"] = sq;
}
Square *Square::setLeft(Square *sq) {
this->adjacents[3] = sq;
this->adjacentMap["left"] = sq;
}
pair<int, int> Square::getPosition() {
return position;
}
Square *Square::getAdjacent(string direction) {
return adjacentMap[direction];
}
vector<Square *> Square::getDirectionalPath(vector<string> knightMove) {
vector<Square *> *path = new vector<Square *>();
path->push_back(this);
path->push_back(this->getAdjacent(knightMove[0]));
if(path->at(1) == NULL){
delete path;
return std::vector<Square *>();
}
path->push_back(path->at(1)->getAdjacent(knightMove[1]));
if(path->at(2) == NULL){
delete path;
return std::vector<Square *>();
}
path->push_back(path->at(2)->getAdjacent(knightMove[2]));
if(path->at(3) == NULL){
delete path;
return std::vector<Square *>();
}
for(auto square : *path){
if(square->symbol == 'B') {
delete path;
return std::vector<Square *>();
}
}
if(path->at(3)->symbol == 'R'){
delete path;
return std::vector<Square *>();
}
if(path->at(3)->symbol == 'T'){
path->at(3) = this->getBoard()->getOtherTeleport(path->at(3));
}
return *path;
}
void Square::determineConnections() {
for(auto move : moves){
vector<Square *> path = getDirectionalPath(move);
if(path.size() == 0)
continue;
int weight = this->board->symbolWeights[path[0]->symbol];
this->connections.push_back(*(new pair<Square *, int>(path[3], weight)));
}
}
vector<vector<string> > Square::moves = {
{"up","up","left"},
{"up","up","right"},
{"up","left","left"},
{"up","right","right"},
{"right","right","up"},
{"right","right","down"},
{"right","up","up"},
{"right","down","down"},
{"down","down","right"},
{"down","down", "left"},
{"down","right","right"},
{"down","left","left"},
{"left","left","down"},
{"left","left","up"},
{"left","down","down"},
{"left","up","up"}
}; | f2069c3bb0d1f5b6123105dd57a498d34db6c663 | [
"Markdown",
"CMake",
"C++"
] | 13 | C++ | wheelium-m/cruiseKnightBoard | 346381e2a258f56280dd643fea14008b3244dcf2 | f1392f2a7d8baff5e58b3c68334e4dfffb4030d1 |
refs/heads/master | <file_sep>#!/usr/bin/env python
"""
OpenCMISS C Interface Generation
--------------------------------
This python script generates the C interface for the OpenCMISS library from opencmiss.f90.
It finds integer constants from the source code and includes them in opencmiss.h
It generates C functions in opencmiss_c.f90 from subroutines in opencmiss.f90 and puts
the function declaration in opencmiss.h.
For interfaces where one routine takes parameters as scalars and another takes them as arrays,
only the routine that takes arrays is included. This is done by checking the routine names for
"Number0", "Number1", "Number01" etc. so relies on this naming convention to work correctly.
Limitations
-----------
- Doesn't support multi-dimensional arrays of CMISS types or Logicals, but this can be added
if required.
- Doesn't account for the difference in storage order of multi-dimensional arrays between C
and Fortran, except in CMISSC2FStrings.
"""
from __future__ import with_statement
import sys
import re
from operator import attrgetter
def main():
import os
if len(sys.argv) == 4:
(cm_path,opencmiss_h_path,opencmiss_c_f90_path) = sys.argv[1:]
else:
sys.stderr.write('Usage: %s cm_path opencmiss_h_path opencmiss_c_f90_path\n' % sys.argv[0])
exit(1)
cm_source_path=cm_path+os.sep+'src'
sources = [cm_source_path+os.sep+file_name \
for file_name in os.listdir(cm_source_path) \
if file_name.endswith('.f90') and file_name != 'opencmiss.f90']
library = LibrarySource(cm_source_path+os.sep+'opencmiss.f90',sources)
with open(opencmiss_h_path,'w') as opencmissh:
library.write_c_header(opencmissh)
with open(opencmiss_c_f90_path,'w') as opencmisscf90:
library.write_c_f90(opencmisscf90)
class LibrarySource(object):
"""Holds info on all the library source code"""
class SourceFile(object):
"""Info for an individual source file"""
class SectionFinder(object):
"""Match a section within a source file"""
def __init__(self,source_file):
self.match = None
self.lineno = 0
self.lines = []
self.source_file = source_file
def check_for_end(self,line):
if self.end_re.search(line):
self.finish()
self.lines = []
return True
return False
def check_for_start(self,lineno,line):
match = self.start_re.search(line)
if match:
self.match = match
self.lineno = lineno
self.lines.append(line)
return True
return False
class LineFinder(object):
"""Match a line within a source file"""
def __init__(self,source_file):
self.source_file = source_file
def check_match(self,line,lineno):
match = self.line_re.search(line)
if match:
self.add(match,lineno)
class SubroutineFinder(SectionFinder):
start_re = re.compile(r'^\s*(RECURSIVE\s+)?SUBROUTINE\s+([A-Z0-9_]+)\(',re.IGNORECASE)
end_re = re.compile(r'^\s*END\s*SUBROUTINE',re.IGNORECASE)
def finish(self):
name = self.match.group(2)
self.source_file.subroutines[name] = Subroutine(name,self.lineno,self.lines,self.source_file)
class InterfaceFinder(SectionFinder):
start_re = re.compile(r'^\s*INTERFACE\s+([A-Z0-9_]+)',re.IGNORECASE)
end_re = re.compile(r'^\s*END\s*INTERFACE',re.IGNORECASE)
def finish(self):
name = self.match.group(1)
self.source_file.interfaces[name] = Interface(name,self.lineno,self.lines,self.source_file)
class TypeFinder(SectionFinder):
start_re = re.compile(r'^\s*TYPE\s+([A-Z0-9_]+)',re.IGNORECASE)
end_re = re.compile(r'^\s*END\s*TYPE',re.IGNORECASE)
def finish(self):
name = self.match.group(1)
self.source_file.types[name] = Type(name,self.lineno,self.lines,self.source_file)
class PublicFinder(LineFinder):
line_re = re.compile(r'^\s*PUBLIC\s+([A-Z0-9_,\s]+)',re.IGNORECASE)
def add(self,match,lineno):
for symbol in match.group(1).split(','):
self.source_file.public.append(symbol.strip())
class ConstantFinder(LineFinder):
line_re = re.compile(r'^\s*INTEGER\([A-Z0-9\(\),_\s]+::\s*([A-Z0-9_]+)\s*=\s*([A-Z0-9_\-\.]+)[^!]*(!<.*$)?',re.IGNORECASE)
def add(self,match,lineno):
name = match.group(1)
assignment = match.group(2)
if match.group(3) is None:
doxy = ''
else:
doxy = match.group(3)[2:].strip()
self.source_file.constants[name] = Constant(name,lineno,assignment,doxy)
class DoxygenGroupingFinder(LineFinder):
#match at least one whitespace character before the ! to make sure
#we don't get stuff from the file header
line_re = re.compile(r'^\s+!\s*>\s*(\\(addtogroup|brief|see)|@[\{\}])(.*$)',re.IGNORECASE)
def add(self,match,lineno):
line = match.group(1)
if match.group(3) is not None:
line += match.group(3)
self.source_file.doxygen_groupings.append(DoxygenGrouping(lineno,line))
def __init__(self,source_file,params_only=False):
"""Initialise SourceFile object
Arguments:
source_file -- Path to the source file
"""
self.file_path = source_file
self.public = []
self.doxygen_groupings = []
self.interfaces = {}
self.subroutines = {}
self.constants = {}
self.types = {}
self.parse_file(params_only)
def parse_file(self,params_only=False):
"""Run through file once, getting everything we'll need"""
source_lines = _join_lines(open(self.file_path,'r').read()).splitlines(True)
if not params_only:
#only keep the source_lines if we need them
self.source_lines = source_lines
#Set the things we want to find
line_finders = []
section_finders = []
line_finders.append(self.ConstantFinder(self))
if not params_only:
line_finders.extend((
self.PublicFinder(self),
self.DoxygenGroupingFinder(self)))
section_finders.extend((
self.SubroutineFinder(self),
self.InterfaceFinder(self),
self.TypeFinder(self)))
#Find them
current_section = None
for (lineno,line) in enumerate(source_lines):
if current_section is not None:
current_section.lines.append(line)
if current_section.check_for_end(line):
current_section = None
else:
for line_finder in line_finders:
line_finder.check_match(line,lineno)
for section in section_finders:
if section.check_for_start(lineno,line):
current_section = section
break
def __init__(self,lib_source,source_files):
"""Load library information from source files
Arguments:
lib_source -- Path to library source file
source_files -- List of other source files used by the library
"""
self.lib_source = self.SourceFile(lib_source)
self.sources = [self.SourceFile(source,params_only=True) for source in source_files]
self.resolve_constants()
#Get all public types, constants and routines to include
#Store all objects to be output in a dictionary with line number as key
self.public_objects = {}
for t in self.lib_source.types.values():
if t.name in self.lib_source.public:
self.public_objects[t.lineno] = t
for const in self.lib_source.constants.values():
if const.name in self.lib_source.public:
self.public_objects[const.lineno] = const
self.public_subroutines=[routine for routine in self.lib_source.subroutines.values() \
if routine.name in self.lib_source.public]
for interface in self.lib_source.interfaces.values():
if interface.name in self.lib_source.public:
self.public_subroutines += [self.lib_source.subroutines[routine] \
for routine in interface.get_subroutines()]
self.public_subroutines=sorted(self.public_subroutines,key=attrgetter('name'))
#Remove CMISS...TypesCopy routines, as these are only used within the C bindings
#Also remove CMISSGeneratedMeshSurfaceGet for now as it takes an allocatable array but will be removed soon anyways.
self.public_subroutines = filter(lambda r: not (r.name.startswith('CMISSGeneratedMeshSurfaceGet') or r.name.endswith('TypesCopy')),self.public_subroutines)
for routine in self.public_subroutines:
self.public_objects[routine.lineno] = routine
for doxygen_grouping in self.lib_source.doxygen_groupings:
self.public_objects[doxygen_grouping.lineno] = doxygen_grouping
def resolve_constants(self):
"""Go through all public constants and work out their actual values"""
for pub in self.lib_source.public:
if self.lib_source.constants.has_key(pub):
self.get_constant_value(pub)
def get_constant_value(self,constant):
"""Get the actual value for a constant from the source files
Arguments:
constant -- Name of the constant to get the value for
"""
assignment = self.lib_source.constants[constant].assignment
exhausted = False
while (not self.lib_source.constants[constant].resolved) and (not exhausted):
for (i,source) in enumerate(self.sources):
if source.constants.has_key(assignment):
if source.constants[assignment].resolved:
self.lib_source.constants[constant].value=source.constants[assignment].value
self.lib_source.constants[constant].resolved=True
break
else:
assignment = source.constants[assignment].assignment
break
if i == (len(self.sources) - 1):
exhausted = True
if not self.lib_source.constants[constant].resolved:
sys.stderr.write("Warning: Couldn't resolve constant value: %s\n" % constant)
def write_c_header(self,output):
"""Write opencmiss.h containing constants, typedefs and routine declarations
Arguments:
output -- File to write to
"""
output.write('/*\n * opencmiss.h automatically generated from opencmiss.f90\n * Do not edit this file directly, instead edit opencmiss.f90 or generatec.py\n */\n\n' + \
'#ifndef OPENCMISS_H\n' + \
'#define OPENCMISS_H\n' + \
'\n/*\n * Defines\n */\n\n' + \
'const int CMISSNoError = 0;\n' + \
'const int CMISSPointerIsNULL = -1;\n' + \
'const int CMISSPointerNotNULL = -2;\n' + \
'const int CMISSCouldNotAllocatePointer = -3;\n' + \
'const int CMISSErrorConvertingPointer = -4;\n\n' + \
'typedef %s CMISSBool;\n' % _logical_type() + \
'const CMISSBool CMISSTrue = 1;\n' + \
'const CMISSBool CMISSFalse = 0;\n\n' + \
'typedef int CMISSError;\n\n')
for lineno in sorted(self.public_objects.keys()):
output.write(self.public_objects[lineno].to_c_header())
output.write('\n#endif\n')
def write_c_f90(self,output):
"""Write opencmiss_c.f90 containing Fortran routines
Arguments:
output -- File to write to
"""
output.write('!\n! opencmiss_c.f90 automatically generated from opencmiss.f90\n! Do not edit this file directly, instead edit opencmiss.f90 or generatec.py\n!\n' + \
'MODULE OPENCMISS_C\n\n' + \
' USE ISO_C_BINDING\n' + \
' USE ISO_VARYING_STRING\n' + \
' USE OPENCMISS\n' + \
' USE CMISS_FORTRAN_C\n\n' + \
' IMPLICIT NONE\n\n' + \
' PRIVATE\n\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSTrue = 1\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSFalse = 0\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSNoError = 0\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSPointerIsNULL = -1\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSPointerNotNULL = -2\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSCouldNotAllocatePointer = -3\n' + \
' INTEGER(C_INT), PARAMETER :: CMISSErrorConvertingPointer = -4\n\n')
output.write('\n'.join((' PUBLIC %s' % subroutine.c_f90_name for subroutine in self.public_subroutines)))
output.write('\nCONTAINS\n\n')
for subroutine in self.public_subroutines:
output.write(subroutine.to_c_f90())
output.write('END MODULE OPENCMISS_C')
class Constant(object):
"""Information on a public constant"""
def __init__(self,name,lineno,assignment,doxygen_comment):
"""Initialise Constant
Arguments:
name -- Variable name
assignment -- Value or another variable assigned to this variable
doxygen_comment -- Contents of the doxygen comment describing the constant
"""
self.name = name
self.lineno = lineno
self.assignment = assignment
self.doxygen_comment = doxygen_comment
try:
self.value = int(self.assignment)
self.resolved = True
except ValueError:
try:
self.value = float(self.assignment)
self.resolved = True
except ValueError:
self.value = None
self.resolved = False
def to_c_header(self):
"""Return the C definition of this constant"""
if self.resolved:
if self.doxygen_comment != '':
return 'static int %s = %d; /*<%s */\n' % (self.name,self.value,self.doxygen_comment)
else:
return 'static int %s = %d;\n' % (self.name,self.value)
else:
return ''
class Interface(object):
"""Information on an interface"""
def __init__(self,name,lineno,lines,source_file):
"""Initialise an interface
Arguments:
name -- Interface name
lineno -- Line number where the interface starts
lines -- Contents of interface as a list of lines
source_file -- Source file containing the interface
"""
self.name = name
self.lineno = lineno
self.lines = lines
self.source = source_file
def get_subroutines(self):
"""Find the subroutines for an interface
Choose the one with the highest number if there are options. This
corresponds to the routine that takes array parameters
Returns a list of subroutines
"""
all_subroutines = []
routine_re=re.compile(r'MODULE PROCEDURE ([A-Z0-9_]+)',re.IGNORECASE)
varying_string_re=re.compile(r'VSC*(Obj|Number|)[0-9]*$',re.IGNORECASE)
for line in self.lines:
match = routine_re.search(line)
if match:
routine_name = match.group(1)
if varying_string_re.search(routine_name):
#Don't include routines using varying_string parameters
pass
else:
all_subroutines.append(routine_name)
subroutines = self._get_array_routines(all_subroutines)
for routine in subroutines:
self.source.subroutines[routine].interface = self
return subroutines
def _get_array_routines(self,routine_list):
"""Return a list of the routines that take array parameters if there
is an option between passing an array or a scalar
Arguments:
routine_list -- List of subroutine names
"""
routine_groups = {}
routines = []
#Group routines depending on their name, minus any number indicating
#whether they take a scalar or array
for routine in routine_list:
routine_group = re.sub('\d','0',routine)
if routine_groups.has_key(routine_group):
routine_groups[routine_group].append(routine)
else:
routine_groups[routine_group] = [routine]
for group in routine_groups.keys():
max_number = -1
for routine in routine_groups[group]:
try:
number = int(filter(str.isdigit,routine))
if number > max_number:
array_routine = routine
except ValueError:
#only one routine in group
array_routine = routine
routines.append(array_routine)
return routines
class Subroutine(object):
"""Store information for a subroutine"""
def __init__(self,name,lineno,lines,source_file):
self.name = name
self.lineno = lineno
self.lines = lines
self.source_file = source_file
self.parameters = None
self.interface = None
self._set_c_name()
self._get_comments()
def get_parameters(self):
"""Get details of the subroutine parameters
Sets the Subroutines parameters property as a list of all parameters, excluding the Err parameter
"""
def filter_match(string):
if string is None: return ''
else: return string.strip()
self.parameters = []
match = re.search(r'^\s*(RECURSIVE\s+)?SUBROUTINE\s+([A-Z0-9_]+)\(([A-Z0-9_,\s]*)\)',self.lines[0],re.IGNORECASE)
parameters = [p.strip() for p in match.group(3).split(',')]
try:
parameters.remove('Err')
except ValueError:
sys.stderr.write("Warning: Routine doesn't take Err parameter: %s\n" % self.name)
for param in parameters:
param_pattern = r"""
^\s*([A-Z_]+\s*(\(([A-Z_=\*0-9]+)\))?) # parameter type at start of line, followed by possible type parameters in brackets
\s*([A-Z0-9\s_\(\):,\s]+)?\s* # extra specifications such as intent
::
[A-Z_,\s\(\):]* # Allow for other parameters to be included on the same line
[,\s:] # Make sure we matched the full parameter name
%s # Parameter name
(\(([0-9,:]+)\))? # Array dimensions if present
[,\s$] # Whitespace, comma or end of line to make sure we've matched the full parameter name
[^!]*(!<(.*)$)? # Doxygen comment
""" % param
param_re = re.compile(param_pattern,re.IGNORECASE|re.VERBOSE)
for line in self.lines:
match = param_re.search(line)
if match:
param_type = match.group(1)
(type_params,extra_stuff,array,doxygen) = (filter_match(match.group(i)) for i in (3,4,6,8))
self.parameters.append(Parameter(param,self,param_type,type_params,extra_stuff,array,doxygen))
break
if not match:
raise RuntimeError, "Couldn't find parameter %s for subroutine %s" % (param,self.name)
def _set_c_name(self):
"""Get the name of the routine as used from C and as used in opencmiss_c.f90
Sets the subroutines c_name and c_f90_name parameters
"""
#Note that some interfaces have a 'C' variant with C in the name already:
if re.search(r'Obj[0-9]*C?$',self.name):
#For routines with a Region and Interface variant, the Region one is default
#and Region is removed from the name
self.c_name = re.sub(r'(Region)?C?(Obj)[0-9]*C?$','',self.name)
self.c_f90_name = re.sub(r'(Region)?C?Obj[0-9]*C?$','C',self.name)
elif re.search(r'Number[0-9]*C?$',self.name):
self.c_name = re.sub(r'C?Number[0-9]*C?$',r'Num',self.name)
self.c_f90_name = re.sub(r'C?Number[0-9]*C?$',r'CNum',self.name)
else:
self.c_name = re.sub(r'C?[0-9]*$','',self.name)
self.c_f90_name = re.sub(r'C?[0-9]*$',r'C',self.name)
#Make sure names are different, might have matched a C at the end of the subroutine name
if self.c_f90_name == self.name:
self.c_f90_name = self.name+'C'
def _get_comments(self):
"""Sets the comment_lines property, a list of comments above the subroutine definition"""
self.comment_lines = []
line_num = self.lineno - 1
while self.source_file.source_lines[line_num].strip().startswith('!>'):
self.comment_lines.append(self.source_file.source_lines[line_num].strip()[2:].strip())
line_num -= 1
self.comment_lines.reverse()
def to_c_header(self):
"""Returns the function declaration in C"""
if self.parameters is None:
self.get_parameters()
output = '\n/*>'
output += '\n *>'.join(self.comment_lines)
output += ' */\n'
output += 'CMISSError %s(' % self.c_name
c_parameters = _chain_iterable([p.to_c() for p in self.parameters])
comments = _chain_iterable([p.doxygen_comments() for p in self.parameters])
output += ',\n '.join(['%s /*<%s */' % (p,c) for (p,c) in zip(c_parameters,comments)])
output += ');\n'
return output
def local_c_f90_vars(self):
"""Returns a list of extra local variables required for this subroutine, for use in converting
to and from C variables
"""
local_variables = [param.local_variables for param in self.parameters]
return list(_chain_iterable(local_variables))
def pre_call(self):
"""Returns a list of lines to add before calling the Fortran routine
for converting to and from C
"""
pre_lines = [param.pre_call for param in self.parameters]
return list(_chain_iterable(pre_lines))
def post_call(self):
"""Returns a list of lines to add after calling the Fortran routine
for converting to and from C
"""
#reverse to keep everything in order, as some if statements need to line up
#from the pre_call lines
post_lines = [param.post_call for param in reversed(self.parameters)]
return list(_chain_iterable(post_lines))
def to_c_f90(self):
"""Returns the C function implemented in Fortran for opencmiss_c.f90"""
if self.parameters is None:
self.get_parameters()
c_f90_params = [param.c_f90_names() for param in self.parameters]
c_f90_declarations = [param.c_f90_declaration() for param in self.parameters]
if self.interface is not None:
function_call = self.interface.name
else:
function_call = self.name
output = ' FUNCTION %s(%s) &\n & BIND(C, NAME="%s")\n\n' %(self.c_f90_name,','.join(c_f90_params),self.c_name)
output += ' !Argument variables\n'
output += ' %s\n' % '\n '.join(c_f90_declarations)
output += ' !Function return variable\n'
output += ' INTEGER(C_INT) :: %s\n' % self.c_f90_name
output += ' !Local variables\n'
content = []
content.extend(self.local_c_f90_vars())
content.append('')
content.append('%s = CMISSNoError' % self.c_f90_name)
content.extend(self.pre_call())
content.append('CALL %s(%s)' % (function_call,','.join([p.call_name() for p in self.parameters]+[self.c_f90_name])))
content.extend(self.post_call())
output += _indent_lines(content,2,4)
output += '\n RETURN\n\n'
output += ' END FUNCTION %s\n\n' % self.c_f90_name
output += ' !\n'
output += ' !'+'='*129+'\n'
output += ' !\n\n'
output = '\n'.join([_fix_length(line) for line in output.split('\n')])
return output
class Parameter(object):
"""Information on a subroutine parameter"""
#Parameter types enum:
(INTEGER, \
FLOAT, \
DOUBLE, \
CHARACTER, \
LOGICAL, \
CUSTOM_TYPE) \
= range(6)
#Corresponding variable types for C
CTYPES = ('int','float','double','char','CMISSBool',None)
#Variable types as used in opencmiss_c.f90
F90TYPES = ('INTEGER(C_INT)','REAL(C_FLOAT)','REAL(C_DOUBLE)','CHARACTER(LEN=1,KIND=C_CHAR)','LOGICAL','TYPE(C_PTR)')
def __init__(self,name,routine,param_type,type_params,extra_stuff,array,doxygen):
"""Initialise a parameter
Arguments:
name -- Parameter name
routine -- Pointer back to the subroutine this parameter belongs to
param_type -- String from the parameter declaration
type_params -- Any parameters for parameter type, eg "DP" for a real
extra_stuff -- Any extra parameter properties listed after the type, including intent
array -- The array dimensions included after the parameter name if they exist, otherwise an empty string
doxygen -- The doxygen comment after the parameteter
"""
self.name = name
self.routine = routine
self.pointer = False
self.doxygen = doxygen
intent = None
if extra_stuff != '':
match = re.search(r'INTENT\(([A-Z]+)\)?',extra_stuff,re.IGNORECASE)
if match is not None:
intent = match.group(1)
if extra_stuff.find('DIMENSION') > -1:
sys.stderr.write("Warning: Ignoring DIMENSION specification on parameter %s of routine %s\n" % (self.name,routine.name))
sys.stderr.write(" Using DIMENSION goes against the OpenCMISS style guidelines.\n")
if extra_stuff.find('POINTER') > -1:
self.pointer = True
#Get parameter intent
if intent is None:
#cintent is the intent used in opencmiss_c.f90, which may be different to the intent in opencmiss.f90
self.intent = 'INOUT'
self.cintent = 'INOUT'
sys.stderr.write("Warning: No intent for parameter %s of routine %s\n" % (self.name,routine.name))
else:
self.intent = intent
self.cintent = intent
#Get array dimensions and work out how many dimension sizes are variable
if array != '':
self.array_spec = [a.strip() for a in array.split(',')]
self.array_dims = len(self.array_spec)
self.required_sizes = self.array_spec.count(':')
if self.array_dims > 0 and not self.pointer:
#Need to pass C pointer by value
self.cintent = 'IN'
else:
self.array_spec = []
self.array_dims = 0
self.required_sizes = 0
#Work out the type of parameter
param_type = param_type.upper()
if param_type.startswith('INTEGER'):
self.var_type = Parameter.INTEGER
elif param_type.startswith('REAL'):
self.precision = type_params
if self.precision == 'DP':
self.var_type = Parameter.DOUBLE
else:
self.var_type = Parameter.FLOAT
elif param_type.startswith('CHARACTER'):
self.var_type = Parameter.CHARACTER
#Add extra dimension, 1D array of strings in Fortran is a 2D array of chars in C
self.array_spec.append(':')
self.array_dims += 1
self.required_sizes += 1
#Need to pass C pointer by value
self.cintent = 'IN'
elif param_type.startswith('LOGICAL'):
self.var_type = Parameter.LOGICAL
elif param_type.startswith('TYPE'):
self.var_type = Parameter.CUSTOM_TYPE
self.type_name = type_params
if self.array_dims == 0 and self.intent == 'INOUT':
#Should actually be in, as we need to pass the pointer by value
self.cintent = 'IN'
else:
sys.stderr.write("Error: Unknown type %s for routine %s\n" % (param_type,routine.name))
self.var_type = None
self.type_name = param_type
self._set_size_list()
self._set_conversion_lines()
def _set_size_list(self):
"""Get the list of dimension sizes for an array, as constants or variable names
Sets the size_list, required_size_list and size_doxygen properties
required_size_list does not include any dimensions that are constant
size_doxygen has the same length as required_size_list
"""
self.size_list = []
self.required_size_list = []
self.size_doxygen = []
i=0
for dim in self.array_spec:
if dim == ':':
if self.required_sizes == 1:
self.size_list.append('%sSize' % (self.name))
if self.var_type == Parameter.CHARACTER:
self.size_doxygen.append('Length of %s string' % self.name)
else:
self.size_doxygen.append('Length of %s' % self.name)
elif self.var_type == Parameter.CHARACTER:
try:
self.size_list.append(['%sNumStrings' % self.name, '%sStringLength' % self.name][i])
self.size_doxygen.append(['Number of strings in %s' % self.name, 'Length of strings in %s' % self.name][i])
except IndexError:
raise ValueError, ">2D arrays of strings not supported"
else:
self.size_list.append('%sSize%d' % (self.name,i+1))
self.size_doxygen.append('Size of dimension %d of %s' % (i+1,self.name))
i += 1
self.required_size_list.append(self.size_list[-1])
else:
self.size_list.append(dim)
def _set_conversion_lines(self):
"""Get any pointer or string conversions/checks as well as extra local variables required
Sets pre_call and post_call properties, which are lines to add before and after calling
the routine in opencmiss.f90
"""
self.local_variables = []
self.pre_call = []
self.post_call = []
#CMISS Types
if self.var_type == Parameter.CUSTOM_TYPE:
if self.array_dims > 0:
self.local_variables.append('TYPE(%s), TARGET :: %s(%s)' % (self.type_name,self.name,','.join(self.size_list)))
else:
self.local_variables.append('TYPE(%s), POINTER :: %s' % (self.type_name,self.name))
# If we're in a CMISS...TypeInitialise routine, then objects get allocated
# in Fortran and we need to convert pointers to C pointers before returning them.
# For all other routines the pointer to the buffer object doesn't change so we
# ignore the intent and always check for association before calling the Fortran routine.
if self.routine.name.endswith('TypeInitialise'):
self.local_variables.append('INTEGER(C_INT) :: Err')
self.pre_call.extend(('IF(C_ASSOCIATED(%sPtr)) THEN' % self.name,
'%s = CMISSPointerNotNULL' % self.routine.c_f90_name,
'ELSE',
'NULLIFY(%s)' % self.name,
'ALLOCATE(%s, STAT = Err)' % self.name,
'IF(Err /= 0) THEN',
'%s = CMISSCouldNotAllocatePointer' % self.routine.c_f90_name,
'ELSE'))
self.post_call.extend(('%sPtr=C_LOC(%s)' % (self.name,self.name),
'ENDIF',
'ENDIF'))
elif self.routine.name.endswith('TypeFinalise'):
self.pre_call.extend(('IF(C_ASSOCIATED(%sPtr)) THEN' % self.name,
'CALL C_F_POINTER(%sPtr,%s)' % (self.name,self.name),
'IF(ASSOCIATED(%s)) THEN' % self.name))
self.post_call.extend(('DEALLOCATE(%s)' % self.name,
'%sPtr = C_NULL_PTR' % self.name,
'ELSE',
'%s = CMISSErrorConvertingPointer' % self.routine.c_f90_name,
'ENDIF',
'ELSE',
'%s = CMISSPointerIsNULL' % self.routine.c_f90_name,
'ENDIF'))
else:
if self.array_dims > 0:
self.pre_call.append('IF(C_ASSOCIATED(%sPtr)) THEN' % self.name)
if self.intent == 'IN':
# Passing an array of CMISS Types to Fortran
self.pre_call.append('CALL %ssCopy(%s,%sSize,%sPtr,%s)' % (self.type_name,self.name,self.name,self.name,self.routine.c_f90_name))
else:
# Getting an array of CMISS Types from Fortran and setting an array of C pointers
self.local_variables.append('INTEGER(C_INT) :: %sIndex' % self.name)
self.local_variables.append('TYPE(C_PTR), POINTER :: %sCPtrs(:)' % self.name)
self.post_call.extend(('CALL C_F_POINTER(%sPtr,%sCPtrs,[%s])' % (self.name,self.name,','.join(self.size_list)),
'DO %sIndex=1,%sSize' % (self.name,self.name),
'%sCPtrs(%sIndex) = C_LOC(%s(%sIndex))' % ((self.name,) * 4),
'ENDDO'))
self.post_call.extend(('ELSE',
'%s = CMISSPointerIsNULL' % self.routine.c_f90_name,
'ENDIF'))
else:
self.pre_call.extend(('IF(C_ASSOCIATED(%s)) THEN' % self.c_f90_name(),
'CALL C_F_POINTER(%sPtr,%s)' % (self.name, self.name),
'IF(ASSOCIATED(%s)) THEN' % self.name))
self.post_call.extend(('ELSE',
'%s = CMISSErrorConvertingPointer' % self.routine.c_f90_name,
'ENDIF',
'ELSE',
'%s = CMISSPointerIsNULL' % self.routine.c_f90_name,
'ENDIF'))
#Character arrays
elif self.var_type == Parameter.CHARACTER:
if self.array_dims > 1:
#Fortran array has one less dimension
char_sizes = '(%s)' % ','.join(self.size_list[:-1])
else:
char_sizes = ''
self.local_variables.append('CHARACTER(LEN=%s-1) :: Fortran%s%s' % (self.size_list[-1],self.name,char_sizes))
self.local_variables.append('%s, POINTER :: %sCChars(%s)' % (Parameter.F90TYPES[self.var_type],self.name,','.join(':'*self.array_dims)))
if self.intent == 'IN':
#reverse to account for difference in storage order
self.pre_call.append('CALL C_F_POINTER(%s,%sCChars,[%s])' % (self.name,self.name,','.join(reversed(self.size_list))))
if self.array_dims > 1:
char_sizes = '(%s)' % ','.join(self.size_list[:-1])
self.pre_call.append('CALL CMISSC2FStrings(%sCChars,Fortran%s)' % (self.name,self.name))
else:
char_sizes = ''
self.pre_call.append('CALL CMISSC2FString(%sCChars,Fortran%s)' % (self.name,self.name))
else:
if self.array_dims > 1:
raise ValueError, "output of strings >1D not implemented"
self.post_call.append('CALL C_F_POINTER(%s,%sCChars,[%s])' % (self.name,self.name,self.size_list[0]))
self.post_call.append('CALL CMISSF2CString(Fortran%s,%sCChars)' % (self.name,self.name))
#Arrays of floats, integers or logicals
elif self.array_dims > 0:
if self.var_type == Parameter.CHARACTER:
self.local_variables.append('CHARACTER, POINTER :: %s(%s)' % (self.name,','.join([':']*self.array_dims)))
else:
self.local_variables.append('%s, POINTER :: %s(%s)' % (Parameter.F90TYPES[self.var_type],self.name,','.join([':']*self.array_dims)))
if self.pointer == True and self.cintent == 'OUT':
#we are setting the value of a pointer
self.pre_call.append('NULLIFY(%s)' % self.name)
self.post_call.extend(('%sPtr = C_LOC(%s(1))' % (self.name,self.name),
'%sSize = SIZE(%s,1)' % (self.name,self.name),
'IF(.NOT.C_ASSOCIATED(%sPtr)) THEN' % self.name,
'%s = CMISSErrorConvertingPointer' % self.routine.c_f90_name,
'ENDIF'))
else:
#pointer is pointing to allocated memory that is being set
self.pre_call.extend(('IF(C_ASSOCIATED(%s)) THEN' % self.c_f90_name(),
'CALL C_F_POINTER(%s,%s,[%s])' % (self.c_f90_name(),self.name,','.join(self.size_list)),
'IF(ASSOCIATED(%s)) THEN' % self.name))
self.post_call.extend(('ELSE',
'%s = CMISSErrorConvertingPointer' % self.routine.c_f90_name,
'ENDIF',
'ELSE',
'%s = CMISSPointerIsNULL' % self.routine.c_f90_name,
'ENDIF'))
def c_f90_name(self):
"""Return the name of the parameter as used by the routine in opencmiss_c.f90"""
c_f90_name = self.name
if self.var_type == Parameter.CUSTOM_TYPE or \
(self.array_dims > 0 and self.var_type != Parameter.CHARACTER):
c_f90_name += 'Ptr'
return c_f90_name
def c_f90_names(self):
"""Return param name + name of size param if it exists,
separated by a comma for use in the function declaration in Fortran
"""
return ','.join([s for s in self.required_size_list]+[self.c_f90_name()])
def c_f90_declaration(self):
"""Return the parameter declaration for use in the subroutine in opencmiss_c.f90"""
c_f90_name=self.c_f90_name()
output = ''
#pass by value?
if self.cintent == 'IN':
value = 'VALUE, '
else:
value = ''
#possible size parameter
if self.pointer == True and self.cintent == 'OUT':
size_type = 'INTEGER(C_INT), INTENT(OUT)'
else:
size_type = 'INTEGER(C_INT), VALUE, INTENT(IN)'
output += ''.join([size_type+' :: '+size_name+'\n ' for size_name in self.required_size_list])
if self.array_dims > 0:
output += 'TYPE(C_PTR), %sINTENT(%s) :: %s' % (value,self.cintent,c_f90_name)
else:
output += '%s, %sINTENT(%s) :: %s' % (Parameter.F90TYPES[self.var_type],value,self.cintent,c_f90_name)
return output
def call_name(self):
"""Return the parameter name to be used in the opencmiss.f90 subroutine call
Used to pass the name of a converted variable
"""
output = self.name
if self.var_type == Parameter.CHARACTER:
output = 'Fortran'+output
return output
def to_c(self):
"""Calculate C parameter declaration for opencmiss.h
For arrays, return two parameters with the first being the size
"""
param = self.name
#pointer argument?
if self.array_dims > 0 or self.var_type == Parameter.CHARACTER \
or self.cintent == 'OUT':
param = '*'+param
if self.cintent == 'OUT' and self.pointer == True:
#add another * as we need a pointer to a pointer, to modify the pointer value
param = '*'+param
#parameter type
if self.var_type != Parameter.CUSTOM_TYPE:
param = Parameter.CTYPES[self.var_type]+' '+param
else:
param = self.type_name+' '+param
#const?
if self.intent == 'IN':
param = 'const '+param
#size?
if self.pointer == True and self.cintent == 'OUT':
#Size is an output
size_type = 'int *'
else:
size_type = 'const int '
return tuple([size_type+size_name for size_name in self.required_size_list]+[param])
def doxygen_comments(self):
"""Return a list of doxygen comments corresponding to the list of
parameters returned by to_c
"""
return self.size_doxygen+[self.doxygen]
class Type(object):
"""Information on a Fortran type"""
def __init__(self,name,lineno,lines,source_file):
"""Initialise type
Arguments:
name -- Type name
lineno -- Line number in source where this is defined
lines -- Contents of lines where this type is defined
"""
self.name = name
self.lineno = lineno
self.lines = lines
self.source_file = source_file
self._get_comments()
def _get_comments(self):
"""Sets the comment_lines property, a list of comments above the type definition"""
self.comment_lines = []
line_num = self.lineno - 1
while self.source_file.source_lines[line_num].strip().startswith('!>'):
self.comment_lines.append(self.source_file.source_lines[line_num].strip()[2:].strip())
line_num -= 1
self.comment_lines.reverse()
def to_c_header(self):
"""Return the struct and typedef definition for use in opencmiss.h"""
output = 'struct %s_;\n' % self.name
output += '/*>'
output += '\n *>'.join(self.comment_lines)
output += ' */\n'
output += 'typedef struct %s_ *%s;\n\n' % (self.name,self.name)
return output
class DoxygenGrouping(object):
"""Store a line used for grouping in Doxygen"""
def __init__(self,lineno,line):
self.lineno = lineno
self.line = line.strip()
def to_c_header(self):
"""Return the doxygen comment for use in opencmiss.h"""
return '/*>'+self.line+' */\n'
def _join_lines(source):
"""Remove Fortran line continuations"""
return re.sub(r'[\t ]*&[\t ]*\n[\t ]*&[\t ]*',' ',source)
def _fix_length(line,max_length=132):
"""Add Fortran line continuations to break up long lines
Tries to put the line continuation after a comma
"""
max_length=132
line = line.rstrip()
#account for comments
commentsplit=line.split('!')
if len(commentsplit) < 2:
content = line
comment = ''
else:
content = commentsplit[0]
comment = '!'.join(commentsplit[1:])
if content.strip() == '':
return line
remaining_content = content
indent = _get_indent(content)
content = ''
while len(remaining_content) > max_length:
break_pos = remaining_content.rfind(',',0,130)+1
if break_pos < 0:
sys.stderr.write("Error: Couldn't truncate line: %s\n" % line)
exit(1)
content += remaining_content[0:break_pos]+' &\n'
remaining_content = indent+' & '+remaining_content[break_pos:]
content = content + remaining_content
if comment:
content = content+'!'+comment
return content
def _get_indent(line):
"""Return the indentation in front of a line"""
indent = line.replace(line.lstrip(),'')
return indent
def _chain_iterable(iterables):
"""Implement itertools.chain.from_iterable so we can use it in Python 2.5"""
for it in iterables:
for element in it:
yield element
def _indent_lines(lines,indent_size=2,initial_indent=4):
"""Indent function content to show nesting of if, else and endif statements"""
output = ''
indent = 0
for line in lines:
if line.startswith('ELSE') \
or line.startswith('ENDIF') \
or line.startswith('ENDDO'):
indent -= 1
output += ' '*(initial_indent+indent*indent_size)+line+'\n'
if line.startswith('IF') \
or line.startswith('ELSE') \
or line.startswith('DO'):
indent += 1
return output
def _logical_type():
"""Return the C type to match Fortran logical type depending on the compiler used"""
#Both ifortran and gfortran use 4 bytes
#uint32_t is optional so might not be defined
return "unsigned int"
if __name__ == '__main__':
main()
<file_sep># -*- makefile -*-
#
# For use with GNU make.
#
#
#----------------------------------------------------------------------------------------------------------------------------------
# Makefile for compiling OpenCMISS library
#
# Original by <NAME> adapted from the CMISS Makefile by <NAME>
# Changes:
#
#----------------------------------------------------------------------------------------------------------------------------------
#
# LICENSE
#
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is OpenCMISS
#
# The Initial Developer of the Original Code is University of Auckland,
# Auckland, New Zealand, the University of Oxford, Oxford, United
# Kingdom and King's College, London, United Kingdom. Portions created
# by the University of Auckland, the University of Oxford and King's
# College, London are Copyright (C) 2007-2010 by the University of
# Auckland, the University of Oxford and King's College, London.
# All Rights Reserved.
#
# Contributor(s):
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
#----------------------------------------------------------------------------------------------------------------------------------
MAKEFLAGS = --no-builtin-rules --warn-undefined-variables
#----------------------------------------------------------------------------------------------------------------------------------
ifndef OPENCMISS_ROOT
OPENCMISS_ROOT = $(CURDIR)/../
endif
GLOBAL_CM_ROOT = $(CURDIR)
ifndef GLOBAL_CELLML_ROOT
GLOBAL_CELLML_ROOT := ${OPENCMISS_ROOT}/cellml
endif
ifndef GLOBAL_FIELDML_ROOT
GLOBAL_FIELDML_ROOT := ${OPENCMISSEXTRAS_ROOT}/fieldml
endif
ifndef GLOBAL_UTILS_ROOT
GLOBAL_UTILS_ROOT := ${OPENCMISSEXTRAS_ROOT}/utils
endif
#----------------------------------------------------------------------------------------------------------------------------------
EXTERNAL_CM_ROOT := ${OPENCMISSEXTRAS_ROOT}/cm/external
include $(GLOBAL_UTILS_ROOT)/Makefile.inc
#----------------------------------------------------------------------------------------------------------------------------------
ifndef MPI
MPI := mpich2
endif
ifndef USECELLML
USECELLML := false
#USECELLML := true
endif
ifndef USEFIELDML
# USEFIELDML := false
USEFIELDML := true
endif
ifeq ($(MPI),mpich2)
MPI := mpich2
else
ifeq ($(MPI),intel)
ifeq ($(OPERATING_SYSTEM),linux)
ifdef I_MPI_ROOT
MPI := intel
else
$(error Intel MPI libraries not setup)
endif
else
$(error can only use intel mpi with Linux)
endif
else
ifeq ($(MPI),openmpi)
MPI := openmpi
else
ifeq ($(MPI),mvapich2)
MPI := mvapich2
else
ifeq ($(MPI),cray)
MPI := cray
else
ifeq ($(MPI),poe)
MPI := poe
else
$(error unknown MPI type - $(MPI))
endif
endif
endif
endif
endif
endif
ifeq ($(MPIPROF),true)
ifeq ($(MPI),intel)
ifndef VT_ROOT
$(error intel trace collector not setup)
endif
ifndef VT_ADD_LIBS
$(error intel trace collector not setup)
endif
endif
endif
#----------------------------------------------------------------------------------------------------------------------------------
BASE_LIB_NAME = OpenCMISS
ifeq ($(OPERATING_SYSTEM),linux)# Linux
ifdef COMPILER_VERSION
ifndef EXTERNAL_CM_DIR
EXTERNAL_CM_DIR := $(EXTERNAL_CM_ROOT)/$(LIB_ARCH_DIR)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(MPI)/$(COMPILER)_$(COMPILER_VERSION)
endif
OBJECT_DIR := $(GLOBAL_CM_ROOT)/object/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(MPI)/$(COMPILER)_$(COMPILER_VERSION)
INC_DIR := $(GLOBAL_CM_ROOT)/include/$(BIN_ARCH_DIR)/$(MPI)/$(COMPILER)_$(COMPILER_VERSION)
LIB_DIR := $(GLOBAL_CM_ROOT)/lib/$(BIN_ARCH_DIR)/$(MPI)/$(COMPILER)_$(COMPILER_VERSION)
else
ifndef EXTERNAL_CM_DIR
EXTERNAL_CM_DIR := $(EXTERNAL_CM_ROOT)/$(LIB_ARCH_DIR)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(MPI)/$(COMPILER)
endif
OBJECT_DIR := $(GLOBAL_CM_ROOT)/object/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(MPI)/$(COMPILER)
INC_DIR := $(GLOBAL_CM_ROOT)/include/$(BIN_ARCH_DIR)/$(MPI)/$(COMPILER)
LIB_DIR := $(GLOBAL_CM_ROOT)/lib/$(BIN_ARCH_DIR)/$(MPI)/$(COMPILER)
endif
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
ifndef EXTERNAL_CM_DIR
EXTERNAL_CM_DIR := $(EXTERNAL_CM_ROOT)/$(LIB_ARCH_DIR)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(MPI)/$(COMPILER)
endif
else# windows
ifndef EXTERNAL_CM_DIR
EXTERNAL_CM_DIR := $(EXTERNAL_CM_ROOT)/$(LIB_ARCH_DIR)$(DEBUG_SUFFIX)$(PROF_SUFFIX)
endif
endif
OBJECT_DIR := $(GLOBAL_CM_ROOT)/object/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(MPI)/$(COMPILER)
INC_DIR := $(GLOBAL_CM_ROOT)/include/$(BIN_ARCH_DIR)/$(MPI)/$(COMPILER)
LIB_DIR := $(GLOBAL_CM_ROOT)/lib/$(BIN_ARCH_DIR)/$(MPI)/$(COMPILER)
endif
SOURCE_DIR = $(GLOBAL_CM_ROOT)/src
MODULE_DIR := $(OBJECT_DIR)
MOD_INC_NAME := opencmiss.mod
MOD_INCLUDE := $(INC_DIR)/$(MOD_INC_NAME)
MOD_SOURCE_INC := $(OBJECT_DIR)/$(MOD_INC_NAME)
HEADER_INC_NAME := opencmiss.h
HEADER_INCLUDE := $(INC_DIR)/$(HEADER_INC_NAME)
C_F90_SOURCE := $(SOURCE_DIR)/opencmiss_c.f90
C_GENERATE_SCRIPT := $(GLOBAL_CM_ROOT)/utils/C_interface/generatec.py
LIB_NAME := lib$(BASE_LIB_NAME)$(EXE_ABI_SUFFIX)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX).a
LIBRARY := $(LIB_DIR)/$(LIB_NAME)
C_INCLUDE_DIRS := $(SOURCE_DIR)
F_INCLUDE_DIRS := $(MODULE_DIR)
#----------------------------------------------------------------------------------------------------------------------------------
# compiling commands
ifeq ($(MPI),mpich2)
MPIFC = mpif90
MPICC = mpicc
else
MPIFC = mpiifort
MPICC = mpiicc
endif
FC = $(MPIFC)
CC = $(MPICC)
AR = ar
EXE_LINK = $(FC)
DSO_LINK = ld
DBGCF_FLGS = -g #OPT=false flags for C and fortran
# Option lists
# (suboption lists become more specific so that later ones overrule previous)
CFLAGS = $(strip $(CFL_FLGS) $(CFE_FLGS) $(CF_FLGS) $(C_FLGS))
FFLAGS = $(strip $(CFL_FLGS) $(CFE_FLGS) $(CF_FLGS) $(F_FLGS))
CPPFLAGS := $(addprefix -I, $(C_INCLUDE_DIRS) )
FPPFLAGS := $(addprefix -I, $(F_INCLUDE_DIRS) )
ELFLAGS = $(strip $(CFL_FLGS) $(L_FLGS) $(CFE_FLGS))
DLFLAGS = $(strip $(CFL_FLGS) $(L_FLGS) $(D_FLGS))
ifneq ($(DEBUG),false)
CFLAGS += $(strip $(DBGCF_FLGS) $(DBGC_FLGS))
FFLAGS += $(strip $(DBGCF_FLGS) $(DBGF_FLGS))
CPPFLAGS += -DDEBUG
else
ifneq ($(MPIPROF),false)
CFLAGS += $(strip $(DBGCF_FLGS) $(DBGC_FLGS))
FFLAGS += $(strip $(DBGCF_FLGS) $(DBGF_FLGS))
CPPFLAGS += -DDEBUG
else
CFLAGS += $(strip $(OPTCFE_FLGS) $(OPTCF_FLGS) $(OPTC_FLGS))
FFLAGS += $(strip $(OPTCFE_FLGS) $(OPTCF_FLGS) $(OPTF_FLGS))
ELFLAGS += $(OPTCFE_FLGS)
endif
endif
ifneq ($(MP),false)
CFLAGS += $(MP_FLGS)
FFLAGS += $(MP_FLGS)
endif
ARFLAGS = -crsv
# suboption lists
CFL_FLGS =# flags for C fortran and linking
L_FLGS =# flags for linking only
CFE_FLGS =# flags for C fortran and linking executables only
CF_FLGS = -c# flags for C and fortran only
C_FLGS =# flags for C only
F_FLGS =# flags for fortran only
D_FLGS = -shared# for linking dynamic shared objects only
DBGC_FLGS =# OPT=false flags for C only
DBGF_FLGS =# OPT=false flags for fortran only
OPTCFE_FLGS =# OPT=true flags for C and fortran and linking executables
OPTCF_FLGS = -O#OPT=true flags for C and fortran only
OPTC_FLGS =# OPT=true flags for C only
OPTF_FLGS =# OPT=true flags for fortran only
# The list of objects may be too long for the operating system limit on
# argument length so the list of objects is stored in a file. This linker
# arguments for this file depend on the linker. If the linker cannot
# interpret such a file then try to use the shell and hope the list isn't too
# long.
olist_args = `cat $1`
#----------------------------------------------------------------------------------------------------------------------------------
ifeq ($(OPERATING_SYSTEM),linux)
OPTCF_FLGS =# Use separate flags for fortran and c
olist_args = $1
CC = gcc
FC = gfortran
ifeq ($(COMPILER),intel)
#Use Intel compilers if available (icc -V sends output to STDERR and exits with error).
ifneq (,$(shell icc -V 2>&1 | grep -i intel))
CC = icc
endif
ifneq (,$(shell ifort -V 2>&1 | grep -i intel))
FC = ifort
endif
endif
# Set the flags for the various different CC compilers
ifeq ($(CC),gcc)# gcc
C_FLGS += -pipe -m$(ABI)
# Position independent code is actually only required for objects
# in shared libraries but debug version may be built as shared libraries.
DBGC_FLGS += -fPIC
ifeq ($(MACHNAME),x86_64)
ifneq ($(shell grep Intel /proc/cpuinfo 2>/dev/null),)
C_FLGS += -march=nocona
endif
endif
DBGC_FLGS += -O0 -fbounds-check
OPTC_FLGS = -O3 -funroll-all-loops
ifeq ($(PROF),false)
ifneq ($(filter $(INSTRUCTION),i686 x86_64),)# i686 or x86_64
OPTC_FLGS += -momit-leaf-frame-pointer
endif
else
C_FLGS += -g -pg -fprofile-arcs -ftest-coverage
endif
endif
ifeq ($(CC),icc)
# Turn on all warnings
C_FLGS += -Wall -m$(ABI)
ifeq ($(MACHNAME),x86_64)
ifneq ($(shell grep Intel /proc/cpuinfo 2>/dev/null),)
ifneq ($(shell grep Duo /proc/cpuinfo 2>/dev/null),)
ifneq ($(shell grep "Core(TM)2" /proc/cpuinfo 2>/dev/null),)
C_FLGS += -xT# Core2 Duo
else
C_FLGS += -x0# Core Duo
endif
else
C_FLGS += -xP# for sse3 (90nm Pentium 4 series)
endif
else
C_FLGS += -xW# Pentium4 compatible (?sse2)
endif
endif
ifeq ($(filter-out i%86,$(MACHNAME)),)
ifneq ($(shell grep sse2 /proc/cpuinfo 2>/dev/null),)
C_FLGS += -xN# for Pentium 4
endif
endif
DBGC_FLGS += -O0
OPTC_FLGS = -O3 -ansi_alias
ifneq ($(PROF),false)
C_FLGS += -g -pg
ELFLAGS += -pg
endif
ifeq ($(MPIPROF),true)
ifeq ($(MPI),mpich2)
C_FLGS += -Wl,--export-dyanmic
DBGC_FLGS += -Wl,--export-dyanmic
else
C_FLGS += -tcollect
endif
endif
endif
ifeq ($(filter-out xlc%,$(CC)),)# xlc* C compiler
CFLAGS += -qinfo=gen:ini:por:pro:trd:tru:use
C_FLGS += -q$(ABI) -qarch=auto -qhalt=e
# -qinitauto for C is bytewise: 7F gives large integers.
DBGC_FLGS += -qfullpath -C -qflttrap=inv:en -qinitauto=7F
OPTC_FLGS += -O3
# for trailing _ on fortran symbols
CPPFLAGS += -Dunix
endif
ifeq ($(CC),cc)# cray cc
DBGC_FLGS += -O0 -g
OPTC_FLGS = -O3
ifeq ($(PROF),true)
C_FLGS += -g -pg
endif
endif
# Set the flags for the various different Fortran compilers
ifeq ($(FC),gfortran)
#FC = /home/users/local/packages/gfortran/irun/bin/gfortran
# -fstatck-check
F_FLGS += -pipe -m$(ABI) -fno-second-underscore -Wall -x f95-cpp-input
# Restrict line length to 132
F_FLGS += -ffree-line-length-132
# for now change max identifier length. Should restrict to 63 (F2003) in future
F_FLGS += -fmax-identifier-length=63
# Position independent code is actually only required for objects
# in shared libraries but debug version may be built as shared libraries.
DBGF_FLGS += -fPIC
ifeq ($(MACHNAME),x86_64)
ifneq ($(shell grep Intel /proc/cpuinfo 2>/dev/null),)
F_FLGS += -march=nocona
endif
endif
DBGF_FLGS += -O0 -ffpe-trap=invalid,zero
ifdef COMPILER_VERSION
ifeq ($(COMPILER_VERSION),4.5)
DBGF_FLGS += -fcheck=all
endif
ifeq ($(COMPILER_VERSION),4.4)
DBGF_FLGS += -fbounds-check
endif
endif
OPTF_FLGS = -O3 -Wuninitialized -funroll-all-loops
#OPTF_FLGS = -g -O3 -Wuninitialized -funroll-all-loops
ifeq ($(PROF),false)
ifneq ($(filter $(INSTRUCTION),i686 x86_64),)# i686 or x86_64
OPTF_FLGS += -momit-leaf-frame-pointer
endif
else
F_FLGS += -g -pg -fprofile-arcs -ftest-coverage
ELFLAGS += -pg -fprofile-arcs -ftest-coverage
endif
ELFLAGS += -m$(ABI)
endif
ifeq ($(FC),g95)
F_FLAGS += -fno-second-underscore -Wall -m$(ABI) -std=f2003
DBGF_FLGS += -fPIC
DBGF_FLGS += -O0 -fbounds-check
OPTF_FLGS = -O3 -Wuninitialized -funroll-all-loops
ELFLAGS += -m$(ABI)
#$(error g95 not implemented)
endif
ifeq ($(FC),ifort)
# turn on preprocessing,
# turn on warnings,
# warn about non-standard Fortran 95
F_FLGS += -cpp -warn all -m$(ABI)
ifeq ($(MACHNAME),x86_64)
ifneq ($(shell grep Intel /proc/cpuinfo 2>/dev/null),)
ifneq ($(shell grep Duo /proc/cpuinfo 2>/dev/null),)
ifneq ($(shell grep "Core(TM)2" /proc/cpuinfo 2>/dev/null),)
F_FLGS += -xT# Core2 Duo
else
F_FLGS += -x0# Core Duo
endif
else
F_FLGS += -xP# for sse3 (90nm Pentium 4 series)
endif
else
F_FLGS += -xW# Pentium4 compatible (?sse2)
endif
endif
ifeq ($(filter-out i%86,$(MACHNAME)),)
ifneq ($(shell grep sse2 /proc/cpuinfo 2>/dev/null),)
F_FLGS += -xN# for Pentium 4
endif
endif
DBGF_FLGS += -O0 -check all -traceback -debug all
OPTF_FLGS = -O3
ifneq ($(PROF),false)
F_FLGS += -g -pg
ELFLAGS += -pg
endif
ifeq ($(MPIPROF),true)
ifeq ($(MPI),mpich2)
F_FLAS += -Wl,--export-dyanmic
DBGF_FLGS += -Wl,--export-dyanmic
else
F_FLGS += -tcollect
endif
endif
# MP_FLGS = -openmp
ELFLAGS += -nofor_main -m$(ABI) -traceback
endif
ifeq ($(filter-out xlf%,$(FC)),)# xlf* fortran compiler
F_FLGS += -q$(ABI) -qarch=auto -qhalt=e -qextname -qsuffix=cpp=f90
ELFLAGS += -q$(ABI)
ifeq ($(ABI),64)
F_FLGS += -qwarn64
endif
ifeq ($(DEBUG),false)
MP_FLGS = -qsmp=omp
else
MP_FLGS = -qsmp=omp:noopt
endif
# -qinitauto for Fortran 7FF7FFFF is a large integer or NaNQ real*4 or NaNS real*8
DBGF_FLGS += -qfullpath -C -qflttrap=inv:en -qextchk -qinitauto=7FF7FFFF
OPTF_FLGS += -O3
endif
ifeq ($(FC),ftn)
DBGF_FLGS += -O0 -g
OPTF_FLGS = -O3
ifeq ($(PROF),true)
F_FLGS += -g -pg
ELFLAGS += -pg
endif
endif
# Avoid versioning problems with libgcc_s by linking statically.
# libgcc2.c from gcc 3.4.4 says:
# In addition to the permissions in the GNU General Public License, the
# Free Software Foundation gives you unlimited permission to link the
# compiled version of this file into combinations with other programs,
# and to distribute those combinations without any restriction coming
# from the use of this file.
# (With dynamic version, should copy libgcc_s.so.N if copying libstdc++.so.N)
ELFLAGS += -static-libgcc
# Use the BSD timers
CPPFLAGS += -DBSD_TIMERS
endif
ifeq ($(OPERATING_SYSTEM),win32)
FC = gfortran
F_FLGS += -fno-second-underscore
OPTCF_FLGS = -O2
ELFLAGS += -Wl,-static
# Use the ANSI C timers
CPPFLAGS += -DANSI_C_TIMERS
olist_args = $1
endif
ifeq ($(OPERATING_SYSTEM),aix)
ifeq ($(MP),false)
FC = mpxlf95
CC = xlc
else
FC = mpxlf95_r
CC = xlc_r
endif
F_FLGS += -qsuffix=cpp=f90 -qnoextname
CFLAGS += -qinfo=gen:ini:por:pro:trd:tru:use
ELFLAGS += -q$(ABI)
CFE_FLGS += -q$(ABI) -qarch=auto -qhalt=e
L_FLGS += -b$(ABI)
D_FLGS = -G -bexpall -bnoentry
ifeq ($(ABI),32)
# Without -bmaxdata, the only one 256M virtual segment is available for
# data.
# In AIX 5.3, 0xAFFFFFFF is the largest value we can use here and still
# use global shared libraries. (see aixprggd/genprogc/lrg_prg_support.htm)
# However, 0xAFFFFFFF/dsa causes the system to crash on loading of perl
# modules (File::Find and Time::HiRes atleast). 0x80000000 seems to work.
# dsa allows segments to be allocated dynamically for shmat/mmap or data
# as required.
ELFLAGS += -bmaxdata:0x80000000/dsa
else
CF_FLGS += -qwarn64
# It seems that somewhere between AIX 5.1 and 5.3 the kernel loader
# started modifying a process's soft data resource limit to match to match
# its maxdata value (if non-zero). As 32-bit applications need a non-zero
# maxdata value to access more than 256M of data many applications
# (including perl) will cause the data limit to be lowered to a 32-bit
# addressable value. As cmiss is likely to be a child of such 32-bit
# processes, to access more than 32-bit addressable memory, it either
# needs to raise its data limit or use its own maxdata value.
# max heap size is 0x06FFFFFFFFFFFFF8
# Arbitrary. 0x0000100000000000 should provide ~16TB.
ELFLAGS += -bmaxdata:0x0000100000000000
endif
ifeq ($(DEBUG),false)
MP_FLGS = -qsmp=omp
else
MP_FLGS = -qsmp=omp:noopt
endif
# Should -qflttrap=nans be used as well or instead of -qflttrap=inv:en?
DBGCF_FLGS += -qfullpath -C -qflttrap=inv:en -qextchk
# -qinitauto for Fortran: 7FF7FFFF is a large integer or NaNQ real*4 or NaNS real*8
# -qinitauto for C is bytewise: 7F gives large integers.
DBGF_FLGS += -qinitauto=7FF7FFFF
DBGC_FLGS += -qinitauto=7F
OPTCF_FLGS = -O3
OPTC_FLGS += -qnoignerrno
olist_args = -f $1
# Use the BSD timers
CPPFLAGS += -DBSD_TIMERS
endif
# This returns an empty string if not found
searchdirs = $(firstword $(wildcard $(addsuffix /$(strip $2),$1)))
# This still returns the name of the desired file if not found and so is useful for error checking and reporting.
searchdirsforce = $(firstword $(wildcard $(addsuffix /$(strip $2),$1)) $2)
# Check that call function works (for searchdirs, olist_args, etc.)
ifeq ($(call olist_args,test),)
$(error call function not available. Use GNU make version 3.78 or newer)
endif
#TAO
TAO_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
TAO_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
TAO_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
TAO_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/finclude )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
TAO_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
TAO_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
TAO_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/finclude )
else# windows
TAO_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#PETSc
PETSC_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
PETSC_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
PETSC_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
PETSC_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/conf )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
PETSC_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
PETSC_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
PETSC_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/conf/ )
else# windows
PETSC_LIB_PATH += $(addprefix -L, /home/users/local/lib/ )
PETSC_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#SUNDIALS
SUNDIALS_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
SUNDIALS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
SUNDIALS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
SUNDIALS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
SUNDIALS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else# windows
SUNDIALS_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#HYPRE
HYPRE_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
HYPRE_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
HYPRE_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
HYPRE_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
HYPRE_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else# windows
HYPRE_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#MUMPS
MUMPS_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
MUMPS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
MUMPS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
MUMPS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
MUMPS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else# windows
MUMPS_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#ScaLAPACK
SCALAPACK_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
SCALAPACK_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
SCALAPACK_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
SCALAPACK_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
SCALAPACK_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else# windows
SCALAPACK_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#BLACS
BLACS_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
BLACS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
BLACS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
BLACS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/ )
BLACS_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/include/ )
else# windows
BLACS_INCLUDE_PATH = $(addprefix -I, /home/users/local/ )
endif
endif
#ParMETIS
PARMETIS_INCLUDE_PATH =#
#CELLML
CELLML_INCLUDE_PATH =#
ifeq ($(USECELLML),true)
ifeq ($(OPERATING_SYSTEM),linux)# Linux
ifdef COMPILER_VERSION
CELLML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_CELLML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)_$(COMPILER_VERSION)/include/ )
else
CELLML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_CELLML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)/include/ )
endif
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
CELLML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_CELLML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)/include/ )
else# windows
CELLML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_CELLML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)/include/ )
endif
endif
endif
#FIELDML
FIELDML_INCLUDE_PATH =#
MOD_FIELDML_TARGET = #
ifeq ($(USEFIELDML),true)
MOD_FIELDML_TARGET = MOD_FIELDML
ifeq ($(OPERATING_SYSTEM),linux)# Linux
ifdef COMPILER_VERSION
FIELDML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_FIELDML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)_$(COMPILER_VERSION)/include/ )
else
FIELDML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_FIELDML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)/include/ )
endif
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
FIELDML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_FIELDML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)/include/ )
else# windows
FIELDML_INCLUDE_PATH += $(addprefix -I, $(GLOBAL_FIELDML_ROOT)/$(LIB_ARCH_DIR)$(MT_SUFFIX)$(DEBUG_SUFFIX)$(PROF_SUFFIX)/$(COMPILER)/include/ )
endif
endif
endif
#TAU/PAPI
ifeq ($(TAUPROF),true)
CPPFLAGS += -DTAUPROF
FPPFLAGS += -DTAUPROF
endif
#MPI
MPI_INCLUDE_PATH =#
ifeq ($(OPERATING_SYSTEM),linux)# Linux
ifeq ($(MPI),mpich2)
else
ifeq ($(MPI),intel)
ifeq ($(MPIPROF),true)
MPI_INCLUDE_PATH += $(addprefix -I, $(VT_ROOT)/include/ )
endif
ifeq ($(ABI),64)
MPI_INCLUDE_PATH += $(addprefix -I, $(I_MPI_ROOT)/include64/ )
else
MPI_INCLUDE_PATH += $(addprefix -I, $(I_MPI_ROOT)/include/ )
endif
else
MPI_INCLUDE_PATH += $(addprefix -I, $(EXTERNAL_CM_DIR)/lib/ )
endif
endif
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
else# windows
endif
endif
#BLAS/lapack
BLAS_INCLUDE_PATH =#
EXTERNAL_INCLUDE_PATH = $(strip $(TAO_INCLUDE_PATH) $(PETSC_INCLUDE_PATH) $(SUNDIALS_INCLUDE_PATH) $(HYPRE_INCLUDE_PATH) $(MUMPS_INCLUDE_PATH) $(SCALAPACK_INCLUDE_PATH) $(BLACS_INCLUDE_PATH) $(PARMETIS_INCLUDE_PATH) $(MPI_INCLUDE_PATH) $(BLAS_INCLUDE_PATH))
ifeq ($(USECELLML),true)
EXTERNAL_INCLUDE_PATH += $(CELLML_INCLUDE_PATH)
FPPFLAGS += -DUSECELLML
CPPFLAGS += -DUSECELLML
endif
ifeq ($(USEFIELDML),true)
EXTERNAL_INCLUDE_PATH += $(FIELDML_INCLUDE_PATH)
FPPFLAGS += -DUSEFIELDML
CPPFLAGS += -DUSEFIELDML
endif
CPPFLAGS += $(EXTERNAL_INCLUDE_PATH)
FPPFLAGS += $(EXTERNAL_INCLUDE_PATH)
ELFLAGS += $(EXTERNAL_LIB_PATH)
.SUFFIXES: .f90 .c
$(OBJECT_DIR)/%.o : $(SOURCE_DIR)/%.f90
( cd $(OBJECT_DIR) ; $(FC) -o $@ $(FFLAGS) $(FPPFLAGS) -c $< )
$(OBJECT_DIR)/%.o : $(SOURCE_DIR)/%.c
( cd $(OBJECT_DIR) ; $(CC) -o $@ $(CFLAGS) $(CPPFLAGS) -c $< )
ifeq ($(USEFIELDML),true)
FIELDML_OBJECT = \
$(OBJECT_DIR)/fieldml_util_routines.o \
$(OBJECT_DIR)/fieldml_input_routines.o \
$(OBJECT_DIR)/fieldml_output_routines.o \
$(OBJECT_DIR)/fieldml_types.o
else
FIELDML_OBJECT = #
endif
ifeq ($(COMPILER),intel) # TODO: temporarily disable intel build for opencmiss.f90 and etc.
FIELDML_OBJECT = #
MOD_INCLUDE := #
MOD_SOURCE_INC := #
MOD_FIELDML_TARGET := #
WRAPPER_OBJECTS = #
else
WRAPPER_OBJECTS = \
$(OBJECT_DIR)/opencmiss.o \
$(OBJECT_DIR)/opencmiss_c.o
endif
OBJECTS = $(OBJECT_DIR)/advection_diffusion_equation_routines.o \
$(OBJECT_DIR)/analytic_analysis_routines.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/bioelectric_routines.o \
$(OBJECT_DIR)/biodomain_equation_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/blas.o \
$(OBJECT_DIR)/Burgers_equation_routines.o \
$(OBJECT_DIR)/classical_field_routines.o \
$(OBJECT_DIR)/cmiss.o \
$(OBJECT_DIR)/cmiss_c.o \
$(OBJECT_DIR)/cmiss_cellml.o \
$(OBJECT_DIR)/cmiss_fortran_c.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/cmiss_parmetis.o \
$(OBJECT_DIR)/cmiss_petsc.o \
$(OBJECT_DIR)/cmiss_petsc_types.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/Darcy_equations_routines.o \
$(OBJECT_DIR)/Darcy_pressure_equations_routines.o \
$(OBJECT_DIR)/finite_elasticity_Darcy_routines.o \
$(OBJECT_DIR)/finite_elasticity_fluid_pressure_routines.o \
$(OBJECT_DIR)/bioelectric_finite_elasticity_routines.o \
$(OBJECT_DIR)/data_point_routines.o \
$(OBJECT_DIR)/data_projection_routines.o \
$(OBJECT_DIR)/diffusion_advection_diffusion_routines.o \
$(OBJECT_DIR)/diffusion_diffusion_routines.o \
$(OBJECT_DIR)/diffusion_equation_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/distributed_matrix_vector_IO.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/elasticity_routines.o \
$(OBJECT_DIR)/electromechanics_routines.o \
$(OBJECT_DIR)/electrophysiology_cell_routines.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/equations_set_routines.o \
$(OBJECT_DIR)/external_dae_solver_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/field_IO_routines.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/fluid_mechanics_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/FieldExport.o \
$(OBJECT_DIR)/fitting_routines.o \
$(OBJECT_DIR)/generated_mesh_routines.o \
$(OBJECT_DIR)/Hamilton_Jacobi_equations_routines.o \
$(OBJECT_DIR)/Helmholtz_equations_routines.o \
$(OBJECT_DIR)/history_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_routines.o \
$(OBJECT_DIR)/interface_conditions_routines.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/interface_equations_routines.o \
$(OBJECT_DIR)/interface_mapping_routines.o \
$(OBJECT_DIR)/interface_matrices_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/Laplace_equations_routines.o \
$(OBJECT_DIR)/linear_elasticity_routines.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/maths.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/monodomain_equations_routines.o \
$(OBJECT_DIR)/multi_compartment_transport_routines.o \
$(OBJECT_DIR)/multi_physics_routines.o \
$(OBJECT_DIR)/Navier_Stokes_equations_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(WRAPPER_OBJECTS) \
$(OBJECT_DIR)/Poiseuille_equations_routines.o \
$(OBJECT_DIR)/Poisson_equations_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/problem_routines.o \
$(OBJECT_DIR)/reaction_diffusion_equation_routines.o \
$(OBJECT_DIR)/reaction_diffusion_IO_routines.o \
$(OBJECT_DIR)/region_routines.o \
$(OBJECT_DIR)/Stokes_equations_routines.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/solver_mapping_routines.o \
$(OBJECT_DIR)/solver_matrices_routines.o \
$(OBJECT_DIR)/sorting.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/test_framework_routines.o \
$(OBJECT_DIR)/timer_c.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/trees.o \
$(OBJECT_DIR)/types.o \
$(OBJECT_DIR)/util_array.o \
$(FIELDML_OBJECT)
ifeq ($(OPERATING_SYSTEM),linux)# Linux
MACHINE_OBJECTS = $(OBJECT_DIR)/machine_constants_linux.o
else
ifeq ($(OPERATING_SYSTEM),aix)# AIX
MACHINE_OBJECTS = $(OBJECT_DIR)/machine_constants_aix.o
else# windows
MACHINE_OBJECTS = $(OBJECT_DIR)/machine_constants_windows.o
endif
endif
OBJECTS += $(MACHINE_OBJECTS)
main: preliminaries \
$(LIBRARY) \
$(MOD_INCLUDE) \
$(MOD_FIELDML_TARGET) \
$(HEADER_INCLUDE)
preliminaries: $(OBJECT_DIR) \
$(INC_DIR) \
$(LIB_DIR)
$(OBJECT_DIR) :
mkdir -p $@
$(INC_DIR) :
mkdir -p $@;
$(LIB_DIR) :
mkdir -p $@;
$(LIBRARY) : $(OBJECTS)
$(AR) $(ARFLAGS) $@ $(OBJECTS)
$(MOD_INCLUDE) : $(MOD_SOURCE_INC)
cp $(MOD_SOURCE_INC) $@
MOD_FIELDML: $(FIELDML_OBJECT)
cp $(OBJECT_DIR)/fieldml_input_routines.mod $(INC_DIR)/fieldml_input_routines.mod
cp $(OBJECT_DIR)/fieldml_output_routines.mod $(INC_DIR)/fieldml_output_routines.mod
cp $(OBJECT_DIR)/fieldml_util_routines.mod $(INC_DIR)/fieldml_util_routines.mod
cp $(OBJECT_DIR)/fieldml_types.mod $(INC_DIR)/fieldml_types.mod
$(HEADER_INCLUDE) $(C_F90_SOURCE): $(SOURCE_DIR)/opencmiss.f90 $(C_GENERATE_SCRIPT)
python $(C_GENERATE_SCRIPT) $(GLOBAL_CM_ROOT) $(HEADER_INCLUDE) $(C_F90_SOURCE)
# Place the list of dependencies for the objects here.
#
# ----------------------------------------------------------------------------
ifeq ($(OPERATING_SYSTEM),aix)
#Need to disable argument list checking for MPI calls which may have multiple types for the same parameters
$(OBJECT_DIR)/computational_environment.o : DBGCF_FLGS = -qfullpath -C -qflttrap=inv:en
$(OBJECT_DIR)/distributed_matrix_vector.o : DBGCF_FLGS = -qfullpath -C -qflttrap=inv:en
$(OBJECT_DIR)/field_IO_routines.o : DBGCF_FLGS = -qfullpath -C -qflttrap=inv:en
$(OBJECT_DIR)/analytic_analysis_routines.o : DBGCF_FLGS = -qfullpath -C -qflttrap=inv:en
$(OBJECT_DIR)/data_projection_routines.o : DBGCF_FLGS = -qfullpath -C -qflttrap=inv:en
#Need to disable argument list checking for c interface modules to allow for the c->fortran char->integer string conversion
$(OBJECT_DIR)/timer_c.o : DBGCF_FLGS = -qfullpath -C -qflttrap=inv:en
#Need to to auto-promote single precision constants to doubles
$(OBJECT_DIR)/finite_elasticity_routines.o : DBGCF_FLGS = -qdpc
endif
$(OBJECT_DIR)/advection_diffusion_equation_routines.o : $(SOURCE_DIR)/advection_diffusion_equation_routines.f90 \
$(OBJECT_DIR)/analytic_analysis_routines.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/analytic_analysis_routines.o : $(SOURCE_DIR)/analytic_analysis_routines.f90 \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/base_routines.o : $(SOURCE_DIR)/base_routines.f90 \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(MACHINE_OBJECTS)
$(OBJECT_DIR)/basis_routines.o : $(SOURCE_DIR)/basis_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/blas.o : $(SOURCE_DIR)/blas.f90 \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/bioelectric_routines.o : $(SOURCE_DIR)/bioelectric_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/biodomain_equation_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/monodomain_equations_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/biodomain_equation_routines.o : $(SOURCE_DIR)/biodomain_equation_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/field_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/boundary_condition_routines.o : $(SOURCE_DIR)/boundary_condition_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/classical_field_routines.o : $(SOURCE_DIR)/classical_field_routines.f90 \
$(OBJECT_DIR)/advection_diffusion_equation_routines.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/diffusion_equation_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/fitting_routines.o \
$(OBJECT_DIR)/Hamilton_Jacobi_equations_routines.o \
$(OBJECT_DIR)/Helmholtz_equations_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/Laplace_equations_routines.o \
$(OBJECT_DIR)/Poisson_equations_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/reaction_diffusion_equation_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o \
$(MACHINE_OBJECTS)
$(OBJECT_DIR)/cmiss.o : $(SOURCE_DIR)/cmiss.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/cmiss_cellml.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/generated_mesh_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/problem_routines.o \
$(OBJECT_DIR)/region_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o \
$(MACHINE_OBJECTS)
$(OBJECT_DIR)/cmiss_c.o : $(SOURCE_DIR)/cmiss_c.c
$(OBJECT_DIR)/cmiss_cellml.o : $(SOURCE_DIR)/cmiss_cellml.f90 \
$(OBJECT_DIR)/cmiss_fortran_c.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/cmiss_cellml_dummy.o : $(SOURCE_DIR)/cmiss_cellml_dummy.f90
$(OBJECT_DIR)/cmiss_fortran_c.o : $(SOURCE_DIR)/cmiss_fortran_c.f90
$(OBJECT_DIR)/cmiss_mpi.o : $(SOURCE_DIR)/cmiss_mpi.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/strings.o
$(OBJECT_DIR)/cmiss_parmetis.o : $(SOURCE_DIR)/cmiss_parmetis.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o
$(OBJECT_DIR)/cmiss_petsc.o : $(SOURCE_DIR)/cmiss_petsc.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/cmiss_petsc_types.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/cmiss_petsc_types.o : $(SOURCE_DIR)/cmiss_petsc_types.f90 \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/computational_environment.o : $(SOURCE_DIR)/computational_environment.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/cmiss_petsc.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o
$(OBJECT_DIR)/constants.o : $(SOURCE_DIR)/constants.f90 \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/control_loop_routines.o : $(SOURCE_DIR)/control_loop_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/coordinate_routines.o : $(SOURCE_DIR)/coordinate_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/maths.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Darcy_equations_routines.o : $(SOURCE_DIR)/Darcy_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Darcy_pressure_equations_routines.o : $(SOURCE_DIR)/Darcy_pressure_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/maths.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/fieldml_input_routines.o: $(SOURCE_DIR)/fieldml_input_routines.f90 \
$(OBJECT_DIR)/fieldml_util_routines.o \
$(OBJECT_DIR)/fieldml_types.o \
$(OBJECT_DIR)/util_array.o
$(OBJECT_DIR)/fieldml_output_routines.o: $(SOURCE_DIR)/fieldml_output_routines.f90 \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/fieldml_util_routines.o \
$(OBJECT_DIR)/fieldml_types.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/strings.o
$(OBJECT_DIR)/fieldml_util_routines.o: $(SOURCE_DIR)/fieldml_util_routines.f90 \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/fieldml_types.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/finite_elasticity_Darcy_routines.o : $(SOURCE_DIR)/finite_elasticity_Darcy_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/Darcy_equations_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/finite_elasticity_fluid_pressure_routines.o : $(SOURCE_DIR)/finite_elasticity_fluid_pressure_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/bioelectric_finite_elasticity_routines.o : $(SOURCE_DIR)/bioelectric_finite_elasticity_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/bioelectric_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/data_point_routines.o : $(SOURCE_DIR)/data_point_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/data_projection_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/trees.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/data_projection_routines.o : $(SOURCE_DIR)/data_projection_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/sorting.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/trees.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/diffusion_advection_diffusion_routines.o : $(SOURCE_DIR)/diffusion_advection_diffusion_routines.f90 \
$(OBJECT_DIR)/advection_diffusion_equation_routines.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/diffusion_equation_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/diffusion_diffusion_routines.o : $(SOURCE_DIR)/diffusion_diffusion_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/diffusion_equation_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/diffusion_equation_routines.o : $(SOURCE_DIR)/diffusion_equation_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Burgers_equation_routines.o : $(SOURCE_DIR)/Burgers_equation_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/distributed_matrix_vector.o : $(SOURCE_DIR)/distributed_matrix_vector.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/cmiss_petsc.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/distributed_matrix_vector_IO.o : $(SOURCE_DIR)/distributed_matrix_vector_IO.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/domain_mappings.o : $(SOURCE_DIR)/domain_mappings.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/elasticity_routines.o : $(SOURCE_DIR)/elasticity_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/linear_elasticity_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/electromechanics_routines.o : $(SOURCE_DIR)/electromechanics_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/electrophysiology_cell_routines.o : $(SOURCE_DIR)/electrophysiology_cell_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/equations_routines.o : $(SOURCE_DIR)/equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/equations_mapping_routines.o : $(SOURCE_DIR)/equations_mapping_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/equations_matrices_routines.o : $(SOURCE_DIR)/equations_matrices_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/equations_set_constants.o : $(SOURCE_DIR)/equations_set_constants.f90 \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/equations_set_routines.o : $(SOURCE_DIR)/equations_set_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/bioelectric_routines.o \
$(OBJECT_DIR)/classical_field_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/elasticity_routines.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_routines.o \
$(OBJECT_DIR)/interface_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/monodomain_equations_routines.o \
$(OBJECT_DIR)/multi_physics_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/external_dae_solver_routines.o : $(SOURCE_DIR)/external_dae_solver_routines.c \
$(SOURCE_DIR)/external_dae_solver_routines.h
$(OBJECT_DIR)/field_routines.o : $(SOURCE_DIR)/field_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/maths.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/field_IO_routines.o : $(SOURCE_DIR)/field_IO_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(SOURCE_DIR)/FieldExportConstants.h \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/lists.o \
$(MACHINE_OBJECTS) \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/finite_elasticity_routines.o : $(SOURCE_DIR)/finite_elasticity_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/generated_mesh_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/maths.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/fluid_mechanics_routines.o : $(SOURCE_DIR)/fluid_mechanics_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/Burgers_equation_routines.o \
$(OBJECT_DIR)/Darcy_equations_routines.o \
$(OBJECT_DIR)/Darcy_pressure_equations_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/Navier_Stokes_equations_routines.o \
$(OBJECT_DIR)/Poiseuille_equations_routines.o \
$(OBJECT_DIR)/Stokes_equations_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o : $(SOURCE_DIR)/fluid_mechanics_IO_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/FieldExport.o : $(SOURCE_DIR)/FieldExport.c \
$(SOURCE_DIR)/FieldExportConstants.h
$(OBJECT_DIR)/input_output.o : $(SOURCE_DIR)/input_output.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/strings.o
$(OBJECT_DIR)/fitting_routines.o : $(SOURCE_DIR)/fitting_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/Darcy_equations_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/generated_mesh_routines.o : $(SOURCE_DIR)/generated_mesh_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/maths.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Helmholtz_equations_routines.o : $(SOURCE_DIR)/Helmholtz_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/history_routines.o : $(SOURCE_DIR)/history_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/interface_routines.o : $(SOURCE_DIR)/interface_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/generated_mesh_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/interface_conditions_constants.o : $(SOURCE_DIR)/interface_conditions_constants.f90 \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/interface_conditions_routines.o : $(SOURCE_DIR)/interface_conditions_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/interface_equations_routines.o \
$(OBJECT_DIR)/interface_mapping_routines.o \
$(OBJECT_DIR)/interface_matrices_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/interface_equations_routines.o : $(SOURCE_DIR)/interface_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/interface_mapping_routines.o \
$(OBJECT_DIR)/interface_matrices_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/interface_mapping_routines.o : $(SOURCE_DIR)/interface_mapping_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/interface_matrices_routines.o : $(SOURCE_DIR)/interface_matrices_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/iso_varying_string.o : $(SOURCE_DIR)/iso_varying_string.f90
$(OBJECT_DIR)/kinds.o : $(SOURCE_DIR)/kinds.f90
$(OBJECT_DIR)/Hamilton_Jacobi_equations_routines.o : $(SOURCE_DIR)/Hamilton_Jacobi_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Laplace_equations_routines.o : $(SOURCE_DIR)/Laplace_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/linear_elasticity_routines.o : $(SOURCE_DIR)/linear_elasticity_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/lists.o : $(SOURCE_DIR)/lists.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/linkedlist_routines.o : $(SOURCE_DIR)/linkedlist_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/machine_constants_aix.o : $(SOURCE_DIR)/machine_constants_aix.f90 \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/machine_constants_linux.o : $(SOURCE_DIR)/machine_constants_linux.f90 \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/machine_constants_windows.o : $(SOURCE_DIR)/machine_constants_windows.f90 \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/maths.o : $(SOURCE_DIR)/maths.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o
$(OBJECT_DIR)/matrix_vector.o : $(SOURCE_DIR)/matrix_vector.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/mesh_routines.o : $(SOURCE_DIR)/mesh_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/cmiss_parmetis.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/trees.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/monodomain_equations_routines.o : $(SOURCE_DIR)/monodomain_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/electrophysiology_cell_routines.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/fitting_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/multi_compartment_transport_routines.o : $(SOURCE_DIR)/multi_compartment_transport_routines.f90 \
$(OBJECT_DIR)/advection_diffusion_equation_routines.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/diffusion_equation_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/multi_physics_routines.o : $(SOURCE_DIR)/multi_physics_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/diffusion_advection_diffusion_routines.o \
$(OBJECT_DIR)/diffusion_diffusion_routines.o \
$(OBJECT_DIR)/finite_elasticity_Darcy_routines.o \
$(OBJECT_DIR)/finite_elasticity_fluid_pressure_routines.o \
$(OBJECT_DIR)/bioelectric_finite_elasticity_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/multi_compartment_transport_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Navier_Stokes_equations_routines.o : $(SOURCE_DIR)/Navier_Stokes_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/node_routines.o : $(SOURCE_DIR)/node_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/trees.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/opencmiss.mod : $(OBJECT_DIR)/opencmiss.o
$(OBJECT_DIR)/opencmiss.o : $(SOURCE_DIR)/opencmiss.f90 \
$(OBJECT_DIR)/analytic_analysis_routines.o \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/cmiss.o \
$(OBJECT_DIR)/cmiss_cellml.o \
$(OBJECT_DIR)/cmiss_mpi.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/data_point_routines.o \
$(OBJECT_DIR)/data_projection_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/equations_set_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/field_IO_routines.o \
$(FIELDML_OBJECT) \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_routines.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/interface_conditions_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/problem_routines.o \
$(OBJECT_DIR)/region_routines.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/test_framework_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/opencmiss_c.o : $(C_F90_SOURCE) \
$(OBJECT_DIR)/cmiss_fortran_c.o \
$(OBJECT_DIR)/opencmiss.o
$(OBJECT_DIR)/Poiseuille_equations_routines.o : $(SOURCE_DIR)/Poiseuille_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/Poisson_equations_routines.o : $(SOURCE_DIR)/Poisson_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/problem_constants.o : $(SOURCE_DIR)/problem_constants.f90 \
$(OBJECT_DIR)/kinds.o
$(OBJECT_DIR)/problem_routines.o : $(SOURCE_DIR)/problem_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/bioelectric_routines.o \
$(OBJECT_DIR)/classical_field_routines.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/elasticity_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/equations_set_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/finite_elasticity_routines.o \
$(OBJECT_DIR)/fluid_mechanics_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/multi_physics_routines.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/solver_matrices_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/reaction_diffusion_equation_routines.o : $(SOURCE_DIR)/reaction_diffusion_equation_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/reaction_diffusion_IO_routines.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/reaction_diffusion_IO_routines.o : $(SOURCE_DIR)/reaction_diffusion_IO_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/region_routines.o : $(SOURCE_DIR)/region_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/coordinate_routines.o \
$(OBJECT_DIR)/cmiss_cellml.o \
$(OBJECT_DIR)/data_point_routines.o \
$(OBJECT_DIR)/equations_set_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/generated_mesh_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/mesh_routines.o \
$(OBJECT_DIR)/node_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/solver_routines.o : $(SOURCE_DIR)/solver_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/cmiss_cellml.o \
$(OBJECT_DIR)/cmiss_petsc.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/external_dae_solver_routines.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/solver_mapping_routines.o \
$(OBJECT_DIR)/solver_matrices_routines.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/solver_mapping_routines.o : $(SOURCE_DIR)/solver_mapping_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/computational_environment.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/interface_conditions_routines.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/lists.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/solver_matrices_routines.o : $(SOURCE_DIR)/solver_matrices_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/interface_conditions_constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/sorting.o : $(SOURCE_DIR)/sorting.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o
$(OBJECT_DIR)/Stokes_equations_routines.o : $(SOURCE_DIR)/Stokes_equations_routines.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/basis_routines.o \
$(OBJECT_DIR)/boundary_condition_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/control_loop_routines.o \
$(OBJECT_DIR)/distributed_matrix_vector.o \
$(OBJECT_DIR)/domain_mappings.o \
$(OBJECT_DIR)/equations_routines.o \
$(OBJECT_DIR)/equations_mapping_routines.o \
$(OBJECT_DIR)/equations_matrices_routines.o \
$(OBJECT_DIR)/equations_set_constants.o \
$(OBJECT_DIR)/field_routines.o \
$(OBJECT_DIR)/fluid_mechanics_IO_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/problem_constants.o \
$(OBJECT_DIR)/strings.o \
$(OBJECT_DIR)/solver_routines.o \
$(OBJECT_DIR)/timer_f.o \
$(OBJECT_DIR)/types.o
$(OBJECT_DIR)/strings.o : $(SOURCE_DIR)/strings.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o
$(OBJECT_DIR)/test_framework_routines.o : $(SOURCE_DIR)/test_framework_routines.f90 \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/matrix_vector.o \
$(OBJECT_DIR)/strings.o
$(OBJECT_DIR)/timer_c.o : $(SOURCE_DIR)/timer_c.c
$(OBJECT_DIR)/timer_f.o : $(SOURCE_DIR)/timer_f.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o
$(OBJECT_DIR)/trees.o : $(SOURCE_DIR)/trees.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/input_output.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/strings.o
$(OBJECT_DIR)/types.o : $(SOURCE_DIR)/types.f90 \
$(OBJECT_DIR)/cmiss_petsc_types.o \
$(OBJECT_DIR)/constants.o \
$(OBJECT_DIR)/kinds.o \
$(OBJECT_DIR)/iso_varying_string.o \
$(OBJECT_DIR)/linkedlist_routines.o \
$(OBJECT_DIR)/trees.o
$(OBJECT_DIR)/util_array.o : $(SOURCE_DIR)/util_array.f90 \
$(OBJECT_DIR)/base_routines.o \
$(OBJECT_DIR)/types.o
# ----------------------------------------------------------------------------
#
# clean and clobber for removing objects and executable.
clean:
@echo "Cleaning house ..."
rm -rf $(OBJECT_DIR) $(LIBRARY) $(MOD_INCLUDE) $(HEADER_INCLUDE) $(C_F90_SOURCE)
allclean:
@echo "Cleaning house ..."
rm -rf object/* lib/*
clobber: clean
rm -f $(LIBRARY)
externallibs:
$(MAKE) --no-print-directory -f $(EXTERNAL_CM_ROOT)/packages/Makefile DEBUG=$(DEBUG) ABI=$(ABI)
debug opt debug64 opt64:
$(MAKE) --no-print-directory DEBUG=$(DEBUG) ABI=$(ABI)
debug debug64: DEBUG=true
opt opt64: DEBUG=false
ifneq (,$(filter $(MACHNAME),ia64 x86_64))# ia64 or x86_64
debug opt: ABI=64
else
debug opt: ABI=32
endif
debug64 opt64: ABI=64
all: debug opt
all64: debug64 opt64
ifndef SIZE
SIZE=small
endif
ifndef DIR
DIR=.
endif
test: main
@echo "================================================================================================"
@echo "By default, this will test small set of examples. (All tests in the nightly build)"
@echo "To test large set of examples (All tests in the nightly build), please set SIZE=large"
@echo "To test examples inside a given directory, please set DIR=<DIR>, e.g. DIR=ClassicalField/Laplace"
@echo "You need to install nosetests in order to run the tests."
@echo "Please go to http://readthedocs.org/docs/nose/ for details."
@echo "For detailed logfiles, go to <OPENCMISS_ROOT>/build/logs directory."
@echo "================================================================================================"
COMPILER=$(COMPILER) SIZE=${SIZE} DIR=$(DIR) ABI=${ABI} nosetests ${OPENCMISSEXAMPLES_ROOT}/noseMain.py:test_example
#-----------------------------------------------------------------------------
help:
@echo " Compile a library version of OpenCMISS"
@echo " ======================================"
@echo
@echo "Examples of usage: "
@echo
@echo " gmake"
@echo " gmake OPT= ABI=32"
@echo " gmake PROF="
@echo " gmake debug64"
@echo
@echo "Options: (The former is the default unless specified.)"
@echo
@echo " (DEBUG=|OPT=)"
@echo " MPI=(mpich2|intel|openmpi|mvapich2|cray)"
@echo " PROF=(true|)"
@echo " MPIPROF=(true|)"
@echo " ABI=(32|64)"
@echo " COMPILER=(intel|gnu|ibm|cray)"
@echo " USECELLML=(false|true)"
@echo " USEFIELDML=(false|true)"
@echo
@echo "Available targets: "
@echo
@echo " clean"
@echo " Remove generated files associated with a single"
@echo " version."
@echo
@echo " clobber"
@echo " Remove all files associated with a single version."
@echo
@echo " help"
@echo " Display this message."
@echo
@echo " debug opt debug64 opt64"
@echo " Compile the specified version with automatic setting"
@echo " of DEBUG, ABI, and MP."
@echo
@echo " all"
@echo " Compile all versions."
@echo
@echo " all64"
@echo " Compile all 64-bit versions."
@echo
@echo
@echo " externallibs"
@echo " Compile the external libraries."
@echo
@echo " test"
@echo " Build, execute and check for test."
@echo
| db1d7109235b2a8d85b7470bce17f88e1477794c | [
"Python",
"Makefile"
] | 2 | Python | msteghofer/cm | 9e4ae786e12a7e9158f9566c1e514d519c1bd89f | a82819b1a3a25dda79f852847eddd31252f40e9e |
refs/heads/main | <file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Gaps problem
without traceback (only final scores). It is a Dynamic Programming
(DP) with pruning approach, by keeping three DP matrices: Q, S and T
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Declaration of variables and function prototypes
* related with the establishment and initialization
* of all bounds: lower (MIN, MID's and MAX) and upper bounds.
* MIN is the score vector with minimum #gaps and minimum substitution score
* MAX is the score vector with maximum #gaps and maximum substitution score
* MID's are all the score vectors between.
* It also includes the function responsible for pruning.
*/
#ifndef _BOUNDS_H
#define _BOUNDS_H
#include "pareto_set.h"
/* length of the alphabet to the substitution score table
(includes all the letters from '*' to 'Z' to get constant time access)
*/
#define LEN_ALPHABET ('Z'-'*'+1)
VMG *LB; /* MIN, MIDs, MAX together (ordered by substitution score) */
VMG *MIN, *MAX; /* MIN and MAX are calculated in a different way */
VMG ** L; /* Dynamic Programming (DP) table for the main lower bound states table (m,g) */
VMG ** LT; /* DP table for the lower bound states table (m,g) that keeps solutions ending in (ai,'-') */
VMG * LS; /* DP table for the lower bound states table (m,g) that keeps solutions ending in ('-',bj) */
char ** TL; /* lower bound traceback directions (needed to know if a previous gap already exists to improve puning) */
/* MID bound states tables */
VMG ** M_; /* main DP table */
VMG * MS; /* DP table S */
VMG ** MT; /* DP table T */
int ** U; /* DP table for the upper bound states table (only substitution score, #gaps are calculated in another simpler way) */
int MAX_MID_BOUNDS_NUM; /* number of mid bounds */
int BOUNDS_NUM; /* total number of bounds */
extern int M, N;
extern char seq1[];
extern char seq2[];
extern int MAX_STATES;
extern int SS[][LEN_ALPHABET];
/* bounds initialization and determination (calls all init_*_bound() and calculate_*_bound() functions )*/
void init_bounds( int mid_bounds );
void init_lower_bound( ); /* initialization of the lower bound structures (memory allocations and base cases specification) */
void calculate_lower_bound( ); /* computation of all lower bounds (MIN, MAX and MID's) by filling 'VMG ** L' and 'VMG ** M_' */
void init_upper_bound( ); /* initialization of the upper bound structures (memory allocations and base cases specification) */
void calculate_upper_bound( ); /* computation of all upper bounds by filling 'int ** U' */
/**
* Returns the lexicographically larger vector between
* LS and L current score vectors
* This is used to determine MAX, together with lexmaxM3() - 'matches' are priority
*/
VMG lexmaxMS( VMG p1, VMG p2, int i, int j );
/**
* Returns the lexicographically larger vector between
* LT and L current score vectors
* This is used to determine MAX, together with lexmaxM3() - 'matches' are priority
*/
VMG lexmaxMT( VMG p1, VMG p2, int i, int j );
/**
* Returns the lexicographically larger vector between the score
* vectors of cells 'S', 'T' and 'Q'
* 'score'- the value of the subs score corresponding the current letters at position (i,j) (used by the 'Q' score vector).
* This is used to determine MAX - 'matches' are priority
*/
VMG lexmaxM3( VMG S, VMG T, VMG Q, int score, int i, int j);
void calc_MAX(); /* calculates MAX, based on lexmaxM() */
void calc_MIN(); /* calculates MIN */
/**
* Returns the score vector that maximizes the scalarized score function
* between the MS, MT and M_('Q') current score vectors.
* (another version of the bicriteria alignment problem).
* 'subs_score'- the value of the subs score corresponding the current letters at position (i,j) (used by the 'Q' score vector).
* 'ws' and 'wd' are the weighting coefficients.
*/
VMG scalar_max3( VMG S, VMG T, VMG Q, int subs_score, int ws, int wg );
/**
* Returns the score vector that maximizes the scalarized score function
* between the MS and M_('Q') or MT and M_('Q') current score vectors.
* (another version of the bicriteria alignment problem).
* 'ws' and 'wd' are the weighting coefficients.
*/
VMG scalar_max2( VMG p1, VMG p2, int ws, int wg );
void calc_MID(); /* calculates all MID bounds for each MID bound DP table */
/**
* Determines if the last score vector of the
* pareto set 'set' can be pruned and, if so,
* removes it from the set.
* Based on the lower and upper bounds previously calculated.
* The 'dir' improves pruning by knowing if a previous gap already exists
*/
void prune( Pareto_set *set, int i, int j, char dir );
void remove_bounds_tables(); /* frees tables still in memory and used during the algorithm */
int min2(int n1, int n2); /* returns the minimum of two numbers */
int max2(int n1, int n2); /* returns the maximum of two numbers */
int max3(int n1, int n2, int n3); /* returns the maximum of three numbers */
/* get substitution scores of the pair of letters seq1[i] and seq2[j] */
int get_score( int i, int j );
int get_score2(char *s1, int i, char *s2, int j );
#endif<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Gaps problem
without traceback (only final scores). It is a Dynamic Programming
(DP) without pruning approach, by keeping three DP matrices: Q, S and T
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include "pareto_set.h"
#define MAX_LENGTH (4000) /* maximum length of the sequences */
void read_sequence(char seq[] , char *filename);
void init_dynamic_tables( );
void align( );
void remove_dynamic_tables();
/* read sequences */
char seq1[MAX_LENGTH];
char seq2[MAX_LENGTH];
/* DP main table */
Pareto_set ** Q;
/* DP table with first sequences ending with '-' ('-',bj ) */
Pareto_set * S;
/* DP table with second sequences ending with '-' (ai ,'-') */
Pareto_set ** T;
/* sizes of the DP table (M-#lines, N-#colunms) */
int M, N;
/* maximum #states for each DP table cell (not using linked lists) */
int MAX_STATES = 3000; /* can't evaluate MAX_STATES (only on the pruning version) */
/**
* For the sake of memory, the Dynamic Programming (DP) tables used
* have only two lines (just like on #Matches-#Indels problem), because there is no
* traceback step (the traceback pointers do not need to be stored). Instead of two lines
* table S has only one line, because, in each iteration the only cells that
* are needed are the ones immediately left of the current cell. The other DP tables
* need cells that are in the line above the current line.
*/
int main( int argc, char *argv[]) {
if(argc != 3){
printf("Usage: %s <seq1_file> <seq2_file>\n", argv[0]);
return 0;
}
read_sequence(seq1, argv[1]);
read_sequence(seq2, argv[2]);
M = strlen(seq1); N = strlen(seq2);
init_dynamic_tables();
align();
/* print the result scores */
int i, line;
line = M % 2; /* determine from which line to start printing */
for( i = 0; i < Q[line][N].num ; ++i )
printf("%d %d\n", Q[line][N].scores[i].matches, Q[line][N].scores[i].gaps);
remove_dynamic_tables();
return 0;
}
void read_sequence(char seq[], char *filename){
/**
* Reads the sequence contained in 'filename'.
* This file must follow the FASTA format.
*/
char fasta_header[300];
char line[300];
FILE *f = fopen(filename, "r");
if(f){
if( fscanf(f, ">%[^\n]\n", fasta_header)>0 ){ /* determine if file is valid */
while( fscanf(f, "%s", line)!=EOF )
strcat(seq, line);
}
else{
printf("Sequence file format is not correct!\n");
exit(-1);
}
fclose(f);
}
else{
fprintf(stderr, "Failed to open sequence file: %s\n", strerror(errno));
exit(-1);
}
}
void init_dynamic_tables( ){
/**
* Allocates memory for the all the DP tables and
* initialize the its base cases.
*/
int i, j;
Q = (Pareto_set **) malloc( 2 * sizeof(Pareto_set *) );
T = (Pareto_set **) malloc( 2 * sizeof(Pareto_set *) );
for(i=0; i<2 ; i++){
Q[i] = (Pareto_set *) malloc( (N+1) * sizeof(Pareto_set) );
T[i] = (Pareto_set *) malloc( (N+1) * sizeof(Pareto_set) );
/* allocate memory */
for( j = 0; j < N+1; ++j ){
Q[i][j].scores = (VMG *) malloc(MAX_STATES * sizeof(VMG));
Q[i][j].num = 0;
T[i][j].scores = (VMG *) malloc(MAX_STATES * sizeof(VMG));
T[i][j].num = 0;
}
}
S = (Pareto_set *) malloc( (N+1) * sizeof(Pareto_set) );
for( i = 0; i < N+1; ++i ){
S[i].scores = (VMG *)malloc( MAX_STATES * sizeof(VMG));
S[i].num = 0;
}
/* base cases */
append_node( &Q[0][0], 0, 0 );
for( i = 1; i <= N; ++i ){
append_node( &T[0][i], 0, INT_MAX ); /* against DP table definition (wrong position of gap if traceback is done) */
append_node( &Q[0][i], 0, 1 );
}
append_node( &S[0], 0, INT_MAX); /* against table definition (wrong position of gap if traceback is done) */
}
void align( ){
/**
* Filling of the main DP table Q by filling the other tables too.
* For simplicity, two pointers were created:
* 'curr' and 'prev' that point to the
* current and previous line of the DP tables,
* because there are only two lines (or one line).
*/
int i, j, k, match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
for( i = 1; i <= M; ++i ){
/* exchange lines for tables T and Q */
prev = !( i % 2);
curr = (i % 2);
/* first column of Q is a base case */
append_node( &Q[curr][0], 0, 1);
/* first column of T is out of reach (does not need base case) */
/* first column of S is a base case but was calculated before once in init_dynamic_tables() ) */
for( j = 1; j <= N; ++j ){
match = seq1[i-1] == seq2[j-1];
pareto_merge2( &S[j], S[j-1], Q[curr][j-1] );
pareto_merge2( &T[curr][j], T[prev][j], Q[prev][j] );
pareto_merge3( &Q[curr][j], S[j], T[curr][j], Q[prev][j-1], match);
}
/* reset previous lines of Q and T to store new scores */
for( k = 0; k < N+1; ++k ){
Q[prev][k].num = 0;
T[prev][k].num = 0;
}
/* reset previous lines of S to store new scores */
for( k = 1; k < N+1; ++k ){
S[k].num = 0;
}
}
}
void remove_dynamic_tables(){
/**
* Free all DP tables.
*/
int i, j;
/* Q */
for( i = 0; i < 2; ++i )
for( j = 0; j < N+1; ++j )
free( Q[i][j].scores );
for( i = 0; i < 2; ++i )
free(Q[i]);
free(Q);
/* T */
for( i = 0; i < 2; ++i )
for( j = 1; j < N+1; ++j )
free( T[i][j].scores );
for( i = 0; i < 2; ++i )
free(T[i]);
free(T);
/* S */
for( i = 0; i < N+1; ++i )
free( S[i].scores );
free(S);
}
<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Indels problem
without traceback (only final scores). It is a Dynamic Programming
(DP) without pruning approach, by filling a DP matrix - P
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "pareto_set.h"
#define MAX_LENGTH (4000) /* maximum length of the sequences */
void read_sequence(char seq[] , char *filename);
void init_dynamic_table( );
void align( );
void remove_dynamic_table();
/* read sequences */
char seq1[MAX_LENGTH];
char seq2[MAX_LENGTH];
/* DP table */
Pareto_set ** P;
/* sizes of the DP table (M-#lines, N-#colunms) */
int M, N;
/* maximum #states for each DP table cell (not using linked lists) */
int MAX_STATES = 3000; /* can't evaluate MAX_STATES (only on the pruning version) */
/**
* For the sake of memory, the DP table used
* has only two lines, because there is no traceback step (the traceback
* pointers do not need to be stored). Also, in each iteration, the
* only cells that are needed for the algorithm are the ones that
* are immediately left, up and diagonal(up and left) of the current cell.
*/
int main( int argc, char ** argv ) {
if(argc != 3){
printf("Usage: %s <seq1_file> <seq2_file>\n", argv[0]);
return 0;
}
read_sequence(seq1, argv[1]);
read_sequence(seq2, argv[2]);
M = strlen(seq1); N = strlen(seq2);
init_dynamic_table();
align( );
/* print the result scores */
int i, line;
line = M % 2; /* determine from which line to start printing */
for( i = 0; i < P[line][N].num; i++ )
printf( "%d %d\n", P[line][N].scores[i].matches , P[line][N].scores[i].indels);
remove_dynamic_table();
return 0;
}
void read_sequence(char seq[], char *filename){
/**
* Reads the sequence contained in 'filename'.
* This file must follow the FASTA format.
*/
char fasta_header[300];
char line[300];
FILE *f = fopen(filename, "r");
if(f){
if( fscanf(f, ">%[^\n]\n", fasta_header)>0 ){ /* determine if file is valid */
while( fscanf(f, "%s", line)!=EOF )
strcat(seq, line);
}
else{
printf("Sequence file format is not correct!\n");
exit(-1);
}
fclose(f);
}
else{
fprintf(stderr, "Failed to open sequence file: %s\n", strerror(errno));
exit(-1);
}
}
void init_dynamic_table( ){
/**
* Allocates memory for the DP table and
* initialize the base cases.
*/
int i, j;
P = (Pareto_set **) malloc( 2 * sizeof(Pareto_set *) );
for(i=0; i < 2 ; i++){
P[i] = (Pareto_set *) malloc( (N+1) * sizeof(Pareto_set) );
/* allocate memory */
for( j = 0; j < N+1; ++j ){
P[i][j].scores = (VMD *) malloc( MAX_STATES * sizeof(VMD) );
P[i][j].num = 0; /* number of scores is zero (initially) */
}
}
/* init top line (base cases) */
for( i = 0; i <= N ; i++ ){
append_node( &P[0][i], 0, i);
}
}
void align( ){
/**
* Filling of the DP table.
* For simplicity, two pointers were created:
* 'curr' and 'prev' that point to the
* current and previous line of the DP table,
* because there are only two lines.
*/
int i, j, k, match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
for( i = 1; i <= M; ++i ){
/* exchange lines */
prev = !(i % 2);
curr = (i % 2);
/* first column is a base case */
append_node( &P[curr][0], 0, i);
for( j = 1; j <= N; ++j ){
match = seq1[i-1] == seq2[j-1];
pareto_merge( &P[curr][j], P[prev][j], P[prev][j-1], P[curr][j-1], match);
}
/* reset previous line to store new scores */
for( k = 0; k <= N; ++k )
P[prev][k].num = 0;
}
}
void remove_dynamic_table(){
/**
* Free DP table.
*/
int i, j;
for( i = 0; i < 2; ++i ){
for( j = 0; j < N+1; ++j )
free( P[i][j].scores );
}
for( i = 0; i < 2; ++i ){
free(P[i]);
}
free(P);
}<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Indels problem.
It is a Dynamic Programming (DP) without pruning approach, by filling a DP
matrix - P (with dimensions (M+1)*(N+1), where M and N are the sizes of the
1st and 2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Implementation of the functions in 'pareto_set.h'.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "pareto_set.h"
Pareto_set create_list( ){
Node *ptr = (Node *)malloc(sizeof(Node));
if(ptr){
ptr->score.matches = 0;
ptr->score.indels = 0;
ptr->traceback_ptr = NULL;
ptr->traceback_ptr = '\0';
ptr->next = NULL;
}
return ptr;
}
void append_node(Node *ptr, int m, int i, Node *tb_ptr, char tb_dir){
ptr->next = (Node *)malloc(sizeof(Node));
ptr->next->score.matches = m;
ptr->next->score.indels = i;
ptr->next->traceback_ptr = tb_ptr;
ptr->next->traceback_dir = tb_dir;
ptr->next->next = NULL;
}
Pareto_set pareto_merge( Pareto_set up, Pareto_set diagonal, Pareto_set left, int match ){
/**
* Scores are assumed to be ordered incrementally by their #indels.
* Until all the iterators reach the end, it is selected the score with
* minimum #indels and, in case of equality, with maximum #matches, from
* the three scores: up-(mu,iu), diagonal-(md,id) and left-(ml,il).
* (If the score vectors are exactly the same, than one is chosen randomly.)
* This score is appended to the result as it is always non dominated.
* The #matches of that score (to be stored in M_MAX) is also used to
* eliminate the (dominated) scores following in each set, by advancing
* the iterators until the #matches of the pointed score is greater than M_MAX.
* The dominance of these scores is also assured because the sets are ordered by #indels
* and they all have greater #indels compared to the selected score.
*
*/
/* allocate memory for the result set */
Pareto_set res = create_list();
Node * ptr_res = res;
/* defines the number of matches of the score to be inserted */
int M_MAX;
/* auxiliar variables for comparisons */
int iu, id, il;
int mu, md, ml;
/* these linked lists have headers */
up = up->next;
diagonal = diagonal->next;
left = left->next;
while( up || diagonal || left ){
/* Initialization of the auxiliar variables for the up, diagonal and left directions
In case iterators reach the end of its set (first comparison),
its values are not inserted, keeping the algorithm structure */
/* UP */
if ( up ){
iu = up->score.indels + 1;
mu = up->score.matches;
}
else{
iu = INT_MAX;
mu = INT_MIN;
}
/* DIAGONAL */
if( diagonal ){
id = diagonal->score.indels;
md = diagonal->score.matches + match;
}
else{
id = INT_MAX;
md = INT_MIN;
}
/* LEFT */
if( left ){
il = left->score.indels + 1;
ml = left->score.matches;
}
else{
il = INT_MAX;
ml = INT_MIN;
}
/* End of auxiliar variables initialization */
/* Select score with minimum #indels and, in case of equality,
with maximum #matches */
if( iu < id ){
if( iu < il ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else if( iu == il ){
if( mu > ml ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else if( mu == ml && (rand()%2) ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else{
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
}
else{
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
}
else if( iu == id ){
if( il < iu ){
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
else if( iu == il ){
if( mu > md ){
if( mu > ml ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else if( mu == ml && (rand()%2) ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else{
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
}
else if( mu == md ){
if( ml > mu ){
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
else if( mu == ml ){
int var = rand()%3;
if( var == 0){
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
else if (var == 1){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else{
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
}
else{
if( rand()%2 ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else{
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
}
}
else{ /* iu == il == id && md > mu */
if( md > ml ){
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
else if( md == ml && (rand()%2) ){
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
else{
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
}
}
else{ /* iu==id && iu < il */
if( mu > md ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else if( mu == md && (rand()%2) ){
M_MAX = mu;
append_node( ptr_res, mu, iu , up, 'u' );
}
else{
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
}
}
else{
if( id < il ){
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
else if( id == il ){
if( md > ml ){
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
else if( md == ml && (rand()%2) ){
M_MAX = md;
append_node( ptr_res, md, id , diagonal, 'd' );
}
else{
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
}
else{
M_MAX = ml;
append_node( ptr_res, ml, il , left, 'l' );
}
}
/* End of minimum #indels score selection */
ptr_res = ptr_res->next;
/* Exclude dominated scores, advancing iterators, based on the value M_MAX */
while( up && up->score.matches <= M_MAX ) up = up->next;
while( left && left->score.matches <= M_MAX ) left = left->next;
while( diagonal && diagonal->score.matches + match <= M_MAX ) diagonal = diagonal->next;
}
return res;
}
void remove_list( Node * ptr ){
Node * tmp;
while( ptr->next ){
tmp = ptr;
ptr = ptr->next;
free(tmp);
}
free(ptr);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define GAPS "/Gaps"
#define INDELS "/Indels"
#define DP "/DP"
#define DPP "/DP_prune"
#define SS "/Subs_score"
#define MAT "/Matches"
#define NO_TB "/No_traceback"
#define TB "/Traceback"
void choose_program( char prog[], char *args[], int argc, char const * argv[] );
int check_main_args( int argc, char const *argv[] );
int main(int argc, char const *argv[]){
char prog[512]=""; // paths to external files can be big
char *args[6];
printf("%s\n", argv[1]);
if( argc < 5 || !check_main_args(argc, argv) ){
printf("\nUsage: %s seq1_file seq2_file [gaps|indels] [dp|dpp -b=NUMBER] [-ss=FILE] [--no-traceback]\n", argv[0]);
printf("\nOptions:\n");
printf(" seq1_file\t\tpath to the 1st sequence file (FASTA format)\n");
printf(" seq2_file\t\tpath to the 2nd sequence file (FASTA format)\n");
printf(" gaps\t\t\tspecify the problem to be relative to gaps.\n");
printf(" indels\t\tspecify the problem to be relative to indels.\n");
printf(" dp\t\t\tuse Dynamic Programming approach.\n");
printf(" dpp\t\t\tuse Dynamic Programming approach with pruning (need to specify -b=NUMBER).\n");
printf(" -ss=FILE\t\tuse substitution score(ss) instead of #matches (path to the ss table).\n");
printf(" -b=NUMBER\t\tspecify the number of MID bounds to prune.\n");
printf(" --no-traceback\toutput only the scores without the result alignments.\n");
return -1;
}
// relative path to program from the location execution started
char path_to_prog[300];
char * last_slash = strrchr(argv[0], '/');
memcpy( path_to_prog, argv[0], last_slash-argv[0] ) ;
// add relative path to current program
strcat(prog, path_to_prog);
choose_program( prog, args, argc, argv );
printf("running \"%s ", prog);
int i;
for( i = 1; i < 5; ++i )
if(args[i])
printf("%s ", args[i]);
printf("\"\n");
if (execv(prog, args) == -1)
perror("Error executing program");
return 0;
}
int check_main_args( int argc, char const *argv[] ){
return ( ( strcmp(argv[3],"gaps")==0 || strcmp(argv[3],"indels")==0 ) &&
( strcmp(argv[4],"dp")==0 || strcmp(argv[4],"dpp")==0 )
);
}
void choose_program( char prog[], char *args[], int argc, char const * argv[] ){
int i;
char * ss = NULL;
int tb = 1;
int num_args = 3;
args[0] = "prog";
args[1] = (char *) argv[1];
args[2] = (char *) argv[2];
args[3] = NULL;
args[4] = NULL;
args[5] = NULL;
// load sequences
// gaps or indels
if( !strcmp( argv[3], "gaps" ) )
strcat( prog, GAPS );
else
strcat( prog, INDELS );
// match or subs_score
for( i = 3; i < argc && !ss ; ++i )
ss=strstr( argv[i], "-ss=" );
if(ss){
strcat( prog, SS );
args[num_args++] = strchr(ss, '=')+sizeof(char); // keep just the value of '-ss'
}
else
strcat( prog, MAT );
// traceback or no traceback
for( i = 3; i < argc && tb; ++i )
tb=strcmp(argv[i], "--no-traceback");
if(!tb) strcat( prog, NO_TB);
else strcat( prog, TB);
// choose algorithm
if( !strcmp( argv[4], "dp" ) )
strcat(prog, DP);
else if( !strcmp( argv[4], "dpp" ) ){
strcat(prog, DPP);
// number of bounds
char * b = NULL;
for( i = 3; i < argc && !b; ++i )
b=strstr( argv[i], "-b=" );
if(b)
args[num_args] = strchr(b,'=')+sizeof(char); // keep just the value of '-b'
else{
printf("Prune version specified but no number of bounds (-b=X)\n");
exit(-1);
}
}
else{
printf("Wrong algorithm chosen: %s\n", argv[4]);
exit(-1);
}
strcat(prog, "/prog");
}
<file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Indels
problem without traceback (only final scores). It is a Dynamic Programming
(DP) without pruning approach, by filling a DP matrix - P
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "pareto_set.h"
#define MAX_LENGTH (4000)
/* length of the alphabet to the substitution score table
(includes all the letters from '*' to 'Z' to get constant time access)
*/
#define LEN_ALPHABET ('Z'-'*'+1)
void read_sequence(char seq[] , char *filename);;
void init_dynamic_table( );
void init_subs_table( char * filename );
void align( );
int get_score( int i, int j );
void remove_dynamic_table();
/* read sequences */
char seq1[MAX_LENGTH];
char seq2[MAX_LENGTH];
/* DP table */
Pareto_set ** P;
/* substitution score table */
int S[LEN_ALPHABET][LEN_ALPHABET];
/* sizes of the DP table (M-#lines, N-#colunms) */
int M, N;
/* maximum #states for each DP table cell (not using linked lists) */
int MAX_STATES = 3000; /* can't evaluate MAX_STATES (only on the pruning version) */
/**
* For the sake of memory, the Dynamic Programming (DP) table used
* has only two lines, because there is no traceback step (the traceback
* pointers do not need to be stored). Also, in each iteration, the
* only cells that are needed for the algorithm are the ones that
* are immediately left, up and diagonal(up and left) of the current cell.
*/
int main( int argc, char ** argv ) {
if(argc <= 3){
printf("Usage: %s <seq1_file> <seq2_file> <subs_file>\n", argv[0]);
return 0;
}
read_sequence(seq1, argv[1]);
read_sequence(seq2, argv[2]);
M = strlen(seq1); N = strlen(seq2);
init_subs_table( argv[3] );
init_dynamic_table();
align( );
/* print the result scores */
int i, line;
line = M % 2; /* determine from which line to start printing */
for( i = 0; i < P[line][N].num; i++ )
printf( "%d %d\n", P[line][N].scores[i].matches , P[line][N].scores[i].indels);
remove_dynamic_table();
return 0;
}
void read_sequence(char seq[], char *filename){
/**
* Reads the sequence contained in 'filename'.
* This file must follow the FASTA format.
*/
char fasta_header[300];
char line[300];
FILE *f = fopen(filename, "r");
if(f){
if( fscanf(f, ">%[^\n]\n", fasta_header)>0 ){ /* determine if file is valid */
while( fscanf(f, "%s", line)!=EOF )
strcat(seq, line);
}
else{
printf("Sequence file format is not correct!\n");
exit(-1);
}
fclose(f);
}
else{
fprintf(stderr, "Failed to open sequence file: %s\n", strerror(errno));
exit(-1);
}
}
void init_dynamic_table( ){
/**
* Allocates memory for the DP table and
* initialize the base cases.
*/
int i, j;
P = (Pareto_set **) malloc( 2 * sizeof(Pareto_set *) );
for(i=0; i < 2 ; i++){
P[i] = (Pareto_set *) malloc( (N+1) * sizeof(Pareto_set) );
/* allocate memory */
for( j = 0; j < N+1; ++j ){
P[i][j].scores = (VMD *) malloc( MAX_STATES * sizeof(VMD) );
P[i][j].num = 0; /* number of scores is zero (initially) */
}
}
/* init top line (base cases) */
for( i = 0; i <= N ; i++ ){
append_node( &P[0][i], 0, i);
}
}
void init_subs_table( char * filename ){
/**
* Builds substitution table from files that have a table with the format:
* A1 A2 ... An *
* A1 - - - - -
* A2 - - - - -
* ... - - - - -
* An - - - - -
* * - - - - -
* -> the Ai is the ith letter of the alphabet and each in each cell is an
* integer with the correspnding substitution score of the letters crossing
* -> The * column is optional and corresponds to the minimum score
*/
FILE *f;
char *f_contents, *it, *A, c, *sep = " \r\n\t", alphabet[LEN_ALPHABET];
int i, j, f_size, len_alphabet = 0, result;
f = fopen(filename, "r");
if(f){
/* obtain file size */
fseek(f, 0 , SEEK_END);
f_size = ftell(f);
rewind(f);
/* obtain memory */
f_contents = (char *)malloc(f_size * sizeof(char));
if(!f_contents){ fprintf(stderr, "Failed to allocate memory: %s\n", strerror(errno)); exit(-1);}
result = fread(f_contents, sizeof(char), f_size, f);
if(result != f_size){fprintf(stderr, "Failed to load file: %s\n", strerror(errno)); exit(-1);}
/* skip comments */
it = f_contents;
while(*it=='#') it = strchr(it, '\n')+1;
/* read alphabet */
while(*it != '\n'){
c = *it++;
if((c>='A' && c<='Z') || (c=='*')){
alphabet[ len_alphabet++ ] = c;
}
}
it++;
/* read scores */
for (i = 0; i < len_alphabet; ++i){
A = strtok(i==0 ? it:NULL, sep);
for (j = 0; j < len_alphabet; ++j)
S[ alphabet[i]-'*' ][ alphabet[j]-'*' ] = atoi(strtok(NULL , sep));
}
free(f_contents);
fclose(f);
}
else{
fprintf(stderr, "Failed to open subsitution score file: %s\n", strerror(errno));
exit(-1);
}
}
void align( ){
/**
* Filling of the DP table.
* For simplicity, two pointers were created:
* 'curr' and 'prev' that point to the
* current and previous line of the DP table,
* because there are only two lines.
*/
int i, j, k, subs_score;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
for( i = 1; i <= M; ++i ){
/* exchange lines */
prev = !(i % 2);
curr = (i % 2);
/* first column is a base case */
append_node( &P[curr][0], 0, i);
for( j = 1; j <= N; ++j ){
subs_score = get_score(i-1,j-1);
pareto_merge( &P[curr][j], P[prev][j], P[prev][j-1], P[curr][j-1], subs_score );
}
/* reset previous line to store new scores */
for( k = 0; k <= N; ++k ){
P[prev][k].num = 0;
}
}
}
int get_score( int i, int j ){
/**
* Returns the substitution score associated with the letters
* at position i in seq1 and j in seq2.
*/
return S[ seq1[i]-'*' ][ seq2[j]-'*' ];
}
void remove_dynamic_table(){
/**
* Free DP table.
*/
int i, j;
for( i = 0; i < 2; ++i ){
for( j = 0; j < N+1; ++j )
free( P[i][j].scores );
}
for( i = 0; i < 2; ++i ){
free(P[i]);
}
free(P);
}<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Indels problem
without traceback (only final scores). It is a Dynamic Programming
(DP) with pruning approach, by filling a DP matrix - P
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Implementation of the functions in 'bounds.h'.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "bounds.h"
void init_bounds( int mid_bounds ){
MAX_MID_BOUNDS_NUM = mid_bounds;
BOUNDS_NUM = mid_bounds + 2;
init_lower_bound( );
calculate_lower_bound( );
init_upper_bound( );
calculate_upper_bound( );
}
void init_lower_bound( ){
int i, j;
LB = (VMD *) malloc( BOUNDS_NUM * sizeof(VMD) );
/* L malloc (MAX and MIN) */
L = (VMD **) malloc( (2)*sizeof(VMD *) );
for( i = 0; i < 2; ++i )
L[i] = (VMD *) malloc( (N+1)*sizeof(VMD) );
/* base cases */
L[0][0].matches = 0;
L[0][0].indels = 0;
for( j = 1; j < N+1; ++j ){
L[0][j].matches = 0;
L[0][j].indels = j;
}
/* M's mallocs (MID's) */
M_ = (VMD **) malloc( (2)*sizeof(VMD *) );
for( i = 0; i < 2; ++i )
M_[i] = (VMD *) malloc( (N+1)*sizeof(VMD) );
}
void calculate_lower_bound( ){
int i;
calc_MIN();
calc_MID();
calc_MAX();
/* remove tables (not needed anymore) */
for( i = 0; i < 2; ++i )
free( L[i] );
free(L);
for( i = 0; i < 2; ++i )
free( M_[i] );
free( M_ );
/* calculates the maximum number of scores vectors per cell
(used to allocate memory for the main DP table)
*/
MAX_STATES = min2( MAX->matches-MIN->matches, MAX->indels-MIN->indels ) + 1;
}
void calc_MAX(){
/* LexMDP */
int i, j, match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
/* base cases */
L[0][0].matches = 0;
L[0][0].indels = 0;
for( j = 1; j < N+1; ++j ){
L[0][j].matches = 0;
L[0][j].indels = j;
}
for( i = 1; i < M+1; ++i ){
/* exchange lines */
prev = !( i % 2);
curr = (i % 2);
/* base cases */
L[curr][0].matches = 0;
L[curr][0].indels = i;
for( j = 1; j < N+1; ++j ){
match = seq1[i-1] == seq2[j-1];
L[curr][j] = lexmaxM( L[prev][j], L[curr][j-1], L[prev][j-1], match );
}
}
LB[ BOUNDS_NUM-1 ] = L[curr][N];
if( LB[ BOUNDS_NUM-1 ].matches == LB[ BOUNDS_NUM-2 ].matches ) /* if MAX is equal to last MID point */
BOUNDS_NUM--;
MAX = &LB[ BOUNDS_NUM-1 ] ;
// printf("MAX=(%d,%d)\n", MAX->matches, MAX->indels );
}
void calc_MIN(){
/* LexDMP */
int i, j,match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
for( i = 1; i < M+1; ++i ){
/* exchange lines */
prev = !( i % 2);
curr = (i % 2);
/* base cases */
L[curr][0].matches = 0;
L[curr][0].indels = i;
for( j = 1; j < N+1; ++j ){
match = seq1[i-1] == seq2[j-1];
L[curr][j] = lexminD( L[prev][j], L[curr][j-1], L[prev][j-1], match );
}
}
LB[0] = L[curr][N];
MIN = &LB[0];
//printf("MIN=(%d,%d)\n", MIN->matches, MIN->indels);
}
void calc_MID(){
int m, i, j, ws, wd, match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
int last_mid_matches = MIN->matches; /* discard same MID points */
int mid_bounds_num = 0;
for( m = 0; m < MAX_MID_BOUNDS_NUM; ++m ){
/* base cases */
M_[0][0].matches = 0;
M_[0][0].indels = 0;
for( j = 1; j < N+1; ++j ){
M_[0][j].matches = 0;
M_[0][j].indels = j;
}
for( i = 1; i < M+1; ++i ){
/* exchange lines for tables M_ and MT */
prev = !( i % 2);
curr = (i % 2);
/* base cases */
M_[curr][0].matches = 0;
M_[curr][0].indels = i;
for( j = 1; j < N+1; ++j ){
match = seq1[i-1] == seq2[j-1];
ws = m + 1;
wd = MAX_MID_BOUNDS_NUM - m;
M_[curr][j] = scalar_max( M_[prev][j], M_[curr][j-1], M_[prev][j-1], match, ws, wd );
}
}
if( last_mid_matches != M_[curr][N].matches ){ /* if MID does not exist yet */
LB[1 + mid_bounds_num++] = M_[curr][N];
}
last_mid_matches = M_[curr][N].matches;
/* printf("MID=(%d,%d)\n", M_[curr][N].matches, M_[curr][N].indels ); */
}
/* update value */
BOUNDS_NUM = 2 + mid_bounds_num;
}
void init_upper_bound( ){
int i;
U = (VMD **) malloc( (M+1)*sizeof(VMD *) );
for( i = 0; i <= M; ++i )
U[i] = (VMD *) malloc( (N+1)*sizeof(VMD) );
}
void calculate_upper_bound( ){
/**
* Based on the classical DP algorithm for computing the LCS
* in the reversed sequences.
*/
int i, j ;
/* base cases */
U[M][N].matches = 0;
U[M][N].indels = 0;
for( i = 0; i < M; ++i ){
U[i][N].matches = 0;
U[i][N].indels = M-i ;
}
for( j = 0; j < N; ++j ){
U[M][j].matches = 0;
U[M][j].indels = (N-j) ;
}
for( i = M-1; i >= 0; --i ){ /* begins in the oposite corner of the table (reversed sequences) */
for( j = N-1; j >= 0; --j ){
if( seq1[i] == seq2[j] ){
U[i][j].matches = U[i+1][j+1].matches + 1;
U[i][j].indels = abs( (M-i)-(N-j) ) ;
}
else{
U[i][j].matches = max2(U[i+1][j].matches , U[i][j+1].matches);
U[i][j].indels = abs( (M-i)-(N-j) ) ;
}
}
}
}
VMD lexmaxM( VMD up, VMD left, VMD diagonal, int match ){
/* match priority */
VMD result;
int mu, ml, md, iu, il, id; /* auxiliar variables */
mu = up.matches;
ml = left.matches;
md = diagonal.matches + match;
iu = up.indels + 1;
il = left.indels + 1;
id = diagonal.indels;
if( mu > ml ){
if( mu > md ){
result.matches = mu;
result.indels = iu;
}
else if( mu == md ){
if( iu <= id ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = md;
result.indels = id;
}
}
else{
result.matches = md;
result.indels = id;
}
}
else if( mu == ml ){
if( mu > md ){
if( iu <= il ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = ml;
result.indels = il;
}
}
else if( mu == md ){
if( iu <= il ){
if( iu <= id ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = md;
result.indels = id;
}
}
else{
if( il <= id ){
result.matches = ml;
result.indels = il;
}
else{
result.matches = md;
result.indels = id;
}
}
}
else{ /* mu < md */
result.matches = md;
result.indels = id;
}
}
else{ /* mu < ml */
if( ml > md ){
result.matches = ml;
result.indels = il;
}
else if( ml == md){
if( il <= id ){
result.matches = ml;
result.indels = il;
}
else{
result.matches = md;
result.indels = id;
}
}
else{
result.matches = md;
result.indels = id;
}
}
return result;
}
VMD lexminD( VMD up, VMD left, VMD diagonal, int match ){
/* indels priority */
VMD result;
int mu, ml, md, iu, il, id; /* auxiliar variables */
mu = up.matches;
ml = left.matches;
md = diagonal.matches + match;
iu = up.indels + 1;
il = left.indels + 1;
id = diagonal.indels;
if( iu < id ){
if( iu < il ){
result.matches = mu;
result.indels = iu;
}
else if( iu == il && mu >= ml ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = ml;
result.indels = il;
}
}
else if( iu == id ){
if( il < iu ){
result.matches = ml;
result.indels = il;
}
else if( iu == il ){
if( mu >= md ){
if( mu >= ml ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = ml;
result.indels = il;
}
}
else{
if( md >= ml ){
result.matches = md;
result.indels = id;
}
else{
result.matches = ml;
result.indels = il;
}
}
}
else{ /* iu==id && iu < il */
if( mu >= md ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = md;
result.indels = id;
}
}
}
else{
if( id < il ){
result.matches = md;
result.indels = id;
}
else if( id == il && md >= ml ){
result.matches = md;
result.indels = id;
}
else{
result.matches = ml;
result.indels = il;
}
}
return result;
}
VMD scalar_max( VMD up, VMD left, VMD diagonal, int match, int ws, int wd ){
VMD result;
/* auxiliar variables */
int iu, il, id;
int mu, ml, md;
int ru, rl, rd; /* temporary results */
iu = up.indels + 1;
il = left.indels + 1;
id = diagonal.indels;
mu = up.matches;
ml = left.matches;
md = diagonal.matches + match;
ru = ws * mu - wd * iu;
rl = ws * ml - wd * il;
rd = ws * md - wd * id;
if( ru >= rl ){
if( ru >= rd ){
result.matches = mu;
result.indels = iu;
}
else{
result.matches = md;
result.indels = id;
}
}
else{
if( rl >= rd ){
result.matches = ml;
result.indels = il;
}
else{
result.matches = md;
result.indels = id;
}
}
return result;
}
void prune( Pareto_set *set, int i, int j ){
/**
* If the current score vector plus the corresponding upper bound
* score vector is dominated by any of the lower bound scores, than
* it is pruned.
*/
int k;
/* auxiliar variables 'm', 'd' */
int m = set->scores[ set->num-1 ].matches + U[i][j].matches;
int d = set->scores[ set->num-1 ].indels + U[i][j].indels;
k = 0;
while( k < BOUNDS_NUM && LB[k].matches < m ) k++; /* advance in bound scores */
if( k < BOUNDS_NUM ){
if( m == LB[k].matches ){
if( d > LB[k].indels ){
set->num--;
}
}
else{
if( d >= LB[k].indels ){
set->num--;
}
}
}
else{ /* advanced all bounds (this should never happen) */
set->num--;
}
}
int min2(int n1, int n2){
return n1 <= n2 ? n1 : n2;
}
int max2(int n1, int n2){
return n1 >= n2 ? n1 : n2;
}
void remove_bounds_tables(){
int i;
free(LB);
for( i = 0; i < M+1; ++i ){
free( U[i] );
}
free(U);
}<file_sep># MOSAL
Multiobjective sequence alignment
MOSAL is a program for computing the Pareto optimal alignments for the bicriteria pairwise sequence alignment. It allows the use of substitution matrices.
Support material for M.Abbasi, <NAME>, A.Liefooghe, <NAME> and P.Matias, Improvements on bicriteria pairwise sequence alignment: algorithms and applications, Bioinformatics, 29(8):996-1003, 2013. http://dx.doi.org/10.1093/bioinformatics/btt098
See http://mosal.dei.uc.pt for more information.
<file_sep>gap = Gaps
ind = Indels
mat = Matches
ss = Subs_score
tb = Traceback
ntb = No_traceback
dp = DP
dpp = DP_prune
all:
make -C $(gap)/$(mat)/$(ntb)/$(dp)
make -C $(gap)/$(mat)/$(ntb)/$(dpp)
make -C $(gap)/$(mat)/$(tb)/$(dp)
make -C $(gap)/$(mat)/$(tb)/$(dpp)
make -C $(gap)/$(ss)/$(ntb)/$(dp)
make -C $(gap)/$(ss)/$(ntb)/$(dpp)
make -C $(gap)/$(ss)/$(tb)/$(dp)
make -C $(gap)/$(ss)/$(tb)/$(dpp)
make -C $(ind)/$(mat)/$(ntb)/$(dp)
make -C $(ind)/$(mat)/$(ntb)/$(dpp)
make -C $(ind)/$(mat)/$(tb)/$(dp)
make -C $(ind)/$(mat)/$(tb)/$(dpp)
make -C $(ind)/$(ss)/$(ntb)/$(dp)
make -C $(ind)/$(ss)/$(ntb)/$(dpp)
make -C $(ind)/$(ss)/$(tb)/$(dp)
make -C $(ind)/$(ss)/$(tb)/$(dpp)
gcc main.c -Wall -o mosal
clean:
rm -f $(gap)/$(mat)/$(ntb)/$(dp)/*.o $(gap)/$(mat)/$(ntb)/$(dp)/prog
rm -f $(gap)/$(mat)/$(ntb)/$(dpp)/*.o $(gap)/$(mat)/$(ntb)/$(dpp)/prog
rm -f $(gap)/$(mat)/$(tb)/$(dp)/*.o $(gap)/$(mat)/$(tb)/$(dp)/prog
rm -f $(gap)/$(mat)/$(tb)/$(dpp)/*.o $(gap)/$(mat)/$(tb)/$(dpp)/prog
rm -f $(gap)/$(ss)/$(ntb)/$(dp)/*.o $(gap)/$(ss)/$(ntb)/$(dp)/prog
rm -f $(gap)/$(ss)/$(ntb)/$(dpp)/*.o $(gap)/$(ss)/$(ntb)/$(dpp)/prog
rm -f $(gap)/$(ss)/$(tb)/$(dp)/*.o $(gap)/$(ss)/$(tb)/$(dp)/prog
rm -f $(gap)/$(ss)/$(tb)/$(dpp)/*.o $(gap)/$(ss)/$(tb)/$(dpp)/prog
rm -f $(ind)/$(mat)/$(ntb)/$(dp)/*.o $(ind)/$(mat)/$(ntb)/$(dp)/prog
rm -f $(ind)/$(mat)/$(ntb)/$(dpp)/*.o $(ind)/$(mat)/$(ntb)/$(dpp)/prog
rm -f $(ind)/$(mat)/$(tb)/$(dp)/*.o $(ind)/$(mat)/$(tb)/$(dp)/prog
rm -f $(ind)/$(mat)/$(tb)/$(dpp)/*.o $(ind)/$(mat)/$(tb)/$(dpp)/prog
rm -f $(ind)/$(ss)/$(ntb)/$(dp)/*.o $(ind)/$(ss)/$(ntb)/$(dp)/prog
rm -f $(ind)/$(ss)/$(ntb)/$(dpp)/*.o $(ind)/$(ss)/$(ntb)/$(dpp)/prog
rm -f $(ind)/$(ss)/$(tb)/$(dp)/*.o $(ind)/$(ss)/$(tb)/$(dp)/prog
rm -f $(ind)/$(ss)/$(tb)/$(dpp)/*.o $(ind)/$(ss)/$(tb)/$(dpp)/prog
rm -f mosal
<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Indels problem.
It is a Dynamic Programming (DP) with pruning approach, by filling a DP
matrix - P (with dimensions (M+1)*(N+1), where M and N are the sizes of the
1st and 2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Definition of the structures that compose
* each Dynamic Programming (DP) table cell and the
* functions that fill the table.
*/
#ifndef _PARETO_SET_H
#define _PARETO_SET_H
/* score vector */
typedef struct score_vector{
int matches;
int indels;
}VMD;
typedef struct n{
VMD score; /* score vector */
struct n* traceback_ptr; /* traceback pointer */
char traceback_dir; /* 'u'-up 'l'-left 'd'-diagonal */
struct n* next; /* pointer to next score */
}Node;
typedef Node * Pareto_set; /* linked list of nodes 'Node' */
/**
* Returns a new linked list to store pareto optimal alignments.
* The list has a header.
*/
Node * create_list( );
/**
* Appends a new score vector to the linked list pointed by 'ptr'
* m - #matches
* i - #indels
*/
void append_node(Node *ptr, int m, int i, Node *tb_ptr, char tb_dir);
/**
* Calculates the set of pareto optimal alignments already pruned
* between 'up', 'diagonal' and 'left' sets.
* Called in each DP algorithm iteration.
* 'match' - if the current sequence letters match (used by the diagonal set).
*
* Returns a linked list with the result of non dominated score vectors.
*/
Pareto_set pareto_merge( Pareto_set up, Pareto_set diagonal, Pareto_set left, int match, int i, int j );
/* frees the linked list pointed to by 'ptr' */
void remove_list( Node * ptr );
#endif<file_sep>CC = gcc -Wall -O3
OBJS = main.o pareto_set.o bounds.o
PROG = prog
# GENERIC
all: ${PROG}
clean:
rm ${OBJS} ${PROG}
${PROG}: ${OBJS}
${CC} ${OBJS} -o $@
.c.o:
${CC} $< -c -o $@
#############################
pareto_set.o: pareto_set.c pareto_set.h
bounds.o: bounds.c bounds.h
main.o: main.c pareto_set.h bounds.h
<file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Indels
problem without traceback (only final scores). It is a Dynamic Programming
(DP) with pruning approach, by filling a DP matrix - P
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Definition of the structures that compose
* each Dynamic Programming (DP) table cell and the
* functions that fill the table.
*/
#ifndef _PARETO_SET_H
#define _PARETO_SET_H
/* score vector */
typedef struct score_vector{
int matches;
int indels;
}VMD;
/* Set of pareto optimal alignment scores.
Corresponds to a DP table cell.
*/
typedef struct set{
VMD * scores;
int num; /* number of scores */
}Pareto_set;
extern int MAX_STATES;
/**
* Stores a new score to the array of scores in set->scores.
* m - #matches
* i - #indels
*/
void append_node(Pareto_set *set, int m, int i );
/**
* Calculates the set of pareto optimal alignments alreadt pruned
* between 'up', 'diagonal' and 'left' sets.
* Called in each DP algorithm iteration.
* 'subs_score' - the value of the subs score corresponding the current letters at position (i,j) (used by the diagonal set).
*
* Stores the result in the set pointed by 'ptr_res'
*/
void pareto_merge( Pareto_set *ptr_res, Pareto_set up, Pareto_set diagonal, Pareto_set left, int subs_score, int i, int j );
#endif<file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Indels
problem without traceback (only final scores). It is a Dynamic Programming
(DP) with pruning approach, by filling a DP matrix - P
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Declaration of variables and function prototypes
* related with the establishment and initialization
* of all bounds: lower (MIN, MID's and MAX) and upper bounds.
* MIN is the score vector with minimum #indels and minimum #substitution score
* MAX is the score vector with maximum #indels and maximum #substitution score
* MID's are all the score vectors between.
* It also includes the function responsible for pruning.
*/
#ifndef _BOUNDS_H
#define _BOUNDS_H
#include "pareto_set.h"
/* length of the alphabet to the substitution score table
(includes all the letters from '*' to 'Z' to get constant time access)
*/
#define LEN_ALPHABET ('Z'-'*'+1)
VMD *LB; /* MIN, MIDs, MAX together (ordered by #substitution score) */
VMD *MIN, *MAX; /* MIN and MAX are calculated in a different way */
VMD ** L; /* Dynamic Programming (DP) table for the lower bound states table (ss,d) */
VMD ** U; /* DP table for the upper bound states table (ss,d) */
VMD ** M_; /* MID bound states DP tables */
int MAX_MID_BOUNDS_NUM; /* number of mid bounds */
int BOUNDS_NUM; /* total number of bounds */
extern int M, N;
extern char seq1[];
extern char seq2[];
extern int S[][LEN_ALPHABET];
extern int MAX_STATES;
/* bounds initialization and determination (calls all init_*_bound() and calculate_*_bound() functions )*/
void init_bounds( int mid_bounds );
void init_lower_bound( ); /* initialization of the lower bound structures (memory allocations and base cases specification) */
void calculate_lower_bound( ); /* computation of all lower bounds (MIN, MAX and MID's) by filling 'VMD ** L' */
void init_upper_bound( ); /* initialization of the upper bound structures (memory allocations and base cases specification) */
void calculate_upper_bound( ); /* computation of all upper bounds by filling 'VMD ** U' */
/**
* Returns the lexicographically larger vector between the score
* vectors of cells 'up', 'left' and 'diagonal' of the current cell
* in the DP table 'VMD ** L'.
* 'score'- the value of the subs score corresponding the current letters at position (i,j) (used by the diagonal score vector).
* This is used to determine MAX - 'matches' are priority
*/
VMD lexmaxM( VMD up, VMD left, VMD diagonal, int score );
void calc_MAX(); /* calculates MAX, based on lexmaxM() */
/**
* Returns the lexicographically smaller vector between the score
* vectors of cells 'up', 'left' and 'diagonal' of the current cell
* in the DP table 'VMD ** L'.
* 'score'- the value of the subs score corresponding the current letters at position (i,j) (used by the diagonal score vector).
* This is used to determine MIN - 'indels' are priority
*/
VMD lexminD( VMD up, VMD left, VMD diagonal, int score );
void calc_MIN(); /* calculates MIN, based on lexminD() */
/**
* Returns the score vector that maximizes the scalarized score function
* (another version of the bicriteria alignment problem).
* 'score'- the value of the subs score corresponding the current letters at position (i,j) (used by the diagonal score vector).
* 'ws' and 'wd' are the weighting coefficients.
*/
VMD scalar_max( VMD up, VMD left, VMD diagonal, int score, int ws, int wd );
void calc_MID(); /* calculates all MID bounds for each MID bound DP table */
/**
* Determines if the last score vector of the
* pareto set 'set' can be pruned and, if so,
* removes it from the set.
* Based on the lower and upper bounds previously calculated.
*/
void prune( Pareto_set *set, int i, int j );
void remove_bounds_tables(); /* frees tables still in memory and used during the algorithm */
int min2(int n1, int n2); /* returns the minimum of two numbers */
int max3(int n1, int n2, int n3); /* returns the maximum of three numbers */
int get_score( int i, int j );
#endif<file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Indels
problem without traceback (only final scores). It is a Dynamic Programming
(DP) without pruning approach, by filling a DP matrix - P
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Implementation of the functions in 'pareto_set.h'.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "pareto_set.h"
void append_node(Pareto_set *set, int m, int i ){
if( set->num < MAX_STATES ){
set->scores[ set->num ].matches = m;
set->scores[ set->num ].indels = i;
set->num++;
}
else{
printf("Error on inserting node! Exceeded MAX_STATES=%d\n", MAX_STATES);
exit(-1);
}
}
void pareto_merge( Pareto_set *ptr_res, Pareto_set up, Pareto_set diagonal, Pareto_set left, int subs_score ){
/**
* Scores are assumed to be ordered incrementally by their #indels.
* Until all the iterators reach the end, it is selected the state with
* minimum #indels and, in case of equality, with maximum substitution score, from
* the three states: up-(mu,iu), diagonal-(md,id) and left-(ml,il).
* This state is appended to the result as it is always non dominated.
* The substitution score of that state (to be stored in SS_MAX) is also used to
* eliminate the (dominated) states following in each set, by advancing
* the iterators until the substitution score of the pointed state is greater than SS_MAX.
* The dominance of these states is also assured because the sets are ordered by #indels
* and they all have greater #indels compared to the selected state.
*/
/* defines substitution score of the state to be inserted */
int SS_MAX;
/* auxiliar variables for comparisons */
int iu, id, il;
int mu, md, ml;
int it_up, it_diagonal, it_left; /* iterators to each set ot pareto optimal alignments */
it_up = it_diagonal = it_left = 0;
while( (it_up < up.num) || (it_diagonal < diagonal.num) || (it_left < left.num) ){
/* Initialization of the auxiliar variables for the up, diagonal and left directions
In case iterators reach the end of its set (first comparison),
its values are not inserted, keeping the algorithm structure */
/* UP */
if ( it_up < up.num ){
iu = up.scores[ it_up ].indels + 1;
mu = up.scores[ it_up ].matches;
}
else{
iu = INT_MAX;
mu = INT_MIN;
}
/* DIAGONAL */
if( it_diagonal < diagonal.num ){
id = diagonal.scores[ it_diagonal ].indels;
md = diagonal.scores[ it_diagonal ].matches + subs_score;
}
else{
id = INT_MAX;
md = INT_MIN;
}
/* LEFT */
if( it_left < left.num ){
il = left.scores[ it_left ].indels + 1;
ml = left.scores[ it_left ].matches;
}
else{
il = INT_MAX;
ml = INT_MIN;
}
/* End of auxiliar variables initialization */
/* Select score with minimum #indels and, in case of equality,
with maximum substitution score */
if( iu < id ){
if( iu < il ){
SS_MAX = mu;
append_node( ptr_res, mu, iu );
}
else if( iu == il && mu >= ml ){
SS_MAX = mu;
append_node( ptr_res, mu, iu );
}
else{
SS_MAX = ml;
append_node( ptr_res, ml, il );
}
}
else if( iu == id ){
if( il < iu ){
SS_MAX = ml;
append_node( ptr_res, ml, il );
}
else if( iu == il ){
if( mu >= md ){
if( mu >= ml ){
SS_MAX = mu;
append_node( ptr_res, mu, iu );
}
else{
SS_MAX = ml;
append_node( ptr_res, ml, il );
}
}
else{
if( md >= ml ){
SS_MAX = md;
append_node( ptr_res, md, id );
}
else{
SS_MAX = ml;
append_node( ptr_res, ml, il );
}
}
}
else{ /* iu==id && iu < il */
if( mu >= md ){
SS_MAX = mu;
append_node( ptr_res, mu, iu );
}
else{
SS_MAX = md;
append_node( ptr_res, md, id );
}
}
}
else{
if( id < il ){
SS_MAX = md;
append_node( ptr_res, md, id );
}
else if( id == il && md >= ml ){
SS_MAX = md;
append_node( ptr_res, md, id );
}
else{
SS_MAX = ml;
append_node( ptr_res, ml, il );
}
}
/* End of minimum #indels score selection */
/* Exclude dominated scores, advancing iterators, based on the value SS_MAX */
while( it_up < up.num && up.scores[ it_up ].matches <= SS_MAX ) it_up++;
while( it_left < left.num && left.scores[ it_left ].matches <= SS_MAX ) it_left++;
while( it_diagonal < diagonal.num && diagonal.scores[ it_diagonal ].matches + subs_score <= SS_MAX ) it_diagonal++;
}
}
<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Gaps problem
without traceback (only final scores). It is a Dynamic Programming
(DP) with pruning approach, by keeping three DP matrices: Q, S and T
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Definition of the structures that compose
* each Dynamic Programming (DP) table cell and the
* functions that fill the DP tables.
*/
#ifndef _PARETO_SET_H
#define _PARETO_SET_H
#define IND_PENALTY (0) /* value for each additional indel */
/* score vector */
typedef struct score_vector{
int matches;
int gaps;
}VMG;
/* Set of pareto optimal alignment scores.
Corresponds to a DP table cell.
*/
typedef struct set{
VMG * scores;
int num; /* number of scores */
}Pareto_set;
extern int MAX_STATES;
/**
* Stores a new score to the array of scores in set->scores.
* m - #matches
* g - #gaps
*/
void append_node(Pareto_set *set, int m, int g );
/**
* Calculates the set of pareto optimal alignments
* between 'S' and 'Q' or 'T' and 'Q' sets.
* Called in each DP algorithm iteration.
* Also, it passes the position on the DP table and also the traceback
* direction (S or T) in order to prune or not the result to be inserted.
*
* Stores the result in the set pointed by 'ptr_res'.
*
*/
void pareto_merge2( Pareto_set *ptr_res, Pareto_set p1, Pareto_set p2 , int i, int j, char dir);
/**
* Calculates the set of pareto optimal alignments
* between 'Q', 'S' and 'T' sets.
* Called in each DP algorithm iteration.
* 'match' - if the current sequence letters match (used by the 'Q' set).
* Also, it passes the position in order to prune or not the result
* to be inserted.
*
* Stores the result in the set pointed by 'ptr_res'
*/
void pareto_merge3( Pareto_set *ptr_res, Pareto_set S, Pareto_set T, Pareto_set Q, int match, int i, int j );
#endif<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Indels problem.
It is a Dynamic Programming (DP) without pruning approach, by filling a DP
matrix - P (with dimensions (M+1)*(N+1), where M and N are the sizes of the
1st and 2nd sequence respectively).
Each entry P[i,j] will store the set of states corresponding to Pareto
optimal alignments of subsequences (a_1,...,a_i) and (b_1,...,b_j).
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include "pareto_set.h"
#define MAX_LENGTH (4000) /* maximum length of the sequences */
void read_sequence(char seq[] , char *filename);
void init_dynamic_table( );
void align( );
void traceback( );
void reverse(char s[]);
void remove_dynamic_table();
/* read sequences */
char seq1[MAX_LENGTH];
char seq2[MAX_LENGTH];
/* DP table */
Pareto_set ** P;
/* sizes of the DP table (M-#lines, N-#colunms) */
int M, N;
int main( int argc, char *argv[] ) {
srand( time(NULL) ); /* random seed to choose one score between equal score vectores */
if(argc != 3){
printf("Usage: %s <seq1_file> <seq2_file>\n", argv[0]);
return 0;
}
read_sequence(seq1, argv[1]);
read_sequence(seq2, argv[2]);
M = strlen(seq1); N = strlen(seq2);
init_dynamic_table( );
align( );
traceback( );
remove_dynamic_table();
return 0;
}
void read_sequence(char seq[], char *filename){
/**
* Reads the sequence contained in 'filename'.
* This file must follow the FASTA format.
*/
char fasta_header[300];
char line[300];
FILE *f = fopen(filename, "r");
if(f){
if( fscanf(f, ">%[^\n]\n", fasta_header)>0 ){ /* determine if file is valid */
while( fscanf(f, "%s", line)!=EOF )
strcat(seq, line);
}
else{
printf("Sequence file format is not correct!\n");
exit(-1);
}
fclose(f);
}
else{
fprintf(stderr, "Failed to open sequence file: %s\n", strerror(errno));
exit(-1);
}
}
void init_dynamic_table( ){
/**
* Allocates memory for the all the DP tables and
* initialize the its base cases.
*/
int i;
P = (Pareto_set **) malloc( (M+1) * sizeof(Pareto_set *) );
for(i=0; i<M+1 ; i++)
P[i] = (Pareto_set *) malloc( (N+1) * sizeof(Pareto_set) );
P[0][0] = create_list( );
append_node( P[0][0], 0, 0, NULL, '\0' );
/* base cases */
for( i = 1; i <= M ; i++ ){
P[i][0] = create_list();
append_node( P[i][0], 0, i, P[i-1][0]->next, 'u' ); /* pointing upwards */
}
for( i = 1; i <= N ; i++ ){
P[0][i] = create_list( );
append_node(P[0][i], 0, i, P[0][i-1]->next, 'l' ); /* pointing leftwards */
}
}
void align( ){
/**
* Filling of the DP table.
*/
int i, j, match;
for( i = 1; i <= M; ++i ){
for( j = 1; j <= N; ++j ){
match = seq1[i-1] == seq2[j-1];
P[i][j] = pareto_merge( P[i-1][j], P[i-1][j-1], P[i][j-1], match );
}
}
}
void traceback( ){
/**
* Traceback (based on the direction and pointer
* stored in each Node struct).
* Outputs the two aligned sequences to each solution.
*/
int i, j;
/* length of the each solution to each sequence */
int len1, len2;
int matches, indels; /* auxiliar variables */
Node * solution, *tb_ptr;
char res1[MAX_LENGTH*2], res2[MAX_LENGTH*2];
solution = P[M][N]->next;
while( solution ){
tb_ptr = solution;
len1 = len2 = 0;
i = M; j = N; /* start at the bottom right corner of the DP table */
matches = solution->score.matches;
indels = solution->score.indels;
while( i!=0 || j!=0 ){ /* while the upper left corner of the DP table isn't reached */
switch( tb_ptr->traceback_dir ){
case 'u': /* going up */
i--;
res2[len2++] = '-';
res1[len1++] = seq1[i];
break;
case 'l': /* going left */
j--;
res1[len1++] = '-';
res2[len2++] = seq2[j];
break;
case 'd': /* going up and left */
i--; j--;
res1[len1++] = seq1[i];
res2[len2++] = seq2[j];
break;
}
tb_ptr = tb_ptr->traceback_ptr;
}
res1[len1] = '\0';
res2[len2] = '\0';
/* sequences must be reversed */
reverse(res1);
reverse(res2);
printf("matches=%d indels=%d\n%s\n%s\n\n", matches, indels, res1, res2);
solution = solution -> next; /* next solution */
}
}
void reverse(char s[]){
int i, len;
char tmp;
len = strlen(s);
for(i=0; i<len/2; i++){
tmp = s[i];
s[i] = s[len-i-1];
s[len-i-1] = tmp;
}
}
void remove_dynamic_table(){
/**
* Free DP table.
*/
int i, j;
for( i = 0; i < M+1; ++i )
for( j = 0; j < N+1; ++j )
remove_list( P[i][j] );
for( i = 0; i < M+1; ++i ){
free(P[i]);
}
free(P);
}<file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Gaps problem
without traceback (only final scores). It is a Dynamic Programming
(DP) without pruning approach, by keeping three DP matrices: Q, S and T
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Implementation of the functions in 'pareto_set.h'.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "pareto_set.h"
void append_node(Pareto_set *set, int m, int g ){
if( set->num < MAX_STATES ){
set->scores[ set->num ].matches = m;
set->scores[ set->num ].gaps = g;
set->num++;
}
else{
printf("Error on inserting node! Exceeded MAX_STATES=%d\n", MAX_STATES);
exit(-1);
}
}
void pareto_merge2( Pareto_set *ptr_res, Pareto_set p1, Pareto_set p2 ){
/**
* Scores are assumed to be ordered incrementally by their #gaps.
* Until all the iterators reach the end, it is selected the state with
* minimum #gaps score and, in case of equality, with maximum substitution score, from
* the two scores: p1-(ss_p1,gap_p1), p2-(ss_p2,gap_p2).
* This state is appended to the result as it is always non dominated.
* The substitution score of that state (to be stored in SS_MAX) is also used to
* eliminate the (dominated) states following in each set, by advancing
* the iterators until the substitution score of the pointed state is greater than SS_MAX.
* The dominance of these states is also assured because the sets are ordered by #gaps
* and they all have greater #gaps compared to the selected state.
*/
/* defines the substitution score of the state to be inserted */
int SS_MAX;
/* auxiliar variables for comparisons */
int gap_p1, gap_p2;
int ss_p1, ss_p2;
int it_p1, it_p2; /* iterators to each set ot pareto optimal alignments */
it_p1 = it_p2 = 0;
while( (it_p1 < p1.num) || (it_p2 < p2.num) ){
/* Initialization of the auxiliar variables for the p1 and p2 cells.
In case iterators reach the end of its set (first comparison),
its values are not inserted, keeping the algorithm structure */
/* P1 */
if( it_p1 < p1.num ){
gap_p1 = p1.scores[ it_p1 ].gaps + IND_PENALTY; /* additional indel penalty */
ss_p1 = p1.scores[ it_p1 ].matches;
}
else{
gap_p1 = INT_MAX;
ss_p1 = INT_MIN;
}
/* P2 */
if( it_p2 < p2.num ){
gap_p2 = p2.scores[ it_p2 ].gaps + 1; /* open a new gap */
ss_p2 = p2.scores[ it_p2 ].matches;
}
else{
gap_p2 = INT_MAX;
ss_p2 = INT_MIN;
}
/* End of auxiliar variables initialization */
/* Select score with minimum #gaps and, in case of equality,
with maximum substitution score */
if( gap_p1 < gap_p2 || (gap_p1==gap_p2 && ss_p1 >= ss_p2) ){
SS_MAX = ss_p1;
append_node( ptr_res, ss_p1, gap_p1);
}
else{
SS_MAX = ss_p2;
append_node( ptr_res, ss_p2, gap_p2);
}
/* End of minimum #gaps score selection */
/* Exclude dominated scores, advancing iterators, based on the value SS_MAX */
while( it_p1 < p1.num && p1.scores[ it_p1 ].matches <= SS_MAX ) it_p1++;
while( it_p2 < p2.num && p2.scores[ it_p2 ].matches <= SS_MAX ) it_p2++;
}
}
void pareto_merge3( Pareto_set *ptr_res, Pareto_set S, Pareto_set T, Pareto_set Q, int subs_score){
/**
* Scores are assumed to be ordered incrementally by their #gaps.
* Until all the iterators reach the end, it is selected the state with
* minimum #gaps and, in case of equality, with maximum substitution score, from
* the three stats: S-(sss,gs), Q-(ssq,gq) and T-(sst,gt).
* This state is appended to the result as it is always non dominated.
* The substitution score of that state (to be stored in SS_MAX) is also used to
* eliminate the (dominated) states following in each set, by advancing
* the iterators until the substitution score of the pointed state is greater than SS_MAX.
* The dominance of these states is also assured because the sets are ordered by #gaps
* and they all have greater #gaps compared to the selected state.
*/
/* defines the substitution score of the state to be inserted */
int SS_MAX;
/* auxiliar variables for comparisons */
int gt, gq, gs;
int sst, ssq, sss;
int it_s, it_t, it_q;
it_s = it_t = it_q = 0;
while( (it_t < T.num) || (it_q < Q.num) || (it_s < S.num) ){
/* Initialization of the auxiliar variables for the Q, S and T cells.
In case iterators reach the end of its set (first comparison),
its values are not inserted, keeping the algorithm structure */
/* Q */
if( it_q < Q.num ){
gq = Q.scores[ it_q ].gaps;
ssq = Q.scores[ it_q ].matches + subs_score;
}
else{
gq = INT_MAX;
ssq = INT_MIN;
}
/* S */
if( it_s < S.num){
gs = S.scores[ it_s ].gaps;
sss = S.scores[ it_s ].matches;
}
else{
gs = INT_MAX;
sss = INT_MIN;
}
/* T */
if( it_t < T.num ){
gt = T.scores[ it_t ].gaps;
sst = T.scores[ it_t ].matches;
}
else{
gt = INT_MAX;
sst = INT_MIN;
}
/* End of auxiliar variables initialization */
/* Select score with minimum #gaps and, in case of equality,
with maximum substitution score */
if( gt < gq ){
if( gt < gs ){
SS_MAX = sst;
append_node( ptr_res, sst, gt );
}
else if( gt == gs && sst >= sss ){
SS_MAX = sst;
append_node( ptr_res, sst, gt );
}
else{
SS_MAX = sss;
append_node( ptr_res, sss, gs );
}
}
else if( gt == gq ){
if( gs < gt ){
SS_MAX = sss;
append_node( ptr_res, sss, gs );
}
else if( gt == gs ){
if( sst >= ssq ){
if( sst >= sss ){
SS_MAX = sst;
append_node( ptr_res, sst, gt );
}
else{
SS_MAX = sss;
append_node( ptr_res, sss, gs );
}
}
else{
if( ssq >= sss ){
SS_MAX = ssq;
append_node( ptr_res, ssq, gq );
}
else{
SS_MAX = sss;
append_node( ptr_res, sss, gs );
}
}
}
else{ /* gt==gq && gt < gs */
if( sst >= ssq ){
SS_MAX = sst;
append_node( ptr_res, sst, gt );
}
else{
SS_MAX = ssq;
append_node( ptr_res, ssq, gq );
}
}
}
else{
if( gq < gs ){
SS_MAX = ssq;
append_node( ptr_res, ssq, gq );
}
else if( gq == gs && ssq >= sss ){
SS_MAX = ssq;
append_node( ptr_res, ssq, gq );
}
else{
SS_MAX = sss;
append_node( ptr_res, sss, gs );
}
}
/* End of minimum #gaps score selection */
/* Exclude dominated scores, advancing iterators, based on the value SS_MAX */
while( it_s < S.num && S.scores[ it_s ].matches <= SS_MAX ) it_s++;
while( it_t < T.num && T.scores[ it_t ].matches <= SS_MAX ) it_t++;
while( it_q < Q.num && Q.scores[ it_q ].matches + subs_score <= SS_MAX ) it_q++;
}
}
<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Gaps problem.
It is a Dynamic Programming (DP) with pruning approach, by keeping three
DP matrices: Q, S and T (with dimensions (M+1)*(N+1), where M and N are the
sizes of the 1st and 2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Definition of the structures that compose
* each Dynamic Programming (DP) table cell and the
* functions that fill the DP tables.
*/
#ifndef _PARETO_SET_H
#define _PARETO_SET_H
#define IND_PENALTY (0) /* value for each additional indel */
/* score vector */
typedef struct score_vector{
int matches;
int gaps;
}VMG;
/* Set of pareto optimal alignment scores.
Corresponds to a DP table cell.
*/
typedef struct n{
VMG score; /* score vector */
struct n* traceback_ptr; /* traceback pointer */
char traceback_dir; /* 'T'-up 'S'-left 'Q'-diagonal */
struct n* next; /* pointer to next score */
}Node;
typedef Node * Pareto_set; /* linked list of nodes 'Node' */
/**
* Returns a new linked list to store pareto optimal alignments.
* The list has a header.
*/
Pareto_set create_list( );
/**
* Appends a new score vector to the linked list pointed by 'ptr'
* m - #matches
* g - #gaps
*/
void append_node(Node *ptr, int m, int g, Node *tb_ptr, char tb_dir);
/**
* Calculates the set of pareto optimal alignments
* between 'S' and 'Q' or 'T' and 'Q' sets.
* Called in each DP algorithm iteration.
* Also, it passes the position on the DP table and also the traceback
* direction (S or T) in order to prune or not the result to be inserted.
*
* Returns a linked list with the result of non dominated score vectors.
*/
Pareto_set pareto_merge2( Pareto_set p1, Pareto_set p2, char tb_dir );
/**
* Calculates the set of pareto optimal alignments
* between 'S', 'T' and 'Q' sets.
* Called in each DP algorithm iteration.
* 'match' - if the current sequence letters match (used by the 'Q' set).
* Also, it passes the position in order to prune or not the result
* to be inserted.
*
* Returns a linked list with the result of non dominated score vectors.
*/
Pareto_set pareto_merge3( Pareto_set S, Pareto_set T, Pareto_set Q, int match, int i, int j );
/* frees the linked list pointed to by 'ptr' */
void remove_list( Node * ptr );
#endif<file_sep>/****************************************************************************
It computes the set of non dominated scores for the "Substitution score"-#Gaps
problem.
It is a Dynamic Programming (DP) with pruning approach, by keeping three
DP matrices: Q, S and T (with dimensions (M+1)*(N+1), where M and N are the
sizes of the 1st and 2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Implementation of the functions in 'pareto_set.h'.
*/
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "pareto_set.h"
#include "bounds.h"
Pareto_set create_list( ){
Node *ptr = (Node *)malloc(sizeof(Node));
if(ptr){
ptr->score.matches = 0;
ptr->score.gaps = 0;
ptr->traceback_ptr = NULL;
ptr->traceback_ptr = '\0';
ptr->next = NULL;
}
return ptr;
}
void append_node(Node *ptr, int m, int g, Node *tb_ptr, char tb_dir){
ptr->next = (Node *)malloc(sizeof(Node));
ptr->next->score.matches = m;
ptr->next->score.gaps = g;
ptr->next->traceback_ptr = tb_ptr;
ptr->next->traceback_dir = tb_dir;
ptr->next->next = NULL;
}
Pareto_set pareto_merge2( Pareto_set p1, Pareto_set p2, char tb_dir ){
/**
* Scores are assumed to be ordered incrementally by their #gaps.
* Until all the iterators reach the end, it is selected the state with
* minimum #gaps and, in case of equality, with maximum substitution score, from
* the two states: p1-(ss_p1,gap_p1), p2-(ss_p2,gap_p2).
* (If the score vectors are exactly the same, than one is chosen randomly.)
* This state is appended to the result as it is always non dominated.
* The substitution score of that state (to be stored in SS_MAX) is also used to
* eliminate the (dominated) states following in each set, by advancing
* the iterators until the substitution score of the pointed state is greater than SS_MAX.
* The dominance of these states is also assured because the sets are ordered by #gaps
* and they all have greater #gaps compared to the selected state.
*
* 'tb_dir' indicates the traceback direction as this function is used
* by both tables S and T.
*/
/* allocate memory for the result set */
Pareto_set res = create_list();
Node * ptr_res = res;
/* these linked lists have headers */
p1 = p1->next;
p2 = p2->next;
/* defines the substitution score of the state to be inserted */
int SS_MAX;
/* auxiliar variables for comparisons */
int gap_p1, gap_p2;
int ss_p1, ss_p2;
while( p1 || p2 ){
/* Initialization of the auxiliar variables for the p1 and p2 cells.
In case iterators reach the end of its set (first comparison),
its values are not inserted, keeping the algorithm structure */
/* P1 */
if(p1){
gap_p1 = p1->score.gaps + IND_PENALTY; /* add indel */
ss_p1 = p1->score.matches;
}
else{
gap_p1 = INT_MAX;
ss_p1 = INT_MIN;
}
/* P2 */
if(p2){
gap_p2 = p2->score.gaps + 1; /* open a new gap */
ss_p2 = p2->score.matches;
}
else{
gap_p2 = INT_MAX;
ss_p2 = INT_MIN;
}
/* End of auxiliar variables initialization */
/* Select score with minimum #gaps and, in case of equality,
with maximum substitution score */
if( gap_p1 < gap_p2 ){
SS_MAX = ss_p1;
append_node( ptr_res, ss_p1, gap_p1, p1, tb_dir);
}
else if ( gap_p1 == gap_p2 ){
if( ss_p1 > ss_p2 ){
SS_MAX = ss_p1;
append_node( ptr_res, ss_p1, gap_p1, p1, tb_dir);
}
else if( ss_p1 == ss_p2 && (rand()%2) ){
SS_MAX = ss_p1;
append_node( ptr_res, ss_p1, gap_p1, p1, tb_dir);
}
else{
SS_MAX = ss_p2;
append_node( ptr_res, ss_p2, gap_p2, p2, tb_dir);
}
}
else{
SS_MAX = ss_p2;
append_node( ptr_res, ss_p2, gap_p2, p2, tb_dir);
}
/* End of minimum #gaps score selection */
ptr_res = ptr_res->next;
/* Exclude dominated scores, advancing iterators, based on the value SS_MAX */
while( p1 && p1->score.matches <= SS_MAX ) p1 = p1->next;
while( p2 && p2->score.matches <= SS_MAX ) p2 = p2->next;
}
return res;
}
Pareto_set pareto_merge3(Pareto_set S, Pareto_set T, Pareto_set Q, int subs_score, int i, int j){
/**
* Scores are assumed to be ordered incrementally by their #gaps.
* Until all the iterators reach the end, it is selected the state with
* minimum #gaps and, in case of equality, with maximum substitution score, from
* the three states: S-(ms,gs), Q-(mq,gq) and T-(mt,gt).
* (If the score vectors are exactly the same, than one is chosen randomly.)
* This state is appended to the result as it is always non dominated.
* The substitution score of that state (to be stored in SS_MAX) is also used to
* eliminate the (dominated) states following in each set, by advancing
* the iterators until the substitution score of the pointed state is greater than SS_MAX.
* The dominance of these states is also assured because the sets are ordered by #gaps
* and they all have greater #gaps compared to the selected state.
*/
/* allocate memory for the result set */
Pareto_set res = create_list();
Node * ptr_res = res;
char dir; /* in order to improve the pruning */
/* defines the substitution score of the state to be inserted */
int SS_MAX;
/* auxiliar variables for comparisons */
int gt, gq, gs;
int mt, mq, ms;
/* these linked lists have headers */
T = T->next;
S = S->next;
Q = Q->next;
while( T || Q || S ){
/* Initialization of the auxiliar variables for the Q, S and T cells.
In case iterators reach the end of its set (first comparison),
its values are not inserted, keeping the algorithm structure */
/* Q */
if(Q){
gq = Q->score.gaps;
mq = Q->score.matches + subs_score;
}
else{
gq = INT_MAX;
mq = INT_MIN;
}
/* T */
if(T){
gt = T->score.gaps;
mt = T->score.matches;
}
else{
gt = INT_MAX;
mt = INT_MIN;
}
/* S */
if(S){
gs = S->score.gaps;
ms = S->score.matches;
}
else{
gs = INT_MAX;
ms = INT_MIN;
}
/* End of auxiliar variables initialization */
/* Select score with minimum #gaps and, in case of equality,
with maximum substitution score */
if( gt < gq ){
if( gt < gs ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else if( gt == gs ){
if( mt > ms ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else if( mt == ms && (rand()%2) ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else{
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
}
else{
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
}
else if( gt == gq ){
if( gs < gt ){
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
else if( gt == gs ){
if( mt > mq ){
if( mt > ms ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else if( mt == ms && (rand()%2) ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else{
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
}
else if( mt == mq ){
if( ms > mt ){
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
else if( mt == ms ){
int var = rand()%3;
if( var == 0){
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
else if (var == 1){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else{
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
}
else{
if( rand()%2 ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else{
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
}
}
else{ /* gt == gs == gq && mq > mt */
if( mq > ms ){
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
else if( mq == ms && (rand()%2) ){
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
else{
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
}
}
else{ /* gt==gq && gt < gs */
if( mt > mq ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else if( mt == mq && (rand()%2) ){
SS_MAX = mt;
append_node( ptr_res, mt, gt , T->traceback_ptr, 'u' );
dir= 'u';
}
else{
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
}
}
else{
if( gq < gs ){
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
else if( gq == gs ){
if( mq > ms ){
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
else if( mq == ms && (rand()%2) ){
SS_MAX = mq;
append_node( ptr_res, mq, gq , Q, 'd' );
dir= 'd';
}
else{
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
}
else{
SS_MAX = ms;
append_node( ptr_res, ms, gs , S->traceback_ptr, 'l' );
dir= 'l';
}
}
/* End of minimum #gaps score selection */
/* prune last score appended */
prune(ptr_res, i, j, dir);
if( ptr_res->next ) /* advance ptr only if it was not prunned */
ptr_res = ptr_res->next;
/* Exclude dominated scores, advancing iterators, based on the value SS_MAX */
while( T && T->score.matches <= SS_MAX ) T = T->next;
while( S && S->score.matches <= SS_MAX ) S = S->next;
while( Q && Q->score.matches + subs_score <= SS_MAX ) Q = Q->next;
}
return res;
}
void remove_list( Node * ptr ){
if(ptr){
Node * tmp;
while( ptr->next ){
tmp = ptr;
ptr = ptr->next;
free(tmp);
}
free(ptr);
}
}<file_sep>/****************************************************************************
It computes the set of non dominated scores for the #Matches-#Gaps problem
without traceback (only final scores). It is a Dynamic Programming
(DP) with pruning approach, by keeping three DP matrices: Q, S and T
(with dimensions (M+1)*(N+1), where M and N are the sizes of the 1st and
2nd sequence respectively).
Each entry S[i,j] and T[i,j] will store the set of states corresponding
to Pareto optimal alignments of subsequences ending with ('-',b_j) and
(a_i,'-'), respectively.
Each entry Q[i,j] will store the states corresponding to Pareto optimal
alignments of subsequences ending with (a_i,b_j) computed in S[i,j] and T[i,j].
---------------------------------------------------------------------
Copyright (c) 2013
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
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, you can obtain a copy of the GNU
General Public License at:
http://www.gnu.org/copyleft/gpl.html
or by writing to:
Free Software Foundation, Inc., 59 Temple Place,
Suite 330, Boston, MA 02111-1307 USA
****************************************************************************/
/**
* Implementation of the functions in 'bounds.h'.
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include "bounds.h"
void init_bounds( int mid_bounds ){
MAX_MID_BOUNDS_NUM = mid_bounds;
BOUNDS_NUM = mid_bounds + 2;
init_lower_bound( );
calculate_lower_bound( );
init_upper_bound( );
calculate_upper_bound( );
}
void init_lower_bound( ){
int i, j;
LB = (VMG *) malloc( BOUNDS_NUM * sizeof(VMG) );
/* L and TL malloc (MAX and MIN) */
L = (VMG **) malloc( (2)*sizeof(VMG *) ); /* just 2 lines (just left, upper and upper-left cells are needed) */
LT = (VMG **) malloc( (2)*sizeof(VMG *) );
for( i = 0; i < 2; ++i ){
L[i] = (VMG *) malloc( (N+1)*sizeof(VMG) );
LT[i] = (VMG *) malloc( (N+1)*sizeof(VMG) );
}
LS = (VMG *) malloc( (N+1)*sizeof(VMG) );
TL = (char **) malloc( (M+1)*sizeof(char *) );
for( i = 0; i < M+1; ++i ){
TL[i] = (char *) malloc( (N+1)*sizeof(char) );
}
/* base cases */
L[0][0].matches = 0;
L[0][0].gaps = 0;
L[1][0].matches = 0;
L[1][0].gaps = 1;
for( i = 0; i < M+1; ++i ){
TL[i][0] = 'u';
}
for( j = 1; j < N+1; ++j ){
L[0][j].matches = 0;
L[0][j].gaps = 1;
LT[0][j].matches = 0;
LT[0][j].gaps = INT_MAX;
TL[0][j] = 'l';
}
LS[0].matches = 0;
LS[0].gaps = INT_MAX;
/* M's mallocs (MID's) */
M_ = (VMG **) malloc( 2*sizeof(VMG *) );
MT = (VMG **) malloc( 2*sizeof(VMG *) );
for( i = 0; i < 2; ++i ){
M_[i] = (VMG *) malloc( (N+1)*sizeof(VMG) );
MT[i] = (VMG *) malloc( (N+1)*sizeof(VMG) );
}
MS = (VMG *) malloc( (N+1)*sizeof(VMG) );
MS[0].matches = 0;
MS[0].gaps = INT_MAX;
}
void calculate_lower_bound( ){
int i;
calc_MIN();
calc_MID();
calc_MAX();
/* remove tables (not needed anymore) */
for( i = 0; i < 2; ++i ){
free( L[i] );
free( LT[i] );
}
free(L);
free(LT);
free(LS);
for( i = 0; i < M+1; ++i ){
free( TL[i] );
}
free(TL);
for( i = 0; i < 2; ++i ){
free( M_[i] );
free( MT[i] );
}
free( M_ );
free( MS );
free( MT );
/* calculates the maximum number of scores vectors per cell
(used to allocate memory for the main DP table)
*/
MAX_STATES = min2( MAX->matches-MIN->matches, MAX->gaps-MIN->gaps ) + 1;
}
void calc_MAX(){
/* LexMGP */
int i, j, match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
for( i = 1; i < M+1; ++i ){
/* exchange lines */
prev = !( i % 2);
curr = (i % 2);
L[curr][0].matches = 0;
L[curr][0].gaps = 1;
/* first column of LS is a base case but was calculated before once in init_lower_bound() ) */
/* first column of LT is out of reach (does not need base case) */
for( j = 1; j < N+1; ++j ){
match = seq1[i-1] == seq2[j-1];
LS[j] = lexmaxMS( LS[j-1], L[curr][j-1], i, j );
LT[curr][j] = lexmaxMT( LT[prev][j], L[prev][j], i, j );
L[curr][j] = lexmaxM3( LS[j], LT[curr][j], L[prev][j-1], match, i, j );
}
}
LB[ BOUNDS_NUM-1 ] = L[curr][N];
if( LB[ BOUNDS_NUM-1 ].matches == LB[ BOUNDS_NUM-2 ].matches ) /* if MAX is equal to last MID point */
BOUNDS_NUM--;
MAX = &LB[ BOUNDS_NUM-1 ] ;
/* printf("MAX=(%d,%d)\n", MAX->matches, MAX->gaps ); */
}
void calc_MIN(){
/**
* Instead of filling DP tables, the MIN score vector can be determined
* in a easier way:
* - the minimum #gaps is either 0 (M=N) or 1 (M!=N, indels all together)
* - the corresponding #matches can then be easily determined based on
* all possibilities of the gap position in the smaller sequence
*/
VMG min;
int i, match, gap_size;
char * greater_seq, *smaller_seq;
match = 0;
min.gaps = M == N ? 0 : 1;
if( min.gaps == 0 ){
for( i = 0; i < N; ++i )
match += seq1[i] == seq2[i];
min.matches = match;
}
else{
gap_size = abs( M-N );
/* determine greater sequence */
if( M > N ) {
greater_seq = seq1;
smaller_seq = seq2;
}
else {
greater_seq = seq2;
smaller_seq = seq1;
}
/* gap is at the beginning */
for( i = gap_size; i < strlen(greater_seq); ++i )
match += greater_seq[i] == smaller_seq[i-gap_size];
min.matches = match;
/* iterate through all gap positions that are possible
by advancing the gap one letter in each iteration in the
smaller sequence */
for( i = 0; i < strlen(smaller_seq); ++i ){
match += greater_seq[i] == smaller_seq[i];
match -= greater_seq[i+gap_size] == smaller_seq[i];
/* update minimum #matches */
if( match > min.matches)
min.matches = match;
}
}
/* printf("MIN=(%d,%d)\n", min.matches, min.gaps); */
LB[0] = min;
MIN = &LB[0];
}
void calc_MID(){
int m, i, j, ws, wg, match;
int prev, curr; /* curr - current line in the matrix */
/* prev - previous line */
int last_mid_matches = MIN->matches; /* discard same MID points */
int mid_bounds_num = 0;
for( m = 0; m < MAX_MID_BOUNDS_NUM; ++m ){
/* base cases */
M_[0][0].matches = 0;
M_[0][0].gaps = 0;
M_[1][0].matches = 0;
M_[1][0].gaps = 1;
for( j = 1; j < N+1; ++j ){
M_[0][j].matches = 0;
M_[0][j].gaps = 1;
MT[0][j].matches = 0;
MT[0][j].gaps = INT_MAX;
}
for( i = 1; i < M+1; ++i ){
/* exchange lines for tables M_ and MT */
prev = !( i % 2);
curr = (i % 2);
/* base cases */
M_[curr][0].matches = 0;
M_[curr][0].gaps = 1;
/* first column of MS is a base case but was calculated before once in init_lower_bound() ) */
/* first column of MT is out of reach (does not need base case) */
for( j = 1; j < N+1; ++j ){
match = seq1[i-1] == seq2[j-1];
ws = m + 1;
wg = MAX_MID_BOUNDS_NUM - m;
MS[j] = scalar_max2( MS[j-1], M_[curr][j-1], ws, wg );
MT[curr][j] = scalar_max2( MT[prev][j], M_[prev][j], ws, wg );
M_[curr][j] = scalar_max3( MS[j], MT[curr][j], M_[prev][j-1], match, ws, wg );
}
}
if( last_mid_matches != M_[curr][N].matches ){ /* if MID does not exist yet */
LB[1 + mid_bounds_num++] = M_[curr][N];
}
last_mid_matches = M_[curr][N].matches;
/* printf("MID=(%d,%d)\n", M_[curr][N].matches, M_[curr][N].gaps ); */
}
/* update value */
BOUNDS_NUM = 2 + mid_bounds_num;
}
void init_upper_bound( ){
int i;
U = (int **) malloc( (M+1)*sizeof(int *) );
for( i = 0; i <= M; ++i )
U[i] = (int *) malloc( (N+1)*sizeof(int) );
}
void calculate_upper_bound( ){
/**
* Based on the classical DP algorithm for computing the LCS
* in the reversed sequences.
*/
int i, j ;
/* base cases */
U[M][N] = 0;
for( i = 0; i < M; ++i )
U[i][N] = 0;
for( j = 0; j < N; ++j )
U[M][j] = 0;
for( i = M-1; i >= 0; --i ) /* begins in the oposite corner of the table (reversed sequences) */
for( j = N-1; j >= 0; --j )
if( seq1[i] == seq2[j] )
U[i][j] = U[i+1][j+1] + 1;
else
U[i][j] = max2(U[i+1][j] , U[i][j+1]);
}
VMG lexmaxMS( VMG p1, VMG p2, int i, int j ){
/* match priority */
VMG result;
/* auxiliar variables */
int m1, m2, g1, g2;
m1 = p1.matches;
m2 = p2.matches;
g1 = p1.gaps + IND_PENALTY; /* add additional indel */
g2 = p2.gaps + (TL[i][j-1] != 'l') ; /* adds gaps only if it doesn't already exist */
if( m1 > m2 || (m1==m2 && g1 <= g2) ){
result.matches = m1;
result.gaps = g1;
}
else{
result.matches = m2;
result.gaps = g2;
}
return result;
}
VMG lexmaxMT( VMG p1, VMG p2, int i, int j ){
/* match priority */
VMG result;
/* auxiliar variables */
int m1, m2, g1, g2;
m1 = p1.matches;
m2 = p2.matches;
g1 = p1.gaps + IND_PENALTY; /* add additional indel */
g2 = p2.gaps + (TL[i-1][j] != 'u'); /* adds gaps only if it doesn't already exist */
if( m1 > m2 || (m1==m2 && g1 <= g2) ){
result.matches = m1;
result.gaps = g1;
}
else{
result.matches = m2;
result.gaps = g2;
}
return result;
}
VMG lexmaxM3( VMG S, VMG T, VMG Q, int match, int i, int j){
/* match priority */
VMG result;
int mt, ms, mq, gt, gs, gq;
mt = T.matches;
ms = S.matches;
mq = Q.matches + match;
gt = T.gaps;
gs = S.gaps;
gq = Q.gaps;
if( mt > ms ){
if( mt > mq ){
result.matches = mt;
result.gaps = gt;
TL[i][j] = 'u';
}
else if( mt == mq ){
if( gt <= gq ){
result.matches = mt;
result.gaps = gt;
TL[i][j] = 'u';
}
else{
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
else{
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
else if( mt == ms ){
if( mt > mq ){
if( gt <= gs ){
result.matches = mt;
result.gaps = gt;
TL[i][j] = 'u';
}
else{
result.matches = ms;
result.gaps = gs;
TL[i][j] = 'l';
}
}
else if( mt == mq ){
if( gt <= gs ){
if( gt <= gq ){
result.matches = mt;
result.gaps = gt;
TL[i][j] = 'u';
}
else{
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
else{
if( gs <= gq ){
result.matches = ms;
result.gaps = gs;
TL[i][j] = 'l';
}
else{
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
}
else{ /* mt < mq */
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
else{ /* mt < ms */
if( ms > mq ){
result.matches = ms;
result.gaps = gs;
TL[i][j] = 'l';
}
else if( ms == mq){
if( gs <= gq ){
result.matches = ms;
result.gaps = gs;
TL[i][j] = 'l';
}
else{
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
else{
result.matches = mq;
result.gaps = gq;
TL[i][j] = 'd';
}
}
return result;
}
VMG scalar_max2( VMG p1, VMG p2, int ws, int wg ){
VMG result;
/* auxiliar variables */
int g1, g2;
int m1, m2;
int r1, r2; /* temporary results */
g1 = p1.gaps + IND_PENALTY; /* add additional indel */
g2 = p2.gaps + 1; /* open new gap */
m1 = p1.matches;
m2 = p2.matches;
r1 = g1 == INT_MAX ? INT_MIN : ws * m1 - wg * g1;
r2 = ws * m2 - wg * g2;
if( r1 >= r2 ){
result.matches = m1;
result.gaps = g1;
}
else{
result.matches = m2;
result.gaps = g2;
}
return result;
}
VMG scalar_max3( VMG S, VMG T, VMG Q, int match, int ws, int wg ){
VMG result;
/* auxiliar variables */
int gs, gt, gq;
int ms, mt, mq;
int rs, rt, rq; /* temporary results */
gs = S.gaps;
gt = T.gaps;
gq = Q.gaps;
ms = S.matches;
mt = T.matches;
mq = Q.matches + match;
rs = ws * ms - wg * gs;
rt = ws * mt - wg * gt;
rq = ws * mq - wg * gq;
if( rs >= rt ){
if( rs >= rq ){
result.matches = ms;
result.gaps = gs;
}
else{
result.matches = mq;
result.gaps = gq;
}
}
else{
if( rt >= rq ){
result.matches = mt;
result.gaps = gt;
}
else{
result.matches = mq;
result.gaps = gq;
}
}
return result;
}
void prune( Pareto_set * set, int i, int j, char dir ){
/**
* If the current score vector plus the corresponding upper bound
* score vector is dominated by any of the lower bound scores, than
* it is pruned.
*/
int add_gap, m, g, h, l, k;
h = M-i;
l = N-j;
/* checks if a gap already exists */
if( h == l ) add_gap = 0;
else if( h > l ) add_gap = dir == 'u' ? 0 : 1;
else add_gap = dir == 'l' ? 0 : 1;
/* auxiliar variables 'm', 'g' */
m = set->scores[ set->num-1 ].matches + U[i][j];
g = set->scores[ set->num-1 ].gaps + add_gap;
k = 0;
while( k < BOUNDS_NUM && LB[k].matches < m ) k++; /* advance in bound scores */
if( k < BOUNDS_NUM ){
if( m == LB[k].matches ){
if( g > LB[k].gaps ){
set->num--;
}
}
else{
if( g >= LB[k].gaps ){
set->num--;
}
}
}
else{ /* advanced all bounds (this should never happen) */
set->num--;
}
}
int max2(int n1, int n2){
return n1 >= n2 ? n1 : n2;
}
int min2(int n1, int n2){
return n1 <= n2 ? n1 : n2;
}
void remove_bounds_tables(){
int i;
free(LB);
for( i = 0; i < M+1; ++i ){
free( U[i] );
}
free(U);
}
| c93d1941b88733939f4d3ab95449af441b3a466b | [
"Markdown",
"C",
"Makefile"
] | 20 | C | luis-paquete/MOSAL | 5fbe81433c53705d49a418127ddcc71e52510b97 | 276dcc497405184865c322bc7eebe79ea728b8e4 |
refs/heads/master | <file_sep>class Calculator {
constructor() {
this.val1 = 0;
this.val2 = 0;
this.operation = "";
this.check = false;
}
setValue(value) {
if (this.check == true || document.getElementById("screen").innerHTML == 0) {
document.getElementById("screen").innerHTML = ""; /////////////////////////
this.check = false;
}
document.getElementById("screen").innerHTML += value;
}
setOperation(operation) {
if (!this.check) {
this.calculate();
this.operation = operation;
}
}
calculate() {
this.val2 = this.val1;
this.val1 = parseFloat(document.getElementById("screen").innerHTML);
switch(this.operation) {
case "sum":
this.sum();
break;
case "sub":
this.sub();
break;
case "mul":
this.mul();
break;
case "div":
this.div();
break;
case "mod":
this.mod();
break;
}
this.check = true;
}
sum() {
this.val1 += this.val2;
document.getElementById("screen").innerHTML = +this.val1.toFixed(5);
}
sub() {
this.val1 = this.val2 - this.val1;
document.getElementById("screen").innerHTML = +this.val1.toFixed(5);
}
mul() {
this.val1 = this.val2 * this.val1;
document.getElementById("screen").innerHTML = +this.val1.toFixed(5);
}
div() {
this.val1 = this.val2 / this.val1;
document.getElementById("screen").innerHTML = +this.val1.toFixed(5);
}
mod() {
this.val1 = this.val2 % this.val1;
document.getElementById("screen").innerHTML = +this.val1.toFixed(5);
}
c() {
this.val1 = "";
this.val2 = "";
this.operation = "";
this.check = false;
document.getElementById("screen").innerHTML = 0;
}
}
let calculator = new Calculator(); | 93fea64ed305cba68abb4b21069baa18c16402c1 | [
"JavaScript"
] | 1 | JavaScript | PatrykJankowski/JSCalc | 7befc51fd0bbf7aacbef619a6b84b643de2f553b | ca692f24bc35f30045dccad3962338e3e1bf5d3c |
refs/heads/main | <repo_name>t108368530/RESTful-API-Audio-<file_sep>/src/webservice/api/routes/nn/ctc_1.py
from fastapi import APIRouter, UploadFile, File
from fastapi.responses import UJSONResponse
from typing import Optional
from webservice.core.config import message_queue2, settings
from webservice.utils.preprocessor import make_spec
from pydub import AudioSegment
import base64
import uuid
import ujson
import io
import soundfile as sf
import time
router = APIRouter()
@router.post("/ctc_1", response_class=UJSONResponse)
async def get_res_predict(
input_data: UploadFile = File(...),
) -> Optional[UJSONResponse]:
# X = input_data.file
# data = io.BytesIO(input_data)
if (
input_data.content_type == "audio/wav"
or input_data.content_type == "audio/x-wav"
):
ID = str(uuid.uuid4())
sub = message_queue2.pubsub()
sub.subscribe(ID)
# input_data.seek(0)
# input_data = await input_data.read()
for mes in sub.listen():
responses = mes.get("data")
if isinstance(responses, bytes):
res = responses.decode("utf-8")
res = ujson.loads(res)
break
elif responses == 1:
await input_data.seek(0)
input_data = await input_data.read()
with io.BytesIO() as mem_temp_file:
mem_temp_file.write(input_data)
mem_temp_file.seek(0)
# AudioSegment.from_file(mem_temp_file).export(f"{time.time()}.wav","wav")
# # temp=mem_temp_file
# data, samplerate = sf.read(mem_temp_file)
# sf.write(f'{time.time()}.wav', data, samplerate)
data = make_spec(mem_temp_file)
data = base64.b64encode(data).decode("utf-8")
Q_DATA = {"id": ID, "audio_feature": data}
message_queue2.rpush(settings.QUEUE_NAME_2, ujson.dumps(Q_DATA))
message_queue2.close()
sub.close()
return res
else:
return {"Error": "Type Error"}
<file_sep>/docker/redis/docker-compose.yml
version: '3.6'
services:
redis:
image: 'redis:latest'
# environment:
# ALLOW_EMPTY_PASSWORD is recommended only for development.
# - ALLOW_EMPTY_PASSWORD=yes
# - REDIS_DISABLE_COMMANDS=FLUSHDB,FLUSHALL
ports:
- '8987:8987/tcp'
sysctls:
net.core.somaxconn: '65535'
volumes:
- ./config/redis.conf:/usr/local/redis/redis.conf:Z
- ./redis-socket:/tmp:Z
command:
- /usr/local/redis/redis.conf
<file_sep>/src/webservice/api/routes/nn/api.py
from fastapi import APIRouter
from webservice.api.routes.nn import cnn_1,ctc_1
router = APIRouter()
router.include_router(cnn_1.router, tags=["cnn_model"], prefix="/nn")
router.include_router(ctc_1.router, tags=["ctc_model"], prefix="/nn")
<file_sep>/src/webservice/core/config.py
import logging
import sys
from typing import Optional
from loguru import logger
from pydantic import BaseSettings
from webservice.core.logging import InterceptHandler
from redis import StrictRedis ,ConnectionPool
class Settings(BaseSettings):
DEV_MOD: Optional[str] = None
REDIS_HOST: Optional[str] = None
REDIS_PASSWORD: Optional[str] = None
REDUS_UNIX_SOCKET_PATH: Optional[str] = None
REDIS_PORT: Optional[str] = None
QUEUE_NAME: Optional[str] = None
QUEUE_NAME_2: Optional[str] = None
class Config:
env_file: str = ".env"
settings = Settings()
LOGGING_LEVEL = logging.DEBUG if settings.DEV_MOD == "true" else logging.INFO
LOGGERS = ("uvicorn.asgi", "uvicorn.access", "fastapi")
logging.getLogger().handlers = [InterceptHandler()]
for logger_name in LOGGERS:
logging_logger = logging.getLogger(logger_name)
logging_logger.handlers = [InterceptHandler(level=LOGGING_LEVEL)]
logger.configure(
handlers=[
{
"sink": sys.stderr,
"level": LOGGING_LEVEL,
}
]
)
message_queue = StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
password=settings.REDIS_PASSWORD,
db=0,
)
message_queue2 = StrictRedis(
unix_socket_path=settings.REDUS_UNIX_SOCKET_PATH,
password=settings.REDIS_<PASSWORD>,
max_connections=2000,
db=0,
)
# pool=ConnectionPool(
# unix_socket_path=settings.REDUS_UNIX_SOCKET_PATH,
# password=settings.REDIS_PASSWORD,
# max_connections=10000,
# db=0,
# )
# message_queue3 = StrictRedis(connection_pool=pool)<file_sep>/README.md
# Server Backend
- [Server Backend](#server-backend)
- [專案結構](#專案結構)
## 專案結構
```shell=
[Project]
├── docker
│ ├── get-docker.sh #安裝Docker 腳本
│ └── redis #Redis 的 Docker配置資料夾
| ├── config
| │ └── redis.conf #Redis-Server配置檔案
| ├── redis-socket
| │ └── redis.sock #Redis sock 連接
| └── docker-compose.yml #Redis-Server 的 docker-compose 啟動腳本
├── img #本MD內的圖片放置資料夾
├── poetry.lock
├── pyproject.toml #專案 Lib 配置檔案
├── README.md #本MD
├── src
│ └── webservice #本專案
└── tests #專案單元測試((本專案沒有使用
```
<file_sep>/src/webservice/api/routes/api.py
from fastapi import APIRouter
from webservice.api.routes import ping
from webservice.api.routes.nn import api as nn
router = APIRouter()
router.include_router(ping.router, tags=["ping"], prefix="/ping")
router.include_router(nn.router, tags=["nn"], )
<file_sep>/src/webservice/api/routes/nn/cnn_1.py
from fastapi import APIRouter, UploadFile, File
from fastapi.responses import UJSONResponse
from typing import Optional
from webservice.core.config import message_queue, settings
from webservice.utils.preprocessor import extract_Features
import base64
import uuid
import ujson
import io
router = APIRouter()
@router.post("/cnn_1", response_class=UJSONResponse)
async def get_res_predict(
input_data: UploadFile = File(...),
) -> Optional[UJSONResponse]:
# X = input_data.file
# data = io.BytesIO(input_data)
if input_data.content_type == "audio/x-wav":
await input_data.seek(0)
input_data = await input_data.read()
# print (input_data.content_type)
## In memory temporary file
with io.BytesIO() as mem_temp_file:
mem_temp_file.write(input_data)
mem_temp_file.seek(0)
data = extract_Features(mem_temp_file)
data = base64.b64encode(data).decode("utf-8")
ID = str(uuid.uuid4())
Q_DATA = {"id": ID, "audio_feature": data}
message_queue.rpush(settings.QUEUE_NAME, ujson.dumps(Q_DATA))
QUIT_COUNT=0
while QUIT_COUNT<1000:
QUIT_COUNT+=1
res = message_queue.get(ID)
if res != None:
res = res.decode('utf-8')
message_queue.delete(ID)
res=ujson.loads(res)
res["res"]=int(res["res"])
break
return res
else:
return {"Error": "Content Type Error"}
<file_sep>/src/webservice/nn/model_1.py
from webservice.core.config import message_queue,settings
import ujson
import base64
import numpy as np
import tensorflow as tf
import ujson
import os
from time import sleep
def load_model():
with open('/home/alien/webservice/src/webservice/nn_model/model_2.json','r') as jsonf:
model=tf.keras.models.model_from_json(jsonf.read())
model.load_weights('/home/alien/webservice/src/webservice/nn_model/model_2.h5')
return model
def classify_process():
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
model=load_model()
while True:
if message_queue.llen(settings.QUEUE_NAME) != 0:
q = ujson.loads(message_queue.lpop(settings.QUEUE_NAME).decode("utf-8"))
feature = bytes(q["audio_feature"], encoding="utf-8")
ID = q["id"]
feature = np.frombuffer(base64.decodebytes(feature),dtype=np.float)
yp=np.argmax(model.predict(feature.reshape(1, 277, 1)))
message_queue.set(ID, ujson.dumps({"res": str(yp)}))
if __name__ == "__main__":
classify_process()<file_sep>/pyproject.toml
[tool.poetry]
name = "webservice"
version = "0.1.0"
description = ""
authors = ["alien <<EMAIL>>"]
[tool.poetry.dependencies]
python = "^3.8"
tensorflow-gpu = "2.3.1"
librosa = "^0.8.0"
fastapi = "^0.61.1"
ujson = "^4.0.1"
uvicorn = "^0.12.1"
gunicorn = "^20.0.4"
PyYAML = "^5.3.1"
pydantic = {extras = ["dotenv"], version = "^1.6.1"}
loguru = "^0.5.3"
uvloop = "^0.14.0"
httptools = "^0.1.1"
python-multipart = "^0.0.5"
redis = "^3.5.3"
pydub = "^0.24.1"
[tool.poetry.dev-dependencies]
pytest = "^5.2"
requests = "^2.24.0"
black = {version = "^20.8b1", allow-prereleases = true}
pylint = "^2.6.0"
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
<file_sep>/src/webservice/nn/model_ctc.py
from webservice.core.config import message_queue2, settings
import ujson
import base64
import numpy as np
from tensorflow.keras.layers import *
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.layers import Add
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.models import Model
from tensorflow.keras import backend as K
from tensorflow.keras.utils import plot_model
import ujson
import os
from time import sleep
char_map_str = """
<SPACE> 0
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
k 11
l 12
m 13
n 14
o 15
p 16
q 17
r 18
s 19
t 20
u 21
v 22
w 23
x 24
y 25
z 26
' 27
"""
char_map = {}
index_map = {}
for line in char_map_str.strip().split("\n"):
ch, index = line.split()
char_map[ch] = int(index)
index_map[int(index)] = ch
index_map[0] = " "
def ctc_lambda_func(args):
y_pred, labels, input_length, label_length = args
return K.ctc_batch_cost(labels, y_pred, input_length, label_length)
def ctc(y_true, y_pred):
return y_pred
class CTC:
"""
Usage:
sr_ctc = CTC(enter input_size and output_size)
sr_ctc.build()
sr_ctc.m.compile()
sr_ctc.tm.compile()
"""
def __init__(self, input_size=None, output_size=None, initializer="glorot_uniform"):
self.input_size = input_size
self.output_size = output_size
self.initializer = initializer
self.m = None
self.tm = None
def build(
self,
conv_filters=196,
conv_size=13,
conv_strides=4,
act="relu",
rnn_layers=2,
LSTM_units=128,
drop_out=0.8,
):
print(self.input_size)
i = Input(shape=self.input_size, name="input")
x = Conv1D(
conv_filters,
conv_size,
strides=conv_strides,
name="conv1d",
input_shape=self.input_size,
)(i)
x = BatchNormalization()(x)
x = Activation(act)(x)
for _ in range(rnn_layers):
x = Bidirectional(LSTM(LSTM_units, return_sequences=True))(x)
x = Dropout(drop_out)(x)
x = BatchNormalization()(x)
y_pred = TimeDistributed(Dense(self.output_size, activation="softmax"))(x)
# ctc inputs
labels = Input(
name="the_labels",
shape=[
None,
],
dtype="int32",
)
input_length = Input(name="input_length", shape=[1], dtype="int32")
label_length = Input(name="label_length", shape=[1], dtype="int32")
loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name="ctc")(
[y_pred, labels, input_length, label_length]
)
self.tm = Model(inputs=i, outputs=y_pred)
self.m = Model(inputs=[i, labels, input_length, label_length], outputs=loss_out)
return self.m, self.tm
# def load_model():
# sr_ctc = CTC((122,85), 28)
# sr_ctc.build()
# sr_ctc.m.compile(loss=ctc, optimizer="adam", metrics=["accuracy"])
# sr_ctc.tm.compile(loss=ctc, optimizer="adam")
# sr_ctc.tm.load_weights("/home/alien/webservice/src/webservice/nn_model/ctc.h5")
# return sr_ctc
def classify_process():
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
model = CTC((122,85), 28)
model.build()
model.m.compile(loss=ctc, optimizer="adam", metrics=["accuracy"])
model.tm.compile(loss=ctc, optimizer="adam")
model.tm.load_weights("/home/alien/webservice/src/webservice/nn_model/ctc.h5")
while True:
if message_queue2.llen(settings.QUEUE_NAME_2) != 0:
q = ujson.loads(message_queue2.lpop(settings.QUEUE_NAME_2).decode("utf-8"))
feature = bytes(q["audio_feature"], encoding="utf-8")
ID = q["id"]
feature = np.frombuffer(base64.decodebytes(feature),dtype=np.float32)
# print(feature)
# print(np.array(feature.reshape(), dtype=np.float32).shape)
k_ctc_out = K.ctc_decode(model.tm.predict(np.expand_dims(np.squeeze(feature.reshape(122,85)),axis=0), verbose=0),np.array([28]))
decoded_out = K.eval(k_ctc_out[0][0])
str_decoded_out = []
for i, _ in enumerate(decoded_out):
str_decoded_out.append("".join([index_map[c] for c in decoded_out[i] if not c == -1]))
# print(str_decoded_out)
# message_queue2.set(ID, ujson.dumps({"res": str_decoded_out[0]}))
message_queue2.publish(ID, ujson.dumps({"res": str_decoded_out[0]}))
message_queue2.publish("PPT_COMMAND", str_decoded_out[0])
# yp=np.argmax(model.predict(feature.reshape(1, 277, 1)))
if __name__ == "__main__":
classify_process()
<file_sep>/src/webservice/api/routes/ping.py
from fastapi import APIRouter
from typing import Optional
from webservice.core.config import logger
from fastapi.responses import UJSONResponse
router = APIRouter()
@router.get("/")
async def get_pong() -> Optional[UJSONResponse]:
# logger.info()
return {"ping":"PONG!"}<file_sep>/src/webservice/app.py
from fastapi import FastAPI
from webservice.api.routes.api import router as api_router
from webservice.core.config import settings
def get_application() -> FastAPI:
application = FastAPI(title="RESTful API", debug=True)
application.include_router(api_router, prefix="/api")
return application
app = get_application()
<file_sep>/src/webservice/utils/preprocessor.py
import numpy as np
from pydub import AudioSegment
import librosa
def extract_Features(data) -> np.ndarray:
try:
X, sampleRate = librosa.load(
data,
sr=None,
offset=0.0,
res_type="kaiser_best",
dtype=np.float32,
)
spectral_contrast_fmin = 0.5 * sampleRate * 2 ** (-6)
if sampleRate < 8000:
spectral_contrast_fmin = 200
mel = np.mean(librosa.feature.melspectrogram(X, sr=sampleRate).T, axis=0)
tonnetz = np.mean(
librosa.feature.tonnetz(y=librosa.effects.harmonic(X), sr=sampleRate).T,
axis=0,
)
mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sampleRate, n_mfcc=40).T, axis=0)
mfcc_delta = librosa.feature.delta(mfccs) # TONY
mfcc_delta2 = librosa.feature.delta(mfccs, order=2) # TONY
stft = np.abs(librosa.stft(X))
chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sampleRate).T, axis=0)
contrast = np.mean(
librosa.feature.spectral_contrast(
S=stft, sr=sampleRate, fmin=spectral_contrast_fmin
).T,
axis=0,
)
###### ADD NEW FEATURES (SPECTRAL RELATED)##### 24-SEP
cent = np.mean(librosa.feature.spectral_centroid(y=X, sr=sampleRate).T, axis=0)
flatness = np.mean(librosa.feature.spectral_flatness(y=X).T, axis=0)
rolloff = np.mean(
librosa.feature.spectral_rolloff(S=stft, sr=sampleRate).T, axis=0
)
rms = np.mean(librosa.feature.rms(S=stft).T, axis=0)
ext_features = np.hstack(
[
mfccs,
mfcc_delta,
mfcc_delta2,
chroma,
mel,
contrast,
tonnetz,
cent,
flatness,
rolloff,
rms,
]
)
except Exception as e:
print("Error : %s" % e)
return None
return np.array(ext_features)
def make_spec(data, st=4) -> np.ndarray:
sig, _ = librosa.load(data, sr=16000)
remove_silence_res = []
for item in librosa.effects.split(sig, frame_length=512, top_db=40):
remove_silence_res.append(sig[item[0] : item[1]])
sig = np.concatenate(remove_silence_res, axis=0)
if len(sig) < 16000: # pad shorter than 1 sec audio with ramp to zero
sig = np.pad(sig, (0, 16000 - len(sig)), "linear_ramp")
D = librosa.amplitude_to_db(
librosa.stft(sig[:16000], n_fft=512, hop_length=128, center=False), ref=np.max
)
S = librosa.feature.melspectrogram(S=D, n_mels=85).T
S = np.ascontiguousarray(S, dtype=np.float32)
return np.expand_dims(S, -1) + 1.29
| 5053e5a3c39fec9d123fed7c9a312d1fe1988599 | [
"Markdown",
"TOML",
"Python",
"YAML"
] | 13 | Python | t108368530/RESTful-API-Audio- | d9e9491b715d8187330be158616d85affd0ef0b5 | 1a968ba3e04be71cc4a5612c8a018b6303892012 |
refs/heads/master | <file_sep>package org.fly.scsso.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
* Created by overfly on 2017/9/20.
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private static final String DEMO_RESOURCE_ID = "order";
@Autowired
AuthenticationManager authenticationManager;
@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//配置两个客户端,一个用于password认证一个用于client认证
/*clients.inMemory()
.withClient("my-trusted-client")//客户端ID
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")//授权用户的操作权限
.secret("secret")//密码
.accessTokenValiditySeconds(6000);//token有效期为120秒*/
//配置两个客户端,一个用于password认证一个用于client认证
clients.inMemory().withClient("client_1")
.resourceIds(DEMO_RESOURCE_ID)
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("select")
.authorities("client")
.secret("123456")
.and().withClient("client_2")
.resourceIds(DEMO_RESOURCE_ID)
.authorizedGrantTypes("password", "refresh_token")
.scopes("select")
.authorities("client")
.secret("123456");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
/*endpoints.
authenticationManager(authenticationManager)
// .userDetailsService(userDetailsService)//若无,refresh_token会有UserDetailsService is required错误
.tokenStore(tokenStore());*/
endpoints
.tokenStore(new InMemoryTokenStore())
.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
/*oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");*/
oauthServer.allowFormAuthenticationForClients();
}
}
| 28dce4e183286000e4ce857a97e5f16fdbb14c4e | [
"Java"
] | 1 | Java | nooverfly/springsecurity | 81f9975ddac86032842b78a62e647e61bb6bee09 | 415397b0a9b19af63a8e9f60d100778b404a8189 |
refs/heads/master | <file_sep>
var cal=function(){
var width=document.getElementById('rectangle_width');
var height=document.getElementById('rectangle_height');
var calc=document.getElementById('rectangle_calc');
var perimeter=document.getElementById('rectangle_perimeter');
var area=document.getElementById('rectangle_area');
perimeter.value=2*width.value+2*height.value;
area.value=width.value*height.value;
};
<file_sep>jQuery(document).ready(function($) {
console.log
$('#btn1').change(function() {
/* Act on the event */
var val=$('#btn1').val();
$('#sp').html(val);
})
});<file_sep>jQuery(document).ready(function($) {
console.log(1);
$('#btn2').hide();
$('#btn3').click(function() {
$('#btn2').val($('#btn1').val());
if($('#btn3').is(':checked')){
$('#btn2').show();
$('#btn1').hide();
}else{
$('#btn1').show();
$('#btn2').hide();
}
});
}); | d051107c7a8de61f36ad19ecddbe3f55fcc1bafc | [
"JavaScript"
] | 3 | JavaScript | gengkangning/spa | f15ad4e71d85cc9c747270771e94701cdb779296 | 8b677c565ab68f24bf2b68c69d3fe2e2a9704186 |
refs/heads/master | <file_sep>
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
from .tearsheet import Tearsheet
from .perf import DailyPerformance, AggregateDailyPerformance
from .paramscan import ParamscanTearsheet
from .shortfall import ShortfallTearsheet | 9044e24536ad3eb61b36a2963d03c008b1bb0964 | [
"Python"
] | 1 | Python | jmscraig/moonchart | 80221b3482fd35cf55358600b95e30d7a9abd361 | 52a6976ee6386a70d6145daefa1cc4dd4878e46d |
refs/heads/master | <repo_name>beaubellamy/Transaction-Time<file_sep>/TransactionTime/Settings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrainLibrary;
namespace TransactionTime
{
class Settings
{
/* Set up default parameters */
public static bool excludeListOfTrains = false;
public static string dataFile = null;
public static string geometryFile = null;
/* Default number of simulation Categories is 3, hence, the default number of simulation files is 6, one for each direction */
public static string actualAveragePerformanceFile = null;
public static string aggregatedDestination = null;
public static analysisCategory analysisCategory = analysisCategory.TrainOperator;
public static bool PacificNational = false;
public static bool Freightliner = false;
public static bool Aurizon = false;
public static bool CityRail = false;
public static bool CountryLink = false;
public static bool Qube = false;
public static bool SCT = false;
public static bool Combined = false;
public static DateTime[] dateRange = new DateTime[2];
public static double startInterpolationKm; /* Start km for interpoaltion data. */
public static double endInterpolationKm; /* End km for interpolation data. */
public static double interpolationInterval; /* Interpolation interval (metres). */
public static double minimumJourneyDistance; /* Minimum distance of a train journey to be considered valid. */
public static double distanceThreshold; /* Minimum distance between successive data points. */
public static double throughTrainTime; /* The minimum time between the through train and the train restarting. */
public static double timethreshold; /* Minimum time between data points to be considered a seperate train. */
public static double trainLength; /* The assumed train length. */
public static double trackSpeedFactor; /* The percentage of the simualtion to be considered to have reached track speed. */
public static double maxDistanceToTrackSpeed; /* The maximum permissible distance to achieve track speed. */
public static double stoppingSpeedThreshold; /* The speed at which a train is considered to have stopped. */
public static double restartSpeedThreshold; /* The speed at which a train is considered to have restarted. */
public static double transactionTimeOutlierThreshold; /* The maximum permissible transaction time to include in analysis. */
}
}
<file_sep>/TransactionTime/Algorithm.cs
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* Custom libaries */
using TrainLibrary;
using IOLibrary;
using Statistics;
namespace TransactionTime
{
class Algorithm
{
/* The minimum gap in time between points to indicate a large gap when a train is restarting. */
private static double fineTuneTimeGap_sec = 30;
/// <summary>
/// Calaculate the transaction time for each opposing cross encountered by trains in the supplied region.
/// </summary>
public static void transactionTime()
{
/* Ensure there is a empty list of trains to exclude to start. */
List<string> excludeTrainList = new List<string> { };
/* Read in the track geometry data. */
List<TrackGeometry> trackGeometry = new List<TrackGeometry>();
trackGeometry = FileOperations.readGeometryfile(Settings.geometryFile);
/* Read the data. */
List<TrainRecord> TrainRecords = new List<TrainRecord>();
//TrainRecords = FileOperations.readICEData(Settings.dataFile, excludeTrainList, Settings.excludeListOfTrains, Settings.dateRange);
//TrainRecords = FileOperations.readAzureExtractICEData(Settings.dataFile, excludeTrainList, Settings.excludeListOfTrains, Settings.dateRange);
TrainRecords = FileOperations.readAzureICEData(Settings.dataFile, excludeTrainList, Settings.excludeListOfTrains, Settings.dateRange);
if (TrainRecords.Count() == 0)
{
Tools.messageBox("There are no records in the list to analyse.", "No trains available.");
return;
}
List<trainOperator> operators = TrainRecords.Select(t => t.trainOperator).Distinct().ToList();
operators.Remove(trainOperator.Unknown);
int numberOfOperators = operators.Count();
/* Set simulation categories [TRAP:Set analysis categories] */
List<Category> simCategories = new List<Category>();
if (Settings.PacificNational)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.PacificNational));
if (Settings.Aurizon)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Aurizon));
if (Settings.Freightliner)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Freightliner));
if (Settings.CityRail)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.CityRail));
if (Settings.CountryLink)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Countrylink));
if (Settings.Qube)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.QUBE));
if (Settings.SCT)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.SCT));
if (Settings.Combined)
simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Combined));
//// Gunnedah Basin
//simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.PacificNational));
//simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Aurizon));
//// Add when running Ulan Line data
////simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Freightliner));
//simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Combined));
// Southern Highlands
//simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.CityRail));
//simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.Countrylink));
//simCategories.Add(Processing.convertTrainOperatorToCategory(trainOperator.PacificNational));
/* TRAP: Multiple if conditions */
/* If further development is required to use different train types (ie, operators, by commodity, etc),
* the neccesasry code is in the TRAP tool.
* Will need to define the operator and commodity categories on the Form.
*/
/* Create the list of simulated trains. */
List<Train> simulatedTrains = new List<Train>();
/* Read the actual averaged train performance for each category. */
List<Train> interpolatedSimulations = new List<Train>();
interpolatedSimulations.AddRange(FileOperations.readSimulationData(Settings.actualAveragePerformanceFile, simCategories.Count()));
/* Sort the data by [trainID, locoID, Date & Time, kmPost]. */
List<TrainRecord> OrderdTrainRecords = new List<TrainRecord>();
OrderdTrainRecords = TrainRecords.OrderBy(t => t.trainID).ThenBy(t => t.locoID).ThenBy(t => t.dateTime).ThenBy(t => t.kmPost).ToList();
/* Clean the records and create individual train journeys. */
List<Train> trainList = new List<Train>();
trainList = Processing.CleanData(OrderdTrainRecords, trackGeometry, Settings.timethreshold, Settings.distanceThreshold, Settings.minimumJourneyDistance, Settings.analysisCategory);
/* Perform minor cleaning porocedures and create individual train journeys. */
//List<Train> rawTrainList = new List<Train>();
//rawTrainList = Processing.MakeTrains(OrderdTrainRecords, trackGeometry, Settings.timethreshold, Settings.distanceThreshold, Settings.minimumJourneyDistance, Settings.analysisCategory);
///* Write the raw data to file - usefull for creating train graphs */
//FileOperations.writeRawTrainDataWithTime(rawTrainList, Settings.aggregatedDestination);
/* Interpolate data */
/******** Should only be required while we are waiting for the data in the prefered format ********/
List<Train> interpolatedTrains = new List<Train>();
List<Train> utilisationTrains = new List<Train>();
interpolatedTrains = Processing.interpolateTrainDataWithGaps(trainList, trackGeometry, Settings.startInterpolationKm, Settings.endInterpolationKm, Settings.interpolationInterval);
/* Interpoalte for utilisation calculations. ie interpoalte through the gaps */
utilisationTrains = Processing.interpolateTrainData(trainList, trackGeometry, Settings.startInterpolationKm, Settings.endInterpolationKm, Settings.interpolationInterval);
/**************************************************************************************************/
/* Write the interpolated data to file. */
FileOperations.writeTrainDataWithTime(utilisationTrains, Settings.startInterpolationKm, Settings.interpolationInterval, Settings.aggregatedDestination);
/* Identify all the potential loop locations where a train may be forced to stop. */
List<LoopLocation> loopLocations = findAllLoopLocations(interpolatedTrains[0], Settings.endInterpolationKm);
/* Identify the boundaries of the sections for the section utilisation. */
List<Section> sections = findAllSections(utilisationTrains[0], Settings.endInterpolationKm);
/* Identify all the trains that stop at a loop. */
List<TrainPair> trainPairs = findAllStoppingTrains(interpolatedTrains, loopLocations, Settings.stoppingSpeedThreshold, Settings.restartSpeedThreshold);
/* Identify the corresponding through trains for the trains that have stopped. */
populateThroughTrains(trainPairs, loopLocations, interpolatedTrains, Settings.throughTrainTime);
List<TrainPair> allTrainPairs = trainPairs;
/******************************************************************************************************/
#region transactionTimeCalculations
/* Ignore the train pairs where we do not have an identified through train. */
trainPairs = trainPairs.Where(p => p.throughTrain != null).ToList();
/* Order the remaining pairs by loop location, stopping train direction and ID. */
trainPairs = trainPairs.OrderBy(t => t.loopLocation.loopStart).ThenBy(t => t.stoppedTrain.trainDirection).ThenBy(t => t.stoppedTrain.trainID).ToList();
trainPairs = calculateTransactionTime(trainPairs, interpolatedSimulations, Settings.maxDistanceToTrackSpeed, Settings.trackSpeedFactor, Settings.interpolationInterval, Settings.trainLength);
/* Remove outliers [ie transaction time greater than transaction time outlier threshold (10 min)]*/
trainPairs = trainPairs.Where(p => p.transactionTime < Settings.transactionTimeOutlierThreshold).ToList();
/* Generate the statistics for the list of train pairs in each loop */
List<TrainPairStatistics> stats = new List<TrainPairStatistics>();
foreach (LoopLocation loop in loopLocations)
{
/* Extract the relavant train pairs that are associated to the current loop. */
List<TrainPair> pairs = trainPairs.Where(p => p.loopLocation == loop).ToList();
if (pairs.Count > 0)
stats.Add(TrainPairStatistics.generateStats(pairs));
}
stats.Add(TrainPairStatistics.generateStats(trainPairs));
stats[stats.Count() - 1].Category = "All loops";
/* Write the train pairs to file grouped by loop location. */
FileOperations.writeTrainPairs(trainPairs, loopLocations, Settings.aggregatedDestination);
FileOperations.writeTrainPairStatistics(stats, Settings.aggregatedDestination);
#endregion
#region utilisationCalculations
/* Initialise the current train properties. */
Train train = new Train();
List<TrainJourney> currentTrainJourney = new List<TrainJourney>();
List<TrainJourney> stopInLoopJourney = new List<TrainJourney>();
/* Initialise the time range to search for trains in each section. */
DateTime currentTime = Settings.dateRange[0];
DateTime previousStartTime = new DateTime();
DateTime timeTrainEntersSection = new DateTime();
DateTime timeTrainStopsInLoop = Settings.dateRange[1];
DateTime endTime = new DateTime();
/* Flag to indicate to ignore a train due to lack of data. */
bool ignoreTrain = false;
/* Create a list of occupation block objects to maintain utilisation calculations. */
List<OccupationBlock> occupationBlock = new List<OccupationBlock>();
/* Create a list of each occupation block for each section. */
List<List<OccupationBlock>> sectionUtilisation = new List<List<OccupationBlock>>();
/* A sorted dictionary list of ustilisation section for rolling 24 hourly period. */
SortedDictionary<string, List<double>> rollingUtilisation = new SortedDictionary<string, List<double>>();
List<double> rollingSectionUtilisation = new List<double>();
/* Initialise boundary parameters. */
double trainLength = Settings.trainLength;
double stoppingSpeed = Settings.restartSpeedThreshold;
/* Loop through each sections. */
foreach (Section section in sections)
{
/* Find the first train that occupies the section. */
train = findNextTrainInSection(utilisationTrains, section, currentTime);
currentTrainJourney = train.journey;
/* Reset the current time to the earliest time for this train, where it was still in the section.
* - This is the start time for the utilisation of the current train.
*/
currentTime = currentTrainJourney.Where(t => t.kilometreage > section.sectionStart && t.kilometreage < section.sectionEnd &&
t.speed > 0).Min(t => t.dateTime);
/* Flag, to indicate that the current section block is still active. */
bool activeOccupationBlock = true;
/* Continue searching for trains in the current section until the end of the analysis period is reached. */
while (currentTime < Settings.dateRange[1])
{
/* While the section block is active, continue searching for the end of the block. */
while (activeOccupationBlock)
{
/* Set the current journey to the current train. */
currentTrainJourney = train.journey;
/* If there is a train in the loop waiting to occupy the section, or if there is a
* train about to enter the section, continue with the new train. */
if (isTrainWaitingToOccupySection(train, trainPairs, section))
{
/* Extract the part of journey of that is in the current section. */
if (train.trainDirection == direction.IncreasingKm)
currentTrainJourney = currentTrainJourney.Where(t => t.kilometreage > section.sectionStart &&
t.kilometreage < section.sectionEnd + trainLength &&
t.speed > stoppingSpeed && t.dateTime > endTime).ToList();
else
currentTrainJourney = currentTrainJourney.Where(t => t.kilometreage > section.sectionStart - trainLength &&
t.kilometreage < section.sectionEnd &&
t.speed > stoppingSpeed && t.dateTime > endTime).ToList();
/* Find the time the current train leaves the section. */
if (currentTrainJourney.Count() > 0)
{
endTime = currentTrainJourney.Max(t => t.dateTime);
}
else
{
ignoreTrain = true;
activeOccupationBlock = false;
break;
}
/* Find the next train in the section */
train = findNextTrainInSection(utilisationTrains, section, endTime);
previousStartTime = currentTime;
/* Find the time the next train enters the section. */
timeTrainEntersSection = train.journey.Where(t => t.kilometreage > section.sectionStart && t.kilometreage < section.sectionEnd &&
t.speed > 0).Min(t => t.dateTime);
/* IF: the train entered the section > 10 minutes after the previous train cleared,
* set the end time to the time the previous train cleared the section.
*/
if ((timeTrainEntersSection - endTime).TotalMinutes > Settings.transactionTimeOutlierThreshold)
{
activeOccupationBlock = false;
break;
}
}
else
{
/* This is meant to take into account if the train leaving the section stops in the loop.
* As the train should be clear of the loop clearance point before it stops.
*/
/* Determine the time the rear of the train leaves the section. */
if (train.trainDirection == direction.IncreasingKm)
{
/* Find the point the train stops, if there is one */
stopInLoopJourney = currentTrainJourney.Where(j => j.kilometreage > section.sectionEnd &&
j.kilometreage < section.sectionEnd + trainLength &&
j.speed > 0 && j.speed < Settings.stoppingSpeedThreshold).ToList();
if (stopInLoopJourney.Count > 0)
timeTrainStopsInLoop = stopInLoopJourney.Min(j => j.dateTime);
currentTrainJourney = currentTrainJourney.Where(j => j.kilometreage > section.sectionStart &&
j.kilometreage < section.sectionEnd + trainLength && j.dateTime < timeTrainStopsInLoop && j.speed > stoppingSpeed).ToList();
}
else
{
/* Find the point the train stops, if there is one */
stopInLoopJourney = currentTrainJourney.Where(j => j.kilometreage > section.sectionStart - trainLength &&
j.kilometreage < section.sectionStart &&
j.speed > 0 && j.speed < Settings.stoppingSpeedThreshold).ToList();
if (stopInLoopJourney.Count > 0)
timeTrainStopsInLoop = stopInLoopJourney.Min(j => j.dateTime);
currentTrainJourney = currentTrainJourney.Where(j => j.kilometreage > section.sectionStart - trainLength &&
j.kilometreage < section.sectionEnd && j.dateTime < timeTrainStopsInLoop && j.speed > stoppingSpeed).ToList();
}
if (currentTrainJourney.Count() > 0)
endTime = currentTrainJourney.Max(j => j.dateTime);
else
/* The boundary of the train has been reached. */
ignoreTrain = true;
if (endTime < currentTime)
/* Need to deal with trains that appear to stop in the middle of the section.
* This is likely due to drivers not turning the loco ID off at the end of the journey. */
ignoreTrain = true;
/* Release the active section flag for the next iteration. */
activeOccupationBlock = false;
}
}
/* Add the current section block details to the list. */
if (!ignoreTrain)
{
occupationBlock.Add(new OccupationBlock(section, currentTime, endTime));
previousStartTime = currentTime;
}
else
{
/* Adjust the end time to find the next train after the train we are ignoring. */
ignoreTrain = false;
endTime = currentTime.AddMinutes(5);
}
/* Find the next train that occupies the section. */
train = findNextTrainInSection(utilisationTrains, section, endTime);
if (train != null)
{
currentTime = train.journey.Where(t => t.kilometreage > section.sectionStart && t.kilometreage < section.sectionEnd &&
t.speed > 0 && t.dateTime > endTime).Min(t => t.dateTime);
}
/* If there are no more train's in the current section, continue to the next section. */
else
break;
/* Reset the active section flag */
activeOccupationBlock = true;
timeTrainStopsInLoop = Settings.dateRange[1];
}
/* Determine the utilisation in each section. */
rollingSectionUtilisation = calculate24HourSectionUtilisation(occupationBlock);
/* Build the key string for the dictionary. */
string key = string.Format("{0:0.00} km - {1:0.00} km", section.sectionStart, section.sectionEnd);
rollingUtilisation[key] = new List<double> (rollingSectionUtilisation);
rollingSectionUtilisation.Clear();
/* List of each utilsation block in each section. */
sectionUtilisation.Add(new List<OccupationBlock>(occupationBlock));
occupationBlock.Clear();
/* Reset the search times for the next section. */
currentTime = Settings.dateRange[0];
endTime = currentTime;
}
# endregion
/* Write the occupation blocks for each section to file. */
FileOperations.writeSectionUtilistion(sectionUtilisation, Settings.aggregatedDestination);
/* Write the aggregated rolling 24 hour utilisation times to file for each section. */
FileOperations.writeRollingUtilistion(rollingUtilisation, Settings.aggregatedDestination, Settings.dateRange);
}
/// <summary>
/// Determine if there is a train in the loop waiting to occupy the current section.
/// </summary>
/// <param name="train">The current train in the section.</param>
/// <param name="trainPairs">A list of all train pairs that have been identified.</param>
/// <param name="section">The section being occupied.</param>
/// <returns>A flag indicating if there is a train in teh loop waiting to occupy the section.</returns>
private static bool isTrainWaitingToOccupySection(Train train, List<TrainPair> trainPairs, Section section)
{
/* Find a train that is waiting in the loop. */
Train trainInLoop = findTrainWaitingInLoop(train, trainPairs, section);
/* If there is not train in the loop, there is no train waiting to occupy the section. */
if (trainInLoop != null)
return true;
else
return false;
}
/// <summary>
/// Find the train waiting in the loop as the current train passes it.
/// </summary>
/// <param name="train">The train occupying the section.</param>
/// <param name="trainPairs">A list of all train pairs that have been identified.</param>
/// <param name="section">The section being occupied.</param>
/// <returns>The train waiting in the loop or null, if no train exists.</returns>
public static Train findTrainWaitingInLoop(Train train, List<TrainPair> trainPairs, Section section)
{
/* Search through each train pairs */
foreach (TrainPair pair in trainPairs)
{
/* If the current train is in the increasing direction, check the loop at the end of the section. */
if (train.trainDirection == direction.IncreasingKm)
{
/* The difference needs to be between 0 and 0.5 km to allow for the alignment between loops and sections. */
if (Math.Abs(pair.loopLocation.loopStart - section.sectionEnd) < 0.050001 &&
train == pair.throughTrain)
/* Return the stopped train. */
return pair.stoppedTrain;
}
else
{
/* Check the loop at the begining of the section. */
if (Math.Abs(pair.loopLocation.loopEnd - section.sectionStart) < 0.050001 &&
train == pair.throughTrain)
/* Return the stopped train. */
return pair.stoppedTrain;
}
}
return null;
}
/// <summary>
/// Find the next train in the section.
/// </summary>
/// <param name="trains">A list of all train in the data.</param>
/// <param name="section">The current section being occupied.</param>
/// <param name="currentTime">The time of day to search for the next train.</param>
/// <returns>The next train in the section, or null if none exists.</returns>
public static Train findNextTrainInSection(List<Train> trains, Section section, DateTime currentTime)
{
/* Define a sub journey list to define a trains journey inside the current section. */
List<TrainJourney> sectionJourney = new List<TrainJourney>();
/* The earliest time found ahead of the current time. */
DateTime minimumTime = DateTime.MaxValue;
DateTime time = new DateTime();
/* The train object that will be the next train in section. */
Train firstTrain = null;
/* Loop through each train to find the next train in the section */
foreach (Train train in trains)
{
/* Find the time the front of the train enters the section. */
sectionJourney = train.journey.Where(t => t.kilometreage > section.sectionStart && t.kilometreage < section.sectionEnd &&
t.speed > 0 && t.dateTime > currentTime).ToList();
/* If there are points in the section journey, find the earliest time, greater than the current search time. */
if (sectionJourney.Count > 0)
{
time = sectionJourney.Min(t => t.dateTime);
/* Find the train with the minimum time. */
if (time < minimumTime)
{
minimumTime = time;
firstTrain = train;
}
}
}
/* Return the next train in the section. */
return firstTrain;
}
/// <summary>
/// Find the locations of all loops
/// </summary>
/// <param name="train">A typical train</param>
/// <param name="endInterpolationKm">The end of the interpolation region.</param>
/// <returns>A list of loop locations.</returns>
public static List<LoopLocation> findAllLoopLocations(Train train, double endInterpolationKm)
{
List<TrainJourney> journey = train.journey;
List<LoopLocation> loopLocations = new List<LoopLocation>();
/* Loop location parameters */
bool startLoopFound = false;
double start = 0, end = 0;
for (int index = 0; index < journey.Count(); index++)
{
/* Find the start of the loop */
if (!startLoopFound && journey[index].isLoopHere)
{
/* If the start of the loop is found, set the start parameter. */
startLoopFound = true;
start = journey[index].kilometreage;
}
/* Only when the start is found, look for the end of the loop. */
if (startLoopFound && !journey[index].isLoopHere)
{
/* If the end of the loop is found, set the end parameter. */
startLoopFound = false;
end = journey[index - 1].kilometreage;
/* Create a loop location if its not too close to the end of the data. */
// 30 km prior to the end of the interpolation to allow the through trains to be found.
/* This is somewhat of an arbitrary number based on Gunnedah basin trains. */
if (end < endInterpolationKm - 30)
loopLocations.Add(new LoopLocation(start, end));
}
}
/* Return the loop locations. */
return loopLocations;
}
/// <summary>
/// Find the boundaries of the sections
/// </summary>
/// <param name="train">A typical train</param>
/// <param name="endInterpolationKm">The end of the interpolation region.</param>
/// <returns>A list of section boundaries.</returns>
public static List<Section> findAllSections(Train train, double endInterpolationKm)
{
List<TrainJourney> journey = train.journey;
List<Section> section = new List<Section>();
/* Loop location parameters */
bool sectionFound = true;
double start = 0, end = 0;
/* Loop through the first train for the loop locations */
for (int index = 0; index < journey.Count(); index++)
{
/* Find the start of each section */
if (!sectionFound && !journey[index].isLoopHere)
{
sectionFound = true;
start = journey[index].kilometreage;
}
/* The beginning of the next loop is the end of the current section. */
if (sectionFound && journey[index].isLoopHere)
{
end = journey[index-1].kilometreage;
sectionFound = false;
if(start !=0 && end != 0)
section.Add(new Section(start, end));
}
}
/* Return the loop locations. */
return section;
}
/// <summary>
/// Find the trains that stop within a loop.
/// The lowest speed within a loop is considered to be the stoppping location.
/// The restart location is assumed to be where the train reaches a minimum threshold.
/// </summary>
/// <param name="trains">A list of trains to search through.</param>
/// <param name="loopLocations">A list of locatons a train may stop at.</param>
/// <param name="stoppingSpeedThreshold">The minimum speed a train is travelling before its considered to stop.</param>
/// <param name="restartSpeedThreshold">The minimum speed a train need to reach before it is considered to have restarted.</param>
/// <returns>A list of train pairs that do not have the through trains identified.</returns>
public static List<TrainPair> findAllStoppingTrains(List<Train> trains, List<LoopLocation> loopLocations, double stoppingSpeedThreshold, double restartSpeedThreshold)
{
/* Set the minimum speed. */
double minSpeed = double.MinValue;
List<TrainJourney> speeds = new List<TrainJourney>();
/* Create a list of pairs to store the stopped trains and the details of the cross. */
List<TrainPair> trainPairs = new List<TrainPair>();
/* loop through the trains to find the trains that stop in loops. */
foreach (Train train in trains)
{
/* loop through each loop location. */
for (int loopIdx = 0; loopIdx < loopLocations.Count(); loopIdx++)
{
/* Find the minimum speed within the loop. */
speeds = train.journey.Where(t => t.interpolate == true).
Where(t => t.kilometreage >= loopLocations[loopIdx].loopStart).
Where(t => t.kilometreage <= loopLocations[loopIdx].loopEnd).ToList();
/* Determine the minimum speed of the train journey items within the boundaries of the loop. */
if (speeds.Count() > 0)
minSpeed = speeds.Min(t => t.speed);
else
/* Default minimum speed. */
minSpeed = 0;
/* If the minimm speed is below the threshold, it is considered to be stopping within the loop. */
if (minSpeed > 0 && minSpeed < stoppingSpeedThreshold)
{
/* Find the index, where the train stops. */
int stopIdx = train.journey.FindIndex(t => t.speed == minSpeed);
/* Determine the appropriate index where the train restarts. The train must be
* above a specified speed threshold to be considered to have restarted.
*/
int restartIdx = 0;
if (train.trainDirection == direction.IncreasingKm)
restartIdx = train.journey.FindIndex(stopIdx, t => t.speed >= restartSpeedThreshold);
else
restartIdx = train.journey.FindLastIndex(stopIdx, stopIdx - 1, t => t.speed >= restartSpeedThreshold);
/* Add the stopped train parameters to the list. */
if (stopIdx > 0 && restartIdx > 0)
{
/* Fine tune the restart locaton. */
restartIdx = fineTuneRestart(train.journey, restartIdx, train.trainDirection);
/* Add the stopped train and cross details to the list. */
trainPairs.Add(new TrainPair(train, null, loopLocations[loopIdx], train.journey[stopIdx].kilometreage, train.journey[restartIdx].kilometreage));
}
}
}
}
/* Sort the train pairs in order of loops */
trainPairs = trainPairs.OrderBy(t => t.loopLocation.loopStart).ThenBy(t => t.stoppedTrain.trainID).ToList();
return trainPairs;
}
/// <summary>
/// Fine tune the stopped train restart location.
/// </summary>
/// <param name="journey">The train journey details.</param>
/// <param name="index">The initial restart index.</param>
/// <param name="direction">The train direction.</param>
/// <returns>A new index for the restart location.</returns>
private static int fineTuneRestart(List<TrainJourney> journey, int index, direction direction)
{
/* Define evaluation variables. */
double timeDiff = 0;
int increment = 1;
int restartIndex = index;
/* Determine the increment value based on the train direction. */
if (direction == direction.DecreasingKm)
increment = -1;
/* Fine tune the restart location by looking up to two point ahead for a large time difference. */
timeDiff = (journey[index + increment].dateTime - journey[index].dateTime).TotalSeconds;
/* A time gap of greater than 30 seconds is considered large. */
/* It takes 36 sec for a train travelling at 5 kph to travel a distance of 50m.
* So a gap of less than 30 sec, the train will be travelling faster than 5 kph.
*/
if (timeDiff > fineTuneTimeGap_sec)
{
restartIndex = index + increment;
timeDiff = (journey[index + 2 * increment].dateTime - journey[index + increment].dateTime).TotalSeconds;
/* Check the next point ahead for a large gap in time. */
if (timeDiff > fineTuneTimeGap_sec)
restartIndex = index + 2 * increment;
}
return restartIndex;
}
/// <summary>
/// Find the through trains at each loop associated to the stopped trains.
/// </summary>
/// <param name="trainPairs">A list of train pairs.</param>
/// <param name="loopLocations">A list of loop locations.</param>
/// <param name="trains">A list of trains that may or may not include the through train.</param>
/// <param name="timeThreshold">The maximum time difference between the stopped train and the through train.</param>
public static void populateThroughTrains(List<TrainPair> trainPairs, List<LoopLocation> loopLocations, List<Train> trains, double timeThreshold)
{
double minDifference = double.MaxValue;
Train keepThrough = new Train();
/* Search through each loop location. */
foreach (LoopLocation loop in loopLocations)
{
/* Cycle through the train pairs. */
foreach (TrainPair pair in trainPairs)
{
/* If the current train pair stopped at the current loop, search for the through train. */
if (pair.loopLocation == loop)
{
Train stopped = pair.stoppedTrain;
minDifference = double.MaxValue;
keepThrough = null;
/* Search through each train for the corresponding through train. */
foreach (Train throughTrain in trains)
{
/* Find the location where the stopped train restarts. */
int idx = throughTrain.journey.FindIndex(t => t.kilometreage == pair.restartLocation);
if (throughTrain.trainDirection != pair.stoppedTrain.trainDirection && throughTrain.journey[idx].interpolate)
{
/* Calcualte the time difference of each train at the restart location. */
double timeDifference = (pair.stoppedTrain.journey[idx].dateTime - throughTrain.journey[idx].dateTime).TotalMinutes;
if (timeDifference > -5 && timeDifference < minDifference) // timeDifference > -1
{
/* only keep the through train that is closest in time to the stopped train. */
minDifference = timeDifference;
keepThrough = throughTrain;
}
}
}
/* Populate the through train. */
pair.throughTrain = keepThrough;
}
}
}
}
/// <summary>
/// Calculate the transaction time of all train pairs
/// </summary>
/// <param name="trainPairs">A list of train pairs.</param>
/// <param name="interpolatedSimulations">A list of simualtions.</param>
/// <param name="maxDistanceToTrackSpeed">The maximum permitted distance to achieve track speed.</param>
/// <param name="trackSpeedFactor">The multiplication factor applied to the simualtion speed for comparison.</param>
/// <param name="interpolationInterval">The interpolation interval.</param>
/// <param name="trainLength">The train length to define where the train will clear the loop.</param>
/// <returns>A list of train pairs which have the transaction time components populated.</returns>
public static List<TrainPair> calculateTransactionTime(List<TrainPair> trainPairs, List<Train> interpolatedSimulations, double maxDistanceToTrackSpeed, double trackSpeedFactor, double interpolationInterval, double trainLength)
{
List<int> keepIdx = new List<int>();
Train simulation = new Train();
double timeToReachTrackSpeed, simulatedTrainTime, timeToClearLoop;
double transactionTime = 0;
double distanceToTrackSpeed = 0;
/* Cycle through each train pair. */
foreach (TrainPair pair in trainPairs)
{
timeToReachTrackSpeed = 0;
simulatedTrainTime = 0;
timeToClearLoop = 0;
transactionTime = 0;
distanceToTrackSpeed = 0;
/* Extract the appropriate simulation for comparison. */
simulation = pair.matchToSimulation(interpolatedSimulations);
/* Calcualte the time components for the transaction time. */
List<double> transactionTimeComponents = new List<double>();
transactionTimeComponents = calculateTransactionTimeComponents(pair, simulation, maxDistanceToTrackSpeed, trackSpeedFactor, interpolationInterval, trainLength);
/* Extract each individual time component */
timeToReachTrackSpeed = transactionTimeComponents[0];
simulatedTrainTime = transactionTimeComponents[1];
timeToClearLoop = transactionTimeComponents[2];
/* Extract the required distance to reach track speed. */
distanceToTrackSpeed = transactionTimeComponents[3];
/* Calculate the transaction time. */
transactionTime = timeToReachTrackSpeed - simulatedTrainTime + timeToClearLoop;
/* Identify the pairs that should be kept based on the distance required to achieve
* track speed and positive transaction time.
*/
if (timeToClearLoop > 0 && transactionTime > 0 && distanceToTrackSpeed < maxDistanceToTrackSpeed)
keepIdx.Add(trainPairs.IndexOf(pair));
/* Populate the transaction time and its componenets for each train pair. */
pair.timeForStoppedTrainToReachTrackSpeed = timeToReachTrackSpeed;
pair.distanceToTrackSpeed = distanceToTrackSpeed;
pair.simulatedTrainToReachTrackSpeedLocation = simulatedTrainTime;
pair.timeBetweenClearingLoopAndRestart = timeToClearLoop;
pair.transactionTime = transactionTime;
}
/* Select only the train pairs that are valid. */
trainPairs = keepIdx.Select(item => trainPairs[item]).ToList();
return trainPairs;
}
/// <summary>
/// Calculate the components of the transaction time.
/// This includes the time between the through train clearing the loop and the
/// stopped train to restart, the time the stopped train takes to get to track
/// speed and the corresponding time for the simulated train to reach the
/// track speed location.
/// </summary>
/// <param name="pair">A train pair.</param>
/// <param name="simulation">The corresponding simualtion.</param>
/// <param name="maxDistanceToTrackSpeed">The maximum permitted distance to achieve track speed.</param>
/// <param name="trackSpeedFactor">The multiplication factor applied to the simualtion speed for comparison.</param>
/// <param name="interpolationInterval">The interpolation interval.</param>
/// <param name="trainLength">The train length to define where the train will clear the loop.</param>
/// <returns>A list containing the transaction time components and the distance required to achieve track speed.</returns>
public static List<double> calculateTransactionTimeComponents(TrainPair pair, Train simulation, double maxDistanceToTrackSpeed, double trackSpeedFactor, double interpolationInterval, double trainLength)
{
double timeToReachTrackSpeed = 0;
double simulatedTrainTime = 0;
double timeToClearLoop = 0;
double distanceToTrackSpeed = 0;
DateTime restartTime = DateTime.MinValue;
DateTime clearanceTime = DateTime.MinValue;
int increment = 0;
double loopSide = 0;
int trackSpeedLocationIdx = 0;
int restartIdx = 0;
/* Define the changing parameters based on the direction of the stopping train. */
if (pair.stoppedTrain.trainDirection == direction.IncreasingKm)
{
increment = 1;
loopSide = pair.loopLocation.loopEnd;
trackSpeedLocationIdx = pair.stoppedTrain.journey.FindIndex(t => t.kilometreage == loopSide) + increment * 2;
restartIdx = pair.stoppedTrain.journey.FindIndex(t => t.kilometreage == pair.restartLocation) + increment * 2;
/* Get the index for the latest of the restart time and the loop end. */
trackSpeedLocationIdx = Math.Max(trackSpeedLocationIdx, restartIdx);
}
else
{
increment = -1;
loopSide = pair.loopLocation.loopStart;
trackSpeedLocationIdx = pair.stoppedTrain.journey.FindIndex(t => t.kilometreage == loopSide) + increment * 2;
restartIdx = pair.stoppedTrain.journey.FindIndex(t => t.kilometreage == pair.restartLocation) + increment * 2;
/* Get the index for the latest of the restart time and the loop end. */
trackSpeedLocationIdx = Math.Min(trackSpeedLocationIdx, restartIdx);
}
/* find the location where the train reaches 90% of simulated train speed. */
while (pair.stoppedTrain.journey[trackSpeedLocationIdx].speed < trackSpeedFactor * simulation.journey[trackSpeedLocationIdx].speed)
{
/* Increment the distance travelled, and the time for the stopped train and the simulation to reach the track speed location. */
distanceToTrackSpeed += interpolationInterval * Processing.metresToKilometers;
timeToReachTrackSpeed += (pair.stoppedTrain.journey[trackSpeedLocationIdx].dateTime - pair.stoppedTrain.journey[trackSpeedLocationIdx - increment].dateTime).TotalMinutes;
simulatedTrainTime += (simulation.journey[trackSpeedLocationIdx].dateTime - simulation.journey[trackSpeedLocationIdx - increment].dateTime).TotalMinutes;
/* Check we are not trying to continue outside the bounds of the train journey. */
if (trackSpeedLocationIdx == 1 || trackSpeedLocationIdx == pair.stoppedTrain.journey.Count() - 2)
break;
/* Increment to the next index in the direction the train is travelling. */
trackSpeedLocationIdx = trackSpeedLocationIdx + increment;
}
/* Add the last point */
trackSpeedLocationIdx = trackSpeedLocationIdx + increment;
timeToReachTrackSpeed += (pair.stoppedTrain.journey[trackSpeedLocationIdx].dateTime - pair.stoppedTrain.journey[trackSpeedLocationIdx - increment].dateTime).TotalMinutes;
simulatedTrainTime += (simulation.journey[trackSpeedLocationIdx].dateTime - simulation.journey[trackSpeedLocationIdx - increment].dateTime).TotalMinutes;
/* Time when the stopped train restarts. */
restartTime = pair.stoppedTrain.journey[restartIdx].dateTime;
/* Time when the through train clears the loop. */
clearanceTime = pair.throughTrain.journey[pair.throughTrain.journey.FindIndex(t => t.kilometreage >= loopSide - increment * trainLength)].dateTime;
/* Calculate the time between the through train clearing the loop and the stopped train to restart. */
timeToClearLoop = (restartTime - clearanceTime).TotalMinutes;
/* Return the time compenents as a list. */
return new List<double>(new double[] { timeToReachTrackSpeed, simulatedTrainTime, timeToClearLoop, distanceToTrackSpeed });
}
/// <summary>
/// Calcualte the rolling 24 hour ustilisation of a section
/// </summary>
/// <param name="occupationBlock">The blocks occupied by trains in the current section.</param>
/// <returns>A list of 24 hourly occupation times.</returns>
private static List<double> calculate24HourSectionUtilisation(List<OccupationBlock> occupationBlock)
{
List<double> rollingUtilisation = new List<double>();
/* Calcualte how many 24 hour periods need to be processed. */
int hourlyPeriods = (int)(Settings.dateRange[1] - Settings.dateRange[0]).TotalHours;
/* Aggregate the time to 24 hourly periods. */
for (int periodIdx = 0; periodIdx < hourlyPeriods; periodIdx++)
{
/* Define the time boundaries for the sublist. */
DateTime startDate = Settings.dateRange[0].AddHours(periodIdx);
DateTime endDate = startDate.AddDays(1);
/* Extract the sublist and sum the times */
double totalMinutesOccupied = occupationBlock.Where(u => u.startTime >= startDate && u.endTime < endDate).Sum(u => u.minutesOccupied);
/* Add to the dictionary*/
rollingUtilisation.Add(totalMinutesOccupied);
}
return rollingUtilisation;
}
}
}
<file_sep>/TransactionTime/Program.cs
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using TrainLibrary;
using Statistics;
using IOLibrary;
namespace TransactionTime
{
class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
/// <param name="args">The application arguments.</param>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TransactionTimeFrom());
}
}
}
<file_sep>/TransactionTime/TransactionTimeForm.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IOLibrary;
using TrainLibrary;
namespace TransactionTime
{
public partial class TransactionTimeFrom : Form
{
/* Timer parameters to keep track of execution time. */
private int timeCounter = 0;
private bool stopTheClock = false;
/* Constant time factors. */
public const double secPerHour = 3600;
public const double minutesPerHour = 60;
public const double secPerMinute = 60;
public TransactionTimeFrom()
{
InitializeComponent();
}
/// <summary>
/// Select the data file
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void dataFileButton_Click(object sender, EventArgs e)
{
/* Select the data file. */
Settings.dataFile = Tools.selectDataFile(caption: "Select the data file.");
dataFilename.Text = Path.GetFileName(Settings.dataFile);
dataFilename.ForeColor = System.Drawing.Color.Black;
}
/// <summary>
/// Select the geometry file.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void geometryFileButton_Click(object sender, EventArgs e)
{
/* Select the geometry file. */
Settings.geometryFile = Tools.selectDataFile(caption: "Select the geometry file.");
geometryFilename.Text = Path.GetFileName(Settings.geometryFile);
geometryFilename.ForeColor = System.Drawing.Color.Black;
}
/// <summary>
/// Select a simulation file
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void actualAverageFileButton_Click(object sender, EventArgs e)
{
/* Select the data file. */
Settings.actualAveragePerformanceFile = Tools.selectDataFile(caption: "Select the actual average performance file.");
actualAveragePerformanceFile.Text = Path.GetFileName(Settings.actualAveragePerformanceFile);
actualAveragePerformanceFile.ForeColor = System.Drawing.Color.Black;
}
/// <summary>
/// Select the desination folder to save all the files to.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void directoryButton_Click(object sender, EventArgs e)
{
/* Browse the folders for the desired desination folder. */
Settings.aggregatedDestination = Tools.selectFolder();
destinationDirectory.Text = Settings.aggregatedDestination;
destinationDirectory.ForeColor = System.Drawing.Color.Black;
}
/// <summary>
/// Extract the date range for the data.
/// </summary>
/// <returns>A 2-element array containig the start and end date to consider.</returns>
public DateTime[] getDateRange() { return new DateTime[2] { fromDate.Value, toDate.Value }; }
/// <summary>
/// Extract the value of the start km for interpolation.
/// </summary>
/// <returns>The start km.</returns>
public double getStartKm()
{
double startKm;
if (double.TryParse(startInterpolationKm.Text, out startKm))
return startKm;
return 0;
}
/// <summary>
/// Extract the value of the end km for interpolation.
/// </summary>
/// <returns>The end km.</returns>
public double getEndKm()
{
double endKm;
if (double.TryParse(endInterpolationKm.Text, out endKm))
return endKm;
return 0;
}
/// <summary>
/// Extract the value of the interpolation interval.
/// </summary>
/// <returns>The interpolation interval.</returns>
public double getInterval()
{
double interval;
if (double.TryParse(interpolationInterval.Text, out interval))
return interval;
return 0;
}
/// <summary>
/// Extract the value of the minimum journey distance threshold.
/// </summary>
/// <returns>The minimum distance of the train journey.</returns>
public double getJourneydistance()
{
double journeyDistance;
if (double.TryParse(minimumJourneyDistance.Text, out journeyDistance))
return journeyDistance * 1000;
return 0;
}
/// <summary>
/// Extract the value of the time difference between succesive data points to be considered as seperate trains.
/// </summary>
/// <returns>The time difference in minutes.</returns>
public double getTimeSeparation()
{
double timeDifference;
if (double.TryParse(timeSeparation.Text, out timeDifference))
return timeDifference * 60;
return 0;
}
/// <summary>
/// Extract the value of the minimum distance between successive data points.
/// </summary>
/// <returns>The minimum distance threshold.</returns>
public double getDataSeparation()
{
double distance;
if (double.TryParse(dataSeparation.Text, out distance))
return distance * 1000;
return 0;
}
/// <summary>
/// Extract the value of the allowable time difference between the stopped train restarting and the through train.
/// </summary>
/// <returns>The time difference in minutes.</returns>
public double getThroguhTrainTimeSeperation()
{
double timeDifference;
if (double.TryParse(throughTrainTime.Text, out timeDifference))
return timeDifference;
return 0;
}
/// <summary>
/// Extract the value of the assumed train length.
/// </summary>
/// <returns>The assumed length of the trains.</returns>
public double getTrainLength()
{
double trainLength;
if (double.TryParse(trainLengthKm.Text, out trainLength))
return trainLength;
return 0;
}
/// <summary>
/// Extract the value of the loop speed factor for comparison to the simulation data.
/// </summary>
/// <returns>The comparison factor.</returns>
public double getTrackSpeedFactor()
{
double trackSpeedFactor;
if (double.TryParse(trackSpeedPercent.Text, out trackSpeedFactor))
return trackSpeedFactor / 100.0;
return 0;
}
/// <summary>
/// Extract the value maximum permissable distance to achieve track speed.
/// </summary>
/// <returns>The assumed length of the trains.</returns>
public double getMaxDistanceToTrackSpeed()
{
double distance;
if (double.TryParse(maxDistanceToTrackSpeed.Text, out distance))
return distance;
return 0;
}
/// <summary>
/// Extract the stopping speed threshold
/// </summary>
/// <returns>The assumed stopping speed of the train.</returns>
public double getStoppingSpeed()
{
double speed;
if (double.TryParse(stoppingThreshold.Text, out speed))
return speed;
return 0;
}
/// <summary>
/// Extract the restart speed threshold
/// </summary>
/// <returns>The assumed restart speed of the train.</returns>
public double getRestartSpeed()
{
double speed;
if (double.TryParse(restartThreshold.Text, out speed))
return speed;
return 0;
}
/// <summary>
/// Extract the maximum permissible transaction time
/// </summary>
/// <returns>The maximum premissible transaction time.</returns>
public double getMaxTransactionTime()
{
double time;
if (double.TryParse(transactionTimeOutlier.Text, out time))
return time;
return 0;
}
/// <summary>
/// Validate the form parameters.
/// </summary>
/// <returns>True if all parameters are valid.</returns>
public bool areParametersValid()
{
if (Settings.dataFile == null)
return false;
if (Settings.geometryFile == null)
return false;
if (Settings.dateRange == null ||
Settings.dateRange[0] > DateTime.Today || Settings.dateRange[1] > DateTime.Today ||
Settings.dateRange[0] > Settings.dateRange[1])
return false;
if (Settings.startInterpolationKm < 0 || Settings.startInterpolationKm > Settings.endInterpolationKm)
return false;
if (Settings.endInterpolationKm < 0 || Settings.endInterpolationKm < Settings.startInterpolationKm)
return false;
if (Settings.interpolationInterval < 0)
return false;
if (Settings.minimumJourneyDistance < 0)
return false;
if (Settings.timethreshold < 0)
return false;
if (Settings.throughTrainTime < 0)
return false;
if (Settings.distanceThreshold < 0)
return false;
if (Settings.trainLength < 0)
return false;
if (Settings.trackSpeedFactor < 0 || Settings.trackSpeedFactor > 1)
return false;
if (Settings.maxDistanceToTrackSpeed < 0)
return false;
if (Settings.stoppingSpeedThreshold < 0)
return false;
if (Settings.restartSpeedThreshold < 0)
return false;
if (Settings.transactionTimeOutlierThreshold < 0)
return false;
return true;
}
/// <summary>
/// Assign the form parameters to the Settings parameters.
/// </summary>
/// <param name="form">The current form object.</param>
public void setFormParameters(TransactionTimeFrom form)
{
Settings.dateRange = form.getDateRange();
Settings.startInterpolationKm = form.getStartKm();
Settings.endInterpolationKm = form.getEndKm();
Settings.interpolationInterval = form.getInterval();
Settings.minimumJourneyDistance = form.getJourneydistance();
Settings.timethreshold = form.getTimeSeparation();
Settings.throughTrainTime = form.getThroguhTrainTimeSeperation();
Settings.distanceThreshold = form.getDataSeparation();
Settings.trainLength = form.getTrainLength();
Settings.trackSpeedFactor = form.getTrackSpeedFactor();
Settings.maxDistanceToTrackSpeed = form.getMaxDistanceToTrackSpeed();
Settings.stoppingSpeedThreshold = form.getStoppingSpeed();
Settings.restartSpeedThreshold = form.getRestartSpeed();
Settings.transactionTimeOutlierThreshold = form.getMaxTransactionTime();
}
/// <summary>
/// Begin process to calaculate the transaction time of the specified corridor.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void ProcessButton_Click(object sender, EventArgs e)
{
/* Create a Timer. */
Timer timer = new Timer();
timer.Interval = 1000; // Set the tick interval to 1 second.
timer.Enabled = true; // Set the time to be running.
timer.Tag = executionTime; // Set the timer label
timer.Tick += new EventHandler(tickTimer); // Event handler function.
/* Start the timer. */
timer.Start();
/* Set up the background threads to run asynchronously. */
BackgroundWorker background = new BackgroundWorker();
background.DoWork += (backgroundSender, backgroundEvents) =>
{
/* Set the form parameters */
setFormParameters(this);
if (areParametersValid())
Algorithm.transactionTime();
else
Tools.messageBox("Some form parameters are invalid", "Invalid Form Parameters");
};
background.RunWorkerCompleted += (backgroundSender, backgroundEvents) =>
{
/* When asynchronous execution complete, reset the timer counter ans stop the clock. */
timeCounter = 0;
stopTheClock = true;
};
background.RunWorkerAsync();
}
/// <summary>
/// Event Handler function for the timeCounter.
/// This display the dynamic execution time of the program.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
void tickTimer(object sender, EventArgs e)
{
/* Stop the timer when stopTheClock is set to true. */
if (stopTheClock)
{
((Timer)sender).Stop();
/* Reset the static timer properties. */
timeCounter = 0;
stopTheClock = false;
return;
}
/* Increment the timer*/
++timeCounter;
/* Convert the timeCounter to hours, minutes and seconds. */
double hours = timeCounter / secPerHour;
double minutes = (hours - (int)hours) * minutesPerHour;
double seconds = (minutes - (int)minutes) * secPerMinute;
/* Format a string for display on the form. */
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", (int)hours, (int)minutes, (int)seconds);
((Label)((Timer)sender).Tag).Text = elapsedTime;
}
/// <summary>
/// Set the Gunnedah basin testing parameters.
/// </summary>
private void setGunnedahBasinParameters()
{
resetDefaultParameters();
GunnedahBasinParameters.Checked = true;
string internalDirectory = @"S:\Corporate Strategy\Infrastructure Strategies\Simulations\Train Performance Analysis\Gunned<NAME>";
/* Data File */
Settings.dataFile = internalDirectory + @"\Gunnedah Basin Data 201701-201706 - all trains.txt"; //Gunnedah Basin Data 2016-2017 PN+QR.txt
dataFilename.Text = Path.GetFileName(Settings.dataFile);
dataFilename.ForeColor = SystemColors.ActiveCaptionText;
/* Geometry File */
Settings.geometryFile = internalDirectory + @"\Gunnedah Basin Geometry.csv";
geometryFilename.Text = Path.GetFileName(Settings.geometryFile);
geometryFilename.ForeColor = SystemColors.ActiveCaptionText;
/* Simulation files */
Settings.actualAveragePerformanceFile = internalDirectory + @"\AverageSpeed Jan2019.csv"; //PacificNational-Increasing.csv";
actualAveragePerformanceFile.Text = Path.GetFileName(Settings.actualAveragePerformanceFile);
actualAveragePerformanceFile.ForeColor = SystemColors.ActiveCaptionText;
/* Destination Folder */
Settings.aggregatedDestination = internalDirectory;
destinationDirectory.Text = Settings.aggregatedDestination;
destinationDirectory.ForeColor = SystemColors.ActiveCaptionText;
/* Settings */
fromDate.Value = new DateTime(2019, 1, 1); // 2017, 1, 1
toDate.Value = new DateTime(2019, 2, 1); // 2017, 4, 1
startInterpolationKm.Text = "280";
endInterpolationKm.Text = "540";
interpolationInterval.Text = "50";
minimumJourneyDistance.Text = "20"; // 250
dataSeparation.Text = "4";
timeSeparation.Text = "10";
trainLengthKm.Text = "1.3"; // train length is 1335 m
trackSpeedPercent.Text = "90";
maxDistanceToTrackSpeed.Text = "5";
throughTrainTime.Text = "10";
stoppingThreshold.Text = "5";
restartThreshold.Text = "10";
transactionTimeOutlier.Text = "10";
Settings.analysisCategory = analysisCategory.TrainOperator;
PacificNational.Checked = true;
Settings.PacificNational = true;
Aurizon.Checked = true;
Settings.Aurizon = true;
CombineOperators.Checked = true;
Settings.Combined = true;
}
/// <summary>
/// Set the Ulan Line testing parameters.
/// </summary>
private void setUlanLineParameters()
{
resetDefaultParameters();
UlanLineParameters.Checked = true;
string internalDirectory = @"S:\Corporate Strategy\Infrastructure Strategies\Simulations\Train Performance Analysis\Ulan";
/* Data File */
Settings.dataFile = internalDirectory + @"\Ulan Data 2017-201709.txt"; //Ulan Data 2017-20170531-2.txt
dataFilename.Text = Path.GetFileName(Settings.dataFile);
dataFilename.ForeColor = SystemColors.ActiveCaptionText;
/* Geometry File */
Settings.geometryFile = internalDirectory + @"\Ulan Geometry.csv";
geometryFilename.Text = Path.GetFileName(Settings.geometryFile);
geometryFilename.ForeColor = SystemColors.ActiveCaptionText;
/* Simulation files */
Settings.actualAveragePerformanceFile = internalDirectory + @"\Ulan Actual Average Trains.csv";
actualAveragePerformanceFile.Text = Path.GetFileName(Settings.actualAveragePerformanceFile);
actualAveragePerformanceFile.ForeColor = SystemColors.ActiveCaptionText;
/* Destination Folder */
Settings.aggregatedDestination = internalDirectory;
destinationDirectory.Text = Settings.aggregatedDestination;
destinationDirectory.ForeColor = SystemColors.ActiveCaptionText;
/* Settings */
fromDate.Value = new DateTime(2017, 1, 2); // 2017, 1, 1
toDate.Value = new DateTime(2017, 1, 3); // 2017, 4, 1
startInterpolationKm.Text = "280";
endInterpolationKm.Text = "460";
interpolationInterval.Text = "50";
minimumJourneyDistance.Text = "5"; // 250
dataSeparation.Text = "4";
timeSeparation.Text = "10";
trainLengthKm.Text = "1.5";
trackSpeedPercent.Text = "90";
maxDistanceToTrackSpeed.Text = "5";
throughTrainTime.Text = "10";
stoppingThreshold.Text = "5";
restartThreshold.Text = "10";
transactionTimeOutlier.Text = "10";
Settings.analysisCategory = analysisCategory.TrainOperator;
PacificNational.Checked = true;
Settings.PacificNational = true;
Freightliner.Checked = true;
Settings.Freightliner = true;
Aurizon.Checked = true;
Settings.Aurizon = true;
CombineOperators.Checked = true;
Settings.Combined = true;
}
/// <summary>
/// Function determines if the testing parameters for the Gunnedah basin
/// need to be set, or resets the default settings.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void GunnedahBasinParameters_CheckedChanged(object sender, EventArgs e)
{
/* If Gunnedah testing flag is checked, set the appropriate parameters. */
if (GunnedahBasinParameters.Checked)
setGunnedahBasinParameters();
else
resetDefaultParameters();
}
/// <summary>
/// Function determines if the testing parameters for the Ulan line
/// need to be set, or resets the default settings.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void UlanLineParameters_CheckedChanged(object sender, EventArgs e)
{
/* If Ulan testing flag is checked, set the appropriate parameters. */
if (UlanLineParameters.Checked)
setUlanLineParameters();
else
resetDefaultParameters();
}
/// <summary>
/// function resets the train performance analysis form to default settings.
/// </summary>
private void resetDefaultParameters()
{
/* Data File */
Settings.dataFile = null;
dataFilename.Text = "<Select data file>";
dataFilename.ForeColor = SystemColors.InactiveCaptionText;
/* Geometry File */
Settings.geometryFile = null;
geometryFilename.Text = "<Select geometry file>";
geometryFilename.ForeColor = SystemColors.InactiveCaptionText;
/* Simulation files */
Settings.actualAveragePerformanceFile = null;
actualAveragePerformanceFile.Text = "<Select a simualtion file>";
actualAveragePerformanceFile.ForeColor = SystemColors.InactiveCaptionText;
/* Destination Folder */
Settings.aggregatedDestination = null;
destinationDirectory.Text = "<Select directory>";
destinationDirectory.ForeColor = SystemColors.InactiveCaptionText;
/* Settings */
fromDate.Value = new DateTime(2016, 1, 1);
toDate.Value = new DateTime(2016, 2, 1);
startInterpolationKm.Text = "0";
endInterpolationKm.Text = "100";
interpolationInterval.Text = "50";
minimumJourneyDistance.Text = "80";
dataSeparation.Text = "4";
timeSeparation.Text = "10";
trainLengthKm.Text = "1.5";
trackSpeedPercent.Text = "90";
maxDistanceToTrackSpeed.Text = "5";
throughTrainTime.Text = "10";
stoppingThreshold.Text = "5";
restartThreshold.Text = "10";
transactionTimeOutlier.Text = "10";
Settings.analysisCategory = analysisCategory.Unknown;
Settings.PacificNational = false;
Settings.Aurizon = false;
Settings.Freightliner = false;
Settings.CityRail = false;
Settings.CountryLink = false;
Settings.Qube = false;
Settings.SCT = false;
Settings.Combined = false;
PacificNational.Checked = false;
Aurizon.Checked = false;
Freightliner.Checked = false;
CityRail.Checked = false;
CountryLink.Checked = false;
Qube.Checked = false;
SCT.Checked = false;
CombineOperators.Checked = false;
}
private void PacificNational_CheckedChanged(object sender, EventArgs e)
{
}
/// <summary>
/// This sets the Pacific National Operator to the appropriate value in order
/// to dynamically include Pacific National trains in teh analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void PacificNational_Click(object sender, EventArgs e)
{
Settings.PacificNational = PacificNational.Checked;
}
/// <summary>
/// This sets the Freightliner Operator to the appropriate value in order
/// to dynamically include Freightliner trains in teh analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void FreightLiner_Click(object sender, EventArgs e)
{
Settings.Freightliner = Freightliner.Checked;
}
/// <summary>
/// This sets the Aurizon Operator to the appropriate value in order
/// to dynamically include Aurizon trains in the analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void Aurizon_Click(object sender, EventArgs e)
{
Settings.Aurizon = Aurizon.Checked;
}
/// <summary>
/// This sets the City Rail Operator to the appropriate value in order
/// to dynamically include City Rail trains in the analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void CityRail_Click(object sender, EventArgs e)
{
Settings.CityRail = CityRail.Checked;
}
/// <summary>
/// This sets the Country Link Operator to the appropriate value in order
/// to dynamically include Country Link trains in the analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void CountryLink_Click(object sender, EventArgs e)
{
Settings.CountryLink = CountryLink.Checked;
}
/// <summary>
/// This sets the Spare Operator to the appropriate value in order
/// to dynamically include Spare trains in the analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void Qube_Click(object sender, EventArgs e)
{
Settings.Qube = Qube.Checked;
}
/// <summary>
/// This sets the Spare Operator to the appropriate value in order
/// to dynamically include Spare trains in the analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void SCT_Click(object sender, EventArgs e)
{
Settings.SCT = SCT.Checked;
}
/// <summary>
/// This sets the Combined Operator to the appropriate value in order
/// to dynamically include acombination of train operators in the analysis.
/// </summary>
/// <param name="sender">The object container.</param>
/// <param name="e">The event arguments.</param>
private void Combined_Click(object sender, EventArgs e)
{
Settings.Combined = CombineOperators.Checked;
}
}
}
| 87b6269dbb428a94891539b3f966fd559a146b61 | [
"C#"
] | 4 | C# | beaubellamy/Transaction-Time | d94a594ff0dd429d6c66cf789ba060fb8842a43e | 25423e1ee2e43dd1b55224d72f107f3057a60a58 |
refs/heads/master | <repo_name>pinkston4/Ex_Guinea_Pig<file_sep>/events.js
//Variables
var headerEvent = document.getElementById("page-title");
var inputField = document.getElementById("keypress-input");
var outPutField = document.getElementById("output-target");
var guineaPig = document.getElementById("guinea-pig");
var addColor = document.getElementById("add-color");
var hulkify = document.getElementById("make-large");
var addBorder = document.getElementById("add-border");
var rounding = document.getElementById("add-rounding");
var sections = document.getElementsByClassName("article-section");
var buttons = document.getElementsByTagName("button");
//Event Listeners
//if the mouse if over the header output 1st function
//if the the mouse leaves the header then function 2 runs
headerEvent.addEventListener("mouseover", function (event) {
outPutField.innerHTML = "You moved your mouse over the header.";
});
headerEvent.addEventListener("mouseleave", function (event) {
outPutField.innerHTML = "You left me!";
});
//section click- if the section is clicked, notify in the output field that the user clicked on that section
for(var i = 0; i < sections.length; i++ ) {
sections[i].addEventListener("click", function(event) {
outPutField.innerHTML = "You clicked on, " + event.target.innerHTML;
});
};
//mirroring the input in the output field using event listener
//problem-question for instructor: why does this output character from the previous keypress and not the current?
inputField.addEventListener("keypress", function (event) {
outPutField.innerHTML = inputField.value;
});
//event listeners for the buttons
addColor.addEventListener("click", makeItColorful);
hulkify.addEventListener("click", makeItBig);
addBorder.addEventListener("click", giveItBorder);
rounding.addEventListener("click", roundItOut);
//functions
function makeItColorful () {
guineaPig.style.color = 'blue';
}
function makeItBig () {
guineaPig.style.fontSize = '3em';
}
function giveItBorder () {
guineaPig.style.border = '1px solid black';
}
function roundItOut () {
guineaPig.style.borderRadius = '15%';
}
//styling
sections[0].style.fontWeight = 'bold';
sections[5].style.fontWeight = 'bold';
sections[5].style.fontStyle = 'italic';
buttons[0].style.display = 'block';
buttons[1].style.display = 'block';
buttons[2].style.display = 'block';
buttons[3].style.display = 'block';
| 280328f8964ad85e23900a58694bfa857b71d9db | [
"JavaScript"
] | 1 | JavaScript | pinkston4/Ex_Guinea_Pig | 3dfd5de9b9da0e1065f6d9c0f1bba9b4feb53a3c | 594a295a4b0025b88d548f58110d0036ca2e2540 |
refs/heads/master | <repo_name>jjmengze/micro<file_sep>/auth/handler/handler.go
package handler
import (
"context"
"time"
"github.com/micro/go-micro/v2/auth"
"github.com/micro/go-micro/v2/config/cmd"
"github.com/micro/go-micro/v2/errors"
"github.com/micro/go-micro/v2/store"
pb "github.com/micro/go-micro/v2/auth/service/proto"
)
// New returns an instance of Handler
func New() *Handler {
return &Handler{
auth: *cmd.DefaultOptions().Auth,
store: *cmd.DefaultOptions().Store,
}
}
var (
// Duration the service account is valid for
Duration = time.Hour * 24
)
// Handler processes RPC calls
type Handler struct {
store store.Store
auth auth.Auth
}
// Generate creates a new account in the store
func (h *Handler) Generate(ctx context.Context, req *pb.GenerateRequest, rsp *pb.GenerateResponse) error {
if req.Account == nil {
return errors.BadRequest("go.micro.auth", "account required")
}
if req.Account.Id == "" {
return errors.BadRequest("go.micro.auth", "account id required")
}
opts := []auth.GenerateOption{}
if req.Account.Metadata != nil {
opts = append(opts, auth.Metadata(req.Account.Metadata))
}
if req.Account.Roles != nil {
roles := make([]*auth.Role, len(req.Account.Roles))
for i, r := range req.Account.Roles {
var resouce *auth.Resource
if r.Resource != nil {
resouce = &auth.Resource{
Name: r.Resource.Name,
Type: r.Resource.Type,
}
}
roles[i] = &auth.Role{
Name: r.Name,
Resource: resouce,
}
}
opts = append(opts, auth.Roles(roles))
}
acc, err := h.auth.Generate(req.Account.Id, opts...)
if err != nil {
return err
}
// encode the response
rsp.Account = serializeAccount(acc)
return nil
}
// Verify retrieves a account from the store
func (h *Handler) Verify(ctx context.Context, req *pb.VerifyRequest, rsp *pb.VerifyResponse) error {
if req.Token == "" {
return errors.BadRequest("go.micro.auth", "token required")
}
acc, err := h.auth.Verify(req.Token)
if err != nil {
return err
}
rsp.Account = serializeAccount(acc)
return nil
}
// Revoke deletes the account
func (h *Handler) Revoke(ctx context.Context, req *pb.RevokeRequest, rsp *pb.RevokeResponse) error {
if req.Token == "" {
return errors.BadRequest("go.micro.auth", "token required")
}
return h.auth.Revoke(req.Token)
}
func serializeAccount(acc *auth.Account) *pb.Account {
res := &pb.Account{
Id: acc.Id,
Created: acc.Created.Unix(),
Expiry: acc.Expiry.Unix(),
Metadata: acc.Metadata,
Token: acc.Token,
Roles: make([]*pb.Role, len(acc.Roles)),
}
for i, r := range acc.Roles {
res.Roles[i] = &pb.Role{Name: r.Name}
if r.Resource != nil {
res.Roles[i].Resource = &pb.Resource{
Name: r.Resource.Name,
Type: r.Resource.Type,
}
}
}
return res
}
<file_sep>/auth/auth.go
package auth
import (
"fmt"
"os"
"github.com/micro/cli/v2"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/auth"
srvAuth "github.com/micro/go-micro/v2/auth/service"
pb "github.com/micro/go-micro/v2/auth/service/proto"
"github.com/micro/go-micro/v2/config/cmd"
log "github.com/micro/go-micro/v2/logger"
"github.com/micro/go-micro/v2/util/config"
"github.com/micro/micro/v2/auth/api"
"github.com/micro/micro/v2/auth/handler"
"github.com/micro/micro/v2/auth/web"
)
var (
// Name of the service
Name = "go.micro.auth"
// Address of the service
Address = ":8010"
)
// run the auth service
func run(ctx *cli.Context, srvOpts ...micro.Option) {
log.Init(log.WithFields(map[string]interface{}{"service": "auth"}))
// Init plugins
for _, p := range Plugins() {
p.Init(ctx)
}
if len(ctx.String("address")) > 0 {
Address = ctx.String("address")
}
if len(Address) > 0 {
srvOpts = append(srvOpts, micro.Address(Address))
}
// Init plugins
for _, p := range Plugins() {
p.Init(ctx)
}
// setup service
srvOpts = append(srvOpts, micro.Name(Name))
service := micro.NewService(srvOpts...)
// run service
pb.RegisterAuthHandler(service.Server(), handler.New())
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
func authFromContext(ctx *cli.Context) auth.Auth {
if ctx.Bool("platform") {
os.Setenv("MICRO_PROXY", "service")
os.Setenv("MICRO_PROXY_ADDRESS", "proxy.micro.mu:443")
return srvAuth.NewAuth()
}
return *cmd.DefaultCmd.Options().Auth
}
// login using a token
func login(ctx *cli.Context) {
if ctx.Args().Len() != 1 {
fmt.Println("Usage: `micro login [token]`")
os.Exit(1)
}
token := ctx.Args().First()
// Execute the request
acc, err := authFromContext(ctx).Verify(token)
if err != nil {
fmt.Println(err)
os.Exit(1)
} else if acc == nil {
fmt.Printf("[%v] did not generate an account\n", authFromContext(ctx).String())
os.Exit(1)
}
// Store the token in micro config
if err := config.Set("token", token); err != nil {
fmt.Println(err)
os.Exit(1)
}
// Inform the user
fmt.Println("You have been logged in")
}
func Commands(srvOpts ...micro.Option) []*cli.Command {
commands := []*cli.Command{
&cli.Command{
Name: "auth",
Usage: "Run the auth service",
Action: func(ctx *cli.Context) error {
run(ctx)
return nil
},
Subcommands: append([]*cli.Command{
{
Name: "api",
Usage: "Run the auth api",
Description: "Run the auth api",
Action: func(ctx *cli.Context) error {
api.Run(ctx, srvOpts...)
return nil
},
},
{
Name: "web",
Usage: "Run the auth web",
Description: "Run the auth web",
Action: func(ctx *cli.Context) error {
web.Run(ctx, srvOpts...)
return nil
},
},
}),
Flags: []cli.Flag{
&cli.StringFlag{
Name: "address",
Usage: "Set the auth http address e.g 0.0.0.0:8010",
EnvVars: []string{"MICRO_SERVER_ADDRESS"},
},
&cli.StringFlag{
Name: "auth_provider",
EnvVars: []string{"MICRO_AUTH_PROVIDER"},
Usage: "Auth provider enables account generation",
},
},
},
&cli.Command{
Name: "login",
Usage: "Login using a token",
Action: func(ctx *cli.Context) error {
login(ctx)
return nil
},
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "platform",
Usage: "Connect to the platform",
Value: false,
},
},
},
}
for _, c := range commands {
for _, p := range Plugins() {
if cmds := p.Commands(); len(cmds) > 0 {
c.Subcommands = append(c.Subcommands, cmds...)
}
if flags := p.Flags(); len(flags) > 0 {
c.Flags = append(c.Flags, flags...)
}
}
}
return commands
}
| aaaca2880cf924b522cb9fe3bbf6f2bdf8dc07f2 | [
"Go"
] | 2 | Go | jjmengze/micro | 2de620e5c09bcc84eac38b63b7402f3213d4c176 | a89523381929632a472fcb5806e95fff7babe15e |
refs/heads/master | <repo_name>abiskop/geo-ip-service<file_sep>/vagrant/run-chef-solo.sh
CONFIG=/media/geoip/vagrant/config/$CHEFENV.rb
sudo chef-solo -c $CONFIG -o "recipe[apt]","recipe[geo-ip-service]"
<file_sep>/configure.sh
bash make-cookbook.sh
(cd vagrant && librarian-chef install)
<file_sep>/chef/geo-ip-service/recipes/default.rb
include_recipe "geo-ip-service::install"
include_recipe "geo-ip-service::configure-db-cron-job"
include_recipe "geo-ip-service::configure-upstart"
<file_sep>/chef/geo-ip-service/files/default/geo-ip-service/lib/lookup.js
var exec = require('child_process').exec
return module.exports = {
create: create
}
function create(config) {
return {
lookup: lookup
}
function lookup(ip, done) {
var options = {
timeout: 10000,
maxBuffer: 1024*1024
}
var cliCommand = config.command
exec(cliCommand + ' ' + ip, options, function(err, stdout, stderr) {
if (err) return done(new Error(err + ' ' + stdout + ' ' + stderr))
if (ipWasNotFound(stdout)) return done()
/* geoiplookup prints something like: "GeoIP Country Edition: GB, United Kingdom" */
var values = stdout.replace('GeoIP Country Edition: ', '')
.split(',')
.map(function(value) { return value.trim() })
var countryCode = values[0]
var country = values[1]
if (!country || !countryCode) return done()
return done(null, {
country: country,
countryCode: countryCode
})
})
}
}
function ipWasNotFound(geoiplookupOutput) {
/* if no location was found, geoiplookup prints: "GeoIP Country Edition: IP Address not found" */
return !geoiplookupOutput || (geoiplookupOutput.indexOf('not found') > 0)
}<file_sep>/chef/geo-ip-service/recipes/configure-upstart.rb
template "/etc/init/geoip.conf" do
source "geo-ip-service-upstart.erb"
owner "root"
group "root"
mode 00644
variables({
:installdir => node["geo-ip-service"]["install-dir"],
:logdir => node["geo-ip-service"]["log-dir"]
})
end
service "geoip" do
provider Chef::Provider::Service::Upstart
supports :start => true, :restart => true, :stop => true, :status => true
action [:enable, :start]
notifies :restart, "service[geoip]", :delayed
end
<file_sep>/lib/validate.js
var ipAddressRegex = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/
return module.exports = {
that: that
}
function that(validatee) {
return {
isAnIpAddress: function() {
return ipAddressRegex.test(validatee)
}
}
}<file_sep>/chef/geo-ip-service/files/default/geo-ip-service/lib/routes.js
var restify = require('restify')
var url = require('url')
var validate = require('./validate')
return module.exports = {
create: create
}
function create(service, config) {
var doLookup = require('./lookup').create(config.geoiplookup_cli).lookup
service.get('/', getIndex)
service.get('/lookup', getLookup)
function getIndex(req, res, next) {
res.send({
status: 'ok',
urls: {
lookup: {
method: 'GET',
url: url.resolve(config.service.publicBaseUrl, '/lookup?ip={ip}')
}
}
})
return next()
}
function getLookup(req, res, next) {
var ip = req.query.ip
if (!ip) return next(new restify.BadRequestError())
if (!validate.that(ip).isAnIpAddress()) return next(new restify.BadRequestError())
doLookup(ip, function(err, location) {
if (err) {
log.error(err)
return next(new restify.InternalServerError())
}
if (!location) return next(new restify.NotFoundError())
res.send({ location: location })
return next()
})
}
}
<file_sep>/make-cookbook.sh
set -e
set -x
TARGET_DIR="chef/geo-ip-service/files/default/geo-ip-service"
cp -r ./conf $TARGET_DIR
cp -r ./lib $TARGET_DIR
cp -r ./node_modules $TARGET_DIR
cp ./LICENSE $TARGET_DIR
cp ./npm-shrinkwrap.json $TARGET_DIR
cp ./package.json $TARGET_DIR
cp ./README.md $TARGET_DIR
<file_sep>/vagrant/Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "precise64"
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
config.omnibus.chef_version = :latest
config.vm.define :geoip do |localConfig|
localConfig.vm.network :private_network, ip: "192.168.50.70"
localConfig.vm.network :forwarded_port, host: 7000, guest: 7000
localConfig.vm.synced_folder "../", "/media/geoip"
#localConfig.vm.provision :shell,
# :inline => "CHEFENV=vagrant bash /media/geoip/vagrant/run-chef-solo.sh"
localConfig.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "./cookbooks"
chef.add_recipe "apt"
chef.add_recipe "geo-ip-service"
end
end
end
<file_sep>/chef/geo-ip-service/attributes/default.rb
default["nodejs"]["install_method"] = "binary"
default["geo-ip-service"]["install-dir"] = "/opt/geoip"
default["geo-ip-service"]["log-dir"] = "/var/log/geoip"
default["geo-ip-service"]["port"] = 7000
default["geo-ip-service"]["public-base-url"] = "http://localhost:7000"
default["geo-ip-service"]["cron-mailto"] = nil<file_sep>/chef/geo-ip-service/files/default/geo-ip-service/conf/config.js
return module.exports = {
service: {
port: 7000,
publicBaseUrl: 'http://localhost:7000',
},
geoiplookup_cli: {
// TODO: this should be something like "geoiplookup -f somefile" once DB file is set up via cron/wget
command: 'geoiplookup '
}
}<file_sep>/chef/geo-ip-service/recipes/configure-db-cron-job.rb
cron "update_geoip_database" do
## TODO: interval should be configurable
minute "0"
hour "1"
weekday "3" ## wednesday
user "root"
mailto node["geo-ip-service"]["cron-mailto"]
## dirty: hardcoded use of apt-get to upgrade package
command "apt-get update && apt-get install --only-upgrade geoip-database"
end<file_sep>/test/index.js
var assert = require('assert')
var request = require('superagent')
var url = require('url')
var config = require('../conf/config.js')
describe('geo-ip-service', function() {
describe('index', function() {
it('should return 200 OK with lookup url when it is running', function(done) {
request.get(makeUrl('/')).end(function(res) {
assert.equal(res.status, 200)
assert.ok(res.body.urls.lookup.url)
assert.ok(res.body.urls.lookup.method)
done()
})
})
})
describe('lookup', function() {
it('should return 400 Bad Request if no IP address specified', function(done) {
request.get(makeUrl('/lookup')).end(function(res) {
assert.equal(res.status, 400)
done()
})
})
it('should return 400 Bad Request if malformed IP address specified', function(done) {
request.get(makeUrl('/lookup?ip=asdf')).end(function(res) {
assert.equal(res.status, 400)
done()
})
})
it('should return 404 if no location for IP address available', function(done) {
request.get(makeUrl('/lookup?ip=127.0.0.1')).end(function(res) {
assert.equal(res.status, 404)
done()
})
})
it('should return location if available for IP address', function(done) {
var expectedLocation = {
country: 'Germany',
countryCode: 'DE'
}
request.get(makeUrl('/lookup?ip=192.168.3.11')).end(function(res) {
assert.equal(res.status, 200)
assert.deepEqual(res.body.location, expectedLocation)
done()
})
})
})
})
function makeUrl(relPath) {
return url.resolve(config.service.publicBaseUrl, relPath)
}<file_sep>/chef/geo-ip-service/metadata.rb
name 'geo-ip-service'
maintainer '<NAME>'
maintainer_email '<EMAIL>'
#license 'TODO'
description 'Installs node, configures geo-ip-service as an upstart service and sets up a cron job to download GeoLite Land DB.'
version '0.0.1'
provides "geo-ip-service"
recipe "geo-ip-service", "Installs node, configures geo-ip-service as an upstart service and sets up a cron job to download GeoLite Land DB."
depends "nodejs"
<file_sep>/chef/geo-ip-service/files/default/geo-ip-service/README.md
geo-ip-service
==============
A simple node.js service that performs a geo-lookup on IP addresses using the [geoiplookup](http://manpages.ubuntu.com/manpages/hardy/man1/geoiplookup.1.html) command line tool and the free [GeoLite Country Database](http://dev.maxmind.com/geoip/legacy/geolite/).
##Documentation
###Routes
####`GET /`
Returns
- `HTTP 200 OK` with status information if service is running
####`GET /lookup?ip={ip}`
Expects
- `ip` query parameter: an IP address
Returns
- `HTTP 200 OK` with JSON response body, if lookup was successful:
``` js
{
"countryCode": "GB",
"country": "United Kingdom"
}
```
- `HTTP 404 Not Found` if no location could be found for the given IP address
- `HTTP 400 Bad Request` if a malformed or no IP address was given
###Running Tests
Requirements:
- a VM provider, preferrably VirtualBox
-- tested with VirtualBox v4.1, Guest Additions v4.2.0
- vagrant
- vagrant-omnibus
- librarian-chef
Make/install cookbooks:
```
bash make-cookbook.sh
(cd vagrant && librarian-chef install)
```
Start the Vagrant box:
```
(cd vagrant && vagrant destroy -f && vagrant up)
```
Run tests against the Vagrant box:
```
npm test
```
When making changes to the source code, run `bash make-cookbook.sh && (cd vagrant && vagrant provision)` in order to re-provision the box before re-running tests via `npm test`.
###License
This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com.
<file_sep>/chef/geo-ip-service/recipes/install.rb
include_recipe "nodejs"
package "geoip-bin" do
action :upgrade
end
package "geoip-database" do
action :upgrade
end
user "geoip" do
system true
end
directory node["geo-ip-service"]["install-dir"] do
owner "root"
group "root"
mode 00775
end
directory node["geo-ip-service"]["log-dir"] do
owner "geoip"
group "geoip"
end
remote_directory "copy_to_install_dir" do
recursive true
path node["geo-ip-service"]["install-dir"]
source "geo-ip-service"
files_owner "root"
files_group "root"
files_mode 00775
end
template "config.js" do
path node["geo-ip-service"]["install-dir"] + "/conf/config.js"
source "config.js.erb"
owner "root"
group "root"
mode 00775
variables({
:port => node["geo-ip-service"]["port"],
:publicBaseUrl => node["geo-ip-service"]["public-base-url"]
})
notifies :restart, "service[geoip]", :delayed
end
<file_sep>/vagrant/config/vagrant.rb
cookbook_path "/media/geoip/vagrant/cookbooks"
# role_path "/media/geoip/vagrant/roles"
# environment_path "/media/geoip/vagrant/environments"
# environment "vagrant"
| 642da360029c4818c1ab604d8751cd4ac9608427 | [
"JavaScript",
"Ruby",
"Markdown",
"Shell"
] | 17 | Shell | abiskop/geo-ip-service | 6a10c3da7a4c886b2a5ed9de7029a0a8a67bc83d | 2effd04b34d521e3f1472e91bac79f3d0e54f96c |
refs/heads/master | <file_sep>package com.apps.indiclass.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.apps.indiclass.R;
import com.apps.indiclass.model.DemandData;
import com.apps.indiclass.util.Constant;
import com.apps.indiclass.util.Method;
import com.bumptech.glide.Glide;
import java.util.List;
/**
* Created by Dell_Cleva on 16/10/2018.
*/
public class DemandAdapter extends RecyclerView.Adapter<DemandAdapter.MyViewHolder> {
private final OnItemClickListener listener;
private Context context;
private List<DemandData> progamModels;
public DemandAdapter(Context context, List<DemandData> progamModelList, OnItemClickListener listener) {
this.context = context;
this.progamModels = progamModelList;
this.listener = listener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.demand_row_item, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final DemandData progamModel = progamModels.get(position);
holder.name.setText(progamModel.getUser_name());
holder.price.setText(Method.getFormatIDR(progamModel.getHarga()));
holder.v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onItemClick(progamModel);
}
});
Glide.with(context)
.load(progamModel.getUser_image())
.into(holder.thumbnail);
}
@Override
public int getItemCount() {
return progamModels.size();
}
public interface OnItemClickListener {
void onItemClick(DemandData item);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, price, subject, exp;
public ImageView thumbnail;
View v;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.tvNameT);
exp = view.findViewById(R.id.tvExpT);
subject = view.findViewById(R.id.tvSubjectT);
price = view.findViewById(R.id.tvPriceT);
thumbnail = view.findViewById(R.id.imageView1);
v = view.findViewById(R.id.rlTutorItem);
}
}
}
<file_sep>package com.apps.indiclass;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.apps.indiclass.model.TutorModel;
import com.apps.indiclass.util.Constant;
import com.bumptech.glide.Glide;
public class TutorActivity extends AppCompatActivity {
private static final String TAG = "TutorActivity";
TextView tvNama, tvExp, tvCountry, tvDesc, tvSiswa, tvKelas, tvUlasan;
ImageView imgT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutor);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
setTitle("Detail Tutor");
TutorModel tm = getIntent().getParcelableExtra("data");
imgT = findViewById(R.id.icon_play);
tvNama = findViewById(R.id.tvNameT);
tvExp = findViewById(R.id.tvExpT);
tvCountry = findViewById(R.id.tvSubjectT);
tvDesc = findViewById(R.id.tvDescT);
tvSiswa = findViewById(R.id.tvfollower);
tvKelas = findViewById(R.id.tvclassall);
tvUlasan = findViewById(R.id.tvreview);
tvNama.setText(tm.getsNameTutor());
tvExp.setText(tm.getsExpTutor());
tvCountry.setText(tm.getsSubjectTutor());
Glide.with(this)
.load(Constant.ImageTutor+tm.getsImageTutor())
.into(imgT);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>package com.apps.indiclass;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.apps.indiclass.api.ApiCall;
import com.apps.indiclass.api.ApiUtils;
import com.apps.indiclass.model.ChangePassRest;
import com.apps.indiclass.util.Constant;
import com.apps.indiclass.util.SessionManager;
import org.json.JSONObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ChangePasswordActivity extends AppCompatActivity {
private static final String TAG = "ChangePasswordActivity";
TextInputLayout passwordWrapper, password1Wrapper, password2Wrapper;
SessionManager session;
JSONObject doschedule = new JSONObject();
Button btnChange;
int id_user;
boolean status;
String msg, sToken, rpass1 = "", rpass2 = "";
AlertDialog b;
AlertDialog.Builder dialogBuilder;
ApiCall mAPIService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_password);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
setTitle(getString(R.string.change_password));
session = new SessionManager(this);
id_user = Integer.parseInt(session.getIds());
sToken = session.getToken();
mAPIService = ApiUtils.getRestAPI(Constant.BASE_URL);
passwordWrapper = findViewById(R.id.passwordr1Wrappero);
password1Wrapper = findViewById(R.id.passwordr1Wrapper);
password2Wrapper = findViewById(R.id.passwordr2Wrapper);
btnChange = findViewById(R.id.buttoncpass);
btnChange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rpass1 = password1Wrapper.getEditText().getText().toString();
rpass2 = password2Wrapper.getEditText().getText().toString();
if (passwordWrapper.getEditText().getText().length() == 0) {
passwordWrapper.setError(getString(R.string.cannot_empty));
passwordWrapper.requestFocus();
} else if (rpass1.equals("")) {
password1Wrapper.setError(getString(R.string.cannot_empty));
password1Wrapper.requestFocus();
} else if (!rpass1.equals(rpass2)) {
password2Wrapper.setError(getString(R.string.password_not_match));
password2Wrapper.requestFocus();
} else {
mAPIService.changePassword(String.valueOf(id_user), passwordWrapper.getEditText().getText().toString(), password2Wrapper.getEditText().getText().toString()).enqueue(new Callback<ChangePassRest>() {
@Override
public void onResponse(Call<ChangePassRest> call, Response<ChangePassRest> response) {
if (response.body() != null) {
if (response.body().isStatus()) {
Toast.makeText(ChangePasswordActivity.this, getString(R.string.succes_change_password), Toast.LENGTH_SHORT).show();
passwordWrapper.getEditText().setText("");
password1Wrapper.getEditText().setText("");
password2Wrapper.getEditText().setText("");
} else {
Toast.makeText(ChangePasswordActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<ChangePassRest> call, Throwable t) {
}
});
}
}
});
CloseError(passwordWrapper);
CloseError(password1Wrapper);
CloseError(password2Wrapper);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public void CloseError(final TextInputLayout v) {
v.getEditText().addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable edt) {
if (v.getEditText().getText().length() > 0) {
v.setError(null);
v.setErrorEnabled(false);
}
}
});
}
public void ShowProgressDialog() {
dialogBuilder = new AlertDialog.Builder(ChangePasswordActivity.this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.progress_dialog_layout, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setCancelable(false);
b = dialogBuilder.create();
b.show();
}
public void HideProgressDialog() {
b.dismiss();
}
}
<file_sep>package com.apps.indiclass.api;
import com.apps.indiclass.model.ChangePassRest;
import com.apps.indiclass.model.ClassRest;
import com.apps.indiclass.model.LoginResponse;
import com.apps.indiclass.model.DemandRest;
import com.apps.indiclass.model.LoginRest;
import com.apps.indiclass.model.SendReqRest;
import com.apps.indiclass.model.SessionRest;
import com.apps.indiclass.model.StaticDRest;
import com.apps.indiclass.model.SubjectRest;
import com.apps.indiclass.model.TutorRest;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Created by Dell_Cleva on 08/11/2018.
*/
public interface ApiCall {
@POST("login")
@FormUrlEncoded
Call<LoginRest> login(@Field("email") String email,
@Field("password") String password);
@POST("scheduleone/access_token/{token}")
@FormUrlEncoded
Call<ClassRest> myclass(@Field("id_user") String id_user,
@Field("date") String date,
@Field("user_utc") String utc,
@Path("token") String stoken);
@GET("allsubject_bytutor/id_user/{id_user}/access_token/{token}")
Call<TutorRest> gettutor(@Path("id_user") String iduser, @Path("token") String token);
@GET("allsubject/id_user/{id_user}/access_token/{token}/for/tutor")
Call<SubjectRest> getsubject(@Path("id_user") String iduser, @Path("token") String token);
@GET("ajax_get_ondemand")
Call<DemandRest> requestsearch(@Query("subject_id") String subid, @Query("dtrq") String tgl,
@Query("tmrq") String time, @Query("drrq") String dur,
@Query("user_utc") String utc);
//"?start_time=" + ECTime + "&tutor_id=" + av_id + "&subject_id=" + ECSubid + "&duration=" + ECDuration + "&date="
// + ECTgl + "&id_user=" + id_user + "&username=" + sUsername + "&user_utc=" + Method.getUTCTime() + "&access_token=" + sessionManager.getToken() + "&topic=" + ECTopic
// + "&hr=" + ECTimes[position] + "&hrt=" + ECHargaT[position]
@GET("requestprivate")
Call<SendReqRest> sendreqprivate(@Query("start_time") String start_time, @Query("tutor_id") String tutor_id,
@Query("subject_id") String subject_id, @Query("duration") String duration,
@Query("date") String date, @Query("id_user") String id_user,
@Query("user_utc") String user_utc, @Query("access_token") String access_token,
@Query("hr") String hr, @Query("hrt") String hrt,
@Query("topic") String topic);
@POST("changePassword")
@FormUrlEncoded
Call<ChangePassRest> changePassword(@Field("id_user") String id_user, @Field("oldpass") String oldpass, @Field("newpass") String newpass);
@POST("tps_me_r")
@FormUrlEncoded
Call<SessionRest> getSession(@Field("id_user") String id_user, @Field("class_id") String classid);
@POST("get_static_data")
@FormUrlEncoded
Call<StaticDRest> getStaticData(@Field("session") String s);
@POST("get_token")
@FormUrlEncoded
Call<StaticDRest> getToken(@Field("session") String s, @Field("user_utc") String utc, @Field("janus") String janusServer, @Field("usertype") String usertype,@Field("classid") String classid);
}
<file_sep>package com.apps.indiclass.adapter;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.indiclass.Classroom;
import com.apps.indiclass.R;
import com.apps.indiclass.model.MyClassModel;
import com.apps.indiclass.util.Constant;
import com.apps.indiclass.util.SessionManager;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static com.apps.indiclass.util.Method.dbZero;
/**
* Created by Dell_Cleva on 16/10/2018.
*/
public class MyClassAdapter extends RecyclerView.Adapter<MyClassAdapter.MyViewHolder> {
private final OnItemClickListener listener;
private static final String TAG = "MyClassAdapter";
private Context context;
private List<MyClassModel> progamModels;
SessionManager sessionManager;
private final List<MyViewHolder> lstHolders;
private Handler mHandler = new Handler();
private Timer tmr;
private Runnable updateRemainingTimeRunnable = new Runnable() {
@Override
public void run() {
synchronized (lstHolders) {
for (MyViewHolder holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
public interface OnItemClickListener {
void onItemClick(MyClassModel item);
}
public MyClassAdapter(Context context, List<MyClassModel> progamModelList, OnItemClickListener listener) {
this.context = context;
this.progamModels = progamModelList;
sessionManager = new SessionManager(context);
lstHolders = new ArrayList<>();
this.listener = listener;
startUpdateTimer();
}
private void startUpdateTimer() {
tmr = new Timer();
tmr.schedule(new TimerTask() {
@Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.class_item_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final MyClassModel progamModel = progamModels.get(position);
holder.name.setText(progamModel.getsNama());
holder.desc.setText(progamModel.getsSubject());
holder.time.setText(progamModel.getsTime());
holder.btnMasuk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick: " + progamModel.toString());
Intent in = new Intent(context, Classroom.class);
in.putExtra("visible", "");
in.putExtra("subject", progamModel.getsSubject());
in.putExtra("template", "all_featured");
in.putExtra("id_user", sessionManager.getIds());
in.putExtra("class_id", progamModel.getsClassID());
in.putExtra("isTV", false);
context.startActivity(in);
}
});
holder.rlmasuk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.btnMasuk.isShown()) {
Log.i(TAG, "onClick: " + progamModel.toString());
Intent in = new Intent(context, Classroom.class);
in.putExtra("visible", "");
in.putExtra("subject", progamModel.getsSubject());
in.putExtra("template", "all_featured");
in.putExtra("id_user", sessionManager.getIds());
in.putExtra("class_id", progamModel.getsClassID());
in.putExtra("isTV", false);
context.startActivity(in);
} else
Toast.makeText(context, "Kelas belum dimulai.", Toast.LENGTH_SHORT).show();
}
});
synchronized (lstHolders) {
holder.setData(progamModel);
lstHolders.add(holder);
}
Glide.with(context)
.load(Constant.ImageTutor + progamModel.getsImage())
.into(holder.thumbnail);
holder.setData(progamModel);
}
@Override
public int getItemCount() {
return progamModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, desc, time;
public ImageView thumbnail;
RelativeLayout rlmasuk;
Button btnMasuk, btnWait;
MyClassModel item;
MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.title);
desc = view.findViewById(R.id.desc);
time = view.findViewById(R.id.tvTime);
thumbnail = view.findViewById(R.id.icon);
btnMasuk = view.findViewById(R.id.buttonEnter);
btnWait = view.findViewById(R.id.buttonWait);
rlmasuk = view.findViewById(R.id.rlmasuk);
}
public void setData(MyClassModel items) {
item = items;
}
void updateTimeRemaining() {
if (item.getExpiredTime() != 0) {
long currentTime = System.currentTimeMillis();
long timeDiff = item.getExpiredTime() - currentTime;
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) ((timeDiff / (1000 * 60 * 60)) % 24);
int days = (int) ((timeDiff / (1000*60*60*24)) );
int weeks = (int) (timeDiff / (1000*60*60*24*7));
if (days > 0) {
hours = hours+(days*24);
btnWait.setText(dbZero(hours) + ":" + dbZero(minutes) + ":" + dbZero(seconds));
} else if (hours > 0)
btnWait.setText(dbZero(hours) + ":" + dbZero(minutes) + ":" + dbZero(seconds));
else
btnWait.setText(dbZero(minutes) + ":" + dbZero(seconds));
Log.i("TAG", "updateTimeRemaining: " + hours + " hrs " + minutes + " mins " + seconds + " sec");
} else {
btnMasuk.setVisibility(View.VISIBLE);
btnWait.setVisibility(View.GONE);
tmr.cancel();
}
}
}
}
}
<file_sep>package com.apps.indiclass.fragment;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.apps.indiclass.Classroom;
import com.apps.indiclass.JanusActivity;
import com.apps.indiclass.MainActivity;
import com.apps.indiclass.R;
import com.apps.indiclass.adapter.ClassAdapter;
import com.apps.indiclass.api.ApiCall;
import com.apps.indiclass.api.ApiUtils;
import com.apps.indiclass.model.ClassRest;
import com.apps.indiclass.model.MyClassModel;
import com.apps.indiclass.model.SessionRest;
import com.apps.indiclass.model.StaticDRest;
import com.apps.indiclass.util.Config;
import com.apps.indiclass.util.Constant;
import com.apps.indiclass.util.Method;
import com.apps.indiclass.util.SessionManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* A simple {@link Fragment} subclass.
*/
public class ClassFragment extends Fragment {
private static final String TAG = "ClassFragment";
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat FORMATTERSQL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String name = "AKU", token = "<KEY>";
// String id_user, sToken;
String sSession;
ApiCall mAPIService2, mApi2;
Retrofit retrofit, retrofit2;
TextView tvNo;
ImageView imgNo;
String id_user, sdatekirim, sToken, sftime;
ApiCall mAPIService;
SessionManager session;
MyClassModel progamModel;
android.app.AlertDialog b;
android.app.AlertDialog.Builder dialogBuilder;
android.support.v7.app.ActionBar ab;
LinearLayout llLive, llWait, llPass;
private RecyclerView recyclerView, recyclerViewW, recyclerViewP;
private List<MyClassModel> myClassModels = new ArrayList<>();
private List<MyClassModel> myClassModelsW =new ArrayList<>();
private List<MyClassModel> myClassModelsP =new ArrayList<>();
private ClassAdapter mAdapter, mAdapterW, mAdapterP;
//Creating a broadcast receiver for gcm registration
public BroadcastReceiver mRegistrationBroadcastReceiver;
public ClassFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_class, container, false);
session = new SessionManager(getContext());
id_user = session.getIds();
sToken = session.getToken();
llLive = view.findViewById(R.id.llLive);
llWait = view.findViewById(R.id.llWait);
llPass = view.findViewById(R.id.llPass);
Calendar calendar = Calendar.getInstance();
sdatekirim = FORMATTER.format(calendar.getTime());
mAPIService = ApiUtils.getRestAPI(Constant.BASE_URL);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerViewW = view.findViewById(R.id.recycler_viewwait);
recyclerViewP = view.findViewById(R.id.recycler_viewpass);
tvNo = view.findViewById(R.id.tvnoclassdetail);
imgNo = view.findViewById(R.id.imgNo);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLayoutManager);
RecyclerView.LayoutManager mLayoutManagerW = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerViewW.setLayoutManager(mLayoutManagerW);
RecyclerView.LayoutManager mLayoutManagerP = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerViewP.setLayoutManager(mLayoutManagerP);
// add the decoration to the recyclerView
// SeparatorDivider decoration = new SeparatorDivider(getActivity(), Color.LTGRAY, 0f);
// recyclerView.addItemDecoration(null);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(false);
recyclerViewW.setItemAnimator(new DefaultItemAnimator());
recyclerViewW.setNestedScrollingEnabled(false);
recyclerViewP.setItemAnimator(new DefaultItemAnimator());
recyclerViewP.setNestedScrollingEnabled(false);
//Initializing our broadcast receiver
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.NEW_CLASS)) {
new android.os.Handler().postDelayed(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
fetchStoreItems();
}
}, 50);
}
}
};
fetchStoreItems();
return view;
}
public void fetchStoreItems() {
mAPIService.myclass(id_user, sdatekirim, Method.getUTCTime(), sToken).enqueue(new Callback<ClassRest>() {
@Override
public void onResponse(Call<ClassRest> call, Response<ClassRest> response) {
if (response.body() != null) {
Log.i(TAG, "post submitted to API." + response.body().toString());
if (response.body().getClassData() == null) {
tvNo.setVisibility(View.VISIBLE);
imgNo.setVisibility(View.VISIBLE);
} else {
if (response.body().getClassData().size() > 0) {
myClassModels = new ArrayList<>();
myClassModelsW = new ArrayList<>();
myClassModelsP = new ArrayList<>();
Calendar caal = Calendar.getInstance();
sftime = FORMATTERSQL.format(caal.getTime());
Date datenow = null, datestart = null, dateend = null;
for (int i = 0; i < response.body().getClassData().size(); i++) {
long sums = 0;
try {
datenow = FORMATTERSQL.parse(sftime);
datestart = FORMATTERSQL.parse(response.body().getClassData().get(i).getDate() + " " + response.body().getClassData().get(i).getTime() + ":00");
dateend = FORMATTERSQL.parse(response.body().getClassData().get(i).getEnddate() + " " + response.body().getClassData().get(i).getEndtime() + ":00");
Log.w(TAG, "onResponse: C: "+response.body().getClassData().get(i).getClass_id());
Log.w(TAG, "onResponse: TIME NOW: "+datenow.getTime() );
Log.w(TAG, "onResponse: TIME END: "+dateend.getTime() );
if (datenow.compareTo(datestart) < 0) {
// WAIT
Date mDate = FORMATTERSQL.parse(response.body().getClassData().get(i).getDate() + " " + response.body().getClassData().get(i).getTime() + ":00");
sums = mDate.getTime();
System.out.println("Date in milli WAIT:: " + sums);
MyClassModel m = new MyClassModel();
m.setsClassID(response.body().getClassData().get(i).getClass_id());
m.setsSubject(response.body().getClassData().get(i).getSubject_name() + ", " + response.body().getClassData().get(i).getDescription());
m.setsNama(response.body().getClassData().get(i).getTutorName());
m.setsTime(response.body().getClassData().get(i).getTime() + " - " + response.body().getClassData().get(i).getEndtime());
m.setsImage(response.body().getClassData().get(i).getUser_image());
m.setsDateStart(response.body().getClassData().get(i).getDate() + " " + response.body().getClassData().get(i).getTime() + ":00");
m.setsDateEnd(response.body().getClassData().get(i).getEnddate() + " " + response.body().getClassData().get(i).getEndtime() + ":00");
m.setExpiredTime(sums);
myClassModelsW.add(m);
} else if (datenow.compareTo(datestart) == 0 || datenow.compareTo(datestart) > 0 && datenow.compareTo(dateend) < 0){
// LIVE
Date mDate = FORMATTERSQL.parse(response.body().getClassData().get(i).getEnddate() + " " + response.body().getClassData().get(i).getEndtime() + ":00");
sums = mDate.getTime();
System.out.println("Date in milli LIVE:: " + sums);
MyClassModel m = new MyClassModel();
m.setsClassID(response.body().getClassData().get(i).getClass_id());
m.setsSubject(response.body().getClassData().get(i).getSubject_name() + ", " + response.body().getClassData().get(i).getDescription());
m.setsNama(response.body().getClassData().get(i).getTutorName());
m.setsTime(response.body().getClassData().get(i).getTime() + " - " + response.body().getClassData().get(i).getEndtime());
m.setsImage(response.body().getClassData().get(i).getUser_image());
m.setsDateStart(response.body().getClassData().get(i).getDate() + " " + response.body().getClassData().get(i).getTime() + ":00");
m.setsDateEnd(response.body().getClassData().get(i).getEnddate() + " " + response.body().getClassData().get(i).getEndtime() + ":00");
m.setExpiredTime(sums);
myClassModels.add(m);
} else if (datenow.compareTo(dateend) > 0){
// PASS
System.out.println("Date in milli PASS:: " + sums +" CLASS "+response.body().getClassData().get(i).getClass_id());
MyClassModel m = new MyClassModel();
m.setsClassID(response.body().getClassData().get(i).getClass_id());
m.setsSubject(response.body().getClassData().get(i).getSubject_name() + ", " + response.body().getClassData().get(i).getDescription());
m.setsNama(response.body().getClassData().get(i).getTutorName());
m.setsTime(response.body().getClassData().get(i).getTime() + " - " + response.body().getClassData().get(i).getEndtime());
m.setsImage(response.body().getClassData().get(i).getUser_image());
m.setsDateStart(response.body().getClassData().get(i).getDate() + " " + response.body().getClassData().get(i).getTime() + ":00");
m.setsDateEnd(response.body().getClassData().get(i).getEnddate() + " " + response.body().getClassData().get(i).getEndtime() + ":00");
m.setExpiredTime(sums);
myClassModelsP.add(m);
}
} catch (ParseException e) {
e.printStackTrace();
}
tvNo.setVisibility(View.GONE);
imgNo.setVisibility(View.GONE);
}
} else {
tvNo.setVisibility(View.VISIBLE);
imgNo.setVisibility(View.VISIBLE);
}
}
if (myClassModels.size() > 0) {
// refreshing recycler view
mAdapter = new ClassAdapter(getActivity(), myClassModels, new ClassAdapter.OnItemClickListener() {
@Override
public void onItemClick(MyClassModel item) {
progamModel = item;
ShowProgressDialog();
Intent in = new Intent(getActivity(), Classroom.class);
in.putExtra("visible", "");
in.putExtra("subject", progamModel.getsSubject());
in.putExtra("template", "all_featured");
in.putExtra("id_user", id_user);
in.putExtra("class_id", progamModel.getsClassID());
in.putExtra("token", token);
in.putExtra("isTV", false);
startActivity(in);
HideProgressDialog();
//
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
//
// retrofit = new Retrofit.Builder()
// .baseUrl(Constant.TPS_ME)
// .client(client)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
// retrofit2 = new Retrofit.Builder()
// .baseUrl(Constant.STATIC_REST)
// .client(client)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// mAPIService2 = retrofit.create(ApiCall.class);
//
// mApi2 = retrofit2.create(ApiCall.class);
//
// Toast.makeText(getContext(), "Masuk Kelas", Toast.LENGTH_SHORT).show();
// mAPIService2.getSession(id_user, progamModel.getsClassID()).enqueue(new Callback<SessionRest>() {
// @Override
// public void onResponse(Call<SessionRest> call, Response<SessionRest> response) {
// if (response.body() != null) {
// if (response.body().getAccess_session() != null) {
// sSession = response.body().getAccess_session();
// mApi2.getStaticData(response.body().getAccess_session()).enqueue(new Callback<StaticDRest>() {
// @Override
// public void onResponse(Call<StaticDRest> call, Response<StaticDRest> response) {
// if (response.body() != null) {
// if (response.body().getStaticDRes() != null) {
//
// name = response.body().getStaticDRes().getDisplay_name();
//// roomid = Integer.valueOf(response.body().getStaticDRes().getClass_id());
// getToken(response.body().getStaticDRes().getJanus());
// }
//
// }
// }
//
// @Override
// public void onFailure(Call<StaticDRest> call, Throwable t) {
//
// }
// });
// }
// }
// }
//
// @Override
// public void onFailure(Call<SessionRest> call, Throwable t) {
//
// }
// });
}
}, ClassFragment.this);
recyclerView.setAdapter(mAdapter);
recyclerView.invalidate();
mAdapter.notifyDataSetChanged();
llLive.setVisibility(View.VISIBLE);
} else {
llLive.setVisibility(View.GONE);
}
if (myClassModelsW.size() > 0) {
// refreshing recycler view
mAdapterW = new ClassAdapter(getActivity(), myClassModelsW, new ClassAdapter.OnItemClickListener() {
@Override
public void onItemClick(MyClassModel item) {
//
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
//
// retrofit = new Retrofit.Builder()
// .baseUrl(Constant.TPS_ME)
// .client(client)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
// retrofit2 = new Retrofit.Builder()
// .baseUrl(Constant.STATIC_REST)
// .client(client)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// mAPIService2 = retrofit.create(ApiCall.class);
//
// mApi2 = retrofit2.create(ApiCall.class);
//
// mAPIService2.getSession(id_user, progamModel.getsClassID()).enqueue(new Callback<SessionRest>() {
// @Override
// public void onResponse(Call<SessionRest> call, Response<SessionRest> response) {
// if (response.body() != null) {
// if (response.body().getAccess_session() != null) {
// sSession = response.body().getAccess_session();
// mApi2.getStaticData(response.body().getAccess_session()).enqueue(new Callback<StaticDRest>() {
// @Override
// public void onResponse(Call<StaticDRest> call, Response<StaticDRest> response) {
// if (response.body() != null) {
// if (response.body().getStaticDRes() != null) {
//
// name = response.body().getStaticDRes().getDisplay_name();
//// roomid = Integer.valueOf(response.body().getStaticDRes().getClass_id());
// getToken(response.body().getStaticDRes().getJanus());
// }
//
// }
// }
//
// @Override
// public void onFailure(Call<StaticDRest> call, Throwable t) {
//
// }
// });
// }
// }
// }
//
// @Override
// public void onFailure(Call<SessionRest> call, Throwable t) {
//
// }
// });
}
},ClassFragment.this);
recyclerViewW.setAdapter(mAdapterW);
recyclerViewW.invalidate();
mAdapterW.notifyDataSetChanged();
llWait.setVisibility(View.VISIBLE);
} else {
llWait.setVisibility(View.GONE);
}
if (myClassModelsP.size() > 0) {
// refreshing recycler view
mAdapterP = new ClassAdapter(getActivity(), myClassModelsP, new ClassAdapter.OnItemClickListener() {
@Override
public void onItemClick(MyClassModel item) {
//
// HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
// interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
//
// retrofit = new Retrofit.Builder()
// .baseUrl(Constant.TPS_ME)
// .client(client)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
// retrofit2 = new Retrofit.Builder()
// .baseUrl(Constant.STATIC_REST)
// .client(client)
// .addConverterFactory(GsonConverterFactory.create())
// .build();
//
// mAPIService2 = retrofit.create(ApiCall.class);
//
// mApi2 = retrofit2.create(ApiCall.class);
//
// mAPIService2.getSession(id_user, progamModel.getsClassID()).enqueue(new Callback<SessionRest>() {
// @Override
// public void onResponse(Call<SessionRest> call, Response<SessionRest> response) {
// if (response.body() != null) {
// if (response.body().getAccess_session() != null) {
// sSession = response.body().getAccess_session();
// mApi2.getStaticData(response.body().getAccess_session()).enqueue(new Callback<StaticDRest>() {
// @Override
// public void onResponse(Call<StaticDRest> call, Response<StaticDRest> response) {
// if (response.body() != null) {
// if (response.body().getStaticDRes() != null) {
//
// name = response.body().getStaticDRes().getDisplay_name();
//// roomid = Integer.valueOf(response.body().getStaticDRes().getClass_id());
// getToken(response.body().getStaticDRes().getJanus());
// }
//
// }
// }
//
// @Override
// public void onFailure(Call<StaticDRest> call, Throwable t) {
//
// }
// });
// }
// }
// }
//
// @Override
// public void onFailure(Call<SessionRest> call, Throwable t) {
//
// }
// });
}
},ClassFragment.this);
recyclerViewP.setAdapter(mAdapterP);
recyclerViewP.invalidate();
mAdapterP.notifyDataSetChanged();
llPass.setVisibility(View.VISIBLE);
} else {
llPass.setVisibility(View.GONE);
}
}
}
@Override
public void onFailure(Call<ClassRest> call, Throwable t) {
}
});
}
public void getToken(final String janus) {
mApi2.getToken(sSession, Method.getUTCTime(), janus, "student", progamModel.getsClassID()).enqueue(new Callback<StaticDRest>() {
@Override
public void onResponse(Call<StaticDRest> call, Response<StaticDRest> response) {
if (response.body() != null) {
if (response.body().getStaticDRes() != null) {
if (response.body().getStaticDRes().getToen() != null) {
token = response.body().getStaticDRes().getToen();
Intent in = new Intent(getActivity(), JanusActivity.class);
in.putExtra("visible", "");
in.putExtra("subject", progamModel.getsSubject());
in.putExtra("template", "all_featured");
in.putExtra("id_user", id_user);
in.putExtra("class_id", progamModel.getsClassID());
in.putExtra("token", token);
in.putExtra("isTV", false);
in.putExtra("name", name);
startActivity(in);
HideProgressDialog();
} else
getToken(janus);
}
}
}
@Override
public void onFailure(Call<StaticDRest> call, Throwable t) {
}
});
}
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.NEW_CLASS));
}
public void ShowProgressDialog() {
dialogBuilder = new android.app.AlertDialog.Builder(getActivity());
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.progress_dialog_layout, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setCancelable(false);
b = dialogBuilder.create();
b.show();
}
public void HideProgressDialog() {
b.dismiss();
}
}
<file_sep>package com.apps.indiclass.util;
/**
* Created by Dell_Cleva on 12/11/2018.
*/
public class Constant {
private static String LINK_CDN = "https://cdn.classmiles.com";
public static final String ImageTutor = LINK_CDN + "/usercontent/";
// public static final String BASE_URL = "https://classmiles.com/api/v1/";
public static final String TPS_ME = "https://indiclass.id/V1.0.0/";
public static final String STATIC_REST = "https://id.indiclass.id/Rest/";
public static final String BASE_URL = "https://indiclass.id/api/v1/";
}
<file_sep>include ':app', ':CordovaLibs', ':janusclientapi'
<file_sep>package com.apps.indiclass.util;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.apps.indiclass.LoginActivity;
import com.apps.indiclass.MainActivity;
import java.util.HashMap;
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyClass";
// User name (make variable public to access from outside)
public static final String KEY_TOKEN = "token";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "nama";
// Email address (make variable public to access from outside)
public static final String KEY_JENI = "jenjang";
// Email address (make variable public to access from outside)
public static final String KEY_IDUS = "iduser";
// Email address (make variable public to access from outside)
public static final String KEY_IMGS = "img";
// Email address (make variable public to access from outside)
public static final String KEY_EMAI = "email";
// Email address (make variable public to access from outside)
public static final String KEY_TYPE = "TYPE";
// Email address (make variable public to access from outside)
public static final String KEY_GOOGLE = "GOOGLE";
// Email address (make variable public to access from outside)
public static final String KEY_STAS = "STAS";
public static final String KEY_CLASSID = "CLASSID";
public static final String KEY_KIDSID = "KIDSID";
public static final String KEY_KIDSJENI = "kidsjenjang";
public static final String KEY_KIDSJNAME = "kidsjenjangname";
// Constructor
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getJenjang(){
String user = pref.getString(KEY_JENI, "0");
return user;
}
public String getJenjangKid(){
String user = pref.getString(KEY_KIDSJENI, "0");
return user;
}
public String getJenjangNameKid(){
String user = pref.getString(KEY_KIDSJNAME, "0");
return user;
}
public String getUserType(){
String type = pref.getString(KEY_TYPE, null);
return type;
}
public String getIds(){
String id = pref.getString(KEY_IDUS, "0");
return id;
}
public String getTokenFcm(){
String token = pref.getString("tokenfcm", null);
return token;
}
public void createTokenFcm(String tokenfcm) {
editor.putString("tokenfcm", tokenfcm);
editor.commit();
}
public void updateIMGS(String tokenfcm) {
editor.putString(KEY_IMGS, tokenfcm);
editor.commit();
}
public String getStas(){
String token = pref.getString(KEY_STAS, "0");
return token;
}
public void createClassId(int tokenfcm) {
editor.putInt(KEY_CLASSID, tokenfcm);
editor.commit();
}
public int getKeyClassid(){
int token = pref.getInt(KEY_STAS, 0);
return token;
}
public String getToken(){
return pref.getString(KEY_TOKEN, "");
}
public void createJenjang(String tokenfcm) {
editor.putString(KEY_JENI, tokenfcm);
editor.commit();
}
public void createKidsSession(String kidsid, String kidsjen, String kidsimg, String kidsjname) {
// Storing jenjang in pref
editor.putString(KEY_KIDSID, kidsid);
// Storing jenjang in pref
editor.putString(KEY_KIDSJENI, kidsjen);
// Storing jenjang in pref
editor.putString(KEY_KIDSJNAME, kidsjname);
// Storing jenjang in pref
editor.putString(KEY_IMGS, kidsimg);
// commit changes
editor.commit();
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Create login session
* */
public void createLoginSession(String token, String nama, String email, String iduser, String img, String jenjang, String type, String google, String stuas){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing nama in pref
editor.putString(KEY_TOKEN, token);
// Storing nama in pref
editor.putString(KEY_NAME, nama);
// Storing email in pref
editor.putString(KEY_EMAI, email);
// Storing iduser in pref
editor.putString(KEY_IDUS, iduser);
// Storing img in pref
editor.putString(KEY_IMGS, img);
// Storing jenjang in pref
editor.putString(KEY_JENI, jenjang);
// Storing jenjang in pref
editor.putString(KEY_TYPE, type);
// Storing jenjang in pref
editor.putString(KEY_GOOGLE, google);
// Storing jenjang in pref
editor.putString(KEY_STAS, stuas);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, ""));
// user email id
user.put(KEY_EMAI, pref.getString(KEY_EMAI, ""));
// user id user
user.put(KEY_IDUS, pref.getString(KEY_IDUS, ""));
// user img
user.put(KEY_IMGS, pref.getString(KEY_IMGS, ""));
// user jenjang
user.put(KEY_JENI, pref.getString(KEY_JENI, "0"));
// user jenjang
user.put(KEY_GOOGLE, pref.getString(KEY_GOOGLE, ""));
// user jenjang
user.put(KEY_KIDSID, pref.getString(KEY_KIDSID, "0"));
// user jenjang
user.put(KEY_KIDSJENI, pref.getString(KEY_KIDSJENI, "0"));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
<file_sep>package com.apps.indiclass.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.apps.indiclass.R;
import com.apps.indiclass.adapter.ProgramAdapter;
import com.apps.indiclass.model.ProgamModel;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
private RecyclerView recyclerView;
private List<ProgamModel> progamsModelList;
private ProgramAdapter mAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_blank, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
progamsModelList = new ArrayList<>();
mAdapter = new ProgramAdapter(getActivity(), progamsModelList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLayoutManager);
// recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(8), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.setNestedScrollingEnabled(false);
fetchStoreItems();
return view;
}
private void fetchStoreItems() {
String[] asd ={"SD", "SMP", "SMA - IPA", "SMA - IPS"};
for (int i = 0; i < 4; i++) {
ProgamModel p = new ProgamModel();
p.setsPrice("Rp. 99.000");
p.setsProgamName("Program Belajar " + asd[i]);
progamsModelList.add(p);
}
// refreshing recycler view
mAdapter.notifyDataSetChanged();
}
}
<file_sep>package com.apps.indiclass;
import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import com.apps.indiclass.fragment.ClassFragment;
import com.apps.indiclass.fragment.HomeFragment;
import com.apps.indiclass.fragment.ProfileFragment;
import com.apps.indiclass.fragment.TutorFragment;
import com.apps.indiclass.util.BottomNavigationBehavior;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem;
import java.lang.reflect.Field;
import java.util.ArrayList;
import static android.Manifest.permission.CAMERA;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
final Fragment fragment1 = new HomeFragment();
final Fragment fragment2 = new ClassFragment();
final Fragment fragment3 = new TutorFragment();
final Fragment fragment4 = new ProfileFragment();
final FragmentManager fm = getSupportFragmentManager();
private final int[] colors = {R.color.bgBottomNavigation, R.color.bgBottomNavigation, R.color.bgBottomNavigation};
Fragment active = fragment2;
BottomNavigationView navigation;
FloatingActionButton fab;
boolean current1 = true;
boolean current2 = false;
boolean current3 = false;
public boolean isTV = false, isPermissionOn = false;
private ActionBar toolbar;
private AHBottomNavigation bottomNavigation;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
// case R.id.navigation_home:
// toolbar.setTitle(R.string.title_home);
//
// fm.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).hide(active).show(fragment1).commit();
// active = fragment1;
// fab.setVisibility(View.GONE);
//// loadFragment(new BlankFragment());
// return true;
case R.id.navigation_dashboard:
toolbar.setTitle(R.string.title_dashboard);
fm.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).hide(active).show(fragment2).commit();
active = fragment2;
((ClassFragment) active).fetchStoreItems();
fab.setVisibility(View.VISIBLE);
// loadFragment(new ClassFragment());
return true;
case R.id.navigation_tutor:
toolbar.setTitle(R.string.title_tutor);
fm.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).hide(active).show(fragment3).commit();
active = fragment3;
fab.setVisibility(View.GONE);
// loadFragment(new ClassFragment());
return true;
case R.id.navigation_notifications:
toolbar.setTitle(R.string.title_notifications);
fm.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).hide(active).show(fragment4).commit();
active = fragment4;
fab.setVisibility(View.GONE);
// loadFragment(new NotificationFragment());
return true;
}
return false;
}
};
private ArrayList<String> permissionsToRequest;
private ArrayList<String> permissionsRejected = new ArrayList<>();
private ArrayList<String> permissions = new ArrayList<>();
private final static int ALL_PERMISSIONS_RESULT = 107;
private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
ArrayList<String> result = new ArrayList<String>();
for (String perm : wanted) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (canMakeSmores()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
}
return true;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Batal", cancelListener)
.create()
.show();
}
private boolean canMakeSmores() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case ALL_PERMISSIONS_RESULT:
for (String perms : permissionsToRequest) {
if (hasPermission(perms)) {
Log.e(TAG, "onRequestPermissionsResult: " + perms);
if (perms.equalsIgnoreCase(Manifest.permission.RECORD_AUDIO))
isPermissionOn = true;
permissionsRejected.clear();
} else {
permissionsRejected.add(perms);
}
}
if (permissionsRejected.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
showMessageOKCancel(getString(R.string.permission_message),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.d("API123", "permisionrejected " + permissionsRejected.size());
requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
}
}
},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// progressDialog.dismiss();
}
});
return;
}
}
}
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
permissions.add(CAMERA);
permissions.add(Manifest.permission.RECORD_AUDIO);
permissionsToRequest = findUnAskedPermissions(permissions);
//get the permissions we have asked for before but are not granted..
//we will store this in a global list to access later.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0)
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
else
isPermissionOn = true;
} else {
isPermissionOn = true;
}
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
disableShiftMode(navigation);
// attaching bottom sheet behaviour - hide / show on scroll
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) navigation.getLayoutParams();
layoutParams.setBehavior(new BottomNavigationBehavior());
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, ReqClassActivity.class));
}
});
fm.beginTransaction().add(R.id.frame_container, fragment4, "4").hide(fragment4).commit();
fm.beginTransaction().add(R.id.frame_container, fragment3, "3").hide(fragment3).commit();
fm.beginTransaction().add(R.id.frame_container, fragment2, "2").commit();
// fm.beginTransaction().add(R.id.frame_container,fragment1, "1").commit();
fab.setVisibility(View.VISIBLE);
toolbar.setTitle(R.string.title_home);
// loadFragment(new BlankFragment());
if (findViewById(R.id.bottom_navigation) != null) {
bottomNavigation = findViewById(R.id.bottom_navigation);
setupBottomNavBehaviors();
setupBottomNavStyle();
addBottomNavigationItems();
changeClick();
cc();
c2();
isTV = true;
}
}
public void btClick(View v) {
if (v.getId() == R.id.bottom_navigation_container1) {
current1 = true;
current2 = false;
current3 = false;
changeClick();
cc();
c2();
navigation.setSelectedItemId(R.id.navigation_dashboard);
} else if (v.getId() == R.id.bottom_navigation_container2) {
current1 = false;
current2 = true;
current3 = false;
changeClick();
cc();
c2();
navigation.setSelectedItemId(R.id.navigation_tutor);
} else {
current1 = false;
current2 = false;
current3 = true;
changeClick();
cc();
c2();
navigation.setSelectedItemId(R.id.navigation_notifications);
}
}
void changeClick() {
ImageView icon1 = findViewById(R.id.bottom_navigation_item_icon1);
animateImageView(icon1, current1);
// icon1.setImageDrawable(AHHelper.getTintDrawable(icon1.getDrawable(),
// current1 ? fetchColor(R.color.white) : fetchColor(R.color.bottomtab_item_resting), false));
TextView title1 = findViewById(R.id.bottom_navigation_item_title1);
title1.setTextColor(current1 ? fetchColor(R.color.white) : fetchColor(R.color.bottomtab_item_resting));
title1.setTextSize(TypedValue.COMPLEX_UNIT_SP, current3 ? 14 : 12);
}
void cc() {
// dua
ImageView icon2 = findViewById(R.id.bottom_navigation_item_icon2);
animateImageView(icon2, current2);
// icon2.setImageDrawable(AHHelper.getTintDrawable(icon2.getDrawable(),
// current2 ? fetchColor(R.color.white) : fetchColor(R.color.bottomtab_item_resting), false));
TextView title2 = findViewById(R.id.bottom_navigation_item_title2);
title2.setTextColor(current2 ? fetchColor(R.color.white) : fetchColor(R.color.bottomtab_item_resting));
title2.setTextSize(TypedValue.COMPLEX_UNIT_SP, current3 ? 14 : 12);
}
void c2() {
// tiga
ImageView icon3 = findViewById(R.id.bottom_navigation_item_icon3);
animateImageView(icon3, current3);
// icon3.setImageDrawable(AHHelper.getTintDrawable(icon3.getDrawable(),
// current3 ? fetchColor(R.color.white) : fetchColor(R.color.bottomtab_item_resting), false));
TextView title3 = findViewById(R.id.bottom_navigation_item_title3);
title3.setTextColor(current3 ? fetchColor(R.color.white) : fetchColor(R.color.bottomtab_item_resting));
title3.setTextSize(TypedValue.COMPLEX_UNIT_SP, current3 ? 14 : 12);
}
public void animateImageView(final ImageView v, boolean os) {
final int orange;
if (os) {
TypedValue typedValue = new TypedValue();
TypedArray a = this.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimaryDark});
orange = getResources().getColor(R.color.white);
a.recycle();
} else {
orange = getResources().getColor(R.color.bottomtab_item_resting);
}
// final int orange = getResources().getColor(R.color.colorPrimaryDark);
final ValueAnimator colorAnim = ObjectAnimator.ofFloat(0f, 1f);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float mul = (Float) animation.getAnimatedValue();
int alphaOrange = adjustAlpha(orange, mul);
v.setColorFilter(orange, PorterDuff.Mode.SRC_IN);
}
});
colorAnim.setDuration(100);
colorAnim.start();
}
public int adjustAlpha(int color, float factor) {
Log.e(TAG, "adjustAlpha: " + Color.alpha(color));
int alpha = Color.alpha(color);
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
return Color.argb(alpha, red, green, blue);
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
// Method for disabling ShiftMode of BottomNavigationView
@SuppressLint("RestrictedApi")
private void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
item.setShiftingMode(false);
// set once again checked value, so view will be updated
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
@Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Log.e(TAG, "onBackPressed: " + fm.findFragmentByTag("2").isHidden());
if (fm.findFragmentByTag("2").isHidden()) {
if (isTV)
btClick(findViewById(R.id.bottom_navigation_container1));
else
navigation.setSelectedItemId(R.id.navigation_dashboard);
} else {
super.onBackPressed();
}
}
public void setupBottomNavBehaviors() {
// bottomNavigation.setBehaviorTranslationEnabled(false);
/*
Before enabling this. Change MainActivity theme to MyTheme.TranslucentNavigation in
AndroidManifest.
Warning: Toolbar Clipping might occur. Solve this by wrapping it in a LinearLayout with a top
View of 24dp (status bar size) height.
*/
bottomNavigation.setTranslucentNavigationEnabled(false);
}
/**
* Adds styling properties to {@link AHBottomNavigation}
*/
private void setupBottomNavStyle() {
/*
Set Bottom Navigation colors. Accent color for active item,
Inactive color when its view is disabled.
Will not be visible if setColored(true) and default current item is set.
*/
bottomNavigation.setDefaultBackgroundColor(Color.WHITE);
bottomNavigation.setAccentColor(fetchColor(R.color.bottomtab_0));
bottomNavigation.setInactiveColor(fetchColor(R.color.bottomtab_item_resting));
// Colors for selected (active) and non-selected items.
bottomNavigation.setColoredModeColors(Color.WHITE,
fetchColor(R.color.bottomtab_item_resting));
// Enables Reveal effect
bottomNavigation.setColored(true);
// Displays item Title always (for selected and non-selected items)
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
bottomNavigation.manageFloatingActionButtonBehavior(fab);bottomNavigation.setTranslucentNavigationEnabled(true);
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
@Override
public boolean onTabSelected(int position, boolean wasSelected) {
Log.w(TAG, "onTabSelected: "+position );
if (position == 0) {
bottomNavigation.setNotification("", 0);
navigation.setSelectedItemId(R.id.navigation_dashboard);
fab.setVisibility(View.VISIBLE);
fab.setAlpha(0f);
fab.setScaleX(0f);
fab.setScaleY(0f);
fab.animate()
.alpha(1)
.scaleX(1)
.scaleY(1)
.setDuration(300)
.setInterpolator(new OvershootInterpolator())
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fab.animate()
.setInterpolator(new LinearOutSlowInInterpolator())
.start();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
})
.start();
} else if (position == 1){
navigation.setSelectedItemId(R.id.navigation_tutor);
if (fab.getVisibility() == View.VISIBLE) {
fab.animate()
.alpha(0)
.scaleX(0)
.scaleY(0)
.setDuration(300)
.setInterpolator(new LinearOutSlowInInterpolator())
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fab.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
fab.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animator animation) {
}
})
.start();
}
} else {
navigation.setSelectedItemId(R.id.navigation_notifications);
if (fab.getVisibility() == View.VISIBLE) {
fab.animate()
.alpha(0)
.scaleX(0)
.scaleY(0)
.setDuration(300)
.setInterpolator(new LinearOutSlowInInterpolator())
.setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fab.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
fab.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animator animation) {
}
})
.start();
}
}
return true;
}
});
}
private void addBottomNavigationItems() {
AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.title_dashboard, R.drawable.ic_web_asset_black_24dp, colors[0]);
AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.title_tutor, R.drawable.ic_contacts_black_24dp, colors[1]);
AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.title_notifications, R.drawable.ic_person_black_24dp, colors[2]);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
bottomNavigation.addItem(item3);
}
/**
* Simple facade to fetch color resource, so I avoid writing a huge line every time.
*
* @param color to fetch
* @return int color value.
*/
private int fetchColor(@ColorRes int color) {
return ContextCompat.getColor(this, color);
}
}
<file_sep>package com.apps.indiclass.fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.apps.indiclass.ChangePasswordActivity;
import com.apps.indiclass.R;
import com.apps.indiclass.model.Configuration;
import com.apps.indiclass.util.SessionManager;
import java.util.ArrayList;
import java.util.List;
import static com.apps.indiclass.util.SessionManager.KEY_EMAI;
import static com.apps.indiclass.util.SessionManager.KEY_NAME;
/**
* A simple {@link Fragment} subclass.
*/
public class ProfileFragment extends Fragment {
private static final String TAG = "NotificationFragment";
private List<Configuration> listConfig = new ArrayList<>();
private RecyclerView recyclerView;
private UserInfoAdapter infoAdapter;
private static final String USERNAME_LABEL = "Nama";
private static final String EMAIL_LABEL = "Email";
private static final String SIGNOUT_LABEL = "Keluar";
private static final String RESETPASS_LABEL = "Ganti K<NAME>andi";
public ProfileFragment() {
// Required empty public constructor
}
SessionManager sessionManager;
TextView tvName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_notification, container, false);
sessionManager = new SessionManager(getContext());
tvName= view.findViewById(R.id.tv_username);
tvName.setText(sessionManager.getUserDetails().get(KEY_NAME));
recyclerView = view.findViewById(R.id.info_recycler_view);
infoAdapter = new UserInfoAdapter(listConfig);
setupArrayListInfo();
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(infoAdapter);
return view;
}
public void setupArrayListInfo(){
listConfig.clear();
Configuration userNameConfig = new Configuration(USERNAME_LABEL, sessionManager.getUserDetails().get(KEY_NAME), R.drawable.ic_account_box_black_24dp);
listConfig.add(userNameConfig);
Configuration emailConfig = new Configuration(EMAIL_LABEL, sessionManager.getUserDetails().get(KEY_EMAI), R.drawable.ic_email_blacks_24dp);
listConfig.add(emailConfig);
Configuration resetPass = new Configuration(RESETPASS_LABEL, "", R.drawable.ic_settings_backup_restore_black_24dp);
listConfig.add(resetPass);
Configuration signout = new Configuration(SIGNOUT_LABEL, "", R.drawable.ic_power_settings_new_black_24dp);
listConfig.add(signout);
}
public class UserInfoAdapter extends RecyclerView.Adapter<UserInfoAdapter.ViewHolder>{
private List<Configuration> profileConfig;
public UserInfoAdapter(List<Configuration> profileConfig){
this.profileConfig = profileConfig;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_info_item_layout, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Configuration config = profileConfig.get(position);
holder.label.setText(config.getLabel());
holder.value.setText(config.getValue());
holder.icon.setImageResource(config.getIcon());
((RelativeLayout)holder.label.getParent()).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(config.getLabel().equals(SIGNOUT_LABEL)){android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
builder.setMessage("Apakah Anda yakin ingin keluar dari akun Anda?");
builder.setCancelable(false);
builder.setPositiveButton("Iya", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
sessionManager.logoutUser();
getActivity().finish();
}
});
builder.setNegativeButton("Tidak", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int arg1) {
// TODO Auto-generated method stub
dialog.cancel();
}
}).show();
Log.i(TAG, "onClick: " + SIGNOUT_LABEL);
}
if(config.getLabel().equals(USERNAME_LABEL)){
// View vewInflater = LayoutInflater.from(context)
// .inflate(R.layout.dialog_edit_username, (ViewGroup) getView(), false);
// final EditText input = (EditText)vewInflater.findViewById(R.id.edit_username);
// input.setText(myAccount.name);
// /*Hiển thị dialog với dEitText cho phép người dùng nhập username mới*/
// new AlertDialog.Builder(context)
// .setTitle("Edit username")
// .setView(vewInflater)
// .setPositiveButton("Save", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// String newName = input.getText().toString();
// if(!myAccount.name.equals(newName)){
// changeUserName(newName);
// }
// dialogInterface.dismiss();
// }
// })
// .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// dialogInterface.dismiss();
// }
// }).show();
Log.i(TAG, "onClick: " + USERNAME_LABEL);
}
if(config.getLabel().equals(RESETPASS_LABEL)){
// new AlertDialog.Builder(context)
// .setTitle("Password")
// .setMessage("Are you sure want to reset password?")
// .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// resetPassword(myAccount.email);
// dialogInterface.dismiss();
// }
// })
// .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// dialogInterface.dismiss();
// }
// }).show();
startActivity(new Intent(getContext(), ChangePasswordActivity.class));
Log.i(TAG, "onClick: " + RESETPASS_LABEL);
}
}
});
}
// private void changeUserName(String newName){
// userDB.child("name").setValue(newName);
//
//
// myAccount.name = newName;
// SharedPreferenceHelper prefHelper = SharedPreferenceHelper.getInstance(context);
// prefHelper.saveUserInfo(myAccount);
//
// tvUserName.setText(newName);
// setupArrayListInfo(myAccount);
// }
//
// void resetPassword(final String email) {
// mAuth.sendPasswordResetEmail(email)
// .addOnCompleteListener(new OnCompleteListener<Void>() {
// @Override
// public void onComplete(@NonNull Task<Void> task) {
// new LovelyInfoDialog(context) {
// @Override
// public LovelyInfoDialog setConfirmButtonText(String text) {
// findView(com.yarolegovich.lovelydialog.R.id.ld_btn_confirm).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// dismiss();
// }
// });
// return super.setConfirmButtonText(text);
// }
// }
// .setTopColorRes(R.color.colorPrimary)
// .setIcon(R.drawable.ic_pass_reset)
// .setTitle("Password Recovery")
// .setMessage("Sent email to " + email)
// .setConfirmButtonText("Ok")
// .show();
// }
// })
// .addOnFailureListener(new OnFailureListener() {
// @Override
// public void onFailure(@NonNull Exception e) {
// new LovelyInfoDialog(context) {
// @Override
// public LovelyInfoDialog setConfirmButtonText(String text) {
// findView(com.yarolegovich.lovelydialog.R.id.ld_btn_confirm).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// dismiss();
// }
// });
// return super.setConfirmButtonText(text);
// }
// }
// .setTopColorRes(R.color.colorAccent)
// .setIcon(R.drawable.ic_pass_reset)
// .setTitle("False")
// .setMessage("False to sent email to " + email)
// .setConfirmButtonText("Ok")
// .show();
// }
// });
// }
@Override
public int getItemCount() {
return profileConfig.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView label, value;
public ImageView icon;
public ViewHolder(View view) {
super(view);
label = (TextView)view.findViewById(R.id.tv_title);
value = (TextView)view.findViewById(R.id.tv_detail);
icon = (ImageView)view.findViewById(R.id.img_icon);
}
}
}
}
| 11648904bf1560b2254ff1e8fb5362f64771edc5 | [
"Java",
"Gradle"
] | 12 | Java | AdamFM/indiclass | 333c862e95c25cb07db19fabcc568a9a690e60ed | d3e6ed5d063c9e3012159172adc1276506cab4cb |
refs/heads/master | <repo_name>gamesbykevin/convert_images<file_sep>/src/main/java/com/gamesbykevin/convertimages/Main.java
package com.gamesbykevin.convertimages;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class Main {
public static final String[] EXTENSIONS = {"png", "jpg", "jpeg", "gif"};
public static final String DELIMITER = "\\.";
public static final String DIR_GRAY = "\\gray\\";
public static final String DIR_BLACK = "\\black\\";
public static final String FORMAT = "png";
public static void main(String[] args) {
Main main = new Main();
if (args.length < 1) {
//check current directory if no args provided
main.convertDir(".");
} else {
for (String path : args) {
main.convertDir(path);
}
}
}
private void convertDir(String path) {
convertDir(new File(path));
}
private void convertDir(File folder) {
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
convertDir(file);
} else {
if (!isValid(file))
continue;
try {
String srcPath = file.getAbsolutePath();
String filename = getFilename(srcPath);
srcPath = srcPath.replace(filename, "");
srcPath = srcPath.replace("\\.\\", "");
//convert image to black/white and gray scale
BufferedImage src = ImageIO.read(file);
try {
BufferedImage imageGray = convert(src, BufferedImage.TYPE_BYTE_GRAY);
write(imageGray, srcPath + DIR_GRAY, filename);
} catch (Exception ex1) {
ex1.printStackTrace();
}
try {
BufferedImage imageBlack = convert(src, BufferedImage.TYPE_BYTE_BINARY);
write(imageBlack, srcPath + DIR_BLACK, filename);
} catch (Exception ex2) {
ex2.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void write(BufferedImage image, String dir, String filename) {
try {
new File(dir).mkdirs();
ImageIO.write(image, FORMAT, new File(dir + filename));
System.out.println(dir + filename);
} catch (Exception e) {
e.printStackTrace();
}
}
private BufferedImage convert(BufferedImage src, int type) {
BufferedImage converted = new BufferedImage(src.getWidth(), src.getHeight(), type);
Graphics2D graphics = converted.createGraphics();
graphics.drawImage(src, 0, 0, converted.getWidth(), converted.getHeight(), null);
BufferedImage result = new BufferedImage(converted.getWidth(), converted.getHeight(), BufferedImage.TYPE_INT_ARGB);
graphics = result.createGraphics();
graphics.drawImage(converted, 0, 0, result.getWidth(), result.getHeight(), null);
return result;
}
private String getFilename(String path) {
String[] data = path.split("\\\\");
return data[data.length - 1];
}
private boolean isValid(File file) {
String[] data = file.getAbsolutePath().split(DELIMITER);
if (data.length < 1)
return false;
for (String extension : EXTENSIONS) {
if (data[data.length - 1].equalsIgnoreCase(extension))
return true;
}
return false;
}
}<file_sep>/README.md
## Convert Images
### Read all images in a given directory and convert them to binary and grey scale ".png" images
#### This program will scan all directory and sub directories for images, supported "png", "jpg", "gif"
1) maven clean
2) maven package
3) place jar in the same folder and execute run.bat
```
java -jar convert_images-1.0-SNAPSHOT
```
4) or modify run.bat to include multiple directories to be converted
```
java -jar convert.jar "C:\Users\kevin\image_folder" "C:\Users\kevin\other_folder"
```
| 86730528056a9ed9341f09bc048e0362d199a083 | [
"Markdown",
"Java"
] | 2 | Java | gamesbykevin/convert_images | c611fbad6bdd4dc8e2224ee09eb274cc8d61dba8 | 6f1e814c3cac86f36c0e5c5169cbab6f5d1ed125 |
refs/heads/master | <repo_name>stellarLuminant/DOM-II<file_sep>/js/index.js
// "About Us" navlink mouseover events
let navLinks = document.querySelectorAll('header nav a');
navLinks[1].addEventListener('mouseover', function(event) {
event.target.textContent = 'About Bus';
});
navLinks[1].addEventListener('mouseout', function(event) {
event.target.textContent = 'About Us';
});
// prevents default nav link behavior for clicks.
navLinks.forEach(link => link.addEventListener('click', function (event) {
event.preventDefault();
}))
// Document keydown event
document.addEventListener('keydown', function(event) {
alert(`Fun Bus knows you pressed ${event.key}`);
});
// Adventure Awaits header wheel event
let adventureHeader = document.querySelector('section.inverse-content h2');
document.addEventListener('wheel', function(event) {
adventureHeader.textContent = 'The Wheel on the Mouse Goes Round and Round~';
});
// Welcome section drag events
let welcomeHeader = document.querySelector('header.intro h2');
let welcomeImage = document.querySelector('header.intro img');
welcomeImage.addEventListener('dragstart', function(event) {
welcomeHeader.textContent = 'Take Me on an Adventure~';
});
welcomeImage.addEventListener('dragend', function(event) {
welcomeHeader.textContent = 'Welcome to Fun Bus!';
});
// Taking advantage of closures to manipulate other objects
// with event listeners.
// Window load event
// WINDOW, not document.
window.addEventListener('load', function (event) {
alert('Fun Bus is now self-aware.');
});
// Contact link focus events
navLinks[3].addEventListener('focusin', function (event) {
navLinks[3].textContent = 'Please Contact';
event.stopPropagation();
});
navLinks[3].addEventListener('focusout', function (event) {
navLinks[3].textContent = 'Contact';
event.stopPropagation();
});
// Header banner image resize
let title = document.querySelector('h1.logo-heading');
window.addEventListener('resize', function (event) {
title.textContent = 'I\'m Shrinking!';
});
// Similar bubbling events
// Intended behaviour should be:
// Click 3rd Nav Button: Switch between 'Blog' and 'More Bus'
// Click anything else in the header: header turns yellow/white
navLinks[2].addEventListener('click', function (event) {
if (navLinks[2].textContent === 'More Bus') {
navLinks[2].textContent = 'Blog';
} else {
navLinks[2].textContent = 'More Bus';
}
event.stopPropagation();
});
let headerTop = document.querySelector('div.nav-container');
headerTop.addEventListener('click', function (event) {
if (headerTop.style.background == 'yellow') {
headerTop.style.background = 'unset';
} else {
headerTop.style.background = 'yellow';
}
})
| dbab20052e9766bc5030ba963d20cfd77f6145b9 | [
"JavaScript"
] | 1 | JavaScript | stellarLuminant/DOM-II | 12172684cd7873e134a1d90f583f3937b385b37d | d6a34357e4d7fef4322f2626d1303ec4d0ca48c1 |
refs/heads/master | <repo_name>HeiLiu/BootStrap-Practice<file_sep>/Sql/staffManager.sql
-- MySQL Script generated by MySQL Workbench
-- Mon Sep 4 22:25:26 2017
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema StaffManager
-- -----------------------------------------------------
-- 职工工资在线管理信息
-- -----------------------------------------------------
-- Schema StaffManager
--
-- 职工工资在线管理信息
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `StaffManager` DEFAULT CHARACTER SET utf8 ;
USE `StaffManager` ;
-- -----------------------------------------------------
-- Table `StaffManager`.`staff_info`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `StaffManager`.`staff_info` (
`id` INT NOT NULL DEFAULT 0 COMMENT 'ID',
`snum` INT(10) NOT NULL DEFAULT 0 COMMENT '职工号',
`sname` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '姓名',
`ssex` CHAR(4) NULL DEFAULT 0 COMMENT '性别 0为男 女为1',
`sbir` DATETIME(20) NULL DEFAULT 0 COMMENT '生日',
`gnum` INT(10) NOT NULL DEFAULT 0 COMMENT '岗位编号',
`stime` INT NULL COMMENT '工作年限',
PRIMARY KEY (`id`),
UNIQUE INDEX `sid_UNIQUE` (`id` ASC),
UNIQUE INDEX `snum_UNIQUE` (`snum` ASC))
ENGINE = MyISAM;
-- -----------------------------------------------------
-- Table `StaffManager`.`gang_info`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `StaffManager`.`gang_info` (
`id` INT NOT NULL DEFAULT 0 COMMENT 'ID',
`gname` VARCHAR(45) NOT NULL DEFAULT '' COMMENT '岗位名称',
`gbasemon` FLOAT NULL DEFAULT 0 COMMENT '基本工资',
`gjinmon` FLOAT NULL DEFAULT 0,
`gtemon` FLOAT NULL DEFAULT 0 COMMENT '特殊津贴',
`gnum` INT(10) NULL DEFAULT 0 COMMENT '岗位编号',
`staff_info_id` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `gid_UNIQUE` (`id` ASC),
UNIQUE INDEX `gname_UNIQUE` (`gname` ASC),
INDEX `fk_gang_info_staff_info_idx` (`staff_info_id` ASC))
ENGINE = MyISAM
COMMENT = '岗位信息表';
-- -----------------------------------------------------
-- Table `StaffManager`.`message`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `StaffManager`.`message` (
`id` INT NOT NULL DEFAULT 0 COMMENT '信息id',
`mtitle` VARCHAR(100) NULL DEFAULT '' COMMENT '留言内容',
`mcontent` VARCHAR(445) NULL DEFAULT '' COMMENT '留言内容',
`mtime` DATETIME(20) NULL DEFAULT '' COMMENT '留言时间',
`mwho` VARCHAR(45) NULL DEFAULT '' COMMENT '留言人',
PRIMARY KEY (`id`),
UNIQUE INDEX `mid_UNIQUE` (`id` ASC))
ENGINE = MyISAM;
-- -----------------------------------------------------
-- Table `StaffManager`.`manager`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `StaffManager`.`manager` (
`id` INT NOT NULL DEFAULT 0 COMMENT 'id',
`mname` VARCHAR(45) NOT NULL DEFAULT '' COMMENT '管理员姓名',
`mphone` VARCHAR(45) NOT NULL DEFAULT '' COMMENT '联系电话',
PRIMARY KEY (`id`),
UNIQUE INDEX `mid_UNIQUE` (`id` ASC))
ENGINE = MyISAM;
-- -----------------------------------------------------
-- Table `StaffManager`.`login`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `StaffManager`.`login` (
`id` INT NOT NULL DEFAULT 0 COMMENT 'id\n',
`sname` VARCHAR(45) NOT NULL DEFAULT '' COMMENT '登录名',
`pwd` VARCHAR(45) NOT NULL DEFAULT '' COMMENT '登录密码',
PRIMARY KEY (`id`),
UNIQUE INDEX `lid_UNIQUE` (`id` ASC),
UNIQUE INDEX `lname_UNIQUE` (`lname` ASC))
ENGINE = MyISAM;
-- -----------------------------------------------------
-- Table `StaffManager`.`staff_info_has_message`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `StaffManager`.`staff_info_has_message` (
`staff_info_id` INT NOT NULL,
`message_id` INT NOT NULL,
PRIMARY KEY (`staff_info_id`, `message_id`),
INDEX `fk_staff_info_has_message_message1_idx` (`message_id` ASC),
INDEX `fk_staff_info_has_message_staff_info1_idx` (`staff_info_id` ASC))
ENGINE = MyISAM;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/del1.php
<?php
$sname=$_GET['sname'];
echo $sname;die();
require_once('../condb.php');
$sql="delete from `staff_info` where `sname` = '$sname' ";
$result=$pdo->exec($sql);
if($result){
header('Location:sala_info.php');
}
?><file_sep>/staff/register.php
<?php
header('Content-type:text/html;charset=utf-8');
require_once('../check_login.php');
echo "<h1>注册页面</h1>";
require('condb.php');
$pdo->exec('set names utf8');
$sql="insert into login(`lname`,`lpwd`) values('admin','admin')";
$result=$pdo->exec($sql);
var_dump($result);
?><file_sep>/zhangwang/del_id.php
<?php
require_once('PDO.php');
$sid=$_GET['sid']; //获取要删除的学号sid
$sql = "delete from student where sid={$sid}";
$result = $pdo->exec($sql);
if($result!==false){
header('Location:del.php'); //删除后跳转回之前页面
}
?><file_sep>/admin/del_mes.php
<?php
$mtitle=$_GET['mtitle'];
echo $mtitle;
require_once('../condb.php');
$sql="delete from `message` where `mtitle` = '$mtitle' ";
$result=$pdo->exec($sql);
if($result){
header('Location:message.php');
}
?><file_sep>/admin/admin_gang.php
<?php
require_once('../condb.php');
$sql="select * from gang_info ";
$rs=$pdo->query($sql);
//var_dump($rs);
$list=$rs->fetchAll(PDO::FETCH_ASSOC);
// var_dump($list);
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>工资信息查询,添加,更新</title>
<style>
table{
width:60%;
border-collapse: collapse;
}
table,th,td{
border:1px solid #aaa;
}
a{text-decoration:none;}
</style>
</head>
<body>
<table>
<caption>工资信息表</caption>
<thead>
<tr>
<th>岗位编号</th>
<th>岗位</th>
<th>基本工资</th>
<th>普通津贴</th>
<th>特殊津贴</th>
<th>总计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php
foreach ($list as $key => $value) {
?>
<tr>
<td><?=$value['gnum']?></td>
<td><?=$value['gname']?></td>
<td><?=$value['gbasemon']?></td>
<td><?=$value['gjinmon']?></td>
<td><?=$value['gtemon']?></td>
<td><?=$value['gtemon']+$value['gjinmon']+$value['gbasemon']?></td>
<td><a href="exit.php ?gname=<?=$value['gname']?>">更新</a>
<a href="del.php" onclick="return del_confirm();">删除</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<p>
<button><a href="add.html">添加</a></button>
</p>
<script>
function del_confirm(){
if(confirm('是否确认删除?')){
return true;
}else{
return false;
}
}
</script>
</tbody>
</table>
</body>
</html>
<file_sep>/check_1.php
<?php
session_start();
header('Content-type:text/html;charset=utf-8');
$username=trim($_POST['username']);
$username=htmlspecialchars((strtolower($username)));
$pwd=$_POST['pwd'];
$pwd=addslashes($pwd);
// echo "用户名:".$username."密码:".$pwd;
require('condb.php');
if($username == "" || $pwd == "") {
echo "<script>alert('请输入用户名或密码!'); history.go(-1);</script>";
} else {
$sql = "select sname,pwd from login where sname = '$_POST[username]' and pwd = '$_POST[pwd]'";
$result = $pdo->query($sql);
// var_dump($result);
if($result) {
foreach ($pdo->query($sql) as $value)//将数据以索引方式储存在数组中
// var_dump($value);
$username=$value[0];
$_SESSION['username']=$value[0];
// echo "{$_SESSION['username']}";
if($username=='admin'){
header('Location:admin/admin_index.php');
}else{
$sql1 = "select `gnum` from staff_info where `sname` = '$_POST[username]'";
$result = $pdo->query($sql1);
if($result){
foreach ($result as $key => $value1)
$_SESSION['gnum']=$value1[0];
// echo $value1[0];
}
header('Location:staff/index.php');
}
} else {
echo "<script>alert('密码不正确!');history.go(-1);</script>";
}
}
?>
<file_sep>/staff/sala_info.php
<?php
require_once('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>工资信息</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="message.php"><span class="glyphicon glyphicon-fire"></span> 校园话题</a></li>
<li class="active"><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="#"><?=$_SESSION['username']?></a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<hgroup>
<h1>工资信息</h1>
<h4>业精于勤,荒于嬉;行成于思,毁于随...</h4>
</hgroup>
</div>
</div>
<div class="case">
<div class="container">
<table class="table table-striped table-bordered table-hover">
<thead>
<caption><h4 style="display:inline-block;"><?=$_SESSION['username']?></h4>的工资信息表</caption>
<tr class="success">
<th>岗位编号</th>
<th>岗 位</th>
<th>基本工资</th>
<th>普通津贴</th>
<th>特殊津贴</th>
<th>总 计</th>
</tr>
</thead>
<tbody>
<?php
require_once('../condb.php');
$sname=$_SESSION['username'];
// $sql="select * from staff_info where `sname` = $sname";
// $sql="select * from gang_info ";
//进行多表查询用
$gnum=$_SESSION['gnum'];
$sql="SELECT * FROM gang_info WHERE gnum = $gnum ";
$rs=$pdo->query($sql);
// var_dump($rs);
// die();
$list=$rs->fetchAll(PDO::FETCH_ASSOC);
// var_dump($list);
foreach ($list as $key => $value) {
?>
<tr>
<td><?=$value['gnum']?></td>
<td><?=$value['gname']?></td>
<td><?=$value['gbasemon']?></td>
<td><?=$value['gjinmon']?></td>
<td><?=$value['gtemon']?></td>
<td><?=$value['gtemon']+$value['gjinmon']+$value['gbasemon']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 企业职工网. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function () {
});
</script>
</body>
</html><file_sep>/zhangwang/exit.php
<html>
<head>
<meta charset="UTF-8">
<title>用户信息修改</title>
</head>
<body>
<h3>用户信息修改</h3>
<?php
$gname=$_GET['gname'];
require_once('../condb.php');
$sql="select * from gang_info where `gname` = $gname ";
$rs = $pdo->query($sql);
var_dump($rs);
$result =$rs->fetchAll(PDO::FETCH_ASSOC); // fetchAll(); //返回一个包含结果集中所有行的数组
var_dump($result);
if (!$result) {
exit();
}
?>
<form action="update.php" method="post">
<p>
<input type="text" name="gbasemon" placeholder="基本工资" value="<?=$result['gbasemon']?>">
</p>
<p>
<input type="text" name="gjinmon" placeholder="普通津贴" value="<?=$result['gjinmon']?>">
</p>
<p>
<input type="text" name="gtemon" placeholder="特殊津贴" value="<?=$result['gtemon']?>">
</p>
<p>
<!-- <input type="hidden" name="id" value="<?=$result['id']?>"> -->
<button type="submit">修改</button>
</p>
</form>
</body>
</html>
<file_sep>/admin/admin_index.php
<?php
require('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>青山电子科技</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="admin_index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="message.php"><span class="glyphicon glyphicon-fire"></span> 留言板</a></li>
<li><a href="sta_info.php"><span class="glyphicon glyphicon-list"></span> 职工信息</a></li>
<li><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<!--轮播图-->
<div id="myCarousel" class="carousel slide">
<ol class="carousel-indicators">
<li class="active" data-target="#myCarousel" data-slide-to="0"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active" style="background:#223240"><img src="../img/slide1_1.png" alt="第一张">
<div class="carousel-caption">
<h3>The First picture</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus, tempore!</p>
</div>
</div>
<div class="item" style="background:#F5E4DB"><img src="../img/slide2_1.png" alt="第二张">
<div class="carousel-caption">
<h3>The Second picture</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic, iste!</p>
</div>
</div>
<div class="item" style="background:#DC292C"><img src="../img/slide3_1.png" alt="第三张">
<div class="carousel-caption">
<h3>The Third picture</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi, fugit!</p>
</div>
</div>
</div>
<!--另一种自带的居中方法-->
<!--<a href="#myCarousel" data-slide="prev" class="carousel-control left">‹</a>-->
<!--<a href="#myCarousel" data-slide="next" class="carousel-control right">›</a>-->
<a href="#myCarousel" data-slide="prev" class="carousel-control left">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a href="#myCarousel" data-slide="next" class="carousel-control right">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
<!--内容部分-->
<div class="content">
<div class="container">
<h2 class="header-h2">「 为什么选择青山电子 」</h2>
<p class="header-p">强大的师资力量,完美的实战型管理课程,让您的企业 实现质的腾飞!</p>
<div class="row">
<div class="col-md-6 col">
<div class="media">
<div class="media-left media-top">
<a href="#"><img src="../img/tab1-1.png" alt="特色一" class="media-object"></a>
</div>
<div class="media-body">
<h4 class="media-heading">课程内容</h4>
<p class="others-p">其他:不知名的高校老师编写!</p>
<p>我们:知名企业家、管理学大师联合编写的具有实现性教材!</p>
</div>
</div>
</div>
<div class="col-md-6 col">
<div class="media">
<div class="media-left media-top">
<a href="#"><img src="../img/tab1-2.png" alt="特色二" class="media-object"></a>
</div>
<div class="media-body">
<h4 class="media-heading">师资力量</h4>
<p class="others-p">其他:非欧美正牌大学毕业的、业界没有知名度的讲师!</p>
<p>我们:美国哈佛、耶鲁等世界一流高校、享有声誉的名牌专家!</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col">
<div class="media">
<div class="media-left media-top">
<a href="#"><img src="../img/tab1-3.png" alt="特色三" class="media-object"></a>
</div>
<div class="media-body">
<h4 class="media-heading">课时安排</h4>
<p class="others-p">其他:无法保证上课效率、没有时间表,任务无法完成!</p>
<p>我们:保证正常的上课效率、制定一张时间表、当天的任务当天完成!</p>
</div>
</div>
</div>
<div class="col-md-6 col">
<div class="media">
<div class="media-left media-top">
<a href="#"><img src="../img/tab1-4.png" alt="特色四" class="media-object"></a>
</div>
<div class="media-body">
<h4 class="media-heading">服务团队</h4>
<p class="others-p">其他:社会招聘的、服务水平参差不齐的普通员工!</p>
<p>我们:内部培养、经受过良好高端服务培训的高标准员工!</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="content2">
<div class="container">
<div class="row row1">
<div class="col-md-6 col-sm-6 float-image">
<img src="../img/tab2.png" class="img-responsive center-block" alt="asasa">
</div>
<div class="col-md-6 col-sm-6 text float-text">
<h3>强大的学习体系</h3>
<p>经过管理学大师层层把关、让您的企业突飞猛进。</p>
</div>
</div>
</div>
</div>
<div class="content3">
<div class="container">
<div class="row row2">
<div class="col-md-6 col-sm-6">
<img src="../img/tab3.png" class="img-responsive center-block" alt="asa">
</div>
<div class="col-md-6 col-sm-6 text">
<h3>完美的管理方式</h3>
<p>最新的管理培训方案,让您的企业赶超同行。</p>
</div>
</div>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 青山电子科技. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function () {
$('#myCarousel').carousel({interval:4000});//轮播图两秒自动循环播放
/*
$(window).onload(aSize()).resize(aSize());
function aSize (){ //图片切换链接居中,页面加载、缩放时调用
var aSize=$('.carousel-inner img').eq(0).height() ||$('.carousel-inner img').eq(1).height()
||$('.carousel-inner img').eq(2).height();
$('.carousel-control').css('line-height',aSize+'px');
}*/
// 设置内容区域文字垂直居中
var containerHeight= $('.content2').height();
var imgHeight=$('.content2 img').height()/2;
$('.content2 .text').css('margin-top',containerHeight-imgHeight-40 +'px');
var containerHeight1= $('.content3').height();
var imgHeight1=$('.content3 img').height()/2;
$('.content3 .text').css('margin-top',containerHeight1-imgHeight1-40 +'px');
})
</script>
</body>
</html><file_sep>/admin/aboutus.php
<?php
require('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>关于我们</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="admin_index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="admin_index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="message.php"><span class="glyphicon glyphicon-fire"></span> 留言板</a></li>
<li><a href="sta_info.php"><span class="glyphicon glyphicon-list"></span> 职工信息</a></li>
<li><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li class="active"><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<hgroup>
<h1>关于</h1>
<h4>企业内训的最新动态、资源等...</h4>
</hgroup>
</div>
</div>
<div class="about">
<div class="container">
<div class="row">
<div class="col-md-3 hidden-sm hidden-xs">
<div class="list-group">
<a href="#1" class="list-group-item">1.机构简介</a>
<a href="#2" class="list-group-item">2.加入我们</a>
<a href="#3" class="list-group-item">3.联系方式</a>
</div>
</div>
<div class="col-md-9 about-content">
<a name="1"></a>
<h3>企业简介</h3>
<p>
南昌青山电子有限公司在IT外包领域有着与超过100家企业客户保持长期良好的IT外包合作关系,拥有长达5年之久的IT外包服务经验。专业的技术,周到的服务,合理的价格为企业提供全方位的IT外包服务。如今“江西IT外包服务网”依靠专业技术背景与多年企业IT外包维护经验积累,已经形成一套有的企业IT服务标准,是企业客户IT外包服务的首选。 </p><p> “南昌IT外包服务网”为企业提供专业的IT外包服务,服务内容包括IT外包服务,系统管理优化,电脑维修外包,电脑维护外包,企业IT服务外包,网络维护外包,网络优化,打印机维修维护外包,网络工程,电话交换机外包,企业IT产品采购,数据恢复,企业邮局,网站设计,企业IT人才外包,综合布线,门禁系统,企业宽带申请,企业IP电话申请等。欢迎您来电咨询,我们将热情为您服务。</p>
<a name="2"></a>
<h3>加入我们</h3>
<p>
网络已深刻改变着人们的生活,本地化生活服务市场前景巨大,我们公司每个团队坚信本地化生活服务与互联网的结合将会成就一家梦幻的公司,我们脚踏实地的相信梦 想,我们相信你的加入会让生活半径更可能成为那家梦幻公司!生活半径人有梦想,有魄力, 强执行力,但是要实现这个伟大的梦想,需要更多的有创业精神的你一路前行。公司将提供 有竞争力的薪酬、完善的福利(五险一金)、期权、广阔的上升空间。只要你有能力、有激 情、有梦想,愿意付出,愿意与公司共同成长,请加入我们
</p>
<a name="3"></a>
<h3>联系方式</h3>
<p>地址:江西省南昌市青山湖区广兰大道 418 号</p>
<p>邮编:346400</p>
<p>电话:010-88888888</p>
<p>传真:010-66666666</p>
</div>
</div>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 企业职工网. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function () {
});
</script>
</body>
</html><file_sep>/staff/sta_info.php
<?php
require_once('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>职工信息</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="admin_index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="message.php"><span class="glyphicon glyphicon-fire"></span> 校园话题</a></li>
<li><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="#"><?=$_SESSION['username']?></a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<hgroup>
<h1>个人工资信息</h1>
<h4>企业职工每个人的个人工资信息的维护要做到公平、公正...</h4>
</hgroup>
</div>
</div>
<div class="case">
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">
<div class="thumbnail">
<img src="../img/case1.jpg" alt="中国移动">
<div class="caption">
<h4>中国移动通信</h4>
<P>参与了本机构的总裁管理培训课程,学员反馈意见良好.</P>
</div>
</div>
</div>
</div>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 企业职工网. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function () {
});
</script>
</body>
</html><file_sep>/check_login.php
<?php
//防跳墙文件
session_start();
header('Content-type:text/html;charset=utf-8');
if (!isset($_SESSION['username'])) {
echo "<script>alert('您尚未登陆,请重新登录');location.href='../login.php';</script>";
}
?><file_sep>/admin/information.php
<?php
require('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>资讯</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="admin_index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="admin_index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="case.php"><span class="glyphicon glyphicon-fire"></span> 留言板</a></li>
<li><a href="sta_info.php"><span class="glyphicon glyphicon-list"></span> 职工信息</a></li>
<li><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<hgroup>
<h1>资讯</h1>
<h4>企业内训的最新动态、资源等...</h4>
</hgroup>
</div>
</div>
<div class="info">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="container-fluid">
<div class="row info-content">
<div class="col-md-5 col-sm-5 col-xs-5"><img src="../img/info1.jpg" alt="资讯一" class="img-responsive"></div>
<div class="col-md-7 col-sm-7 col-xs-7">
<h4>广电总局发布 TVOS2.0 华为阿里参与研发</h4>
<p class="hidden-xs">TVOS2.0是在TVOS1.0与华 为 MediaOS 及阿里巴巴 YunOS 融合的基础上,打造的新一代智能电视操作系统。华为主要
承担开发工作,内置的电视购物商城由阿里方面负责。
</p>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row info-content">
<div class="col-md-5 col-sm-5 col-xs-5"><img src="../img/info2.jpg" alt="资讯二" class="img-responsive"></div>
<div class="col-md-7 col-sm-7 col-xs-7">
<h4>苹果四寸手机为何要配置强大的A9处理器</h4>
<p class="hidden-xs">苹果明年初有可能对外发布一款经过升级的四英寸手机,相当于iPhone 5s。该手机将会配置苹果在2015年旗舰手机中采用的A9处理器。配置性能如此强大的应用处理器?</p>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row info-content">
<div class="col-md-5 col-sm-5 col-xs-5"><img src="../img/info3.jpg" alt="资讯三" class="img-responsive"></div>
<div class="col-md-7 col-sm-7 col-xs-7">
<h4>六家互联网公司发声明 抵制流量劫持等违法行为</h4>
<p class="hidden-xs">六家互联网公司(今日头条、美团大众点评网、360、腾讯、微博、小米科技)发布联合声明,呼吁有关运营商打击流量劫持,重视互联网公司被流量劫持,可能导致的严重后果。</p>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row info-content">
<div class="col-md-5 col-sm-5 col-xs-5"><img src="../img/info1.jpg" alt="资讯一" class="img-responsive"></div>
<div class="col-md-7 col-sm-7 col-xs-7">
<h4>广电总局发布 TVOS2.0 华为阿里参与研发</h4>
<p class="hidden-xs">TVOS2.0是在TVOS1.0与华 为 MediaOS 及阿里巴巴 YunOS 融合的基础上,打造的新一代智能电视操作系统。华为主要
承担开发工作,内置的电视购物商城由阿里方面负责。
</p>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row info-content">
<div class="col-md-5 col-sm-5 col-xs-5"><img src="../img/info2.jpg" alt="资讯二" class="img-responsive"></div>
<div class="col-md-7 col-sm-7 col-xs-7">
<h4>苹果四寸手机为何要配置强大的A9处理器</h4>
<p class="hidden-xs">苹果明年初有可能对外发布一款经过升级的四英寸手机,相当于iPhone 5s。该手机将会配置苹果在2015年旗舰手机中采用的A9处理器。配置性能如此强大的应用处理器?</p>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row info-content">
<div class="col-md-5 col-sm-5 col-xs-5"><img src="../img/info3.jpg" alt="资讯三" class="img-responsive"></div>
<div class="col-md-7 col-sm-7 col-xs-7">
<h4>六家互联网公司发声明 抵制流量劫持等违法行为</h4>
<p class="hidden-xs">六家互联网公司(今日头条、美团大众点评网、360、腾讯、微博、小米科技)发布联合声明,呼吁有关运营商打击流量劫持,重视互联网公司被流量劫持,可能导致的严重后果。</p>
<p>admin 15 / 10 / 11</p>
</div>
</div>
</div>
</div>
<div class="col-md-4 info-right hidden-sm hidden-xs">
<div class="container-fluid">
<blockquote>
<h2>热门资讯</h2>
</blockquote>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info3.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>六家互联网公司发声明 抵制流量劫持等违法行为</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info2.jpg" alt="资讯三" class="img-responsive" style="margin:12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>苹果四寸手机为何要配置强大的A9处理器</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info1.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>广电总局发布 TVOS2.0 华为阿里参与研发</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info3.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>六家互联网公司发声明 抵制流量劫持等违法行为</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info2.jpg" alt="资讯三" class="img-responsive" style="margin:12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>苹果四寸手机为何要配置强大的A9处理器</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info1.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>广电总局发布 TVOS2.0 华为阿里参与研发</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info3.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>六家互联网公司发声明 抵制流量劫持等违法行为</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info2.jpg" alt="资讯三" class="img-responsive" style="margin:12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>苹果四寸手机为何要配置强大的A9处理器</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info1.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>广电总局发布 TVOS2.0 华为阿里参与研发</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info3.jpg" alt="资讯三" class="img-responsive" style="margin: 12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>六家互联网公司发声明 抵制流量劫持等违法行为</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<img src="../img/info2.jpg" alt="资讯三" class="img-responsive" style="margin:12px 0;padding: 0;"></div>
<div class="col-md-7 col-sm-7 col-xs-7" style="padding:0;">
<h4>苹果四寸手机为何要配置强大的A9处理器</h4>
<p>admin 15 / 10 / 11</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 企业职工网. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function () {
});
</script>
</body>
</html><file_sep>/zhangwang/update.php
<?php
header('Content-type:text/html;charset=utf-8');
$gname=$_POST['gname'];
$gnum=$_POST['gnum';
$gbasemon=$_POST['gbasemon'];
$gjinmon=$_POST['gjinmon'];
$gtemon=$_POST['gtemon'];
require_once('../condb.php');
$sql="select * from gang_info where gname='{$gname'}";
$rs=$pdo->query($sql);
$result=$rs->fetchAll(PDO::FETCH_ASSOC);
$sql="update gang_info set gbasemon='{$gbasemon}',gjinmon='{$gjinmon}',gtemon='{$gtemon}' where gname='{$gname}'";
$pdo->exec($sql);
header('Location:admin_gang.php');
?><file_sep>/del.php
<?php
require_once('PDO.php');
$sql ="select * from student";
$rs = $pdo->query($sql);
$result =$rs->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>删除学生信息</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>专业</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result as $key => $value) {
?>
<tr>
<td><?=$value['sid']?></td>
<td><?=$value['sname']?></td>
<td><?=$value['sex']?></td>
<td><?=$value['age']?></td>
<td><?=$value['major']?></td>
<td><?=$value['tel']?></td>
<td>
<a href="del_id.php?sid=<?=$value['sid']?>">删除</a>
<a href="update.php?sid=<?=$value['sid']?>">修改</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html><file_sep>/zhangwang/add.php
<?php
header('Content-type:text/html;charset=utf-8');
$gnum=$_POST['gnum'];
$gname=$_POST['gname'];
$gbasemon=$_POST['gbasemon'];
$gjinmon=$_POST['gjinmon'];
$gtemon=$_POST['gtemon'];
$staff_info_id=$_POST['staff_info_id'];
require_once('../condb.php');
$sql="insert into gang_info(gnum,gname,gbasemon,gjinmon,gtemon,staff_info_id) values('{$gnum}','{$gname}', '{$gbasemon}','{$gjinmon}','{$gtemon}','{$staff_info_id}')";
if($pdo->exec($sql)){
echo '添加成功!';
}else{
echo '<script>alert("添加失败");history.back();</script>' ;
exit();
}<file_sep>/staff/message.php
<?php
require_once('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>校园话题</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li ><a href="index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="information.php"><span class="glyphicon glyphicon-list"></span> 资讯</a></li>
<li class="active"><a href="message.php"><span class="glyphicon glyphicon-fire"></span> 校园话题</a></li>
<li><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="#"><?=$_SESSION['username']?></a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<hgroup>
<h1>话题板</h1>
<h4>发生在校园里的最新心情和动态、话题等...</h4>
</hgroup>
</div>
</div>
<div class="case">
<div class="container">
<?php
require_once('../condb.php');
$sql="SELECT * FROM message";
$rs=$pdo->query($sql);
$list=$rs->fetchAll(PDO::FETCH_ASSOC);
foreach ($list as $key => $value) {
?>
<div class="container-fluid">
<div class="row info-content clearfix">
<div class="col-md-2 col-sm-2 col-xs-2" style="margin-top:10px"><img src="../img/info1.jpg" alt="资讯一" class="img-responsive"></div>
<div class="col-md-10 col-sm-10 col-xs-10">
<h4 style="float:left;"><?=$value['mtitle']?></h4>
<p class="hidden-xs" style="clear:both;">
<span style="font-weight:bold;"><?=$value['mwho']?>:</span><?=$value['mcontent']?>
</p>
<p style="float:right;"><?=$value['mtime']?></p>
</div>
</div>
</div>
<?php
}
?>
<div style="margin:10px 0 10px 40px;">
<h4 style="float:left;margin-left:5px;">发表留言</h4><br/><br/>
<form action="message_save.php" method="post" style="margin:10px 0 10px 5px;">
<input class="col-md-7 col-sm-6 col-xs-6" type="text" name="mtitle" placeholder="留言标题">
<br/><br/>
<textarea class="col-md-7 col-sm-6 col-xs-6" placeholder="留言内容" name="mcontent" style="margin-bottom:10px;"></textarea>
<input class="btn btn-default btn-success btn-block" " type="submit" name="message" value="发表留言">
</form>
</div>
</div>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 青山电子科技. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function () {
});
</script>
</body>
</html><file_sep>/zhangwang/query.php
<?php
require_once('PDO.php');
$sql ="select * from student";
$rs = $pdo->query($sql);
$result =$rs->fetchAll(PDO::FETCH_ASSOC); // fetchAll(); //返回一个包含结果集中所有行的数组
var_dump($result);
?>
<table border="1">
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>专业</th>
<th>电话</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result as $key => $value) {
?>
<tr>
<td><?=$value['sid']?></td>
<td><?=$value['sname']?></td>
<td><?=$value['sex']?></td>
<td><?=$value['age']?></td>
<td><?=$value['major']?></td>
<td><?=$value['tel']?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<file_sep>/README.md
BootStrap Practice
=================
Welcome to **BootStrap练习**.
- 好久没有敲代码了,敲敲看.
- 做一个响应式的实训网.
- php+bootstrap+mysql
<file_sep>/admin/add.php
<?php
header('Content-type:text/html;charset=utf-8');
$gnum=$_POST['gnum'];
$gname=$_POST['gname'];
$gbasemon=$_POST['gbasemon'];
$gjinmon=$_POST['gjinmon'];
$gtemon=$_POST['gtemon'];
require_once('../condb.php');
$sql="insert into gang_info(`gnum`,`gname`,`gbasemon`,`gjinmon`,`gtemon`) values('$gnum','$gname','$gbasemon','$gjinmon','$gtemon')";
$result=$pdo->exec($sql);
if($result){
echo '<script>alert("添加成功");location.href="sala_info.php";</script>' ;
}else{
echo '<script>alert("添加失败");location.href="sala_info.php";</script>' ;
exit();
}<file_sep>/admin/update.php
<?php
header('Content-type:text/html;charset=utf-8');
$gname=$_POST['gname'];
echo $gname;
$gnum=$_POST['gnum'];
$gbasemon=$_POST['gbasemon'];
$gjinmon=$_POST['gjinmon'];
$gtemon=$_POST['gtemon'];
require_once('../condb.php');
// $sql="select * from gang_info where gname='$gname'";
// $rs=$pdo->query($sql);
// $result=$rs->fetchAll(PDO::FETCH_ASSOC);
$sql="update gang_info set `gbasemon`='$gbasemon',`gjinmon`='$gjinmon',`gtemon`='$gtemon' where `gname`='$gname'";
// var_dump($sql);
$result=$pdo->exec($sql);
var_dump($result);
header('Location:sala_info.php');
?><file_sep>/admin/del1.php
<?php
header('Content-type:text/html;charset=utf-8');
$sname=$_GET['sname'];
echo $sname;
require_once('../condb.php');
$sql="delete from `staff_info` where `sname` = '$sname' ";
$result=$pdo->exec($sql);
if($result){
header('Location:sala_info.php');
}
?><file_sep>/admin/exit.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户信息修改</title>
</head>
<body>
<h3>用户信息修改</h3>
<?php
$gname=$_GET['gname'];
require_once('../condb.php');
$sql="select * from gang_info where `gname` = '$gname' ";
$rs = $pdo->query($sql);
$result =$rs->fetchAll(PDO::FETCH_ASSOC); // fetchAll(); //返回一个包含结果集中所有行的数组
var_dump($result);
foreach ($result as $key => $value)
if (!$result) {
exit();
}
?>
<form action="update.php" method="post">
<p>
<input type="text" name="gname" value="<?=$value['gname']?>">
</p>
<p>
<input type="text" name="gnum" value="<?=$value['gnum']?>">
</p>
<p>
<input type="text" name="gbasemon" value="<?=$value['gbasemon']?>">
</p>
<p>
<input type="text" name="gjinmon" value="<?=$value['gjinmon']?>">
</p>
<p>
<input type="text" name="gtemon" value="<?=$value['gtemon']?>">
</p>
<p>
<!-- <input type="hidden" name="id" value="<?=$value['id']?>"> -->
<button type="submit">修改</button>
</p>
</form>
</body>
</html>
<file_sep>/admin/exit1.php
<?php
$gname=$_GET['gname'];
require_once('../condb.php');
$sql="select * from gang_info where `gname` = '$gname' ";
$rs = $pdo->query($sql);
$result =$rs->fetchAll(PDO::FETCH_ASSOC); // fetchAll(); //返回一个包含结果集中所有行的数组
var_dump($result);
foreach ($result as $key => $value)
if (!$result) {
exit();
}
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>填写岗位信息</title>
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.min.css">
<style>
/*web background*/
.container{
display:table;
height:100%;
}
.row{
display: table-cell;
vertical-align: middle;
}
/* centered columns styles */
.row-centered {
text-align:center;
}
.col-centered {
display:inline-block;
float:none;
text-align:left;
margin-right:-4px;
}
@media (min-width: 768px)
{
.well{
height:400px;
width:350px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="row row-centered">
<div class="well col-md-6 col-centered">
<h2><?=$value['gname']?>基本信息</h2>
<form action="update.php" method="post">
<div class="input-group input-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-user" aria-hidden="true"></i></span>
<input type="text" class="form-control" name="gnum" value="<?=$value['gnum']?>"/>
</div>
<div class="input-group input-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="text" class="form-control" name="gname" value="<?=$value['gname']?>"/>
</div>
<div class="input-group input-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-usd">基本工资</i></span>
<input type="text" class="form-control" name="gbasemon" value="<?=$value['gbasemon']?>"/>
</div>
<div class="input-group input-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-usd">普通津贴</i></span>
<input type="text" class="form-control" name="gjinmon" value="<?=$value['gjinmon']?>"/>
</div>
<div class="input-group input-group-md">
<span class="input-group-addon"><i class="glyphicon glyphicon-usd">特殊津贴</i></span>
<input type="text" class="form-control" name="gtemon" value="<?=$value['gtemon']?>"/>
</div>
<br/>
<p>
<button type="submit" class="btn btn-info btn-block">确认修改</button>
<button type="reset" class="btn btn-success btn-block">取 消</button>
</p>
</form>
</div>
</div>
</div>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
</body>
</html><file_sep>/admin/sala_info.php
<?php
require('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>工资信息</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="shortcut icon" href="../img/100du.ico">
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/main.css">
<style>
td,th{text-align:center;}
</style>
</head>
<body>
<nav class="nan navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a href="admin_index.php" class="navbar-brand logo"><img src="../img/logo.png" alt=""></a>
<button type="button" class="btn btn-default navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="admin_index.php"><span class="glyphicon glyphicon-home"></span> 首页</a></li>
<li><a href="message.php"><span class="glyphicon glyphicon-fire"></span> 留言板</a></li>
<li><a href="sta_info.php"><span class="glyphicon glyphicon-list"></span> 职工信息</a></li>
<li class="active"><a href="sala_info.php"><span class="glyphicon glyphicon-list"></span> 工资信息</a></li>
<li><a href="aboutus.php"><span class="glyphicon glyphicon-question-sign"></span> 关于我们</a></li>
<li><a href="../logout.php">注销</a></li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron">
<div class="container">
<hgroup>
<h1>工资信息</h1>
<h4>及时进行工资信息的添加、更新...</h4>
</hgroup>
</div>
</div>
<div class="case">
<div class="container">
<table class="table table-striped table-bordered table-hover">
<thead>
<caption>岗位工资信息表</caption>
<tr class="info central">
<th>岗位编号</th>
<th>岗 位</th>
<th>基本工资</th>
<th>普通津贴</th>
<th>特殊津贴</th>
<th>总 计</th>
<th>操 作</th>
</tr>
</thead>
<tbody>
<?php
require_once('../condb.php');
$sql="select * from gang_info ";
$rs=$pdo->query($sql);
// var_dump($rs);
$list=$rs->fetchAll(PDO::FETCH_ASSOC);
// var_dump($list);
foreach ($list as $key => $value) {
$_SESSION['gname']=$value['gname'];
?>
<tr>
<td><?=$value['gnum']?></td>
<td><?=$value['gname']?></td>
<td><?=$value['gbasemon']?></td>
<td><?=$value['gjinmon']?></td>
<td><?=$value['gtemon']?></td>
<td><?=$value['gtemon']+$value['gjinmon']+$value['gbasemon']?></td>
<td><a href="exit1.php ? gname=<?=$value['gname']?>">更新</a>
<a href="del.php ? gname=<?=$value['gname']?>" onclick="return del_confirm();">删除</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<p style="text-align:right;">
<button id='add' class='btn-default btn-warning'>增加岗位</button>
</p>
</div>
</div>
<footer id="footer">
<footer class="container">
<p>企业管理 | 合作事宜 | 版权投诉</p>
<p>赣 ICP 备 12345678. © 2005-2018 企业职工网. Powered by ECUT.</p>
</footer>
</footer>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.js"></script>
<script>
$(function(){
function del_confirm(){
if(confirm('是否确认删除?')){
return true;
}else{
return false;
}
}
var oAdd=document.getElementById('add');
oAdd.onclick=function(){
window.location.href='add.html';
}
});
</script>
</body>
</html><file_sep>/zhangwang/del.php
<?php
$gname=$_GET['gname'];
echo $gname;die();
require_once('../condb.php');
$sql="delete from gang_info where gname={$gname}";
if($pdo->exec($sql)){
header('Location:admin_gang.php');
}
?><file_sep>/admin/del.php
<?php
$gname=$_GET['gname'];
echo $gname;
require_once('../condb.php');
$sql="delete from `gang_info` where `gname` = '$gname' ";
$result=$pdo->exec($sql);
if($result){
header('Location:sala_info.php');
}
?><file_sep>/condb.php
<?php
//连接数据库文件
header('Content-type:text/html;charset=utf-8');
try {
$dsn = 'mysql:host=localhost;dbname=staffmanager';
$pdo = new PDO($dsn,'root','');
$pdo->exec('set names utf8');
// echo "连接成功";
} catch (PODException $e) {
echo 'error:'.$e->getMessage();
exit();
}
?><file_sep>/message_save.php
<?php
session_start();
require_once('condb.php');
header('Content-type:text/html;charset=utf-8');
echo $_SESSION['username'];
$mwho=$_SESSION['username'];
$mtitle=$_POST['mtitle'];
$mcontent=$_POST['mcontent'];
ini_set('date.timezone','Asia/Shanghai'); //修改时区 (不改默认为伦敦)
$mtime = date('Y-m-d H:i:s',time()); //获取当前系统时间
$sql="insert into message set mtitle='$mtitle',mcontent='$mcontent',mwho='$mwho',mtime='$mtime'";
var_dump($sql);
$result=$pdo->exec($sql);
var_dump($result);
header('Location:message.php');
?><file_sep>/admin/zhuce_save.php
<?php
require('../check_login.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>zhuce_save</title>
</head>
<body>
<?php
print_r($_POST);
$username =$_POST["sname"];
$password=$_POST["pwd"];
$zgnum=$_POST["snum"];
$sex =isset($_POST["sex"])?$_POST["sex"]:"男";
$gwnum=$_POST["gnum"];
$birth=$_POST["sbir"];
$worktime=$_POST["stime"];
require("fun.php");
$db=conn();
$sql="insert into login set
sname='$username',
pwd='$<PASSWORD>'";
$count=$db->exec($sql);
$sqll="insert into staff_info set
sname='$username',
snum='$zgnum',
ssex='$sex',
sbir='$birth',
gnum='$gwnum',
stime='$worktime'";
$countt=$db->exec($sqll);
if($countt){
echo "<script>alert('注册成功');location.href='login.php'</script>";
}
?>
</body>
</html><file_sep>/function.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>function</title>
</head>
<body>
<?php
$a =[1,2,3,4,5];
$num = count($a);
echo $num."<br/>";
for ($i=0; $i <$num ; $i++) {
echo $a[$i].",";# code...
}
function a(){
echo "welcome to the hotel"."<br/>";
return "welcome to the hotel"."<br/>";
}
echo a();
function sum($a,$b){
return $a+$b;//return,返回值,终止执行
}
/* echo sum(10,20);
*/ function sub($a,$b,$c)
{
switch ($c) {
case "+":
return $a+$b;
break;
case "-":
return $a-$b;
break;
case "*":
return $a*$b;
break;
case "/":
return $a/$b;
break;
case "%":
return $a%$b;
break;
}
}
echo sub(1,2,"/")."<br/>";
function cal($a,$b,$c)
{
if($c=="+")
return $a+$b;
if($c=="-")
return $a-$b;
if($c=="*")
return $a*$b;
if($c=="/")
return $a/$b;
if($c=="%")
return $a%$b;
}
echo cal(10,5,"-");
?>
</body>
</html> | 4ec1aeede348392df4f20f32045bd549f91d475b | [
"Markdown",
"SQL",
"PHP"
] | 32 | SQL | HeiLiu/BootStrap-Practice | 60aff589ae915265fbacec2148e50d49207e0d61 | 860141588d68e7dc008deaeb814023b8b9ba6f3a |
refs/heads/master | <repo_name>vasyatech/ucsd-javascript<file_sep>/homework5/readme.txt
Using nothing but the DOM, validate the attached html using nothing but javascript so that at all inputs have at least something entered, checked or selected.
Your user has nothing but Internet Explorer 6!
<file_sep>/homework3/myjavascript.js
var statesArray = ['Alabama','Alaska','American Samoa','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Federated States of Micronesia','Florida','Georgia','Guam','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Marshall Islands','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Northern Mariana Islands','Ohio','Oklahoma','Oregon','Palau','Pennsylvania','Puerto Rico','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virgin Island','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
function formatHours(hour){
var ampm = hour >= 12 ? 'pm' : 'am';
var hours = hour % 12;
hours = hours ? hours : 12;
return hours + ':00' + ' ' + ampm;
}
function populateDropDowns(){
var select = document.getElementById("select_state");
for(var i = 0; i < statesArray.length; i++) {
select.options[select.options.length] = new Option(statesArray[i], statesArray[i]);
}
var select = document.getElementById("select_time");
for(var i = 0; i < 24; i++) {
select.options[select.options.length] = new Option(formatHours(i), i);
}
}
function reserveClick(){
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
var selectedState = document.getElementById("select_state").value;
//alert("selectedState = " + selectedState);
var taxRate = 8;
var tax = 0.00;
var price = 0.00;
if (selectedState == "California"){
taxRate = 6;
}
//alert("tax = " + tax);
var selectedTime = document.getElementById("select_time").value;
//alert("selectedTime = " + selectedTime);
if (selectedTime >= 8 && selectedTime < 12) {
price = 20;
}
else if (selectedTime >= 12 && selectedTime <= 18){
price = 25;
}
else if (selectedTime > 18 && selectedTime <=22){
price = 15;
}
else {
alert("This time is not available. Working hours are from 8AM to 10PM");
}
//alert("price = " + price);
document.getElementById("lbl_price").innerHTML = "Price:";
document.getElementById("price").innerHTML = formatter.format(price);
document.getElementById("lbl_tax").innerHTML = "Tax (" + taxRate + "%):";
tax = price*taxRate/100;
document.getElementById("tax").innerHTML = formatter.format(tax);
document.getElementById("lbl_total").innerHTML = "Total:";
document.getElementById("total").innerHTML = formatter.format(price+tax);
}<file_sep>/homework6/readme.txt
Your job is to take that data and output the weather including the description and temperature on a web page.<file_sep>/homework2/myjavascript.js
function calculate(){
var pennies = 1;
for(i=1; i<365; i++){
pennies *= 2;
}
alert(pennies + " pennies");
}<file_sep>/homework7/readme.txt
Question 1
I've got this groovy object of menu items.
Please output them in a discernable fashion so my customers can order
Style is your choice...you're the web guru
Question 2
Now that you've outputted the menu in JavaScript, let the user order and save their order as a JSON string in localStorage
Question 3
Add a button with the label "Your Order". Onclick, show the user what they have ordered | 92cc54fc7a453180d7549a41e1e26db66dc06d4b | [
"JavaScript",
"Text"
] | 5 | Text | vasyatech/ucsd-javascript | c90527e62de2a1ba308eabe8e848df0abbba53ed | 090b56e69baa3de398a38ff063697603dddd67a7 |
refs/heads/master | <repo_name>GoodReserve/GoodReserve-Android<file_sep>/app/src/main/java/kr/edcan/rerant/activity/ReserveCompleteActivity.java
/*
* Created by <NAME> on 2016.
* Copyright by Good-Reserve Project @kotohana5706
* All rights reversed.
*/
package kr.edcan.rerant.activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import org.json.JSONObject;
import kr.edcan.rerant.R;
import kr.edcan.rerant.databinding.ActivityReserveCompleteBinding;
import kr.edcan.rerant.model.Bucket;
import kr.edcan.rerant.model.Menu;
import kr.edcan.rerant.model.Reservation;
import kr.edcan.rerant.utils.NetworkHelper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ReserveCompleteActivity extends AppCompatActivity {
Call<Reservation> reservationCall;
ActivityReserveCompleteBinding binding;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_reserve_complete);
initAppbarLayout();
setDefault();
}
private void setDefault() {
intent = getIntent();
reservationCall = NetworkHelper.getNetworkInstance().getReservationInfo(intent.getStringExtra("id"));
reservationCall.enqueue(new Callback<Reservation>() {
@Override
public void onResponse(Call<Reservation> call, Response<Reservation> response) {
switch (response.code()) {
case 200:
Reservation data = response.body();
String menuResult = "";
Bucket bucket = data.getReservation_menu();
for(Menu m : bucket.getMenus()){
menuResult += m.getName() + " ";
}
binding.reserveCode.setText(data.getReservation_code());
binding.reserveDateStatus.setText(data.getReservation_time().toLocaleString());
binding.reserveResTitle.setText(data.getRestaurant_name());
binding.reserveInfo.setText(menuResult);
binding.reserveMoney.setText(data.getReservation_price()+" 원");
break;
default:
break;
}
}
@Override
public void onFailure(Call<Reservation> call, Throwable t) {
}
});
binding.reserveConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
binding.reserveCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ReserveCompleteActivity.this, "정식 서비스 이용때 지원 예정입니다.", Toast.LENGTH_SHORT).show();
}
});
}
private void initAppbarLayout() {
setSupportActionBar(binding.toolbar);
binding.toolbar.setBackgroundColor(Color.WHITE);
binding.toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimary));
getSupportActionBar().setTitle("예약 완료");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
<file_sep>/README.md
# GoodReserve-Android
Samsung Tomorrow Solution 2016 "No-Show Campaign" Android Client
# Contributor
* iOS Client Developer [Astoration](http://github.com/Astoration)
* Android Client Developer [<NAME>](http://github.com/kotohana5706)
* Backend Server Developer [GrooshBene](http://github.com/GrooshBene)
* IoT Developer [<NAME>](http://github.com/songjun51)
* Service Planner [ENEMNM](http://github.com/ENEMNM)
* Service Planner [SongA](http://github.com/absolsonga)
<file_sep>/app/src/main/java/kr/edcan/rerant/model/User.java
package kr.edcan.rerant.model;
import java.util.ArrayList;
/**
* Created by JunseokOh on 2016. 9. 24..
*/
public class User {
private int userType;
private String email, name, phone, auth_token, reservation, _id;
private ArrayList<String> reservation_waiting;
public User(int userType, String email, String name, String phone, String auth_token) {
this.email = email;
this.userType = userType;
this.name = name;
this.phone = phone;
this.auth_token = auth_token;
}
public User(int userType, String email, String name, String phone, String auth_token, String reservation) {
this.email = email;
this.userType = userType;
this.name = name;
this.phone = phone;
this.auth_token = auth_token;
this.reservation = reservation;
}
public User(int userType, String email, String name, String phone, String auth_token, String reservation, ArrayList<String> reservation_waiting) {
this.email = email;
this.name = name;
this.userType = userType;
this.phone = phone;
this.auth_token = auth_token;
this.reservation = reservation;
this.reservation_waiting = reservation_waiting;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getAuth_token() {
return auth_token;
}
public String getReservation() {
return reservation;
}
public int getUserType() {
return userType;
}
public ArrayList<String> getReservation_waiting() {
return reservation_waiting;
}
public String get_id() {
return _id;
}
public void setUserType(int userType) {
this.userType = userType;
}
public void setEmail(String email) {
this.email = email;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setAuth_token(String auth_token) {
this.auth_token = auth_token;
}
public void setReservation(String reservation) {
this.reservation = reservation;
}
public void set_id(String _id) {
this._id = _id;
}
public void setReservation_waiting(ArrayList<String> reservation_waiting) {
this.reservation_waiting = reservation_waiting;
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/activity/ReserveSearchInfoActivity.java
/*
* Created by <NAME> on 2016.
* Copyright by Good-Reserve Project @kotohana5706
* All rights reversed.
*/
package kr.edcan.rerant.activity;
import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.github.nitrico.lastadapter.LastAdapter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import kr.edcan.rerant.BR;
import kr.edcan.rerant.R;
import kr.edcan.rerant.databinding.ActivityReserveSearchInfoBinding;
import kr.edcan.rerant.databinding.CommonListviewContentBinding;
import kr.edcan.rerant.databinding.ReserveSearchinfoMenuContentBinding;
import kr.edcan.rerant.model.Bucket;
import kr.edcan.rerant.model.CommonListData;
import kr.edcan.rerant.model.MainHeader;
import kr.edcan.rerant.model.Menu;
import kr.edcan.rerant.model.ReserveBenefit;
import kr.edcan.rerant.model.ReserveMenu;
import kr.edcan.rerant.model.Restaurant;
import kr.edcan.rerant.utils.DataManager;
import kr.edcan.rerant.utils.ImageSingleTon;
import kr.edcan.rerant.utils.NetworkHelper;
import kr.edcan.rerant.utils.StringUtils;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ReserveSearchInfoActivity extends AppCompatActivity implements LastAdapter.LayoutHandler, LastAdapter.OnBindListener, LastAdapter.OnClickListener {
public static Activity activity;
public static void finishThis() {
if (activity != null) activity.finish();
}
Intent intent;
String restaurant_id;
ArrayList<Object> arrayList;
Restaurant data;
ActivityReserveSearchInfoBinding binding;
DataManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
binding = DataBindingUtil.setContentView(this, R.layout.activity_reserve_search_info);
initAppbarLayout();
setData();
}
private void initAppbarLayout() {
setSupportActionBar(binding.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
binding.collapsingToolbar.setCollapsedTitleTextAppearance(R.style.collapsedTitleStyle);
binding.collapsingToolbar.setExpandedTitleTextAppearance(R.style.expandedTitleStyle);
binding.collapsingToolbar.setExpandedTitleMargin(
getResources().getDimensionPixelSize(R.dimen.common_titlemargin),
0,
0,
getResources().getDimensionPixelSize(R.dimen.common_titlemargin)
);
}
private void setData() {
arrayList = new ArrayList<>();
intent = getIntent();
restaurant_id = intent.getStringExtra("restaurant_id");
binding.reserveInfoRecyclerView.setLayoutManager(new LinearLayoutManager(this));
binding.bottomReserveList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (manager.canMakeReservation(restaurant_id)) {
if (manager.hasActiveBucket()) {
startActivity(new Intent(getApplicationContext(), ShoppingCartActivity.class));
Log.e("asdfasdf", "1");
}
else
Toast.makeText(ReserveSearchInfoActivity.this, "선택된 메뉴가 없습니다.\n메뉴를 먼저 선택해주세요!", Toast.LENGTH_SHORT).show();
}
else Toast.makeText(getApplicationContext(), "현재 다른 식당에 예약중이거나 예약 준비중입니다.\n계속하시려면 예약중인 식당의 예약을 취소해주세요.", Toast.LENGTH_SHORT).show();
}
});
Call<Restaurant> getRestaurantInfo = NetworkHelper.getNetworkInstance().getRestaurantInfo(restaurant_id);
getRestaurantInfo.enqueue(new Callback<Restaurant>() {
@Override
public void onResponse(Call<Restaurant> call, Response<Restaurant> response) {
switch (response.code()) {
case 200:
data = response.body();
int currentStatus = data.getReservation_check();
int maxTime = data.getReservation_cancel();
String number = data.getPhone();
String location = data.getAddress();
String title = data.getName();
getSupportActionBar().setTitle(title);
binding.reserveSearchHeaderImage.setImageUrl(StringUtils.getFullImageUrl(data.getThumbnail()), ImageSingleTon.getInstance(ReserveSearchInfoActivity.this).getImageLoader());
arrayList.add(new CommonListData("현재 예약 " + ((currentStatus == 0) ? "가능" : "불가"), "지금 예약을 요청할 수 " + ((currentStatus == 0) ? "있습니다." : "없습니다."), R.drawable.ic_reservesebu_reservestatus));
arrayList.add(new CommonListData((maxTime / 60) + "시간 내에 예약 취소 가능", "이후 예약 취소 시 패널티가 발생할 수 있습니다.", R.drawable.ic_reservesebu_reservecancel));
arrayList.add(new CommonListData(number, "음식점에 전화로 문의할수 있습니다.", R.drawable.ic_reservesebu_call));
arrayList.add(new CommonListData(location, "", R.drawable.ic_reservesebu_location));
arrayList.add(new MainHeader("메뉴", "식사할 메뉴를 선택해 주세요."));
setMenuData();
break;
default:
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다!", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<Restaurant> call, Throwable t) {
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다!", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
}
private void setMenuData() {
Call<ArrayList<Menu>> getMenus = NetworkHelper.getNetworkInstance().getMenuList(restaurant_id);
getMenus.enqueue(new Callback<ArrayList<Menu>>() {
@Override
public void onResponse(Call<ArrayList<Menu>> call, Response<ArrayList<Menu>> response) {
switch (response.code()) {
case 200:
arrayList.addAll(response.body());
initUI();
break;
default:
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다!", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<ArrayList<Menu>> call, Throwable t) {
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다!", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
}
private void initUI() {
// arrayList.add(new MainHeader("혜택", "예약이 성사될 시 제공되는 혜택입니다."));
// arrayList.add(new ReserveBenefit("10%", "한글로 드 스테이크 메뉴를 주문 시 한글로 드 스테이크 올 그란디움 시크릿 베이크드로 업그레이드 제공."));
manager = new DataManager(getApplicationContext());
LastAdapter.with(arrayList, BR.item)
.map(CommonListData.class, R.layout.common_listview_content)
.map(MainHeader.class, R.layout.main_first_header)
.layoutHandler(this)
.onBindListener(this)
.onClickListener(this)
.into(binding.reserveInfoRecyclerView);
}
@Override
public int getItemLayout(@NotNull Object item, int i) {
if (item instanceof CommonListData)
return R.layout.common_listview_content;
else if (item instanceof MainHeader)
return R.layout.main_recycler_header;
else if (item instanceof Menu) return R.layout.reserve_searchinfo_menu_content;
else if (item instanceof ReserveBenefit) return R.layout.reserve_searchinfo_menu_benefit;
return 0;
}
@Override
public void onBind(@NotNull Object o, @NotNull View view, int type, int pos) {
switch (type) {
case R.layout.common_listview_content:
CommonListData data = (CommonListData) arrayList.get(pos);
CommonListviewContentBinding binding = DataBindingUtil.getBinding(view);
binding.commonListViewIcon.setVisibility(View.VISIBLE);
binding.commonListViewIcon.setImageResource(data.getIcon());
binding.commonListViewTitle.setText(data.getTitle());
binding.commonListViewContent.setText(data.getContent());
binding.commonListViewTitle.setTextColor(Color.BLACK);
if (data.getContent().trim().equals(""))
binding.commonListViewContent.setVisibility(View.GONE);
break;
case R.layout.reserve_searchinfo_menu_content:
Menu menu = (Menu) o;
ReserveSearchinfoMenuContentBinding contentBinding = DataBindingUtil.getBinding(view);
contentBinding.menuContentImage.setImageUrl(StringUtils.getFullImageUrl(menu.getThumbnail()), ImageSingleTon.getInstance(this).getImageLoader());
break;
}
}
@Override
public void onClick(@NotNull Object o, @NotNull final View view, int type, int position) {
switch (type) {
case R.layout.reserve_searchinfo_menu_content:
Log.e("asdf", restaurant_id + " asdf");
if (manager.canMakeReservation(restaurant_id)) {
final Menu menu = (Menu) o;
boolean hasActiveBucket = manager.hasActiveBucket();
ArrayList<String> newBucket = new ArrayList<>();
newBucket.add(menu.get_id());
if (!hasActiveBucket) {
Call<Bucket> generateBucket = NetworkHelper.getNetworkInstance().newBucket(newBucket);
generateBucket.enqueue(new Callback<Bucket>() {
@Override
public void onResponse(Call<Bucket> call, Response<Bucket> response) {
switch (response.code()) {
case 200:
manager.saveCurrentBucket(response.body(), restaurant_id);
view.performClick();
break;
default:
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<Bucket> call, Throwable t) {
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
} else {
final String bucketid = manager.getCurrentBucket().second.get_id();
final Call<Bucket> getCurrentBucketInfo = NetworkHelper.getNetworkInstance().getBucketInfo(bucketid);
getCurrentBucketInfo.enqueue(new Callback<Bucket>() {
@Override
public void onResponse(Call<Bucket> call, Response<Bucket> response) {
switch (response.code()) {
case 200:
ArrayList<Menu> origin = response.body().getMenus();
ArrayList<String> result = new ArrayList<String>();
for (Menu m : origin) {
Log.e("asdf", m.getName());
result.add(m.get_id());
}
result.add(menu.get_id());
Log.e("asdf convert", StringUtils.convertArraytoString(result));
Call<ResponseBody> updateMenu = NetworkHelper.getNetworkInstance().updateBucket(bucketid, StringUtils.convertArraytoString(result));
updateMenu.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
switch (response.code()) {
case 200:
startActivity(new Intent(getApplicationContext(), ShoppingCartActivity.class));
break;
default:
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
break;
default:
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<Bucket> call, Throwable t) {
Toast.makeText(ReserveSearchInfoActivity.this, "서버와의 연동에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
}
} else {
Toast.makeText(this, "현재 다른 식당에 예약중이거나 예약 준비중입니다.\n계속하시려면 예약중인 식당의 예약을 취소해주세요.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/model/Menu.java
package kr.edcan.rerant.model;
import java.text.DecimalFormat;
/**
* Created by JunseokOh on 2016. 10. 8..
*/
public class Menu {
private String _id;
private String restaurant, name, thumbnail;
private String price;
public Menu(String name, String price) {
this.name = name;
this.price = price;
}
public Menu(String _id, String restaurant, String name, String thumbnail, String price) {
this._id = _id;
this.restaurant = restaurant;
this.name = name;
this.thumbnail = thumbnail;
this.price = price;
}
public String get_id() {
return _id;
}
public String getRestaurant() {
return restaurant;
}
public String getName() {
return name;
}
public String getThumbnail() {
return thumbnail;
}
public String getPrice() {
return price;
}
public String getMoneyString() {
return new DecimalFormat("#,###").format(Integer.parseInt(price)) + "원";
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/model/Reservation.java
package kr.edcan.rerant.model;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by Junseok on 2016-10-03.
*/
public class Reservation {
/*
* Payment
* 0 선금결제
* 1 현장결제
* */
private String _id, reservation_marker, restaurant_id, restaurant_name, reservation_code;
private Date reservation_time;
private Bucket reservation_menu;
private int reservation_people, reservation_payment, reservation_price, cancel_type, reservation_status;
public Reservation(String _id, String reservation_marker, String restaurant_id, String restaurant_name, String reservation_code, Date reservation_time, Bucket reservation_menu, int reservation_people, int reservation_payment, int reservation_price, int cancel_type, int reservation_status) {
this._id = _id;
this.reservation_marker = reservation_marker;
this.restaurant_id = restaurant_id;
this.restaurant_name = restaurant_name;
this.reservation_code = reservation_code;
this.reservation_time = reservation_time;
this.reservation_menu = reservation_menu;
this.reservation_people = reservation_people;
this.reservation_payment = reservation_payment;
this.reservation_price = reservation_price;
this.cancel_type = cancel_type;
this.reservation_status = reservation_status;
}
public String get_id() {
return _id;
}
public String getReservation_marker() {
return reservation_marker;
}
public String getRestaurant_id() {
return restaurant_id;
}
public String getRestaurant_name() {
return restaurant_name;
}
public String getReservation_code() {
return reservation_code;
}
public Date getReservation_time() {
return reservation_time;
}
public Bucket getReservation_menu() {
return reservation_menu;
}
public int getReservation_people() {
return reservation_people;
}
public int getReservation_payment() {
return reservation_payment;
}
public int getReservation_price() {
return reservation_price;
}
public int getCancel_type() {
return cancel_type;
}
public int getReservation_status() {
return reservation_status;
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/activity/MainActivity.java
/*
* Created by <NAME> on 2016.
* Copyright by Good-Reserve Project @kotohana5706
* All rights reversed.
*/
package kr.edcan.rerant.activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Network;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.util.Pair;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.github.nitrico.lastadapter.LastAdapter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import kr.edcan.rerant.BR;
import kr.edcan.rerant.R;
import kr.edcan.rerant.databinding.ActivityMainBinding;
import kr.edcan.rerant.databinding.MainFirstHeaderBinding;
import kr.edcan.rerant.databinding.MainHeaderViewpagerLayoutBinding;
import kr.edcan.rerant.databinding.MainRecyclerContentBinding;
import kr.edcan.rerant.model.MainContent;
import kr.edcan.rerant.model.MainHeader;
import kr.edcan.rerant.model.MainTopHeader;
import kr.edcan.rerant.model.Reservation;
import kr.edcan.rerant.model.Restaurant;
import kr.edcan.rerant.model.User;
import kr.edcan.rerant.utils.DataManager;
import kr.edcan.rerant.utils.ImageSingleTon;
import kr.edcan.rerant.utils.NetworkHelper;
import kr.edcan.rerant.utils.NetworkInterface;
import kr.edcan.rerant.utils.StringUtils;
import kr.edcan.rerant.views.RoundImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity implements LastAdapter.OnClickListener, LastAdapter.OnBindListener, LastAdapter.LayoutHandler, View.OnClickListener {
final static int PAGER_SCROLL_DELAY = 3000;
ActivityMainBinding binding;
ArrayList<Object> mainContentList;
ArrayList<Restaurant> headerList;
ArrayList<RoundImageView> indicatorArr;
PagerAdapterClass pageAdapter;
Handler viewPagerHandler = new Handler();
DataManager manager;
NetworkInterface service;
Reservation reservation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setSupportActionBar(binding.toolbar);
getSupportActionBar().setTitle("");
binding.toolbar.setBackgroundColor(Color.WHITE);
binding.progressLoading.startAnimation();
checkAuthStatus();
}
private void checkAuthStatus() {
manager = new DataManager(this);
service = NetworkHelper.getNetworkInstance();
Pair<Boolean, User> userPair = manager.getActiveUser();
if (!userPair.first) {
startActivity(new Intent(getApplicationContext(), AuthActivity.class));
finish();
} else {
// validate
String token = userPair.second.getAuth_token();
switch (userPair.second.getUserType()) {
case 0:
Call<User> facebookLogin = NetworkHelper.getNetworkInstance().facebookLogin(token);
facebookLogin.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
switch (response.code()) {
case 200:
Toast.makeText(MainActivity.this, response.body().getName() + " 님 안녕하세요!", Toast.LENGTH_SHORT).show();
manager.saveUserInfo(response.body(), 0);
setRecommendData();
break;
default:
Toast.makeText(MainActivity.this, "로그인된 계정의 세션이 만료되어, 다시 로그인이 필요합니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "서버와의 연결에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), AuthActivity.class));
finish();
Log.e("asdf", t.getMessage());
}
});
break;
case 1:
Call<User> authenticateUser = NetworkHelper.getNetworkInstance().authenticateUser(token);
authenticateUser.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
switch (response.code()) {
case 200:
Toast.makeText(MainActivity.this, response.body().getName() + " 님 안녕하세요!", Toast.LENGTH_SHORT).show();
manager.saveUserInfo(response.body(), 1);
setRecommendData();
break;
default:
Toast.makeText(MainActivity.this, "로그인된 계정의 세션이 만료되어, 다시 로그인이 필요합니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "서버와의 연결에 문제가 발생했습니다.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), AuthActivity.class));
finish();
Log.e("asdf", t.getMessage());
}
});
break;
}
}
}
private void setRecommendData() {
headerList = new ArrayList<>();
Call<ArrayList<Restaurant>> getRestaurantList = NetworkHelper.getNetworkInstance().getRestaurantList();
getRestaurantList.enqueue(new Callback<ArrayList<Restaurant>>() {
@Override
public void onResponse(Call<ArrayList<Restaurant>> call, Response<ArrayList<Restaurant>> response) {
switch (response.code()) {
case 200:
for (int i = 0; i < ((response.body().size() < 5) ? response.body().size() : 5); i++) {
headerList.add(response.body().get(i));
Log.e("asdf", response.body().get(i).getName());
}
pageAdapter = new PagerAdapterClass(getApplicationContext());
break;
default:
Toast.makeText(MainActivity.this, "서버와의 연결에 문제가 있습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<ArrayList<Restaurant>> call, Throwable t) {
Toast.makeText(MainActivity.this, "서버와의 연결에 문제가 있습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
setReservationData();
}
private void setReservationData() {
mainContentList = new ArrayList<>();
mainContentList.add(new MainTopHeader());
Call<ArrayList<Reservation>> getMyReservation = NetworkHelper.getNetworkInstance().getMyReservation(manager.getActiveUser().second.get_id());
getMyReservation.enqueue(new Callback<ArrayList<Reservation>>() {
@Override
public void onResponse(Call<ArrayList<Reservation>> call, Response<ArrayList<Reservation>> response) {
switch (response.code()) {
case 200:
if (response.body().size() >= 1) {
mainContentList.add(new MainHeader("곧 예약시간에 도달", "아래의 음식점에 예약한 시간이 얼마 남지 않았습니다."));
reservation = response.body().get(0);
mainContentList.add(new MainContent(reservation.getReservation_code(), reservation.getRestaurant_name(), reservation.getReservation_time().toLocaleString()));
} else mainContentList.add("");
initUI();
break;
default:
Toast.makeText(MainActivity.this, "서버와의 연결에 문제가 있습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<ArrayList<Reservation>> call, Throwable t) {
Toast.makeText(MainActivity.this, "서버와의 연결에 문제가 있습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf1", t.getMessage());
}
});
}
private void initUI() {
getSupportActionBar().setLogo(R.drawable.title_actionbar_main);
binding.mainRecycler.setVisibility(View.VISIBLE);
binding.progressLoading.setVisibility(View.GONE);
binding.toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimary));
binding.bottomBar.setVisibility(View.VISIBLE);
binding.mainRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
binding.bottomReserveHistory.setOnClickListener(this);
binding.bottomReserveLaunch.setOnClickListener(this);
LastAdapter.with(mainContentList, BR.item)
.layoutHandler(this)
.map(MainTopHeader.class, R.layout.main_first_header)
.map(MainHeader.class, R.layout.main_recycler_header)
.map(MainContent.class, R.layout.main_recycler_content)
.map(String.class, R.layout.main_recycler_blank)
.onClickListener(this)
.onBindListener(this)
.into(binding.mainRecycler);
}
private void setViewPagerScroll(final ViewPager pager) {
viewPagerHandler.postDelayed(new Runnable() {
@Override
public void run() {
pager.setCurrentItem((pager.getCurrentItem() + 1 < headerList.size()) ? pager.getCurrentItem() + 1 : 0, true);
setViewPagerScroll(pager);
}
}, PAGER_SCROLL_DELAY);
}
private void setViewPagerIndicator(LinearLayout parent) {
indicatorArr = new ArrayList<>();
int pixels = getResources().getDimensionPixelSize(R.dimen.indicator_width);
LinearLayout.LayoutParams indicatorParams = new LinearLayout.LayoutParams(pixels, pixels);
indicatorParams.setMargins(pixels / 2, 0, 0, 0);
for (int i = 0; i < headerList.size(); i++) {
RoundImageView view = new RoundImageView(getApplicationContext());
view.setLayoutParams(indicatorParams);
view.setImageDrawable(new ColorDrawable(Color.WHITE));
parent.addView(view);
indicatorArr.add(view);
}
updateViewPagerIndicator(0);
}
private void updateViewPagerIndicator(int currentItem) {
for (int i = 0; i < indicatorArr.size(); i++) {
if (i == currentItem) indicatorArr.get(i).setImageResource(R.color.indicatorPrimary);
else indicatorArr.get(i).setImageResource(R.color.indicatorSub);
}
}
@Override
public void onClick(@NotNull Object o, @NotNull View view, int i, int i1) {
}
@Override
public void onBind(@NotNull Object o, @NotNull View view, int type, int position) {
switch (type) {
case R.layout.main_first_header:
MainFirstHeaderBinding binding = DataBindingUtil.getBinding(view);
if (binding.viewPager.getAdapter() == null) {
binding.viewPager.setOffscreenPageLimit(5);
binding.viewPager.setAdapter(pageAdapter);
setViewPagerScroll(binding.viewPager);
setViewPagerIndicator(binding.indicatorParent);
binding.viewPager.addOnPageChangeListener(pageListener);
}
break;
case R.layout.main_recycler_content:
MainRecyclerContentBinding contentBinding = DataBindingUtil.getBinding(view);
contentBinding.mainContentDetailExecute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), ReserveCompleteActivity.class).putExtra("id", reservation.get_id()));
}
});
contentBinding.mainContentAlertExecute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shareText(
manager.getActiveUser().second.getName() + " 님이 품격있는 외식 문화의 시작, Rerant을 통해 " +
reservation.getRestaurant_name() + "에서 예약했습니다. 더 많은 정보를 보려면 아래 링크를 클릭해 주세요. http://goo.gl/rerantdownload"
);
}
});
}
}
@Override
public int getItemLayout(@NotNull Object item, int i) {
if (item instanceof MainHeader) return R.layout.main_recycler_header;
else if (item instanceof MainTopHeader) return R.layout.main_first_header;
else if (item instanceof String) return R.layout.main_recycler_blank;
else return R.layout.main_recycler_content;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bottomReserveHistory:
// startActivity(new Intent(getApplicationContext(), ReserveLogActivity.class));
Toast.makeText(MainActivity.this, "정식 서비스 이용때 지원 예정입니다.", Toast.LENGTH_SHORT).show();
break;
case R.id.bottomReserveLaunch:
startActivity(new Intent(getApplicationContext(), ReserveSearchActivity.class));
break;
}
}
/**
* PagerAdapter
*/
private class PagerAdapterClass extends PagerAdapter {
public PagerAdapterClass(Context c) {
super();
}
@Override
public int getCount() {
return headerList.size();
}
@Override
public Object instantiateItem(final ViewGroup container, int position) {
MainHeaderViewpagerLayoutBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.main_header_viewpager_layout, container, false);
Restaurant data = headerList.get(position);
binding.viewPagerResName.setText(data.getName());
binding.viewPagerResLocation.setText(data.getAddress());
binding.viewPagerImage.setImageUrl(StringUtils.getFullImageUrl(data.getThumbnail()), ImageSingleTon.getInstance(MainActivity.this).getImageLoader());
binding.viewPagerImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
container.addView(binding.getRoot(), 0);
return binding.getRoot();
}
@Override
public void destroyItem(View pager, int position, Object view) {
((ViewPager) pager).removeView((View) view);
}
@Override
public boolean isViewFromObject(View pager, Object obj) {
return pager == obj;
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public void finishUpdate(View arg0) {
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_menu_mypage:
startActivity(new Intent(getApplicationContext(), MyPageActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
updateViewPagerIndicator(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
};
private void shareText(String s) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, s);
startActivity(Intent.createChooser(sharingIntent, "예약 내용 공유하기"));
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/utils/DataManager.java
/*
* Created by <NAME> on 2016.
* Copyright by Good-Reserve Project @kotohana5706
* All rights reversed.
*/
package kr.edcan.rerant.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.util.Pair;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import kr.edcan.rerant.model.Bucket;
import kr.edcan.rerant.model.FacebookUser;
import kr.edcan.rerant.model.User;
public class DataManager {
/* Login Type
* 0 Facebook
* 1: Native
* */
/* Data Keys */
private static String BUCKET_SCHEMA = "bucket";
private static String HAS_ACTIVE_BUCKET = "hasbucket";
private static String USER_SCHEMA = "user_schema";
private static String HAS_ACTIVE_USER = "hasactive";
private static String LOGIN_TYPE = "login_type";
private static String FACEBOOK_TOKEN = "facebook_token";
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private Context context;
public DataManager(Context c) {
this.context = c;
preferences = context.getSharedPreferences("Rerant", Context.MODE_PRIVATE);
editor = preferences.edit();
}
public void save(String key, String data) {
editor.putString(key, data);
editor.apply();
}
public void saveFacebookCredential(String facebookToken) {
editor.putString(FACEBOOK_TOKEN, facebookToken);
editor.apply();
}
public void saveUserInfo(User user, int loginType) {
editor.putInt(LOGIN_TYPE, loginType);
editor.putString(USER_SCHEMA, new Gson().toJson(user));
editor.putBoolean(HAS_ACTIVE_USER, true);
editor.apply();
}
public Pair<Boolean, User> getActiveUser() {
if (preferences.getBoolean(HAS_ACTIVE_USER, false)) {
int userType = preferences.getInt(LOGIN_TYPE, -1);
User user = new Gson().fromJson(preferences.getString(USER_SCHEMA, ""), User.class);
user.setUserType(userType);
return Pair.create(true, user);
} else return Pair.create(false, null);
}
public String getFacebookUserCredential() {
if (preferences.getBoolean(HAS_ACTIVE_USER, false) && preferences.getInt(LOGIN_TYPE, -1) == 0) {
return preferences.getString(FACEBOOK_TOKEN, "");
} else return "";
}
public void saveCurrentBucket(Bucket bucket, String restaurantId) {
bucket.setRestaurantId(restaurantId);
editor.putString(BUCKET_SCHEMA, new Gson().toJson(bucket));
editor.putBoolean(HAS_ACTIVE_BUCKET, true);
editor.apply();
Log.e("asdf", new Gson().fromJson(preferences.getString(BUCKET_SCHEMA, ""), Bucket.class).getRestaurantId());
}
public Pair<Boolean, Bucket> getCurrentBucket() {
if (preferences.getBoolean(HAS_ACTIVE_BUCKET, false)) {
Bucket bucket = new Gson().fromJson(preferences.getString(BUCKET_SCHEMA, ""), Bucket.class);
return Pair.create(true, bucket);
} else return Pair.create(false, null);
}
public boolean canMakeReservation(String restaurantId) {
if (preferences.getBoolean(HAS_ACTIVE_BUCKET, false)) {
return (new Gson().fromJson(preferences.getString(BUCKET_SCHEMA, ""), Bucket.class).getRestaurantId()).equals(restaurantId);
} else return true;
}
public void destroyAllBucket() {
editor.remove(BUCKET_SCHEMA);
editor.remove(HAS_ACTIVE_BUCKET);
editor.apply();
}
public boolean hasActiveBucket() {
return preferences.getBoolean(HAS_ACTIVE_BUCKET, false);
}
public void removeAllData() {
editor.clear();
editor.apply();
}
public String getString(String key) {
return preferences.getString(key, "");
}
public int getInt(String key) {
return preferences.getInt(key, 0);
}
public boolean getBoolean(String key) {
return preferences.getBoolean(key, false);
}
public boolean isFirst() {
return preferences.getBoolean("IS_FIRST", true);
}
public void notFirst() {
editor.putBoolean("IS_FIRST", false);
editor.apply();
}
public long getLong(String key) {
return preferences.getLong(key, 0);
}
}<file_sep>/app/src/main/java/kr/edcan/rerant/model/MainTopHeader.java
package kr.edcan.rerant.model;
/**
* Created by JunseokOh on 2016. 10. 6..
*/
public class MainTopHeader {
}
<file_sep>/app/src/main/java/kr/edcan/rerant/activity/AuthActivity.java
package kr.edcan.rerant.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import kr.edcan.rerant.R;
import kr.edcan.rerant.databinding.ActivityAuthBinding;
import kr.edcan.rerant.model.User;
import kr.edcan.rerant.utils.DataManager;
import kr.edcan.rerant.utils.NetworkHelper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AuthActivity extends AppCompatActivity implements View.OnClickListener {
public static Activity activity;
public static void finishThis() {
if (activity != null) activity.finish();
}
private Call<User> facebookLogin;
private DataManager manager;
CallbackManager fbManager;
ActivityAuthBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
binding = DataBindingUtil.setContentView(this, R.layout.activity_auth);
initDefault();
}
private void initDefault() {
manager = new DataManager(getApplicationContext());
fbManager = CallbackManager.Factory.create();
LoginManager.getInstance().logOut();
setFacebookCallback();
binding.authFacebookLogin.setOnClickListener(this);
binding.authNativeLogin.setOnClickListener(this);
binding.authRegister.setOnClickListener(this);
}
private void setFacebookCallback() {
LoginManager.getInstance().registerCallback(fbManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
facebookLogin = NetworkHelper.getNetworkInstance().facebookLogin(loginResult.getAccessToken().getToken());
facebookLogin.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
switch (response.code()) {
case 200:
manager.saveUserInfo(response.body(), 0);
manager.saveFacebookCredential(loginResult.getAccessToken().getToken());
Toast.makeText(AuthActivity.this, response.body().getName() + " 님 환영합니다!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
break;
default:
Toast.makeText(AuthActivity.this, "인증오류가 발생하였습니다.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(AuthActivity.this, "인증오류가 발생하였습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
}
@Override
public void onCancel() {
Log.e("asdf", "Canceled");
}
@Override
public void onError(FacebookException error) {
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.authFacebookLogin:
binding.authFacebookLaunch.performClick();
break;
case R.id.authNativeLogin:
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
break;
case R.id.authRegister:
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fbManager.onActivityResult(requestCode, resultCode, data);
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/model/ReserveFooter.java
package kr.edcan.rerant.model;
/**
* Created by Junseok on 2016-10-08.
*/
public class ReserveFooter {
public ReserveFooter() {
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/activity/ReserveLogActivity.java
/*
* Created by <NAME> on 2016.
* Copyright by Good-Reserve Project @kotohana5706
* All rights reversed.
*/
package kr.edcan.rerant.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import kr.edcan.rerant.R;
public class ReserveLogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reserved_list);
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/activity/ReserveSearchActivity.java
/*
* Created by <NAME> on 2016.
* Copyright by Good-Reserve Project @kotohana5706
* All rights reversed.
*/
package kr.edcan.rerant.activity;
import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.net.Network;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.github.nitrico.lastadapter.BR;
import com.github.nitrico.lastadapter.LastAdapter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Random;
import kr.edcan.rerant.R;
import kr.edcan.rerant.databinding.ActivityReserveSearchBinding;
import kr.edcan.rerant.databinding.MainFirstHeaderBinding;
import kr.edcan.rerant.databinding.ReserveRecyclerContentBinding;
import kr.edcan.rerant.model.MainHeader;
import kr.edcan.rerant.model.MainTopHeader;
import kr.edcan.rerant.model.Reservation;
import kr.edcan.rerant.model.Restaurant;
import kr.edcan.rerant.utils.ImageSingleTon;
import kr.edcan.rerant.utils.NetworkHelper;
import kr.edcan.rerant.utils.StringUtils;
import kr.edcan.rerant.views.CartaTagView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ReserveSearchActivity extends AppCompatActivity implements LastAdapter.LayoutHandler, LastAdapter.OnBindListener, LastAdapter.OnClickListener {
public static Activity activity;
public static void finishThis() {
if (activity != null) activity.finish();
}
private static final int FILTER_INTENT_CODE = 6974;
ActivityReserveSearchBinding binding;
ArrayList<Restaurant> arrayList = new ArrayList<>();
int colorPrimary, colorSub;
String menu[] = {"한식", "양식", "중식", "일식"};
String meeting[] = {"회식", "회의", "커플", "가족"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
binding = DataBindingUtil.setContentView(this, R.layout.activity_reserve_search);
initAppbarLayout();
setDefault();
setData();
}
private void setData() {
Call<ArrayList<Restaurant>> getRestaurantList = NetworkHelper.getNetworkInstance().getRestaurantList();
getRestaurantList.enqueue(new Callback<ArrayList<Restaurant>>() {
@Override
public void onResponse(Call<ArrayList<Restaurant>> call, Response<ArrayList<Restaurant>> response) {
switch (response.code()) {
case 200:
for (Restaurant restaurant : response.body()) {
arrayList.add(restaurant);
}
initUI();
break;
default:
Toast.makeText(ReserveSearchActivity.this, "서버와의 연결에 문제가 있습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", response.code() + "");
break;
}
}
@Override
public void onFailure(Call<ArrayList<Restaurant>> call, Throwable t) {
Toast.makeText(ReserveSearchActivity.this, "서버와의 연결에 문제가 있습니다.", Toast.LENGTH_SHORT).show();
Log.e("asdf", t.getMessage());
}
});
}
private void initUI() {
binding.reserveSearchRecyclerView.setLayoutManager(new LinearLayoutManager(this));
LastAdapter.with(arrayList, BR.item)
.map(Restaurant.class, R.layout.reserve_recycler_content)
.layoutHandler(this)
.onBindListener(this)
.onClickListener(this)
.into(binding.reserveSearchRecyclerView);
}
private void setDefault() {
colorPrimary = getResources().getColor(R.color.colorPrimary);
colorSub = getResources().getColor(R.color.textColorSub);
String[] items = new String[]{"등록일 순", "예약자 비율 순", "예약 만료일 순"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.row_spn, items);
adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
binding.searchFilterSpinner.setAdapter(adapter);
binding.searchFilterSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(getApplicationContext(), FilterSelectActivity.class), FILTER_INTENT_CODE);
}
});
}
private void initAppbarLayout() {
setSupportActionBar(binding.toolbar);
binding.toolbar.setBackgroundColor(Color.WHITE);
binding.toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimary));
getSupportActionBar().setTitle("예약하기");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILTER_INTENT_CODE:
if (resultCode == RESULT_OK) {
binding.searchTagParent.setVisibility(View.VISIBLE);
setFilter(data.getIntExtra("menuType", 0)
, data.getIntExtra("meetingType", 0));
} else binding.searchTagParent.setVisibility(View.GONE);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setFilter(int menuType, int meetingType) {
binding.menuType.setText(menu[menuType]);
binding.meetingType.setText(meeting[meetingType]);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public int getItemLayout(@NotNull Object o, int i) {
return R.layout.reserve_recycler_content;
}
@Override
public void onBind(@NotNull Object o, @NotNull View view, int type, int position) {
switch (type) {
case R.layout.reserve_recycler_content:
Restaurant data = (Restaurant) o;
ReserveRecyclerContentBinding binding = DataBindingUtil.getBinding(view);
setCurrentStatus(binding.reserveResCardStatus, (data.getReservation_check() == 0));
binding.reserveResCardShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ReserveSearchActivity.this, "공유!", Toast.LENGTH_SHORT).show();
}
});
binding.reserveCardImage.setImageUrl(StringUtils.getFullImageUrl(data.getThumbnail()), ImageSingleTon.getInstance(this).getImageLoader());
break;
}
}
public void setCurrentStatus(CartaTagView currentStatus, boolean canReserve) {
currentStatus.setText((canReserve) ? "예약 가능" : "모두 예약됨");
currentStatus.setTextColorForceFully((canReserve) ? colorPrimary : colorSub);
}
@Override
public void onClick(@NotNull Object o, @NotNull View view, int type, int position) {
switch (type) {
case R.layout.reserve_recycler_content:
startActivity(new Intent(getApplicationContext(), ReserveSearchInfoActivity.class)
.putExtra("restaurant_id", arrayList.get(position).get_id()));
break;
}
}
}
<file_sep>/app/src/main/java/kr/edcan/rerant/model/Benefit.java
package kr.edcan.rerant.model;
/**
* Created by JunseokOh on 2016. 10. 8..
*/
public class Benefit {
private String main_benefit, sub_benefit;
private String _id;
public String getMain_benefit() {
return main_benefit;
}
public String getSub_benefit() {
return sub_benefit;
}
public String get_id() {
return _id;
}
public Benefit(String main_benefit, String sub_benefit, String _id) {
this.main_benefit = main_benefit;
this.sub_benefit = sub_benefit;
this._id = _id;
}
}<file_sep>/app/src/main/java/kr/edcan/rerant/model/ReserveBenefit.java
package kr.edcan.rerant.model;
/**
* Created by Junseok on 2016-10-13.
*/
public class ReserveBenefit {
private String benefitTitle, benefitContent;
public ReserveBenefit(String benefitTitle, String benefitContent) {
this.benefitTitle = benefitTitle;
this.benefitContent = benefitContent;
}
public String getBenefitTitle() {
return benefitTitle;
}
public String getBenefitContent() {
return benefitContent;
}
}
| 6f72c9bc8813a4f550e3fd69b8a2be6afb634a39 | [
"Markdown",
"Java"
] | 15 | Java | GoodReserve/GoodReserve-Android | 59166ac36e5da9f2990fb1c2464b6932aa4ee762 | 505b5f7da69c1be17412980ddffed76a41d7efa3 |
refs/heads/main | <repo_name>cembulucu/cmabrl_n_cgpucbrl_synthetic_experiments<file_sep>/synthetic_environments/gp_env.py
import itertools
import numpy as np
import matplotlib.pylab as ply
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
from scipy.stats import multivariate_normal
import sklearn.metrics as skmetrics
from sklearn.neighbors import NearestNeighbors
def rbf_kernel(x1, x2, coeffs):
data_1n = x1 * coeffs
data_2n = x2 * coeffs
dist_matrix = skmetrics.pairwise_distances(data_1n, data_2n)
kernel_matrix = np.exp(-0.5 * np.square(dist_matrix))
return kernel_matrix
class InfiniteArmedGPEnvironmentWithIrrelevantDimensions:
""" Bandit Environment, first dx_bar and da_bar dimensions are relevant(without loss of generality) """
def __init__(self, granularity=0.2, lims=(0, 1), noise_sigma=1):
self.dx_bar, self.da_bar = 1, 1
self.noise_sigma = noise_sigma
# generate points over context-arm space
self.points = np.array(list(itertools.product(np.arange(lims[0], lims[1]+granularity/2, granularity), repeat=self.dx_bar + self.da_bar)))
self.num_samples = self.points.shape[0]
self.coeffs = np.array([1, 1])
# calculate the kernel matrix and the exp rew associated with each context-arm pair
self.gram = rbf_kernel(self.points, self.points, self.coeffs)
self.exp_rews = np.random.multivariate_normal(np.zeros(shape=(self.num_samples, )), self.gram)
print(max(self.exp_rews), min(self.exp_rews), np.mean(self.exp_rews))
self.nbrs = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(self.points)
self.lims = lims
self.granularity = granularity
def get_reward_at(self, context, arm, return_true_exp_rew=False):
""" get reward at a given context and arm location"""
true_exp_rew = self.get_expected_reward_at(context, arm)
reward = true_exp_rew + np.random.normal(loc=0, scale=self.noise_sigma)
if return_true_exp_rew:
return reward, true_exp_rew
return reward
def get_expected_reward_at(self, context, arm):
""" get expected reward at a given context and arm location"""
p = np.concatenate((context[:self.dx_bar], arm[:self.da_bar]))
nn_ind = self.nbrs.kneighbors(X=np.atleast_2d(p), return_distance=False)
exp_rew = np.squeeze(self.exp_rews[nn_ind])
return exp_rew
def find_best_exp_rew_for(self, context, return_opt_arm=False):
""" find the best arm for a given context and the opt exp rew associated with it"""
arms_1d = np.expand_dims(np.arange(self.lims[0], self.lims[1]+self.granularity/2, self.granularity), axis=-1)
repeat_c = np.expand_dims(np.repeat(context[:self.dx_bar], repeats=arms_1d.shape[0]), axis=-1)
conarms = np.concatenate((repeat_c, arms_1d), axis=-1)
nn_ind = self.nbrs.kneighbors(X=conarms, return_distance=False)
exp_rews_c = np.squeeze(self.exp_rews[nn_ind])
max_exp_rew = np.max(exp_rews_c)
if return_opt_arm:
max_exp_rew_ind = np.argmax(exp_rews_c)
return max_exp_rew, arms_1d[max_exp_rew_ind]
return max_exp_rew
if __name__ == '__main__':
"""Used to generate an environment with 4 dims where first two is relevant, uncomment to do so"""
dim = 4
lims = (0, 10)
xs = np.array(list(itertools.product(np.linspace(lims[0], lims[1], 7), repeat=dim)))
mean = np.zeros(shape=(xs.shape[0]))
coeffs = np.array([1, 1, 0, 0])
gram = rbf_kernel(xs, xs, coeffs=coeffs)
ys = np.random.multivariate_normal(mean, gram)
plt.figure()
subplot_counter = 1
for i in range(dim):
for j in range(dim):
if i >=j :
continue
plt.subplot(3, 2, subplot_counter)
subplot_counter += 1
grid_2d = np.zeros(shape=(xs.shape[0], 2))
grid_2d[:, 0] = xs[:, i]
grid_2d[:, 1] = xs[:, j]
grid_2d_uniq, uniq_inds, uniq_inv = np.unique(grid_2d, axis=0, return_inverse=True, return_index=True)
ys_uniq = ys[uniq_inds]
grid_xs = np.array(list(itertools.product(np.linspace(lims[0], lims[1], 100), repeat=2)))
grid_vals = griddata(points=grid_2d_uniq, values=ys_uniq, xi=grid_xs, method='linear')
plt.scatter(grid_xs[:, 0], grid_xs[:, 1], c=grid_vals, s=100, vmin=-3, vmax=3)
plt.xlabel('Dimension ' + str(i + 1))
plt.ylabel('Dimension ' + str(j + 1))
plt.xlim(lims)
plt.ylim(lims)
frame1 = plt.gca()
frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])
# plt.colorbar()
plt.show()
<file_sep>/drivers/gmm_driver.py
from contextual_bandit_with_relevance_learning.bandit_algorithms.cbrl import ContextualBanditWithRelevanceLearning
import matplotlib.pyplot as plt
import numpy as np
import time
from contextual_bandit_with_relevance_learning.bandit_algorithms.uniform_partition_based_methods import InstanceBasedUniformPartitioning
from contextual_bandit_with_relevance_learning.bandit_algorithms.contextual_x_armed_efficient import ContextualXArmedBanditEfficient
from contextual_bandit_with_relevance_learning.environments.gmm_env import InfiniteArmedGMMEnvironmentWithIrrelevantDimensions
if __name__ == '__main__':
contexts_path = ''
contexts_npz_file = np.load(contexts_path)
contexts_all, opt_arms_all, opt_exp_rews_all = contexts_npz_file['contexts'], contexts_npz_file['opt_arms'], contexts_npz_file['opt_exp_rews']
reps = 20
npz_str = 'CBRL_vs_UCB1_vs_Xarmed_reps' + str(reps)
# npz_str = ''
dx, da = 5, 5
bandit_env = InfiniteArmedGMMEnvironmentWithIrrelevantDimensions(dx=dx, da=da) # see utility for details, like relevant dimension counts
T, dx, da, dx_bar, da_bar = 100000, bandit_env.dx, bandit_env.da, bandit_env.dx_bar, bandit_env.da_bar
rews_cbrl, rew_hist_cbrl, regret_hist_cbrl = 0, np.zeros(shape=(reps, T)), np.zeros(shape=(reps, T))
rews_ucb1, rew_hist_ucb1, regret_hist_ucb1 = 0, np.zeros(shape=(reps, T)), np.zeros(shape=(reps, T))
rews_xarm, rew_hist_xarm, regret_hist_xarm = 0, np.zeros(shape=(reps, T)), np.zeros(shape=(reps, T))
rews_random, rew_hist_random, regret_hist_random = 0, np.zeros(shape=(reps, T)), np.zeros(shape=(reps, T))
for r in range(reps):
print('Repeat: ', r)
rews_cbrl, rews_ucb1, rews_xarm, rews_random = 0, 0, 0, 0
contexts, opt_exp_rews = contexts_all[r], np.squeeze(opt_exp_rews_all[r])
bandit_cbrl = ContextualBanditWithRelevanceLearning(horizon=T, dx=dx, da=da, dx_bar=dx_bar, da_bar=da_bar, lip_c=1.0, conf_scale=0.001)
bandit_xarm = ContextualXArmedBanditEfficient(horizon=T, dx=dx, da=da, conf_scale=0.05)
bandit_ucb1 = InstanceBasedUniformPartitioning(horizon=T, dx=dx, da=da, conf_scale=0.01)
print('Num CBRL partitions: %d' % (bandit_cbrl.arm_size * bandit_cbrl.W_centers.shape[0]))
print('Num CBRL arm size: %d' % bandit_cbrl.arm_size)
print('Num CBRL pw per W size: %d' % (bandit_cbrl.W_centers.shape[0] / bandit_cbrl.V_2dxb_x.shape[0]))
print('Num CBRL m: %d' % bandit_cbrl.m)
print('Num CBRL W size: %d' % bandit_cbrl.W_centers.shape[0])
print('Num CBRL pw size: %d' % bandit_cbrl.V_2dxb_x.shape[0])
print('Num CBRL one sample needed size: %d' % (bandit_cbrl.arm_size*bandit_cbrl.W_centers.shape[0]//bandit_cbrl.V_2dxb_x.shape[0]))
print('Num UCB1 partitions: %d' % bandit_ucb1.partition_size)
print('Num UCB1 m: %d' % bandit_ucb1.m)
print('Num Xarmed max depth: %d' % bandit_xarm.max_depth)
print('Num Xarmed max num partitions: %d' % (2 ** bandit_xarm.max_depth))
print('Num Xarmed v1: %.4f' % bandit_xarm.v1)
print('Num Xarmed rho: %.4f' % bandit_xarm.rho)
start_clock = time.time()
for i, c in enumerate(contexts):
y_cbrl, u_cbrl = bandit_cbrl.determine_arm_one_round(c, return_winner_arm_ind=False, return_ucb=True)
y_xarm, u_xarm = bandit_xarm.determine_arm_one_round(c, return_winner_arm_ind=False, return_ucb=True)
y_ucb1, u_ucb1 = bandit_ucb1.determine_arm_one_round(c, return_winner_arm_ind=False, return_ucb=True)
y_random = np.random.rand(da)
r_cbrl, true_exp_rew_cbrl = bandit_env.get_reward_at(c, y_cbrl, return_true_exp_rew=True)
r_xarm, true_exp_rew_xarm = bandit_env.get_reward_at(c, y_xarm, return_true_exp_rew=True)
r_ucb1, true_exp_rew_ucb1 = bandit_env.get_reward_at(c, y_ucb1, return_true_exp_rew=True)
r_random, true_exp_rew_random = bandit_env.get_reward_at(c, y_random, return_true_exp_rew=True)
reg_cbrl = opt_exp_rews[i] - true_exp_rew_cbrl
reg_xarm = opt_exp_rews[i] - true_exp_rew_xarm
reg_ucb1 = opt_exp_rews[i] - true_exp_rew_ucb1
reg_random = opt_exp_rews[i] - true_exp_rew_random
bandit_cbrl.update_statistics(r_cbrl)
bandit_xarm.update_statistics(r_xarm)
bandit_ucb1.update_statistics(r_ucb1)
rews_cbrl += r_cbrl
rews_xarm += r_xarm
rews_ucb1 += r_ucb1
rews_random += r_random
rew_hist_cbrl[r, i] = r_cbrl
rew_hist_xarm[r, i] = r_xarm
rew_hist_ucb1[r, i] = r_ucb1
rew_hist_random[r, i] = r_random
regret_hist_cbrl[r, i] = reg_cbrl
regret_hist_xarm[r, i] = reg_xarm
regret_hist_ucb1[r, i] = reg_ucb1
regret_hist_random[r, i] = reg_random
if i % 11111 == 0:
end_lap = time.time()
print('Round: ', (i+1), ', total time elapsed: %.2f' % (end_lap - start_clock))
print('CBRL stats, avg_rew: %.5f' % (rews_cbrl / (i + 1)), ', sum rew:', rews_cbrl, ', regret: %.4f' % np.sum(regret_hist_cbrl[r, :i]))
print('XARM stats, avg_rew: %.5f' % (rews_xarm / (i + 1)), ', sum rew:', rews_xarm, ', regret: %.4f' % np.sum(regret_hist_xarm[r, :i]))
print('UCB1 stats, avg_rew: %.5f' % (rews_ucb1 / (i + 1)), ', sum rew:', rews_ucb1, ', regret: %.4f' % np.sum(regret_hist_ucb1[r, :i]))
print('Rand stats, avg_rew: %.5f' % (rews_random / (i + 1)), ', sum rew: %.0f' % rews_random,
', regret: %.4f' % np.sum(regret_hist_random[r, :i]))
print('')
print('-------------------------------------------------')
if npz_str:
npz_str_uniq = npz_str + '_{}'.format(time.strftime("%Y_%m_%d_%H_%M_%S", time.gmtime(time.time())))
np.savez(npz_str_uniq, dx=dx, da=da, dx_bar=dx_bar, da_bar=da_bar, rew_hist_cbrl=rew_hist_cbrl, rew_hist_ucb1=rew_hist_ucb1,
rew_hist_xarm=rew_hist_xarm, rew_hist_random=rew_hist_random, regret_hist_cbrl=regret_hist_cbrl, regret_hist_xarm=regret_hist_xarm,
regret_hist_ucb1=regret_hist_ucb1, regret_hist_random=regret_hist_random)
plt.show()
<file_sep>/utilities/gp_utils.py
import itertools
import numpy as np
import sklearn.metrics as skmetrics
def calculate_power_set(iterable):
""" power set([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3) """
s = list(iterable)
return list(itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s) + 1)))
def rbf_kernel_w_linear_coefficients(data_1, data_2, coefficients=None):
""" calculates pairwise kernels according to coefficients, coefficients=all_ones gives Euclidean distance based kernels"""
coefficients = np.ones(shape=(data_1.shape[1])) if coefficients is None else coefficients
data_1n, data_2n = data_1*coefficients, data_2*coefficients
dist_matrix = skmetrics.pairwise_distances(data_1n, data_2n)
kernel_matrix = np.exp(-0.5 * np.square(dist_matrix))
return kernel_matrix
<file_sep>/bandit_algorithms/iup.py
import itertools
import sklearn.metrics as skmetrics
import numpy as np
class InstanceBasedUniformPartitioning:
def __init__(self, horizon, dx, da, conf_scale=1.0):
self.horizon, self.conf_scale = horizon, conf_scale
self.dx, self.da, self.d = dx, da, (dx + da)
self.m = np.ceil(horizon ** (1 / (2 + self.d))).astype(int)
# calculate centers for one dimension
centers_vector = np.arange(self.m) / self.m + (0.5 / self.m)
# extend centers for all dimensions
self.centers = np.array(list(itertools.product(centers_vector, repeat=self.d)))
self.partition_size = self.centers.shape[0]
# get centers for contexts
self.context_centers, self.int_centers = np.unique(self.centers[:, :self.dx], return_inverse=True, axis=0)
self.sample_counts = np.zeros(shape=(self.partition_size, ))
self.sample_means = np.zeros(shape=(self.partition_size, ))
self.last_played_arm_ind = -1
def select_arm(self, context):
# calculate distances from context to all context centers
dist_to_centers = np.squeeze(skmetrics.pairwise_distances(np.expand_dims(context, axis=0),
self.context_centers, metric='cityblock'))
# get the index of closes context center
min_dist_ind = np.argmin(dist_to_centers)
# from all space get partitions that has the context
relevant_arm_inds = np.squeeze(np.argwhere(self.int_centers == min_dist_ind))
rel_sample_means, rel_sample_counts = self.sample_means[relevant_arm_inds], self.sample_counts[relevant_arm_inds]
# calculate confidence terms
with np.errstate(divide='ignore'):
inside_sqrt_1 = 2 / rel_sample_counts
inside_sqrt_2 = 1 + 2 * np.log(2*(self.m**self.da)*self.partition_size*(self.horizon**1.5))
rel_confidence_radii = np.sqrt(inside_sqrt_1*inside_sqrt_2)
# calculate UCBs(scaled)
rel_ucbs = rel_sample_means + self.conf_scale * rel_confidence_radii
# select the best hypercube, if multiple of them are best, select randomly
winner_rel_arm_pseudo_indices = np.argwhere(rel_ucbs == np.max(rel_ucbs))
if winner_rel_arm_pseudo_indices.shape[0] > 1:
winner_pseudo = np.squeeze(winner_rel_arm_pseudo_indices[np.random.randint(winner_rel_arm_pseudo_indices.shape[0], size=1)])
else:
winner_pseudo = np.squeeze(winner_rel_arm_pseudo_indices)
# get original index for winner hypercube
winner_ind = np.squeeze(relevant_arm_inds[winner_pseudo])
# update last played arm
self.last_played_arm_ind = winner_ind
# select an arm uniformly random inside the hypercube
up_bound_hi, low_bound_hi = self.centers[winner_ind] + 0.5/self.m, self.centers[winner_ind] - 0.5/self.m
arm = np.random.uniform(low=up_bound_hi[self.dx:], high=low_bound_hi[self.dx:])
return arm
def update_statistics(self, reward):
# update counters for the last played arm
y_ind = self.last_played_arm_ind
self.sample_means[y_ind] = (self.sample_means[y_ind]*self.sample_counts[y_ind] + reward) / (self.sample_counts[y_ind] + 1)
self.sample_counts[y_ind] = self.sample_counts[y_ind] + 1
<file_sep>/synthetic_environments/gmm_env.py
import numpy as np
import sklearn.metrics as spm
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
import matplotlib.pylab as pyl
bandit_env_dict = {'m': np.array([[0.25, 0.75], [0.5, 0.5]]),
'c': 0.0005*np.array([[[100, 60],
[60, 50]],
[[50, -60],
[-60, 100]]]),
'w': np.array([0.5, 0.5]),
's': 0.25,
'dx_bar': 1, 'da_bar': 1}
class InfiniteArmedGMMEnvironmentWithIrrelevantDimensions:
""" Bandit Environment, first dx_bar and da_bar dimensions are relevant(without loss of generality) """
def __init__(self, dx, da):
param_dict = bandit_env_dict
self.means = param_dict['m']
self.covs = param_dict['c']
self.weights = param_dict['w']
self.scale = param_dict['s']
self.n_components = self.means.shape[0]
self.dx, self.dx_bar = dx, param_dict['dx_bar']
self.da, self.da_bar = da, param_dict['da_bar']
num_components_check = self.means.shape[0] == self.covs.shape[0] == self.weights.shape[0]
dimension_check = self.means.shape[1] == self.covs.shape[1] == self.covs.shape[2] == (self.dx_bar + self.da_bar)
if not (num_components_check and dimension_check):
raise ValueError('inconsistent dimensions or components')
def get_approx_opt_1D_arm_n_exp_rew_for(self, context, precision=0.01):
""" only for 1D arms """
arm_candidates = np.arange(0, 1.00000000000001, precision)
exp_rews = np.zeros_like(arm_candidates)
for i, a in enumerate(arm_candidates):
exp_rews[i] = self.get_expected_reward_at(context, (a,))
return arm_candidates[np.argmax(exp_rews)], exp_rews[np.argmax(exp_rews)]
def get_approx_opt_1D_arms_for(self, contexts, precision=0.01, verbose_period=2000):
opt_arms, opt_exp_rews = np.zeros(shape=(contexts.shape[0],)), np.zeros(shape=(contexts.shape[0],))
for i, c in enumerate(contexts):
if i % verbose_period == 0:
print('Calculating best arm for ', i, 'th context...')
a, e = self.get_approx_opt_1D_arm_n_exp_rew_for(c, precision=precision)
opt_arms[i] = a
opt_exp_rews[i] = e
return opt_arms, opt_exp_rews
def get_reward_at(self, context, arm, return_true_exp_rew=False):
true_exp_rew = self.get_expected_reward_at(context, arm)
if return_true_exp_rew:
return int(np.random.rand() <= true_exp_rew), true_exp_rew
else:
return int(np.random.rand() <= true_exp_rew)
def get_expected_reward_at(self, context, arm):
p = np.concatenate((context[:self.dx_bar], arm[:self.da_bar]))
gmm_val_at_p = 0
for c in range(self.n_components):
gmm_val_at_p += self.weights[c] * multivariate_normal.pdf(p, self.means[c], self.covs[c])
return np.clip(gmm_val_at_p*self.scale, 0, 1)
def generate_uniform_random_contexts(self, num_samples=1, min_val=0.0, max_val=1.0):
return np.random.uniform(low=min_val, high=max_val, size=(num_samples, self.dx))
def generate_uniform_random_samples_given_contexts(self, contexts, min_val=0.0, max_val=1.0, get_true_expectation=False):
num_samples = contexts.shape[0]
arms = np.random.uniform(low=min_val, high=max_val, size=(num_samples, self.da))
rewards = np.zeros(shape=(num_samples,))
for i in range(num_samples):
if get_true_expectation:
rewards[i] = self.get_expected_reward_at(contexts[i], arms[i])
else:
rewards[i] = self.get_reward_at(contexts[i], arms[i])
return contexts, arms, rewards
def visualize_env(self, num_samples=10000, show_opt_arms=False):
contexts = self.generate_uniform_random_contexts(num_samples=num_samples)
contexts, arms, exp_rews = self.generate_uniform_random_samples_given_contexts(contexts, get_true_expectation=True)
contexts_rel, arms_rel = contexts[:, :self.dx_bar], arms[:, :self.da_bar]
points_rel = np.concatenate((contexts_rel, arms_rel), axis=-1)
subplot_index, sub_size = 0, points_rel.shape[1]-1
for i in range(points_rel.shape[1]):
dim_i = points_rel[:, i]
for j in range(points_rel.shape[1]):
if i >= j:
continue
dim_j = points_rel[:, j]
subplot_index += 1
sort_inds = np.argsort(exp_rews)
plt.subplot(sub_size, sub_size, subplot_index)
plt.scatter(dim_i[sort_inds], dim_j[sort_inds], c=exp_rews[sort_inds], cmap='rainbow')
plt.colorbar()
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.xlabel('Relevant Context Dimension')
plt.ylabel('Relevant Arm Dimension')
if show_opt_arms:
undersampled_contexts = contexts_rel[np.random.randint(low=0, high=num_samples, size=500)]
undersampled_contexts = np.expand_dims(np.linspace(0, 1, 200), axis=1)
opt_arms, opt_exp_rews = self.get_approx_opt_1D_arms_for(undersampled_contexts, precision=0.005, verbose_period=100)
sort_inds = np.argsort(np.squeeze(undersampled_contexts))
plt.plot(undersampled_contexts[sort_inds], opt_arms[sort_inds], c='k', label='Optimal Arms')
plt.legend(loc=3)
plt.show()
def print_info(self):
print('mean: ', self.means)
print('covs: ', self.covs)
print('weights: ', self.weights)
print('scale: ', self.scale)
if __name__ == '__main__':
print('TEST GMM ENVIRONMENT')
reps, horizon = 20, 100000
gmm_env_ = InfiniteArmedGMMEnvironmentWithIrrelevantDimensions(dx=5, da=5)
contexts = gmm_env_.generate_uniform_random_contexts(num_samples=reps*horizon)
gmm_env_.visualize_env(num_samples=30000, show_opt_arms=True)
# opt_arms, opt_exp_rews = gmm_env_.get_approx_opt_1D_arms_for(contexts, precision=0.01, verbose_period=1000)
# contexts = np.reshape(contexts, newshape=(reps, horizon, -1))
# opt_arms = np.reshape(opt_arms, newshape=(reps, horizon, -1))
# opt_exp_rews = np.reshape(opt_exp_rews, newshape=(reps, horizon, -1))
# path = 'D:/python/projects/bandits/contextual_bandit_with_relevance_learning/data_files/'
# np.savez((path + 'context_optarms_optexprews_reps' + str(reps) + '_horizon' + str(horizon)), contexts=contexts,
# opt_exp_rews=opt_exp_rews, opt_arms=opt_arms)
<file_sep>/requirements.txt
cycler==0.10.0
imbalanced-learn==0.8.0
imblearn==0.0
joblib==1.0.1
kiwisolver==1.3.1
matplotlib==3.3.4
numpy==1.19.5
Pillow==8.1.2
pyparsing==2.4.7
python-dateutil==2.8.1
scikit-learn==0.24.1
scipy==1.5.4
six==1.15.0
sklearn==0.0
threadpoolctl==2.1.0
<file_sep>/bandit_algorithms/cgp_ucb_rl.py
import itertools
import numpy as np
from utilities.gp_utils import rbf_kernel_w_linear_coefficients, calculate_power_set
class ContextualGaussianProcessUpperConfidenceBoundWithRelevanceLearning:
""" Implementation of CGP-UCB-RL """
def __init__(self, horizon, dx, da, arm_limits=(0, 1.00000001), arm_granularity=0.01, noise_sigma=1,
confidence_scale=1.0, fit_ard_period=1):
pass
self.horizon, self.dx, self.da = horizon, dx, da
self.t, self.played_points_hist, self.rews_hist = 0, np.zeros(shape=(horizon, dx + da)), np.zeros(shape=(horizon,))
arm_grid_1d = np.arange(arm_limits[0], arm_limits[1], arm_granularity)
self.arm_grid = np.array(list(itertools.product(arm_grid_1d, repeat=da)))
self.kernel_fn = rbf_kernel_w_linear_coefficients
self.noise_sigma = noise_sigma
self.cs = confidence_scale
self.last_played_point = None
self.fit_ard_period = fit_ard_period
self.best_ard_params = np.ones(shape=(dx + da, ))
def select_arm(self, context):
if self.t == 0:
rand_int = np.random.randint(low=0, high=self.arm_grid.shape[0])
selected_arm = self.arm_grid[rand_int]
self.last_played_point = np.concatenate((context, selected_arm))
else:
context_arm_grid = self.calculate_context_arm_grid(context=context)
if self.t % self.fit_ard_period == 0 and self.t != 0:
self.best_ard_params, _ = self.calculate_discrete_best_ard_method_unknown_rel_dims()
mean_est, var_est = self.calculate_posterior_mean_var(context_arm_grid=context_arm_grid)
cgp_arm_ind, cgp_high_ucb = self.calculate_highest_ucb_index(1.0, mean_est, var_est)
# TODO: add highest variance arm selection
self.last_played_point = context_arm_grid[cgp_arm_ind]
selected_arm = context_arm_grid[cgp_arm_ind, self.dx:]
return selected_arm
def update_statistics(self, reward):
self.played_points_hist[self.t] = self.last_played_point
self.rews_hist[self.t] = reward
self.t += 1
def calculate_context_arm_grid(self, context):
"""For each arm, calculates the points when concatenated with the context"""
contexts_repeated = np.repeat(np.expand_dims(context, axis=0), repeats=self.arm_grid.shape[0], axis=0)
context_arm_grid = np.concatenate((contexts_repeated, self.arm_grid), axis=-1)
return context_arm_grid
def calculate_posterior_mean_var(self, context_arm_grid):
"""Calculates statistics of the posterior distribution of expected reward function, possibly ignoring some dimensions acc. to
ard_coeffs """
# all points played so far
data = self.played_points_hist[:self.t]
# kernels between all possible context-arms and the previous rounds
kernel_vectors = self.kernel_fn(context_arm_grid, data, self.best_ard_params)
# kernel matrix of data
kernel_matrix = self.kernel_fn(data, data, self.best_ard_params)
c_matrix = kernel_matrix + (self.noise_sigma ** 2) * np.eye(data.shape[0])
c_matrix_inv = np.linalg.inv(c_matrix)
mu_ests_vector = np.matmul(kernel_vectors, np.matmul(c_matrix_inv, self.rews_hist[:self.t])) # mean estimation
sigma_ests_first_term = np.diag(self.kernel_fn(context_arm_grid, context_arm_grid, self.best_ard_params))
sigma_ests_second_term = np.diag(np.matmul(kernel_vectors, np.matmul(c_matrix_inv, kernel_vectors.T)))
sigma_ests_vector = sigma_ests_first_term - sigma_ests_second_term # variance estimation
return mu_ests_vector, sigma_ests_vector
def calculate_negative_log_likelihood(self):
"""Calculates the negative log marginal likelihood, possibly ignoring some dimensions acc. to ard_coeffs"""
data = self.played_points_hist[:self.t]
kernel_matrix = self.kernel_fn(data, data, self.best_ard_params)
c_matrix = kernel_matrix + (self.noise_sigma ** 2) * np.eye(data.shape[0])
c_matrix_inv = np.linalg.inv(c_matrix)
first_term = np.matmul(self.rews_hist[:self.t].T, np.matmul(c_matrix_inv, self.rews_hist[:self.t]))
second_term = np.log(np.linalg.det(c_matrix))
return first_term + second_term
def calculate_discrete_best_ard_method_unknown_rel_dims(self):
"""Optimization of NLL, find which dimensions should be ignored"""
dx_powset, da_powset = calculate_power_set(np.arange(0, self.dx)), calculate_power_set(np.arange(0, self.da))
dx_powset, da_powset = dx_powset[1:], da_powset[1:] # calculate power set dimensions for contexts and arms and remove empty sets
nlls, ard_params_list = [], []
# for each combination of context and arm dimension tuples calculate NLL
for dx_r in dx_powset:
dx_r_np = np.array(dx_r)
context_ard_params = np.zeros(shape=(self.dx,))
context_ard_params[dx_r_np] = 1
for da_r in da_powset:
da_r_np = np.array(da_r)
arm_ard_params = np.zeros(shape=(self.da,))
arm_ard_params[da_r_np] = 1
ard_params = np.concatenate((context_ard_params, arm_ard_params))
ard_params = np.squeeze(ard_params)
nll = self.calculate_negative_log_likelihood()
nlls.append(nll)
ard_params_list.append(ard_params)
nlls = np.array(nlls)
ard_params_list = np.array(ard_params_list)
argmin_ind = np.argmin(nlls) # find best NLL index
best_ard_params = ard_params_list[argmin_ind] # select coefficient that best ignore the dimensions
return best_ard_params, nlls[argmin_ind]
def calculate_highest_ucb_index(self, beta, means, stds, return_multiple=False):
""" calculate highest UCB """
ucbs = means + self.cs * beta * stds
highest_indices = np.argwhere(ucbs == np.max(ucbs))
if return_multiple:
return highest_indices, ucbs[highest_indices]
else:
if highest_indices.size > 1:
highest_index = np.random.choice(np.squeeze(highest_indices))
else:
highest_index = np.squeeze(highest_indices)
return highest_index, ucbs[highest_index]<file_sep>/bandit_algorithms/cgp_ucb.py
import itertools
import numpy as np
from utilities.gp_utils import rbf_kernel_w_linear_coefficients
class ContextualGaussianProcessUpperConfidenceBoundAlgorithm:
""" Implementation of CGP-UCB """
def __init__(self, horizon, dx, da, space_diameter, delta, arm_limits=(0, 1.00000001), arm_granularity=0.01, noise_sigma=1,
confidence_scale=1.0):
self.horizon, self.dx, self.da = horizon, dx, da
self.t, self.played_points_hist, self.rews_hist = 0, np.zeros(shape=(horizon, dx+da)), np.zeros(shape=(horizon,))
arm_grid_1d = np.arange(arm_limits[0], arm_limits[1], arm_granularity)
self.arm_grid = np.array(list(itertools.product(arm_grid_1d, repeat=da)))
self.kernel_fn = rbf_kernel_w_linear_coefficients
self.noise_sigma = noise_sigma
self.r = space_diameter
self.delta = delta
self.cs = confidence_scale
self.last_played_point = None
def select_arm(self, context):
if self.t == 0:
rand_int = np.random.randint(low=0, high=self.arm_grid.shape[0])
selected_arm = self.arm_grid[rand_int]
self.last_played_point = np.concatenate((context, selected_arm))
else:
context_arm_grid = self.calculate_context_arm_grid(context=context)
mean_est, var_est = self.calculate_posterior_mean_var(context_arm_grid=context_arm_grid)
beta_t = self.calculate_beta_t(t=self.t)
cgp_arm_ind, cgp_high_ucb = self.calculate_highest_ucb_index(beta_t, mean_est, var_est)
self.last_played_point = context_arm_grid[cgp_arm_ind]
selected_arm = context_arm_grid[cgp_arm_ind, self.dx:]
return selected_arm
def update_statistics(self, reward):
self.played_points_hist[self.t] = self.last_played_point
self.rews_hist[self.t] = reward
self.t += 1
def calculate_beta_t(self, t):
"""Calculate beta_t for CGP-UCB"""
# TODO: we have beta for compact, convex spaces -> add beta for arbitrary spaces
a, d = self.delta * np.exp(-1), self.dx + self.da
first_term = 2 * np.log((t ** 2) * 2 * (np.pi ** 2) / (3 * self.delta))
second_term = 2 * d * np.log((t ** 2) * d * self.r * np.sqrt(np.log(4 * d * a / self.delta)))
return first_term + second_term
def calculate_context_arm_grid(self, context):
"""For each arm, calculates the points when concatenated with the context"""
contexts_repeated = np.repeat(np.expand_dims(context, axis=0), repeats=self.arm_grid.shape[0], axis=0)
context_arm_grid = np.concatenate((contexts_repeated, self.arm_grid), axis=-1)
return context_arm_grid
def calculate_posterior_mean_var(self, context_arm_grid):
"""Calculates statistics of the posterior distribution of expected reward function, possibly ignoring some dimensions acc. to
ard_coeffs """
data = self.played_points_hist[:self.t] # all points played so far
kernel_vectors = self.kernel_fn(context_arm_grid, data) # kernels between all possible context-arms and the previous rounds
kernel_matrix = self.kernel_fn(data, data) # kernel matrix of data
c_matrix = kernel_matrix + (self.noise_sigma ** 2) * np.eye(data.shape[0])
c_matrix_inv = np.linalg.inv(c_matrix)
mu_ests_vector = np.matmul(kernel_vectors, np.matmul(c_matrix_inv, self.rews_hist[:self.t])) # mean estimation
sigma_ests_first_term = np.diag(self.kernel_fn(context_arm_grid, context_arm_grid))
sigma_ests_second_term = np.diag(np.matmul(kernel_vectors, np.matmul(c_matrix_inv, kernel_vectors.T)))
sigma_ests_vector = sigma_ests_first_term - sigma_ests_second_term # variance estimation
return mu_ests_vector, sigma_ests_vector
def calculate_highest_ucb_index(self, beta, means, stds, return_multiple=False):
""" calculate highest UCB"""
ucbs = means + self.cs * beta * stds
highest_indices = np.argwhere(ucbs == np.max(ucbs))
if return_multiple:
return highest_indices, ucbs[highest_indices]
else:
if highest_indices.size > 1:
highest_index = np.random.choice(np.squeeze(highest_indices))
else:
highest_index = np.squeeze(highest_indices)
return highest_index, ucbs[highest_index]
<file_sep>/bandit_algorithms/uniform_random_bandit.py
import numpy as np
class UniformRandomBandit:
""" A strategy that pulls arms uniformly at random """
def __init__(self, da):
self.da = da
def select_arm(self):
return np.random.rand(self.da)
<file_sep>/drivers/gp_driver.py
import time
from synthetic_environments.gp_env import InfiniteArmedGPEnvironmentWithIrrelevantDimensions
from helper_functions import calculate_beta_t, calculate_context_arm_grid, rbf_kernel_w_lin_coeffs, calculate_posterior_mean_var, \
calculate_discrete_best_ard_method_unknown_rel_dims, calculate_highest_ucb_index
import numpy as np
def main_fn():
# set parameters for the experiment
T = 100
fit_ard_params_every = 10
dx, da = 10, 2
noise_sigma = 1
reps = 20
conf_scales = np.array([0.01, 0.05, 0.1, 0.25, 0.5, 1.0])
cs_n = conf_scales.shape[0]
kernel_fn = rbf_kernel_w_lin_coeffs
radius = 10
lims = (0, radius)
granularity = radius/20
# npz_str = 'gp_r' + str(radius)
npz_str = 'gp_extra'
# storage for rewards, regrets and played points
cgp_points_hist, cgp_rews_hist, cgp_regret_hist = np.zeros(shape=(cs_n, reps, T, dx + da)), np.zeros(shape=(cs_n, reps, T)), np.zeros(shape=(cs_n, reps, T))
rgp_points_hist, rgp_rews_hist, rgp_regret_hist = np.zeros(shape=(cs_n, reps, T, dx + da)), np.zeros(shape=(cs_n, reps, T)), np.zeros(shape=(cs_n, reps, T))
random_rews_hist, random_regret_hist = np.zeros(shape=(cs_n, reps, T)), np.zeros(shape=(cs_n, reps, T))
# pre generate contexts so that in each repetition, different confidence scales encounter same contexts
contexts = radius * np.random.rand(reps, T, dx)
for r in range(reps):
# create environment
bandit_env = InfiniteArmedGPEnvironmentWithIrrelevantDimensions(granularity=granularity, lims=lims, noise_sigma=noise_sigma)
start = time.time()
for i, cs in enumerate(conf_scales):
# set initial ard parameters
best_ard_params = np.array([1] * (dx + da))
end = time.time()
print('time elapsed: ', end - start)
for t in range(T):
# get context, noise and find optimal exp rew for this context
c = contexts[r, t]
noise_t = np.random.normal(loc=0, scale=noise_sigma)
opt_exp_rew, opt_arm = bandit_env.find_best_exp_rew_for(c, return_opt_arm=True)
# play arms arbitrarily in the first round, uniform random in this case
if t == 0:
context_arm_grid = calculate_context_arm_grid(arm_granularity=granularity, da=da, context=c, lims=lims)
random_arm_cgp = context_arm_grid[np.random.randint(low=0, high=context_arm_grid.shape[0]), dx:]
random_arm_rgp = context_arm_grid[np.random.randint(low=0, high=context_arm_grid.shape[0]), dx:]
random_arm = context_arm_grid[np.random.randint(low=0, high=context_arm_grid.shape[0]), dx:]
_, true_exp_rew_cgp = bandit_env.get_reward_at(c, random_arm_cgp, return_true_exp_rew=True)
_, true_exp_rew_rgp = bandit_env.get_reward_at(c, random_arm_rgp, return_true_exp_rew=True)
_, true_exp_rew_ran = bandit_env.get_reward_at(c, random_arm, return_true_exp_rew=True)
r_cgp = true_exp_rew_cgp + noise_t
r_rgp = true_exp_rew_rgp + noise_t
r_ran = true_exp_rew_ran + noise_t
reg_cgp = opt_exp_rew - true_exp_rew_cgp
reg_rgp = opt_exp_rew - true_exp_rew_rgp
reg_ran = opt_exp_rew - true_exp_rew_ran
cgp_points_hist[i, r, 0] = np.concatenate((c, random_arm_cgp))[np.newaxis, :]
cgp_rews_hist[i, r, 0] = r_cgp
cgp_regret_hist[i, r, 0] = reg_cgp
rgp_points_hist[i, r, 0] = np.concatenate((c, random_arm_rgp))[np.newaxis, :]
rgp_rews_hist[i, r, 0] = r_rgp
rgp_regret_hist[i, r, 0] = reg_rgp
random_rews_hist[i, r, 0] = r_ran
random_regret_hist[i, r, 0] = reg_ran
continue
# calcualte beta_t
beta_t = calculate_beta_t(t=t, delta=0.01, d=dx + da, r=radius)
# calculate all possible points that the current context and all arms can produce
context_arm_grid = calculate_context_arm_grid(arm_granularity=granularity, da=da, context=c, lims=lims)
# calculate posterior distribution stats for CGP-UCB
cgp_mean_est, cgp_var_est = calculate_posterior_mean_var(kernel_fn, cgp_points_hist[i, r, :t, :dx], cgp_points_hist[i, r, :t, dx:],
cgp_rews_hist[i, r, :t], context_arm_grid, noise_sigma=noise_sigma,
ard_coeffs=np.ones(shape=(dx+da)))
# perform optimization and calculate best hyperparameters that fit the data
if t % fit_ard_params_every == 0:
best_ard_params, _ = calculate_discrete_best_ard_method_unknown_rel_dims(rgp_points_hist[i, r, :t, :dx],
rgp_points_hist[i, r, :t, dx:],
rgp_rews_hist[i, r, :t],
noise_sigma=noise_sigma)
# calculate posterior distribution stats for CGP-UCB-RL
rgp_mean_est, rgp_var_est = calculate_posterior_mean_var(kernel_fn, rgp_points_hist[i, r, :t, :dx], rgp_points_hist[i, r, :t, dx:],
rgp_rews_hist[i, r, :t], context_arm_grid, noise_sigma=noise_sigma,
ard_coeffs=best_ard_params)
# calculate UCBs for each approach, find best arms(multiple arms are best for CGP-UCB-RL)
cgp_arm_ind, cgp_high_ucb = calculate_highest_ucb_index(beta_t, cgp_mean_est, cgp_var_est, conf_scale=cs)
rgp_arm_ind, rgp_high_ucb = calculate_highest_ucb_index(1, rgp_mean_est, rgp_var_est, conf_scale=cs, return_multiple=True)
# for CGP-UCB-RL calculate the arm with the highest variance calculated according to all dimensions
_, rgp_var_est2 = calculate_posterior_mean_var(kernel_fn, rgp_points_hist[i, r, :t, :dx], rgp_points_hist[i, r, :t, dx:],
rgp_rews_hist[i, r, :t], context_arm_grid, noise_sigma=noise_sigma,
ard_coeffs=np.ones(shape=(dx+da)))
rgp_var_est2_sels = rgp_var_est2[rgp_arm_ind]
highest_var_ind = np.argmax(rgp_var_est2_sels)
rgp_arm_ind = np.squeeze(rgp_arm_ind[highest_var_ind])
# get arms from context-arm grid
a_cgp = context_arm_grid[cgp_arm_ind, dx:]
a_rgp = context_arm_grid[rgp_arm_ind, dx:]
a_ran = context_arm_grid[np.random.randint(low=0, high=context_arm_grid.shape[0]), dx:]
# get expected reward ass. with each arm
_, true_exp_rew_cgp = bandit_env.get_reward_at(c, a_cgp, return_true_exp_rew=True)
_, true_exp_rew_rgp = bandit_env.get_reward_at(c, a_rgp, return_true_exp_rew=True)
_, true_exp_rew_ran = bandit_env.get_reward_at(c, a_ran, return_true_exp_rew=True)
# get rewards
r_cgp = true_exp_rew_cgp + noise_t
r_rgp = true_exp_rew_rgp + noise_t
r_ran = true_exp_rew_ran + noise_t
# calculate regrets
reg_cgp = opt_exp_rew - true_exp_rew_cgp
reg_rgp = opt_exp_rew - true_exp_rew_rgp
reg_ran = opt_exp_rew - true_exp_rew_ran
# store the played point
cgp_points_hist[i, r, t] = context_arm_grid[cgp_arm_ind]
rgp_points_hist[i, r, t] = context_arm_grid[rgp_arm_ind]
# store rewards, regrets for all approaches
cgp_rews_hist[i, r, t] = r_cgp
cgp_regret_hist[i, r, t] = reg_cgp
rgp_rews_hist[i, r, t] = r_rgp
rgp_regret_hist[i, r, t] = reg_rgp
random_rews_hist[i, r, t] = r_ran
random_regret_hist[i, r, t] = reg_ran
# print some info about how the experiment is going
if t % 33 == 0 or t == T-1:
with np.printoptions(precision=2, suppress=True):
print('cs = ', cs, ', r = ', r, ', t = ', t)
print('rew sums = ', np.sum(cgp_rews_hist[i, r, :t]), np.sum(rgp_rews_hist[i, r, :t]), np.sum(random_rews_hist[i, r, :t]))
print('rew avgs = ', np.sum(cgp_rews_hist[i, r, :t])/t, np.sum(rgp_rews_hist[i, r, :t])/t, np.sum(random_rews_hist[i, r, :t])/t)
print('regret sums = ', np.sum(cgp_regret_hist[i, r, :t]), np.sum(rgp_regret_hist[i, r, :t]), np.sum(random_regret_hist[i, r, :t]))
print('rew est= ', cgp_mean_est[cgp_arm_ind], rgp_mean_est[rgp_arm_ind])
print('var est= ', cgp_var_est[cgp_arm_ind], rgp_var_est[rgp_arm_ind])
print('high ucb= ', cgp_high_ucb, rgp_high_ucb[highest_var_ind])
print('beta t = ', beta_t)
print(best_ard_params)
print('---***---')
# save results with unique time stamp
npz_str_uniq = npz_str + '_{}'.format(time.strftime("%Y_%m_%d_%H_%M_%S", time.gmtime(time.time())))
np.savez(npz_str_uniq, dx=dx, da=da, dx_bar=1, da_bar=1, cgp_rews_hist=cgp_rews_hist, cgp_regret_hist=cgp_regret_hist,
rgp_rews_hist=rgp_rews_hist, rgp_regret_hist=rgp_regret_hist, conf_scales=conf_scales, noise_sigma=noise_sigma,
random_rews_hist=random_rews_hist, random_regret_hist=random_regret_hist,
fit_ard_params_every=fit_ard_params_every)
#
if __name__ == '__main__':
main_fn()<file_sep>/bandit_algorithms/cmab_rl.py
import numpy as np
import sklearn.metrics as skmetrics
import scipy.special as spm
import itertools
def calculate_set_w_st_vcw(v_dx_x, v_2dx_x):
w_inds_list, w_tuples_list = [], []
for v_i, v in enumerate(v_dx_x):
# for each dx_bar tuple keep a list of 2dx_bar tuples that are supersets of the dx_bar tuple(for both tuple index and value)
w_inds_list_v, w_tuples_list_v = [], []
for w_i, w in enumerate(v_2dx_x):
is_subset = set(w).issuperset(set(v))
if is_subset:
w_inds_list_v.append(w_i)
w_tuples_list_v.append(w)
w_inds_list.append(w_inds_list_v)
w_tuples_list.append(w_tuples_list_v)
return np.array(w_inds_list), np.array(w_tuples_list)
def calculate_partial_partitions(m, d, tuples):
# infer d_bar from tuple shape
d_bar = tuples.shape[1]
# contains a partition for a single dimension
centers_vector = np.arange(m) / m + (0.5 / m)
# permutate for num of relevant dimensions
central_val_perms = np.array(list(itertools.product(centers_vector, repeat=d_bar)))
# initialize partition set
part_set = np.zeros(shape=(0, d))
for v in tuples:
# for each tuple create whole set of point, each with value 0.5
y = 0.5 * np.ones(shape=(central_val_perms.shape[0], d))
# set the "assumed" relevant dimensions s.t. they are partitioned
y[:, v] = central_val_perms
part_set = np.append(part_set, y, axis=0)
return part_set
class ContextualMultiArmedBanditWithRelevanceLearning:
""" Implementation of CMAB RL with continuous context and arm sets """
def __init__(self, horizon, dx, da, dx_bar, da_bar, lip_c, conf_scale):
# get params
self.horizon, self.dx, self.da, self.dx_bar, self.da_bar, self.lip_c, self.conf_scale =\
horizon, dx, da, dx_bar, da_bar, lip_c, conf_scale
# calculate m, round to 8 decimals in order to mitigate rounding errors
# at higher decimals which cause ceil function to wrongly ceil to a larger value
# example: 100000**(1 / 5) returns 10.000000000000002, when performed ceil on it, it is then taken as 11. But we know that
# 100000**(1/5) = 10, and its ceil should be 10
self.m = int(np.ceil(np.round(horizon**(1 / (2 + 2 * dx_bar + da_bar)), decimals=8)))
# calculate sets of tuples: num of tuples are (d choose d_bar) for each
self.V_dab_a = np.array(list(itertools.combinations(np.arange(da), da_bar)))
self.V_dxb_x = np.array(list(itertools.combinations(np.arange(dx), dx_bar)))
self.V_2dxb_x = np.array(list(itertools.combinations(np.arange(dx), 2 * dx_bar)))
# calculate arm and 2dx_bar tuple centers(W_centers is such that every m^2dx_bar rows correspond to a different 2dx_tuple)
self.Y_centers = calculate_partial_partitions(self.m, self.da, self.V_dab_a)
self.W_centers = calculate_partial_partitions(self.m, self.dx, self.V_2dxb_x)
# calculate which 2dx_bar tuples are supersets of which dx_bar tuples
self.vCw_inds, self.vCw_tuples = calculate_set_w_st_vcw(self.V_dxb_x, self.V_2dxb_x)
# num of comparisons needed for each v (w vs w_prime comparisons needed in calculating relevance set)
self.full_abs_diff_count_per_v = self.vCw_inds.shape[1]*(self.vCw_inds.shape[1] - 1) // 2
# this for loop prebuilds all the combinations of 2dx_bar tuples that are supersets of corresponding dx_bar needed for relevance set
# (this job is time consuming so instead of doing this every round we calculate the pairs now and iterate in a single loop)
self.w_wp_comb_lists_list, self.w_wp_inds_comb_lists_list = [], []
for v_i, v in enumerate(self.V_dxb_x):
w_wp_comb_list = list(itertools.combinations(self.vCw_tuples[v_i], 2))
w_wp_inds_comb_list = list(itertools.combinations(self.vCw_inds[v_i], 2))
self.w_wp_comb_lists_list.append(w_wp_comb_list)
self.w_wp_inds_comb_lists_list.append(w_wp_inds_comb_list)
# if there are duplicate arms, get rid of those (when m=odd and da_bar < da, this occurs due to 0.5 point)
self.Y_centers = np.unique(self.Y_centers, axis=0)
self.arm_size = self.Y_centers.shape[0]
# initialize counters
self.sample_counts = np.zeros(shape=(self.arm_size, self.W_centers.shape[0]))
self.sample_means = np.zeros(shape=(self.arm_size, self.W_centers.shape[0]))
# initialize some constants
self.c_bar = spm.comb(dx - 1, 2*dx_bar - 1, exact=False)
self.u_nom = 2 + 4 * np.log(2 * self.arm_size * (self.horizon ** 1.5) * self.c_bar * (self.m ** (2*self.dx_bar)))
self.context_err = lip_c * np.sqrt(dx_bar) / self.m
# keep necessary info for last played round to be able to update when reward is received(these values are just placeholders)
self.last_played_arm_ind = -1
self.last_observed_context_pw_inds = []
def find_pws_context_resides(self, context):
""" this method find the pw subsets that context resides """
# get number of 2dx_tuples and number of pws for each 2dx_tuple
num_w, num_parts_each_w = self.V_2dxb_x.shape[0], self.m ** (2*self.dx_bar)
# in this array we will store which pw is "active" for each w
pw_inds = np.zeros(shape=(num_w, ), dtype=np.int)
# calculate distance from the context vector to each pw
distances_to_pws = np.squeeze(skmetrics.pairwise_distances(np.expand_dims(context, axis=0), self.W_centers, metric='cityblock'))
# this for loop for each 2dx_tuple, find the pw that context resides in(by looking at the min distance to pw centers among each w)
for w_ind, w_tuple in enumerate(self.V_2dxb_x):
pws_selection = np.arange(start=w_ind*num_parts_each_w, stop=(w_ind+1)*num_parts_each_w)
dists_w = distances_to_pws[pws_selection]
min_dist_ind_w = np.argmin(dists_w)
pw_inds[w_ind] = w_ind*num_parts_each_w + min_dist_ind_w
return pw_inds
def determine_cys(self, pw_inds):
""" this method determines the cys for each arm y, this is the core of the algorithm """
# get counters
sample_means_pw = self.sample_means[:, pw_inds]
sample_counts_pw = self.sample_counts[:, pw_inds]
# avoid divide by zero warning(nothing important, just prevents np printing warning)
# as u_nom is never 0, we will get infinite ucbs at start. calculate confidence radii.
with np.errstate(divide='ignore'):
u_vals_pw = self.conf_scale * np.sqrt(self.u_nom / sample_counts_pw)
# placeholder for cys array, we will store estimated relevant dimensions for each y in this array
cys = -1*np.ones(shape=(self.arm_size, ), dtype=np.int)
# for each arm, we will calculate dx_tuples that are in relevance set and store their sigmas
for y_i, y in enumerate(self.Y_centers):
sigmas, valid_vs = [], []
# for each dx_tuple we will check every combination of 2dx_tuples
# and if so store the abs_diff(for sigma calculation this is needed, we store it here to avoid calculating again)
for v_i, v in enumerate(self.V_dxb_x):
abs_diffs = []
# get w and w_prime combinations that are supersets of v
w_wp_comb_list = self.w_wp_comb_lists_list[v_i]
w_wp_inds_comb_list = self.w_wp_inds_comb_lists_list[v_i]
# for each combination, check if they are satisfying relevance relation
for w_inds, w_wp in zip(w_wp_inds_comb_list, w_wp_comb_list):
w_i, wp_i, w, wp = w_inds[0], w_inds[1], w_wp[0], w_wp[1]
abs_diff = np.abs(sample_means_pw[y_i, w_i] - sample_means_pw[y_i, wp_i])
up_bound = 2 * self.context_err + u_vals_pw[y_i, w_i] + u_vals_pw[y_i, wp_i]
is_abs_diff_in_bounds = abs_diff <= up_bound
# if even one combination violates relevance relation, do not search for more
if not is_abs_diff_in_bounds:
break
# add only if relevance relation is satisfied
abs_diffs.append(abs_diff)
# if even one combination violates relevance relation, abs_diffs will not be "full"
if len(abs_diffs) == self.full_abs_diff_count_per_v:
# this happens when 2dx_bar = dx
if len(abs_diffs) == 0:
sigmas.append(0)
else:
# add to sigmas only if v is satisfying relevance relation
sigmas.append(np.max(abs_diffs))
valid_vs.append(v_i)
# not even a single v satisfies confident event, then select cy randomly(only happens in unconfident event)
if len(sigmas) == 0:
cys[y_i] = np.random.randint(self.V_dxb_x.shape[0], size=1)
else:
# if multiple v's are satisfying the relevance relation select the one with minimum sigma
winner_v_inds = np.argwhere(sigmas == np.min(sigmas))
# if multiple sigmas are minimum then select randomly among them
if winner_v_inds.shape[0] > 1:
winner = np.squeeze(winner_v_inds[np.random.randint(winner_v_inds.shape[0], size=1)])
else:
winner = np.squeeze(winner_v_inds)
cys[y_i] = valid_vs[int(winner)]
return cys
def calculate_ucbs(self, cys, pw_inds):
""" this method calculates the final ucbs for each arm """
# get counters
sample_means_pw = self.sample_means[:, pw_inds]
sample_counts_pw = self.sample_counts[:, pw_inds]
# calculate confidence radii(conf_scale is done late this time, not that it matters)
with np.errstate(divide='ignore'):
u_vals_pw = np.sqrt(self.u_nom / sample_counts_pw)
# get max for each w
u_vals_pw_ys = np.max(u_vals_pw, axis=-1)
# placeholder for estimated means
est_mean_ys = -1 * np.ones(shape=(self.arm_size, ))
# for each arm get only the 2dx_bar tuples that contain the estimated relevant context dx_bar tuple
v_2dx_x_superset_v = self.vCw_inds[cys]
# this for loop calculates the estimated means for each arm
for y_i, w_list in enumerate(v_2dx_x_superset_v):
# get sample means and counts from pws of 2dx_tuples
sample_means_pw_y = sample_means_pw[y_i, w_list]
sample_counts_pw_y = sample_counts_pw[y_i, w_list]
# calculate estimated mean
with np.errstate(invalid='ignore'):
est_mean_y = np.sum(sample_means_pw_y*sample_counts_pw_y) / np.sum(sample_counts_pw_y)
# nan would mean 0/0 due to sample_counts_pw_y being all zeros
# in this case the confidence radii is inf anyways so just set the mean to 0
if np.isnan(est_mean_y):
est_mean_ys[y_i] = 0
else:
est_mean_ys[y_i] = est_mean_y
# calculate final scaled ucb
ucbs = est_mean_ys + self.conf_scale * 5 * u_vals_pw_ys
return ucbs
def select_arm(self, context):
pw_inds = self.find_pws_context_resides(context)
cys = self.determine_cys(pw_inds)
ucbs = self.calculate_ucbs(cys, pw_inds)
# if multiple arms have the same highest ucb, select randomly among them
winner_arms = np.argwhere(ucbs == np.max(ucbs))
if winner_arms.shape[0] > 1:
winner_arm = np.squeeze(winner_arms[np.random.randint(winner_arms.shape[0], size=1)])
else:
winner_arm = np.squeeze(winner_arms)
# store the selected arm and pws that context hits for update after receiving reward
self.last_played_arm_ind = winner_arm
self.last_observed_context_pw_inds = pw_inds
return self.Y_centers[winner_arm]
def update_statistics(self, reward):
# get selected arm and pws that context hits from prev round
y_ind, pw_inds = self.last_played_arm_ind, self.last_observed_context_pw_inds
# get related counters
y_means, y_counts = self.sample_means[y_ind, pw_inds], self.sample_counts[y_ind, pw_inds]
# update related counters
self.sample_means[y_ind, pw_inds] = (y_means*y_counts + reward)/(y_counts + 1)
# updating for all ws allows for faster convergence
self.sample_counts[y_ind, pw_inds] = y_counts + 1
<file_sep>/bandit_algorithms/c_hoo.py
import numpy as np
def calculate_params(horizon, dim):
# these are given in the paper
v1, rho = 2*np.sqrt(dim), 2**(-1/dim)
# also given in paper, in section related to truncated tree
max_depth = int(np.ceil(np.log(v1*(horizon**0.5)) / np.log(1/rho)))
return v1, rho, max_depth
def calculate_child_centers(center, dim_radii, dim_to_div):
# calculates the child centers and new radii for each children(the same radii for both children since
# they are created by dividing the same dimension)
delta, new_dim_radii, dim = np.copy(dim_radii)/2, np.copy(dim_radii), center.shape[0]
delta[np.arange(dim) != dim_to_div] = 0
new_dim_radii[dim_to_div] /= 2
left_center, right_center = center - delta, center + delta
return left_center, right_center, new_dim_radii
def contains_context(context, center, dim_radii):
# this checks whether the given context vector is in the partition defined by the center and the radii of each dimension
up, low = center + dim_radii, center - dim_radii
return np.all([np.all(context <= up), np.all(context >= low)])
class ContextualHierarchicalOptimisticOptimization:
def __init__(self, dx, da, horizon, conf_scale=1.0):
# input parameters
self.d, self.dx, self.da, self.horizon, self.conf_scale = dx + da, dx, da, horizon, conf_scale
# calculate v1 and who st assumption in paper is satisfied
self.v1, self.rho, self.max_depth = calculate_params(horizon, dx + da)
# keep the tree as a dictionary of nodes: keys are (depth, index) tuples, values are linear indices
self.tree_nodes_dict = {(0, 1): 0}
# for each subset of the partition we will keep the geometric center, as well as the radius in every dimension
self.centers, self.dim_radiis = [0.5*np.ones(shape=(dx + da))], [0.5*np.ones(shape=(dx + da))]
# initial values for root note, all lists will expand as tree grows
self.Bs, self.Ns, self.mus, self.Us = [np.inf], [0], [0.0], [np.inf]
# these are used in update, after receiving reward
self.last_played_hi_pair = (-1, -1)
self.last_path = []
def select_arm(self, context):
""" this method determines an arm given context, follows the pseudo-code in the paper, the difference is that
in every step one has to consider which child contains the context"""
# we will start with the root node everytime
hi_pair = (0, 1)
path = [hi_pair]
left_center, right_center, children_dim_radii, is_sel_hi_left = None, None, None, None
while hi_pair in self.tree_nodes_dict:
# get depth, index and linear index of the node
h, i, lin_ind = hi_pair[0], hi_pair[1], self.tree_nodes_dict[hi_pair]
# get the left and right child indices (even if they are not in the tree yet)
left_hi, right_hi = (h + 1, 2*i - 1), (h + 1, 2*i)
left_b, right_b = np.inf, np.inf
# ucbs are infinite if they are not in the tree
# if they are in the tree access their B values stored in the corresponding array
if left_hi in self.tree_nodes_dict:
left_b = self.Bs[self.tree_nodes_dict[left_hi]]
if right_hi in self.tree_nodes_dict:
right_b = self.Bs[self.tree_nodes_dict[right_hi]]
# center and dimension radii of the region corresponding to this node
center, dim_radii = self.centers[lin_ind], self.dim_radiis[lin_ind]
# we divide partitions each time by the longest side(if multiple sides are longest, select arbitrarily)
# we select the first instance of the longest side, and at each level since we select it in order,
# which dimension to be divided is directly given by the depth of the node and the num of dimensions
dim_to_divide_next = h % self.d
# get child regions
left_center, right_center, children_dim_radii = calculate_child_centers(center, dim_radii, dim_to_divide_next)
# check if children contain the context
c_in_left = contains_context(context, left_center[:self.dx], children_dim_radii[:self.dx])
c_in_right = contains_context(context, right_center[:self.dx], children_dim_radii[:self.dx])
# this is flag, if left is chosen: True, else: False
is_sel_hi_left = True
# if context is in both look at the b values to choose
if c_in_left and c_in_right:
if left_b >= right_b:
hi_pair = left_hi
elif left_b < right_b:
hi_pair, is_sel_hi_left = right_hi, False
else:
z = np.random.randint(0, 2)
hi_pair, is_sel_hi_left = (h + 1, 2 * i - z), bool(z)
elif c_in_left:
# if only one of them contains the context then choose the one that contains
hi_pair = left_hi
elif c_in_right:
# if only one of them contains the context then choose the one that contains
hi_pair, is_sel_hi_left = right_hi, False
else:
# if no of the children contain the context, there must be some error, at least one child must contain the context
raise ValueError('Something is wrong, context must be in at least one of the children!')
# add selected child to path
path.append(hi_pair)
# stop traversing if max depth is reached
if len(path) > self.max_depth:
break
sel_hi = hi_pair
sel_center = right_center
# if the selected node is not in tree(this does not happen when we stop due to truncation)
if sel_hi not in self.tree_nodes_dict:
# add node to the dictionary
self.tree_nodes_dict[sel_hi] = len(self.tree_nodes_dict)
# add the radii info to the related array
self.dim_radiis.append(children_dim_radii)
if is_sel_hi_left:
sel_center = left_center
# add the selected child's center(after determining if it is the right of the left child)
self.centers.append(sel_center)
# new B values are inf
self.Bs.append(np.inf)
# initialize the statistics for the node
self.Ns.append(0)
self.mus.append(0)
self.Us.append(np.inf)
# get the upper and lower boundaries of the region selected
up_bound_hi, low_bound_hi = sel_center + children_dim_radii, sel_center - children_dim_radii
# select an arm uniformly random in the region
arm = np.random.uniform(low=up_bound_hi[self.dx:], high=low_bound_hi[self.dx:])
# update these, we will use these when updating after receiving reward
self.last_played_hi_pair = sel_hi
self.last_path = path
return arm
def update_statistics(self, reward):
""" update the tree statistic according to the paper,
since this is a truncated version the update is much simpler; see the related section in the paper """
# for each node in the previously followed path
for hi_pair in self.last_path:
h, i, lin_ind = hi_pair[0], hi_pair[1], self.tree_nodes_dict[hi_pair]
# increase # of times played
self.Ns[lin_ind] += 1
# update mean rew est for the region
self.mus[lin_ind] = float((1 - (1/self.Ns[lin_ind])) * self.mus[lin_ind] + (reward / self.Ns[lin_ind]))
# update U terms
conf_terms = np.sqrt(2 * np.log(self.horizon) / self.Ns[lin_ind]) + self.v1 * (self.rho ** h)
self.Us[lin_ind] = self.mus[lin_ind] + self.conf_scale * conf_terms
# now starting from the leaf traverse path upwards
for hi_pair in reversed(self.last_path):
h, i, lin_ind = hi_pair[0], hi_pair[1], self.tree_nodes_dict[hi_pair]
left_hi, right_hi = (h + 1, 2 * i - 1), (h + 1, 2 * i)
is_h_leaf = (left_hi not in self.tree_nodes_dict) and (right_hi not in self.tree_nodes_dict)
# if the node is a leaf just update B value as follows
if is_h_leaf:
self.Bs[lin_ind] = self.Us[lin_ind]
else:
# if not then use the B values of the children to update the B value, as well as the U value
left_b, right_b = np.inf, np.inf
if left_hi in self.tree_nodes_dict:
left_b = self.Bs[self.tree_nodes_dict[left_hi]]
if right_hi in self.tree_nodes_dict:
right_b = self.Bs[self.tree_nodes_dict[right_hi]]
self.Bs[lin_ind] = np.min([self.Us[lin_ind], np.max([left_b, right_b])])
| e70a3f2962a4fedbbe424ec08b835b341bb91532 | [
"Python",
"Text"
] | 12 | Python | cembulucu/cmabrl_n_cgpucbrl_synthetic_experiments | a07cbf1214811927e3851dec73588bd16351d0b0 | 003b2dd389c9161370f93c373dd8e191c2ab8d83 |
refs/heads/master | <file_sep># neo-smacco
SMACCO - SMart ACcount COmposer
This project aims to easily generate "smart accounts" for holding assets based on different (and combined) features:
- public/private key validation
- MultiSig
- timelock
- Asset-specific behavior (only allowing withdraws for specific assets, for example)
That will help NEO users to easily create and manage safe account addresses. Initially, only json interface will be provided to allow C# code generation (that will become AVM). After that, visual interfaces can help the design process, keeping in mind this is NOT a tool intended for developers, but to general public.
## Documentation
**Official Documentation on [ReadTheDocs](https://neo-smacco.readthedocs.io)**
[](https://neo-smacco.readthedocs.io/en/latest/?badge=latest)
### Docs Requirements (local build)
`python3 -m pip install -r docs/requirements.txt`
`make docs`
## How to use it
### Install on web browser
```html
<script src="https://unpkg.com/neo-smacco/dist/bundle.js"></script>
```
```js
Smacco = smacco.Smacco;
```
### Install on npm
`npm install neo-smacco`
```js
const Smacco = require('neo-smacco').Smacco;
```
## For Developers
### Tests
`npm test`
### Build Webpack
`npm run build`
### New minor version
`npm version minor`
### Push and Publish
`git push origin master --tags`
`npm publish`
## Examples
### Checking Simple Signature
```json
{
"standard": "smacco-1.0",
"input_type" : "single",
"pubkey_list" : ["036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb"],
"rule" : {
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "CHECKSIG"
}
}
}
```
### Checking Multiple Signatures (2/3 multisig)
```json
{
"standard": "smacco-1.0",
"input_type" : "array",
"pubkey_list" : ["036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb",
"<KEY>", "02e2baf21e36df2007189d05b9e682f4192a101dcdf07eed7d6313625a930874b4"],
"rule" : {
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "CHECKMULTISIG",
"minimum_required" : "2"
},
}
}
```
### Time Locking funds (until timestamp 1536896190)
```json
{
"standard": "smacco-1.0",
"input_type" : "single",
"pubkey_list" : ["036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb"],
"rules" : [
{
"rule_type": "DENY_IF",
"condition" : {
"condition_type" : "TIMESTAMP_LESS",
"timestamp" : "1536896190",
},
},
{
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "CHECKSIG"
},
},
]
}
```
### Complex logic -- Charity Donations Template
This example is inspired by a conversation with @lerider and @vncoelho (https://github.com/neo-project/proposals/issues/53), the idea is to
demonstrate the capability of easily handling different logic for different assets (Neo/Gas/...).
```json
{
"standard": "smacco-1.0",
"input_type" : "single",
"pubkey_list" : ["<KEY>", "036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb"],
"rules" : [
{
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "CHECKSIG",
"pubkey" : "0"
}
},
{
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "AND",
"conditions" : [
{
"condition_type" : "CHECKSIG",
"pubkey" : "1"
},
{
"condition_type" : "OR",
"conditions" : [
{
"condition_type" : "AND",
"conditions" : [
{
"condition_type" : "SELF_TRANSFER"
},
{
"condition_type" : "ONLY_NEO"
}
]
},
{
"condition_type" : "ONLY_GAS"
}
]
}
]
}
}
],
"default_rule" : "DENY_ALL"
}
```
## License
Copyleft 2018
MIT license
<file_sep>.. neo-smacco documentation master file, created by
sphinx-quickstart on Tue Sept 15 19:43:08 2020.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Smacco Documentation
======================
Welcome to Smacco Documentation, please select the desired content section.
.. toctree::
:maxdepth: 2
:caption: Contents
intro
install
quickstart
license
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>Installation
=============
Smacco is written on Javascript and published on NPM.
The tool can be used `online <https://neoresearch.io/smacco>`_, so only
advanced developers are required to install this.
How to install
--------------
Install on web browser
.. code-block:: html
<script src="https://unpkg.com/neo-smacco/dist/bundle.js"></script>
.. code-block:: js
Smacco = smacco.Smacco;
Install on npm
.. code-block:: shell
npm install neo-smacco
.. code-block:: js
const Smacco = require('neo-smacco').Smacco;
Cloning from GitHub
-------------------
To clone OptFrame repository from GitHub:
.. code-block:: shell
git clone https://github.com/neoresearch/neo-smacco.git
Development Workflow
--------------------
Tests
.. code-block:: shell
npm test
Build Webpack
.. code-block:: shell
npm run build
New minor version
.. code-block:: shell
npm version minor
Push and Publish
.. code-block:: shell
git push origin master --tags
npm publish
That's it! If you want to try it, jump to `<./quickstart.html>`_.<file_sep>const Smacco = require('./smacco').Smacco;
test('testing imports', () => {
expect(true).toBe(true);
});
//
<file_sep>Quick start
=============
Smacco is a tool designed to easily generate "smart accounts" for holding assets.
The specification of a smart account is made on JSON language, and the corresponding C# code
is generated for Neo2 blockchain.
A visual diagram is also generated, for simplicity.
The tool can be used `online <https://neoresearch.io/smacco>`_, so `installing <../install>`_
is not required (only for local testing).
First Example
-------------
The first Smart Account is a basic *public key verification contract*, which is the simplest
and most widespread mechanism to hold assets on Neo blockchain (and also on Bitcoin).
.. code-block:: json
{
"standard": "smacco-1.0",
"input_type" : "single",
"pubkey_list" : ["036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb"],
"rule" : {
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "CHECKSIG"
}
}
}
And the corresponding C# smart contract:
.. code-block:: csharp
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
namespace NeoContract1 {
public class Contract1 : SmartContract {
public static readonly byte[] pubkey_0 = "036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb".HexToBytes();
public static bool Main(byte[] signature){
return (VerifySignature(signature, pubkey_0));
}
}
}
.. |contract1| image:: _static/_figs/contract1.png
:width: 300
:alt: First contract
.. hint::
The `online`_ platform already compiles C# code using `NeoCompiler Eco <https://neocompiler.io>`_ infrastructure.
Platform also generates the following diagram:
|contract1|
Definition starts with *standard*, and :code:`smacco-1.0` has two :code:`input_type`: single or multi.
We start with *input_type* :code:`single`, which means that a *single signature* is received as input parameter.
The field :code:`pubkey_list` declares the used keys for public key criptography.
.. note::
Neo uses *NIST P-256 secp256r1* elliptic curve cryptography.
See project `libcrypton <http://github.com/neoresearch/libcrypton>`_ for more information.
The goal of the generated verification contract is to return a :code:`boolean` (*true/false*) response,
when a matching signature is provided.
We then explore :code:`rule` section.
Understanding Rules
-------------------
Every smart account is composed by *one or more rules*, that govern the behavior of the contract.
Smacco provides two fields:
- :code:`rule`: when a single rule is used (the simplest form)
- :code:`rules`: when multiple rules are used
Each *rule* is divided in two parts: *rule_type* and *condition*.
A :code:`rule_type` can be:
- :code:`ALLOW_IF`: directly **accepts** operation (returns *true*) if *condition* is **satisfied**
- :code:`DENY_IF`: directly **rejects** operation (returns *false*) if *condition* is **not satisfied**
Every :code:`condition` has a *condition_type* in many formats, including:
- :code:`CHECKSIG`: checks a single signature parameter against public key
- :code:`CHECKMULTISIG`: checks an array of signatures as parameter against an array of public keys
- and many others... *note that details are not given at this point, let's move on*
Default Rule and Inlining
*************************
It's important to highlight that a :code:`default_rule` governs the corner cases of the contract, and can be:
- :code:`DENY_ALL`: standard option, if no rule explicitly accepts, then operation is rejected
- :code:`ACCEPTS_ALL`: if no rule explicitly rejects, then operation is accepted
.. important::
Note that *default_rule* is only used when :code:`"inline_last"="disabled"`. Since inlining
is enabled by default, we typically don't use a :code:`default_rule`.
MultiSig Example
----------------
Next example validates a subset of public keys against an array of signatures passed as parameter, known as *multisig*.
This account type is generally used to provide extra security, in two common scenarios:
- requiring multiple entities to attach signatures, e.g., a 3/3 multisig (only valid if three-out-of-three sign together)
- accepting fallback signatures, if some of them is lost, e.g., a 2/3 multisig (valid if any two-out-of-three sign together)
We provide an example of 2/3 multisig, with *default_rule* set to :code:`DENY_ALL` (disabling inlining):
.. code-block:: json
{
"standard": "smacco-1.0",
"input_type": "array",
"pubkey_list": [
"036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb",
"<KEY>",
"02e2baf21e36df2007189d05b9e682f4192a101dcdf07eed7d6313625a930874b4"
],
"rule": {
"rule_type": "ALLOW_IF",
"condition": {
"condition_type": "CHECKMULTISIG",
"minimum_required": "2"
}
},
"default_rule" : "DENY_ALL"
}
And the corresponding C# smart contract:
.. code-block:: csharp
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
namespace NeoContract1 {
public class Contract1 : SmartContract {
public static readonly byte[] pubkey_0 = "036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb".HexToBytes();
public static readonly byte[] pubkey_1 = "<KEY>".HexToBytes();
public static readonly byte[] pubkey_2 = "02e2baf21e36df2007189d05b9e682f4192a101dcdf07eed7d6313625a930874b4".HexToBytes();
public static bool CheckMultiSig2_3(byte[][] signatures){
byte[][] vpub = new[] {pubkey_0, pubkey_1, pubkey_2};
byte[][] vsig = new[] {signatures[0], signatures[1]};
return VerifySignatures(vsig, vpub);
}
public static bool Main(byte[][] signatures) {
if(CheckMultiSig2_3(signatures))
return true;
return false;
}
}
}
.. |contract2| image:: _static/_figs/contract2.png
:width: 300
:alt: Multisig contract
.. hint::
The `online`_ platform already compiles C# code using `NeoCompiler Eco <https://neocompiler.io>`_ infrastructure.
Platform also generates the following diagram:
|contract2|
Timelock Contract
-----------------
One of the most powerful capability of Smacco is to easily generate *timelock accounts*.
Many blockchain projects rely on time locks to enforce token governance,
disabling any possible operation *before* or *after* a given time.
We provide an example of a timelock *until timestamp* **1536896190** (*09/14/2018 @ 3:36am UTC*):
.. code-block:: json
{
"standard": "smacco-1.0",
"input_type": "single",
"pubkey_list": [
"036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb"
],
"rules": [
{
"rule_type": "DENY_IF",
"condition": {
"condition_type": "TIMESTAMP_LESS",
"timestamp": "1536896190"
}
},
{
"rule_type": "ALLOW_IF",
"condition": {
"condition_type": "CHECKSIG"
}
}
]
}
And the corresponding C# smart contract:
.. code-block:: csharp
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
namespace NeoContract1 {
public class Contract1 : SmartContract {
public static readonly byte[] pubkey_0 = "036245f426b4522e8a2901be6ccc1f71e37dc376726cc6665d80c5997e240568fb".HexToBytes();
public static bool Main(byte[] signature) {
if(Blockchain.GetHeader(Blockchain.GetHeight()).Timestamp < 1536896190)
return false;
return (VerifySignature(signature, pubkey_0));
}
}
}
.. |contract3| image:: _static/_figs/contract3.png
:width: 300
:alt: Timelock contract
.. hint::
The `online`_ platform already compiles C# code using `NeoCompiler Eco <https://neocompiler.io>`_ infrastructure.
Platform also generates the following diagram:
|contract3|
Logic Operations
----------------
Conditions can also be combined by means of logic AND/OR operations.
For example, by giving two pubkeys as parameter, we can use OR to make a choice between them:
.. code-block:: json
{
"rule_type": "ALLOW_IF",
"condition" : {
"condition_type" : "OR",
"conditions" : [
{
"condition_type" : "CHECKSIG",
"pubkey" : "0"
},
{
"condition_type" : "CHECKSIG",
"pubkey" : "1"
}
]
}
}
.. hint::
The above example is equivalent to a 1/2 MultiSig. Practice a little bit and try that!
Available Conditions
--------------------
We present a short list of available conditions.
.. warning::
This list is **very likely to be incomplete**! If more information is needed, open an Issue for
a discussion on GitHub, or inspect the source code :code:`smacco.js` to find out more details.
Conditions and subfields:
- :code:`AND`: performs logic AND
* :code:`conditions`: json list of conditions to perform AND
- :code:`OR`: performs logic OR
* :code:`conditions`: json list of conditions to perform OR
- :code:`CHECKSIG`: performs CHECKSIG to validate default or explicit pubkey
* :code:`pubkey`: explicit pubkey index (defaults to 0)
- :code:`CHECKMULTISIG`: performs CHECKMULTISIG X/Y
* :code:`pubkeys`: list of public keys to check (value Y). Defaults to global :code:`pubkey_list`.
* :code:`minimum_required`: value X of X/Y multisig
* :code:`signatures`: explicit index of signatures passed as array to contract. Length of list replaces *minimum_required*.
* :code:`condition_name`: name of condition (affects C# function name)
- :code:`TIMESTAMP_LESS`: check if timestamp is *less than* a given value
* :code:`timestamp`: explicit time value in timestamp format
* :code:`utc`: explicit time value in utc format
- :code:`TIMESTAMP_GREATER`: check if timestamp is *greater than* a given value
* :code:`timestamp`: explicit time value in timestamp format
* :code:`utc`: explicit time value in utc format
- :code:`SELF_TRANSFER`: check if transaction is a self-transfer (destination is same as source)
- :code:`ONLY_NEO`: check if only NEO asset is being transferred
- :code:`ONLY_GAS`: check if only GAS asset is being transferred
Interesting examples of each of these options are presented on file :code:`smacco.test.js`.
<file_sep>Introduction
=============
Smacco is a tool designed to easily generate "smart accounts" for holding assets
based on different (and combined) features:
- public/private key validation
- MultiSig
- timelock
- Asset-specific behavior (only allowing withdraws for specific assets, for example)
That will help NEO users to easily create and manage safe account addresses.
Initially, only json interface will be provided to allow C# code generation (that will become AVM).
.. warning::
Only Neo2 smart contracts are currently supported. As soon as Neo3 is launched, Smacco can be
updated to reflect latest changes on asset model, such as UTXO being replaced by Native Contracts.
On Smacco, visual interfaces can also help the design process,
keeping in mind this tool is NOT only intended for developers, but also to general public.
Smacco is available `online <https://neoresearch.io/smacco>`_. Feel free to try it!
More information
-----------------
If you want to build it locally, visit :doc:`install <../install>`, otherwise you can jump to
:doc:`quick start <../quickstart>` and practice `online <https://neoresearch.io/smacco>`_.
.. role:: raw-html(raw)
:format: html
Smacco has been developed with :raw-html:`♥` by NeoResearch Community.
Feel free to visit project `GitHub <https://github.com/neoresearch/neo-smacco>`_.
License
-------
Project released under MIT License.
See complete :doc:`license <../license>`.
<file_sep>all:
.PHONY: docs
docs:
cd docs && make clean && make html
| 6220341083f920c90bbae3c331f2db46c8e10ac5 | [
"Markdown",
"Makefile",
"JavaScript",
"reStructuredText"
] | 7 | Markdown | NeoResearch/neo-smacco | 29789d9684a3176a78e1f43129c70e0e62c0398c | 9364afd915344d3605174cae74513586904d850c |
refs/heads/master | <repo_name>imjasonh/skaffold<file_sep>/cmd/skaffold/app/cmd/docker/deps.go
/*
Copyright 2018 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package docker
import (
"io"
"path/filepath"
cmdutil "github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/cmd/util"
"github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/flags"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/config"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var depsFormatFlag = flags.NewTemplateFlag("{{range .Deps}}{{.}} {{end}}\n", DepsOutput{})
func NewCmdDeps(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "deps",
Short: "Returns a list of dependencies for the input dockerfile",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runDeps(out, filename, dockerfile, context)
},
}
AddDockerFlags(cmd)
return cmd
}
type DepsOutput struct {
Deps []string
}
func runDeps(out io.Writer, filename, dockerfile, context string) error {
// if we don't have a context, infer from the provided dockerfile path
if context == "" {
context = filepath.Dir(dockerfile)
}
// if we don't have a skaffold.yaml, use the one in the docker context dir
if filename == "" {
filename = filepath.Join(context, "skaffold.yaml")
}
config, err := cmdutil.ParseConfig(filename)
if err != nil {
return errors.Wrap(err, "parsing skaffold config")
}
// normalize the provided dockerfile path WRT to the context
normalizedPath, err := docker.NormalizeDockerfilePath(context, dockerfile)
if err != nil {
return errors.Wrap(err, "normalizing dockerfile path")
}
deps, err := docker.GetDependencies(getBuildArgsForDockerfile(config, normalizedPath), context, normalizedPath)
if err != nil {
return errors.Wrap(err, "getting dockerfile dependencies")
}
cmdOut := DepsOutput{Deps: deps}
if err := depsFormatFlag.Template().Execute(out, cmdOut); err != nil {
return errors.Wrap(err, "executing template")
}
return nil
}
func getBuildArgsForDockerfile(config *config.SkaffoldConfig, dockerfile string) map[string]*string {
var err error
for _, artifact := range config.Build.Artifacts {
if artifact.DockerArtifact != nil {
artifactPath := artifact.DockerArtifact.DockerfilePath
if artifact.Workspace != "" {
artifactPath, err = docker.NormalizeDockerfilePath(artifact.Workspace, artifactPath)
if err != nil {
logrus.Warnf("normalizing artifact dockerfile path: %s\n", err.Error())
}
}
if artifactPath == dockerfile {
return artifact.DockerArtifact.BuildArgs
}
}
}
logrus.Infof("no build args found for dockerfile %s", dockerfile)
return map[string]*string{}
}
<file_sep>/cmd/skaffold/app/cmd/docker/context.go
/*
Copyright 2018 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package docker
import (
"bytes"
"io"
"io/ioutil"
"path/filepath"
cmdutil "github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/cmd/util"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var output string
func NewCmdContext(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "context",
Short: "Outputs a minimal context tarball to stdout",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runContext(out, filename, context)
},
}
AddDockerFlags(cmd)
return cmd
}
func runContext(out io.Writer, filename, context string) error {
config, err := cmdutil.ParseConfig(filename)
if err != nil {
return errors.Wrap(err, "parsing skaffold config")
}
dockerFilePath, err := filepath.Abs(filename)
logrus.Info(filename)
logrus.Info(dockerFilePath)
if err != nil {
return err
}
// Write everything to memory, then flush to disk at the end.
// This prevents recursion problems, where the output file can end up
// in the context itself during creation.
var b bytes.Buffer
if err := docker.CreateDockerTarGzContext(getBuildArgsForDockerfile(config, dockerfile), &b, context, dockerFilePath); err != nil {
return err
}
return ioutil.WriteFile(output, b.Bytes(), 0644)
}
<file_sep>/cmd/skaffold/app/cmd/docker/flags.go
/*
Copyright 2018 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package docker
import (
"github.com/spf13/cobra"
)
var (
filename, dockerfile, context string
)
func AddDockerFlags(cmd *cobra.Command) {
cmd.Flags().StringVarP(&filename, "filename", "f", "", "Filename or URL to the pipeline file")
cmd.Flags().StringVarP(&dockerfile, "dockerfile", "d", "Dockerfile", "Dockerfile path")
cmd.Flags().StringVarP(&context, "context", "c", "", "Dockerfile context path")
cmd.Flags().VarP(depsFormatFlag, "output", "o", depsFormatFlag.Usage())
}
| 262ce483a3f0f1638aa2e512f559ca277207f1c4 | [
"Go"
] | 3 | Go | imjasonh/skaffold | 26f58ef576e2f48bd977b4ec67495a23b0c6f8cf | 9d59cd1c4e4e29d9fa2c5409b353cf24beed4539 |
refs/heads/master | <repo_name>jimmyli17/forms_review<file_sep>/config/routes.rb
Rails.application.routes.draw do
get '/forms_review' => 'application#form'
get '/new_input' => 'application#new'
get '/new_input/positive' => 'application#positive'
get '/new_input/negative' => 'application#negative'
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def form
end
def new
n = City.new
n.name = params['name']
if n.name == 'Chicago'
render 'postive'
else
render 'negative'
end
end
def positive
end
def negative
end
end | d0fc7b3cdde5a7e68afa3737787edc63ded90d61 | [
"Ruby"
] | 2 | Ruby | jimmyli17/forms_review | 3726a9dcd617ed468977cd32890d94ff4949b7d3 | c0ceadaecaa00937a161b5d1e88f94fad21846bb |
refs/heads/main | <file_sep># Assignment-Submission-Java-Programmig<file_sep>import java.util.Scanner;
public class Student{
int roll_no;
String name;
float marks;
public void input()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Roll No. of Student: ");
roll_no = in.nextInt();
in.nextLine();
System.out.print("Enter Name of Student: ");
name = in.nextLine();
System.out.print("Enter Marks of student: ");
marks = in.nextFloat();
}
public void display()
{
System.out.println("Roll_No. of Student : " +roll_no);
System.out.println("Name of Student : " +name);
System.out.println("Marks of Student : " +marks);
}
public static void main(String args[])
{
Student obj = new Student();
obj.input();
obj.display();
}
} | 703f0037992ad9e0726f47520862effb7dce1c1f | [
"Markdown",
"Java"
] | 2 | Markdown | sona0707/Assignment-Submission-Java-Programmig | ea272a63e386356b66c7d156cbeaffb670787c57 | 018319179d9fc5cb8619b3b1e9ff63812d0838b7 |
refs/heads/master | <repo_name>JulioZavala/webapp<file_sep>/src/main/java/app/controler/EnviarArchivoServlet.java
package app.controler;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/EnviarArchivoServlet")
public class EnviarArchivoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Content-Disposition", "attachment; filename=texto.pdf");
response.setContentType("application/pdf");
File dir = new File("c:\\");
File f = new File(dir, "HTML.pdf");
byte[] bytearray = new byte[(int) f.length()];
FileInputStream is = new FileInputStream(f);
is.read(bytearray);
OutputStream os = response.getOutputStream();
os.write(bytearray);
os.flush();
}
}
<file_sep>/src/main/java/app/controler/ListarPedidosServlet.java
package app.controler;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ListarPedidosServlet", urlPatterns = {"/ListarPedidosServlet"})
public class ListarPedidosServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Dentro de ListarPedidosServlet");
RequestDispatcher rd = request.getRequestDispatcher("/pedidos.jsp");
rd.forward(request, response);
}
}
| d44190039d86d6bfcc2841ee8a34b6d25784bd34 | [
"Java"
] | 2 | Java | JulioZavala/webapp | dbb618e6ff4c577cf5cd91751bef737a98cf8123 | 016f479fef3f42198507063cef4169c7d91ce695 |
refs/heads/master | <repo_name>francovalledor/valledor-react-form<file_sep>/example/src/App.js
import React from 'react'
import { SimpleForm } from "valledor-react-form";
const App = () => {
let fields = []
fields.push({
name: 'username',
type: 'text',
placeholder: 'Username',
required: true
})
fields.push({
name: 'password',
type: '<PASSWORD>',
placeholder: '<PASSWORD>',
note: 'must include letters in mixed case and numbers'
})
fields.push({
label: 'Date of birth',
name: 'date',
type: 'date',
value: '2020-12-02',
isValid: true,
validMessage: 'Looks good',
invalidMessage: "Doesn't looks good"
})
fields.push({
name: 'email',
type: 'email',
placeholder: '<EMAIL>',
value: '<EMAIL>',
required: true
})
fields.push({
name: 'gender',
type: 'select',
label: 'Gender',
options: [
{value: "M", text: "M"},
{value: "F", text: "F"},
{value: "NB", text: "NB"}
]
})
fields.push({
name: 'submit',
type: 'submit',
value: 'Sign In',
required: true
})
function onSubmit(e) {
e.preventDefault()
console.log('submit')
}
function onChange(e) {
e.preventDefault()
console.log('change')
}
return (
<div className='container p-2 mt-4'>
<SimpleForm fields={fields} />
</div>
)
}
export default App
<file_sep>/src/index.js
import React from 'react'
import SimpleForm from './components/SimpleForm/';
export {SimpleForm}
export default SimpleForm
<file_sep>/src/components/SimpleForm/index.js
import React from "react";
import {
renderTitle,
renderTypeGeneral,
renderTypeSelect,
renderTypeSubmit
} from "./utils";
/**
* ## Create a simple form
*
* @callback onChange
* @callback onSubmit
* @callback onBlur
* @param {array} fields - Array containing form's fields (<input>)
* @param {string} fields[].name - <input>'s name
* @param {string} fields[].type - <input>'s type
* @param {string} [ fields[].placeholder ] - optional <input>'s placeholder
* @param {string} [ fields[].label ] - optional <input>'s label
* @param {string} [ fields[].note ] - optional <input>'s note
*
* @param {string} [title] - optional form's title
* @param {function} [onChange] - optional function for fields change handling
* @param {function} [onSubmit] - optional function for form submit handling
* @param {function} [onBlur] - optional function for focus out handling
* @version 1.0.3
* @author [<NAME>](https://github.com/francovalledor)
*/
export function SimpleForm(props) {
// FUNCTIONS
// Validations
function checkParams() {
let itsOK = true;
if (!props.fields || !props.fields.map) {
itsOK = false;
}
return itsOK;
}
// Event Handlers
function handleChange(e) {
if (props.onChange) {
props.onChange(e);
}
}
function handleSubmit(e) {
e.preventDefault();
if (props.onSubmit) {
props.onSubmit(e);
}
}
function handleFocusOut(e) {
if (props.onBlur) {
props.onBlur(e);
}
}
function renderFields(fields) {
let index = 1;
return props.fields.map((field) => {
let classes = "form-control";
if (field.isValid === true) {
classes += " is-valid";
} else if (field.isValid === false) {
classes += " is-invalid";
}
switch (field.type.toLowerCase()) {
case "submit":
return renderTypeSubmit(field, classes, index);
case "select":
return renderTypeSelect(field, classes, index);
default:
return renderTypeGeneral(field, classes, index);
}
});
}
/**
* BODY
*/
if (checkParams()) {
return (
<form
onSubmit={handleSubmit}
onChange={handleChange}
onBlur={handleFocusOut}
>
{renderTitle(props)}
{renderFields(props.fields)}
</form>
);
} else {
console.error("CreateForm: Missing params");
return "";
}
}
export default SimpleForm;
<file_sep>/README.md
# valledor-react-form
> Create react forms made simple
[](https://www.npmjs.com/package/valledor-react-form) [](https://standardjs.com)
## Install
```bash
npm install --save valledor-react-form
```
## Usage
```jsx
import React, { Component } from 'react'
import SimpleForm from 'valledor-react-form'
function SignInForm(props) {
fields.push({
name: "username",
type: "text",
placeholder: "Username",
required: true
})
fields.push({
name: "<PASSWORD>",
type: "<PASSWORD>",
placeholder: "<PASSWORD>",
note: "must include letters in mixed case and numbers"
})
fields.push({
name: "gender",
type: "select",
label: "gender"
options: [
{value: "M", text:"M"},
{value: "F", text:"F"},
{value: "NB", text:"NB"}
]
})
fields.push({
name: "submit",
type: "submit",
value: "Sign In",
required: true
})
function onSubmit(e) {
formData = new FormData(e.target)
validate(formData)
...
}
///Optional
function onChange(e) {
console.log('field: ', e.target.name)
console.log('value: ', e.target.value)
}
return <SimpleForm
onChange={onChange} //optional
onSubmit={onSubmit} //optional
title="Sign Up" //optional
fields={fields} //required
/>
}
### It is recommended to use bootstrap. SimpleForm is bootstrap formatted.
```
## License
MIT © [francovalledor](https://github.com/francovalledor)
| d284574dec365aa0df614abea9135a40d2f418d3 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | francovalledor/valledor-react-form | 41e50dfd755b37236767800c6ec5d4973ca607d9 | e6e6c2a5491637c0b34d2545943c3d4bd279ee44 |
refs/heads/master | <repo_name>SunflowerNguyen/UnitConversion<file_sep>/src/UnitConversion/UnitConversion.php
<?php
namespace DuyVuSeldat\UnitConversion;
class UnitConversion {
protected static $conversion;
protected $value;
protected $unit;
protected $native;
public function __construct($value = 0 , $unit = '')
{
$this->value = $value;
$this->unit = $unit;
static::$conversion = Units::$conversion;
}
public function convert($quantity , $unit){
return new UnitConversion($quantity, $unit);
}
public function to($unit){
$this->value = $this->handle($this->value , $this->unit , $unit);
$this->unit = $unit;
return $this;
}
public function __toString()
{
return $this->format();
}
protected function handle($value , $from , $to){
return ($value * $this->getUnit($from)) / $this->getUnit($to);
}
protected function getUnit($unit){
if (!isset(self::$conversion[strtoupper($unit)])){
throw new \Exception("Can not convert between 2 units.");
}
return self::$conversion[strtoupper($unit)];
}
public function format($decimals = 4, $decPoint = '.', $thousandSep = ',')
{
return number_format($this->value, $decimals, $decPoint, $thousandSep);
}
}<file_sep>/Test/Test.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
//use DuyVuSeldat\UnitConversion\UnitConversion;
//echo UnitConversion::convert(1 , 'carat')->to('kilogram');<file_sep>/src/UnitConversion/UnitConversionServiceProvider.php
<?php
namespace DuyVuSeldat\UnitConversion;
use Illuminate\Support\ServiceProvider;
class UnitConversionServiceProvider extends ServiceProvider{
public function register()
{
$this->app->bind('unit-conversion', function ($app) {
return new UnitConversion;
});
}
}<file_sep>/src/UnitConversion/Facades/UnitConversion.php
<?php
namespace DuyVuSeldat\UnitConversion\Facades;
use Illuminate\Support\Facades\Facade;
class UnitConversion extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'unit-conversion';
}
} | d5d50cd9520d5a9fd5a2cbd242491a7eb56b27b0 | [
"PHP"
] | 4 | PHP | SunflowerNguyen/UnitConversion | 7b3e7e1618d62b470852bca9d13c094e41822efa | fda5866c54a66636b4d706438b46d1a088506a58 |
refs/heads/master | <repo_name>JimNtexas/Ham-radio-wspr<file_sep>/wspr.py
import subprocess
import time
import argparse
success = True
parser = argparse.ArgumentParser(description='Script to control WsprPI')
parser.add_argument("--x", default=3, help="Number of transmissions per loop")
parser.add_argument("--d", default=2, help="Delay in minutes between calls to wspr")
parser.print_help()
args = parser.parse_args()
print("\nnumber of transmissions per loop: " + str(args.x))
print("delay between loops: " + str(args.d) + " minutes\n")
delayBetweenLoops = args.d
numberOfTransmissions = ("-x " + str(args.x))
while success:
xmitCount = 0
while xmitCount < args.x and success:
result = subprocess.run(['wspr', numberOfTransmissions,'-o','KE5WAN','EM10ck','20','20M'])
success = (result.returncode == 0)
xmitCount += 1
print (str(xmitCount) + ": result: " + str(result.returncode))
if success:
print("sleeping " + str(delayBetweenLoops) + " minutes")
time.sleep(delayBetweenLoops*60)
print("------------------------\n")
localtime = time.asctime( time.localtime(time.time()) )
print ("wspr stopped :", localtime)
| 592eddfc78c7c28f9276e45462d5d0f8f7790403 | [
"Python"
] | 1 | Python | JimNtexas/Ham-radio-wspr | a910ef3bdb8b0088ce83b15b5408e1127b9f326d | 333db460fda64421b888a9e4ad1b60d337d0a8dc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.