hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e4ee79d0150fd0bf352955eb953196e9fe30dc7b | 3,582 | h | C | source/direct3d11/Debug11.h | bartwe/slimdx | 3e6cf800de425ac78717453588a9681527caa576 | [
"MIT"
] | null | null | null | source/direct3d11/Debug11.h | bartwe/slimdx | 3e6cf800de425ac78717453588a9681527caa576 | [
"MIT"
] | null | null | null | source/direct3d11/Debug11.h | bartwe/slimdx | 3e6cf800de425ac78717453588a9681527caa576 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2007-2014 SlimDX Group
*
* 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.
*/
#pragma once
#include "../ComObject.h"
#include "../dxgi/SwapChainDxgi.h"
#include "Enums11.h"
namespace SlimDX
{
namespace Direct3D11
{
ref class Device;
ref class DeviceContext;
/// <summary>
/// An interface for controlling debug state and validating pipeline settings.
/// </summary>
/// <unmanaged>ID3D11Debug</unmanaged>
public ref class Debug : public ComObject
{
COMOBJECT(ID3D11Debug, Debug);
public:
/// <summary>
/// Gets or sets the flags indicating which debug features are enabled.
/// </summary>
property DebugFeatureFlags FeatureFlags
{
DebugFeatureFlags get();
void set( DebugFeatureFlags value );
}
/// <summary>
/// Gets or sets the number of milliseconds to delay after a swap chain is presented.
/// </summary>
property int PresentDelay
{
int get();
void set( int value );
}
/// <summary>
/// Gets or sets the swap chain the runtime will use for automatic presentation.
/// </summary>
property DXGI::SwapChain^ SwapChain
{
DXGI::SwapChain^ get();
void set( DXGI::SwapChain^ value );
}
/// <summary>
/// Initializes a new instance of the <see cref="Debug"/> class.
/// </summary>
/// <param name="device">The device with which the debug interface is to be associated.</param>
Debug( Device^ device );
/// <summary>
/// Validates the current pipeline state of a device context.
/// </summary>
/// <param name="context">The device context to validate.</param>
/// <returns>A <see cref="SlimDX::Result"/> object describing the result of the operation.</returns>
Result ValidateContext(DeviceContext^ context);
/// <summary>
/// Validates the device context for dispatching operations.
/// </summary>
/// <param name="context">The device context to validate.</param>
/// <returns>A <see cref="SlimDX::Result"/> object describing the result of the operation.</returns>
Result ValidateContextForDispatch(DeviceContext^ context);
/// <summary>
/// Reports information about live device objects.
/// </summary>
/// <param name="level">Options for specifying the amount of detail in the output.</param>
/// <returns>A <see cref="SlimDX::Result"/> object describing the result of the operation.</returns>
Result ReportLiveDeviceObjects(ReportingLevel level);
};
}
}; | 35.465347 | 104 | 0.680625 | [
"object"
] |
e4fcde1f03f70e7765c59519111da1a90e57a448 | 3,493 | h | C | SimTracker/TrackerHitAssociation/interface/ClusterTPAssociation.h | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | 1 | 2019-03-09T19:47:49.000Z | 2019-03-09T19:47:49.000Z | SimTracker/TrackerHitAssociation/interface/ClusterTPAssociation.h | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | null | null | null | SimTracker/TrackerHitAssociation/interface/ClusterTPAssociation.h | trackerpro/cmssw | 3e05774a180a5f4cdc70b713bd711c23f9364765 | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | #ifndef SimTracker_TrackerHitAssociation_ClusterTPAssociation_h
#define SimTracker_TrackerHitAssociation_ClusterTPAssociation_h
#include "DataFormats/Provenance/interface/ProductID.h"
#include "DataFormats/Common/interface/HandleBase.h"
#include "DataFormats/TrackerRecHit2D/interface/OmniClusterRef.h"
#include "FWCore/Utilities/interface/VecArray.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h"
#include <vector>
#include <utility>
#include <algorithm>
/**
* Maps OmniClusterRefs to TrackingParticleRefs
*
* Assumes that the TrackingParticleRefs point to a single
* TrackingParticle collection.
*/
class ClusterTPAssociation {
public:
using key_type = OmniClusterRef;
using mapped_type = TrackingParticleRef;
using value_type = std::pair<key_type, mapped_type>;
using map_type = std::vector<value_type>;
using const_iterator = typename map_type::const_iterator;
using range = std::pair<const_iterator, const_iterator>;
ClusterTPAssociation() {}
explicit ClusterTPAssociation(const edm::HandleBase& mappedHandle): ClusterTPAssociation(mappedHandle.id()) {}
explicit ClusterTPAssociation(const edm::ProductID& mappedProductId): mappedProductId_(mappedProductId) {}
void emplace_back(const OmniClusterRef& cluster, const TrackingParticleRef& tp) {
checkMappedProductID(tp);
auto foundKeyID = std::find(std::begin(keyProductIDs_), std::end(keyProductIDs_), cluster.id());
if(foundKeyID == std::end(keyProductIDs_)) {
keyProductIDs_.emplace_back(cluster.id());
}
map_.emplace_back(cluster, tp);
}
void sortAndUnique() {
std::sort(map_.begin(), map_.end(), compareSort);
auto last = std::unique(map_.begin(), map_.end());
map_.erase(last, map_.end());
map_.shrink_to_fit();
}
void swap(ClusterTPAssociation& other) {
map_.swap(other.map_);
mappedProductId_.swap(other.mappedProductId_);
}
bool empty() const { return map_.empty(); }
size_t size() const { return map_.size(); }
const_iterator begin() const { return map_.begin(); }
const_iterator cbegin() const { return map_.cbegin(); }
const_iterator end() const { return map_.end(); }
const_iterator cend() const { return map_.end(); }
range equal_range(const OmniClusterRef& key) const {
checkKeyProductID(key);
return std::equal_range(map_.begin(), map_.end(), value_type(key, TrackingParticleRef()), compare);
}
const map_type& map() const { return map_; }
void checkKeyProductID(const OmniClusterRef& key) const { checkKeyProductID(key.id()); }
void checkKeyProductID(const edm::ProductID& id) const;
void checkMappedProductID(const edm::HandleBase& mappedHandle) const { checkMappedProductID(mappedHandle.id()); }
void checkMappedProductID(const TrackingParticleRef& tp) const { checkMappedProductID(tp.id()); }
void checkMappedProductID(const edm::ProductID& id) const;
private:
static bool compare(const value_type& i, const value_type& j) {
return i.first.rawIndex() > j.first.rawIndex();
}
static bool compareSort(const value_type& i, const value_type& j) {
// For sorting compare also TrackingParticle keys in order to
// remove duplicate matches
return compare(i, j) || (i.first.rawIndex() == j.first.rawIndex() && i.second.key() > j.second.key());
}
map_type map_;
edm::VecArray<edm::ProductID, 2> keyProductIDs_;
edm::ProductID mappedProductId_;
};
#endif
| 37.967391 | 115 | 0.744346 | [
"vector"
] |
e4fd70f23eebd860bd9124e153a3f081dc7ec5a0 | 2,831 | h | C | src/util.h | nodchip/icfpc2021 | e50f0172fd62097049dab19c01875c57468a13f1 | [
"MIT"
] | 1 | 2021-07-12T13:52:18.000Z | 2021-07-12T13:52:18.000Z | src/util.h | nodchip/icfpc2021 | e50f0172fd62097049dab19c01875c57468a13f1 | [
"MIT"
] | null | null | null | src/util.h | nodchip/icfpc2021 | e50f0172fd62097049dab19c01875c57468a13f1 | [
"MIT"
] | 1 | 2021-08-24T08:49:18.000Z | 2021-08-24T08:49:18.000Z | #pragma once
#include <filesystem>
#include <optional>
#include <iostream>
#include <nlohmann/json.hpp>
std::filesystem::path default_data_path();
std::filesystem::path default_problem_path(int num);
bool update_meta(nlohmann::json& solution_json, const std::string& solver_name);
std::vector<std::string> split(std::string s, std::string delimiter);
std::string join(std::vector<std::string> tokens, std::string delimiter);
std::pair<std::string, std::string> split_first(std::string s, std::string delimiter);
bool starts_with(std::string_view s, std::string prefix);
std::string strip(std::string s);
std::optional<std::string> read_file(std::filesystem::path file_path);
/* const */
constexpr double PI = 3.141592653589793238462643;
/* io */
// output tuple
namespace aux {
template<typename T, unsigned N, unsigned L>
struct tp {
static void print(std::ostream& os, const T& v) {
os << std::get<N>(v) << ", ";
tp<T, N + 1, L>::print(os, v);
}
};
template<typename T, unsigned N> struct tp<T, N, N> {
static void print(std::ostream& os, const T& v) {
os << std::get<N>(v);
}
};
}
template<typename... Ts>
std::ostream& operator<<(std::ostream& os, const std::tuple<Ts...>& t) {
os << '[';
aux::tp<std::tuple<Ts...>, 0, sizeof...(Ts) - 1>::print(os, t);
os << ']';
return os;
}
// fwd decl
template <class T, class = typename T::iterator, std::enable_if_t<!std::is_same<T, std::string>::value, int> = 0>
std::ostream& operator<<(std::ostream& os, T const& a);
// output pair
template <class T, class S> std::ostream& operator<<(std::ostream& os, std::pair<T, S> const& p) {
return os << '[' << p.first << ", " << p.second << ']';
}
// input pair
template <class T, class S> std::istream& operator>>(std::istream& is, std::pair<T, S>& p) {
return is >> p.first >> p.second;
}
// output container
template <class T, class, std::enable_if_t<!std::is_same<T, std::string>::value, int>>
std::ostream& operator<<(std::ostream& os, T const& a) {
bool f = true;
os << '[';
for (auto const& x : a) {
os << (f ? "" : ", ") << x;
f = false;
}
os << ']';
return os;
}
// output array
template <class T, size_t N, std::enable_if_t<!std::is_same<T, char>::value, int> = 0>
std::ostream& operator<<(std::ostream& os, const T(&a)[N]) {
bool f = true;
os << '[';
for (auto const& x : a) {
os << (f ? "" : ", ") << x;
f = false;
}
os << ']';
return os;
}
// input container
template <class T, class = decltype(std::begin(std::declval<T&>())), class = typename std::enable_if<!std::is_same<T, std::string>::value>::type>
std::istream& operator>>(std::istream& is, T& a) {
for (auto& x : a) is >> x;
return is;
}
// vim:ts=2 sw=2 sts=2 et ci
| 32.170455 | 145 | 0.593783 | [
"vector"
] |
e4fe87d957b7dbc2db5295230bb7c92e802ff64f | 3,229 | c | C | 3.7.4_3.c | wuzhouhui/pearls | 4ef42b26775dd6145f36f8f3229eab94bc4eac18 | [
"Apache-2.0"
] | 3 | 2018-09-01T03:02:57.000Z | 2019-06-18T07:07:54.000Z | 3.7.4_3.c | wuzhouhui/pearls | 4ef42b26775dd6145f36f8f3229eab94bc4eac18 | [
"Apache-2.0"
] | null | null | null | 3.7.4_3.c | wuzhouhui/pearls | 4ef42b26775dd6145f36f8f3229eab94bc4eac18 | [
"Apache-2.0"
] | 2 | 2017-03-10T10:42:25.000Z | 2021-12-12T03:29:40.000Z | /*
* show calendar of month according specified year and month.
*
* ./a.out <year> <mon>
*/
#include <stdio.h>
#include <stdlib.h>
#define is_leap(year) ((year % 4 == 0 && year % 100) || (year % 400 == 0))
#define START_YEAR 1900
#define START_DAY 1
///* subscript about cal[] */
//#define FEB_NORM 0
//#define FEB_LEAP 1
//#define MON_30DAY 2
//#define MON_31DAY 3
static int mon_day_accu[] = {
0,
31,
31 + 28,
31 + 28 + 31,
31 + 28 + 31 + 30,
31 + 28 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30,
};
//static char *cal[] = {
// "Sun Mon Tue Wed Thu Fri Sat\n"
// " 1 2 3 4 5 6 7 \n"
// " 8 9 10 11 12 13 14\n"
// " 15 16 17 18 19 20 21\n"
// " 22 23 24 25 26 27 28\n"
// " ",
//
// "Sun Mon Tue Wed Thu Fri Sat\n"
// " 1 2 3 4 5 6 7 \n"
// " 8 9 10 11 12 13 14\n"
// " 15 16 17 18 19 20 21\n"
// " 22 23 24 25 26 27 28\n"
// " 29 \n"
// " ",
//
// "Sun Mon Tue Wed Thu Fri Sat\n"
// " 1 2 3 4 5 6 7 \n"
// " 8 9 10 11 12 13 14\n"
// " 15 16 17 18 19 20 21\n"
// " 22 23 24 25 26 27 28\n"
// " 29 30 \n"
// " ",
//
// "Sun Mon Tue Wed Thu Fri Sat\n"
// " 1 2 3 4 5 6 7 \n"
// " 8 9 10 11 12 13 14\n"
// " 15 16 17 18 19 20 21\n"
// " 22 23 24 25 26 27 28\n"
// " 29 30 31 \n"
// " ",
//};
static int get_weekday(int, int, int);
static void show_cal(int, int, int);
int main(int argc, char *argv[])
{
if (argc != 3) {
fputs("./a.out <year> <mon>\n", stderr);
exit(0);
}
int year, mon;
if ((year = atoi(argv[1])) < 1900) {
fputs("the year must great than 1900\n", stderr);
exit(0);
}
if ((mon = atoi(argv[2])) < 1 || mon > 12) {
fputs("the month must between 1 and 12\n", stderr);
exit(0);
}
show_cal(year, mon, get_weekday(year, mon, 1));
exit(0);
}
static int get_weekday(int year, int mon, int day)
{
if (year < 1900 || !(mon > 0 && mon < 13) || !(day > 0 && day < 32))
return(-1);
int days, i;
days = (year - START_YEAR) * 365;
for (i = START_YEAR; i < year; i++)
if (is_leap(i))
days++;
days += mon_day_accu[mon - 1];
if (mon > 2 && is_leap(year))
days++;
days += day - START_DAY;
if ((days = days % 7 + 1) == 7)
days = 0;
return(days);
}
static void show_cal(int year, int mon, int week_start)
{
static char *head = "Su Mo Tu We Th Fr Sa\n";
int i, wrap, day;
switch (mon) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
day = 31;
break;
case 4: case 6: case 9: case 11:
day = 30;
break;
case 2:
day = (is_leap(year) ? 29 : 28);
break;
default:
fputs("month illegal\n", stderr);
return;
}
printf("%s", head);
wrap = 0;
for (i = 0; i < week_start; i++) {
printf(" ");
wrap++;
}
for (i = 1; i <= day; i++) {
printf("%-3d", i);
if (++wrap % 7 == 0)
putchar('\n');
}
putchar('\n');
}
| 22.739437 | 74 | 0.477547 | [
"3d"
] |
90220c57d47a6d2f6d16db1cd324c48601eec9b5 | 590 | h | C | Libs/Globals.h | thiagofigcosta/The.COM-Game | 653b7174767b6dc2351807a44c2c4ac67c7dc1d6 | [
"MIT"
] | null | null | null | Libs/Globals.h | thiagofigcosta/The.COM-Game | 653b7174767b6dc2351807a44c2c4ac67c7dc1d6 | [
"MIT"
] | null | null | null | Libs/Globals.h | thiagofigcosta/The.COM-Game | 653b7174767b6dc2351807a44c2c4ac67c7dc1d6 | [
"MIT"
] | null | null | null | #ifndef GLOBALS_H
#define GLOBALS_H
#include "../Classes/Util.hpp"
#include "../Classes/Player.hpp"
#include "../Classes/AL.hpp"
#include "../Classes/GL.hpp"
#include "../Classes/Tutorials.hpp"
extern vector<nTMap> maps;
extern nTMap usrMap;
extern Player *player;
extern Mechanics *world;
extern nTColor clearColor;
extern vector<vector<string> >playerAnim;
extern vector<vector<int> >playerAnimSize;
extern vector<vector<string> >enemyAnim;
extern vector<vector<int> >enemyAnimSize;
extern AL *al;
extern GL *gl;
extern Tutorials *zero;
extern int languageIdx;
#endif // GLOBALS_H
| 20.344828 | 42 | 0.755932 | [
"vector"
] |
9032520593d6d2cca3c75c8cec524a965466136a | 2,444 | h | C | Libraries/Mytherin/Include/myth/graphics/shaderconstants.h | Mytherin/MythEngine | 852f8126d926497715d736c7c8040a986f90be6b | [
"Apache-2.0"
] | null | null | null | Libraries/Mytherin/Include/myth/graphics/shaderconstants.h | Mytherin/MythEngine | 852f8126d926497715d736c7c8040a986f90be6b | [
"Apache-2.0"
] | null | null | null | Libraries/Mytherin/Include/myth/graphics/shaderconstants.h | Mytherin/MythEngine | 852f8126d926497715d736c7c8040a986f90be6b | [
"Apache-2.0"
] | 1 | 2020-09-23T02:56:18.000Z | 2020-09-23T02:56:18.000Z |
#pragma once
#include <myth\graphics\lightconstants.h>
namespace myth
{
namespace graphics
{
//! A struct that holds indices of specific uniform locations within a specific shader
struct UniformLocations
{
public:
UniformLocations() :
Model(-1),View(-1),Projection(-1),MV(-1),MVP(-1),VP(-1),Ka(-1),Kd(-1),Ks(-1),SpecularPower(-1),SpecularIntensity(-1),EyePos(-1),EyeDir(-1)
{}
~UniformLocations()
{
delete [] directionalLight;
delete [] pointLight;
delete [] spotLight;
delete [] Sampler2D;
delete [] Sampler3D;
}
//matrix uniform locations
int Model; //Model->World matrix (mat4)
int View; //World->View/Eye matrix (mat4)
int Projection; //View/Eye->Screenspace (projection matrix) (mat4)
int MV; //Model-View matrix (View x Model) (mat4)
int MVP; //Model-View-Projection (Projection x ModelView) (mat4)
int VP; //View-Projection matrix (Projection x View) (mat4)
//camera properties
int EyePos; //Camera Position (vec3)
int EyeDir; //Camera Direction (vec3)
//material properties uniform locations
int Ka; //Material Ambient Color (vec3)
int Kd; //Material Diffuse Color (vec3)
int Ks; //Material Specular Color (vec3)
int SpecularPower; //Material Specular Power (float)
int SpecularIntensity; //Material Specular Intensity (float)
int DirectionalLights; //Amount of directional lights whose data has been copied to the shader
int PointLights; //Amount of point lights whose data has been copied to the shader
int SpotLights; //Amount of spot lights whose data has been copied to the shader
//maximum amounts of each light (not uniform variables)
int maxdirectionalLights;
int maxpointLights;
int maxspotLights;
//properties for each individual light
DirectionalLightUL *directionalLight;
PointLightUL *pointLight;
SpotLightUL *spotLight;
//texture sampler array
int sampler2DCount; //amount of 2D samplers supported by this ShaderProgram
int sampler3DCount; //amount of 3D samplers supported by this ShaderProgram
int *Sampler2D; //array of uniform 2D sampler locations (sampler2D)
int *Sampler3D; //array of uniform 3D sampler locations (sampler3D)
};
}
} | 36.477612 | 142 | 0.647709 | [
"model",
"3d"
] |
903d1870d0c0ee7da0786fa05caa1eec6f38e39f | 1,480 | h | C | include/GLKit/GLKSkyboxEffect.h | crossmob/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 6,717 | 2015-08-06T18:04:37.000Z | 2019-05-04T12:38:51.000Z | include/GLKit/GLKSkyboxEffect.h | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 2,711 | 2015-08-06T18:41:09.000Z | 2019-04-29T12:14:23.000Z | include/GLKit/GLKSkyboxEffect.h | Michael-Young48/WinObjC | 7bec24671c4c18b81aaf85eff2887438f18a697c | [
"MIT"
] | 1,021 | 2015-08-06T18:08:56.000Z | 2019-04-14T06:50:57.000Z | //******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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.
//
//******************************************************************************
#pragma once
#import "Foundation/NSObject.h"
#import "GLKit/GLKEffect.h"
GLKIT_EXPORT_CLASS
@interface GLKSkyboxEffect : GLKShaderEffect
@property (readonly, nonatomic) GLKEffectPropertyTexture* textureCubeMap;
@property (assign, nonatomic) GLKVector3 center;
@property (assign, nonatomic) GLfloat xSize;
@property (assign, nonatomic) GLfloat ySize;
@property (assign, nonatomic) GLfloat zSize;
@property (retain) GLKShader* shader;
@property (retain) NSString* shaderName;
@property (readonly, nonatomic) GLKEffectPropertyTransform* transform STUB_PROPERTY;
@property (copy, nonatomic) NSString* label STUB_PROPERTY;
- (void)prepareToDraw;
- (void)draw;
- (BOOL)updateShaderMaterialParams;
@end
| 35.238095 | 84 | 0.689865 | [
"transform"
] |
904b6cac9378d045bd644d10acb9f8b7f9578921 | 1,358 | h | C | Hasher.h | rustysec/fuzzypp | d2e0c7160ebfd5bc737d3f32d4309b85a816e165 | [
"MIT"
] | 3 | 2018-03-20T22:32:03.000Z | 2019-08-11T02:26:25.000Z | Hasher.h | rustysec/fuzzypp | d2e0c7160ebfd5bc737d3f32d4309b85a816e165 | [
"MIT"
] | null | null | null | Hasher.h | rustysec/fuzzypp | d2e0c7160ebfd5bc737d3f32d4309b85a816e165 | [
"MIT"
] | null | null | null | #ifndef HASHER_H_
#define HASHER_H_
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <string.h>
#include "FuzzyHashMode.h"
#include "BlockhashContext.h"
#include "Roll.h"
namespace FuzzyPP {
class Hasher {
unsigned int _bhstart = 0;
unsigned int _bhend = 1;
std::vector<BlockhashContext> _bh;
unsigned int _totalSize = 0;
std::shared_ptr<Roll> _roll;
static int MemcpyEliminateSequences(unsigned char *dst, int pos, unsigned char *src, int n);
/// <summary>
/// Obtain the fuzzy hash from the state.
/// This operation does not change the state at all. It reports the hash for the
/// concatenation of the data previously fed using fuzzy_update.
/// </summary>
std::string Digest(FuzzyHashMode::Mode flags);
void TryForkBlockhash();
void TryReduceBlockhash();
void EngineStep(unsigned char c);
/// <summary>
/// Feed the data contained in the given buffer to the state.
/// </summary>
void Update(unsigned char *buffer, int len);
Hasher();
public:
static std::string HashBuffer(unsigned char *buf, int len, FuzzyPP::FuzzyHashMode::Mode flags = FuzzyPP::FuzzyHashMode::Mode::None);
};
}
#endif /* HASHER_H_ */
| 27.714286 | 140 | 0.626657 | [
"vector"
] |
b0c53a9e0c6208a5ac99c596c2db269689135720 | 6,361 | h | C | Gems/Atom/RHI/Metal/Code/Source/RHI/MetalCopyShaders.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/Atom/RHI/Metal/Code/Source/RHI/MetalCopyShaders.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/Atom/RHI/Metal/Code/Source/RHI/MetalCopyShaders.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
//////////////////////////////////COPY SHADERS//////////////////////////////////
namespace AZ
{
namespace Metal
{
NSString *metalCopyShaderSource = @"\n\
#include <metal_stdlib>\n\
using namespace metal;\n\
struct metalVert_out\n\
{\n\
float4 position [[ position ]];\n\
#define Output0 output.position\n\
float2 tc [[ user(varying1) ]];\n\
};\n\
vertex metalVert_out mainVS(\n\
uint VertexID [[ vertex_id ]])\n\
{\n\
metalVert_out output;\n\
float4 position;\n\
position.x = (VertexID == 0)? 3.0 : -1.0;\n\
position.y = (VertexID == 2)? 3.0 : -1.0;\n\
position.zw = 1.0;\n\
output.position=position;\n\
output.tc = output.position.xy * float2(0.5, -0.5) + 0.5;\n\
return output;\n\
}\n\
struct metalFrag_stageIn\n\
{\n\
float2 tc [[ user(varying1) ]];\n\
};\n\
struct metalFrag_out\n\
{\n\
float4 PixOutput0 [[ color(0) ]];\n\
};\n\
fragment metalFrag_out mainPS(\n\
metalFrag_stageIn stageIn [[ stage_in ]],\n\
sampler Texture0_s[[ sampler(0) ]],\n\
texture2d<float> Texture0_t[[ texture(0) ]])\n\
{\n\
metalFrag_out output;\n\
float2 tc = stageIn.tc;\n\
output.PixOutput0 = ((Texture0_t.sample(Texture0_s, tc.xy)));\n\
return output;\n\
}\n\
";
NSString *metalCopyShaderSourceLanczos = @"\n\
#include <metal_stdlib>\n\
using namespace metal;\n\
struct metalVert_out\n\
{\n\
float4 position [[ position ]];\n\
#define Output0 output.position\n\
float2 tc [[ user(varying1) ]];\n\
};\n\
vertex metalVert_out mainVS(\n\
uint VertexID [[ vertex_id ]])\n\
{\n\
metalVert_out output;\n\
float4 position;\n\
position.x = (VertexID == 0)? 3.0 : -1.0;\n\
position.y = (VertexID == 2)? 3.0 : -1.0;\n\
position.zw = 1.0;\n\
output.position=position;\n\
output.tc = output.position.xy * float2(0.5, -0.5) + 0.5;\n\
return output;\n\
}\n\
struct metalFrag_stageIn\n\
{\n\
float2 tc [[ user(varying1) ]];\n\
};\n\
struct metalFrag_out\n\
{\n\
float4 PixOutput0 [[ color(0) ]];\n\
};\n\
struct Uniforms\n\
{\n\
float4 KernelRadius_ClippedRatio;\n\
float4 SampleSize_FirstSampleOffset;\n\
float4 SampleStep_FirstSamplePos;\n\
};\n\
fragment metalFrag_out mainLanczosPS(\n\
metalFrag_stageIn stageIn [[ stage_in ]],\n\
sampler Texture0_s[[ sampler(0) ]],\n\
texture2d<float> Texture0_t[[ texture(0) ]],\n\
constant Uniforms &uniforms [[buffer(0)]])\n\
{\n\
metalFrag_out output;\n\
float2 tc = stageIn.tc;\n\
float2 baseTc = tc + uniforms.SampleSize_FirstSampleOffset.zw;\n\
float2 kernelPos = uniforms.SampleStep_FirstSamplePos.zw;\n\
float4 accumSample = float4(0,0,0,0);\n\
float accumWeight = 0;\n\
for (; kernelPos.y < uniforms.KernelRadius_ClippedRatio.y; kernelPos.y += uniforms.SampleStep_FirstSamplePos.y)\n\
{\n\
tc.x = baseTc.x;\n\
for (kernelPos.x = uniforms.SampleStep_FirstSamplePos.x;\n\
kernelPos.x < uniforms.KernelRadius_ClippedRatio.x;\n\
kernelPos.x += uniforms.SampleStep_FirstSamplePos.x)\n\
{\n\
float2 piProduct = 3.14159265f * (kernelPos + 1e-4f);\n\
float2 weights2d = (sin(piProduct) * sin(piProduct * 0.5f) * 2.f) / (piProduct * piProduct);\n\
float weight = weights2d.x * weights2d.y;\n\
accumSample += weight * ((Texture0_t.sample(Texture0_s, tc.xy * uniforms.KernelRadius_ClippedRatio.zw)));\n\
accumWeight += weight;\n\
tc.x += uniforms.SampleSize_FirstSampleOffset.x;\n\
}\n\
tc.y += uniforms.SampleSize_FirstSampleOffset.y;\n\
}\n\
output.PixOutput0 = accumSample / accumWeight;\n\
return output;\n\
}\n\
fragment metalFrag_out mainBicubicPS(\n\
metalFrag_stageIn stageIn [[ stage_in ]],\n\
sampler Texture0_s[[ sampler(0) ]],\n\
texture2d<float> Texture0_t[[ texture(0) ]])\n\
{\n\
metalFrag_out output;\n\
int width = Texture0_t.get_width();\n\
int height = Texture0_t.get_height();\n\
float2 texSize = float2((float)width, (float)height);\n\
float2 unnormedTc = stageIn.tc * texSize;\n\
float2 unnormedCenteredTc = floor( unnormedTc - 0.5f ) + 0.5f;\n\
float2 f = unnormedTc - unnormedCenteredTc;\n\
float2 f2 = f*f;\n\
float2 f3 = f*f2;\n\
float2 w0 = f2 - 0.5f * (f3 + f);\n\
float2 w1 = 1.5 * f3 - 2.5 * f2 + 1.0;\n\
float2 w2 = -1.5 * f3 + 2 * f2 + 0.5 *f;\n\
float2 w3 = 0.5 * (f3 - f2);\n\
float2 s0 = w0 + w1;\n\
float2 s1 = w2 + w3;\n\
float2 f0 = w1 / (w0 + w1);\n\
float2 f1 = w3 / (w2 + w3);\n\
float2 t0 = (unnormedCenteredTc - 1.f + f0) / texSize;\n\
float2 t1 = (unnormedCenteredTc + 1.f + f1) / texSize;\n\
output.PixOutput0 = ( (Texture0_t.sample(Texture0_s, float2(t0.x, t0.y))) * s0.x \n\
+ (Texture0_t.sample(Texture0_s, float2(t1.x, t0.y))) * s1.x) * s0.y\n\
+ ( (Texture0_t.sample(Texture0_s, float2(t0.x, t1.y))) * s0.x \n\
+ (Texture0_t.sample(Texture0_s, float2(t1.x, t1.y))) * s1.x) * s1.y;\n\
return output;\n\
}\n\
";
// Bicubic filtering based off Phill Djonov's blog: http://vec3.ca/bicubic-filtering-in-fewer-taps/
////////////////////////////////////////////////////////////////////////////////
}
}
| 40.775641 | 124 | 0.521459 | [
"3d"
] |
b0cc036d7619f48efbe21a98ad04b9e94ec54e57 | 1,544 | h | C | JuegoFINAL/Funciones.h | FJ98/Galaga | 173d5f20a16da0af99653994f6f35b8e7ff72064 | [
"MIT"
] | 1 | 2019-07-07T20:02:31.000Z | 2019-07-07T20:02:31.000Z | JuegoFINAL/Funciones.h | FJ98/Galaga | 173d5f20a16da0af99653994f6f35b8e7ff72064 | [
"MIT"
] | null | null | null | JuegoFINAL/Funciones.h | FJ98/Galaga | 173d5f20a16da0af99653994f6f35b8e7ff72064 | [
"MIT"
] | null | null | null | // Created by felix on 7/5/2019.
#ifndef JUEGOFINAL_FUNCIONES_H
#define JUEGOFINAL_FUNCIONES_H
// Funciones Utiles se utilizan para minimizar el codigo
// al cargar (inicializar) las texturas, fonts y musica.
template<typename T>
void cargar(T &target, const sf::String& path) {
target.loadFromFile(path);
}
template <>
inline void cargar<sf::Music>(sf::Music& target, const sf::String& path) {
target.openFromFile(path);
}
// FUNCION QUE ACEPTA VECTOR
template <typename T>
void confText(T& text,
sf::Font* font, int tamLetra,
std::vector<T>* textVector,
const sf::String& str = "Def Txt",
sf::Color color = sf::Color::White,
sf::Vector2f position = {0.0f,0.0f},
sf::Uint32 style = sf::Text::Italic){
text.setFont(*font);
text.setString(str);
text.setCharacterSize(tamLetra);
text.setFillColor(color);
text.setStyle(style);
text.setPosition(position);
textVector->emplace_back(text);
}
// FUNCION QUE NO ACEPTA VECTOR
template <typename T>
void confText(T& text,
sf::Font* font, int tamLetra,
const sf::String& str = "Def Txt",
sf::Color color = sf::Color::White,
sf::Vector2f position = {0.0f,0.0f},
sf::Uint32 style = sf::Text::Regular){
text.setFont(*font);
text.setString(str);
text.setCharacterSize(tamLetra);
text.setFillColor(color);
text.setStyle(style);
text.setPosition(position);
}
#endif //JUEGOFINAL_FUNCIONES_H
| 30.27451 | 74 | 0.63601 | [
"vector"
] |
b0d5d8ae92345976ef094ffe21c17bc5cc38527c | 5,973 | c | C | pkgs/libs/mesa/src/src/glut/dos/state.c | manggoguy/parsec-modified | d14edfb62795805c84a4280d67b50cca175b95af | [
"BSD-3-Clause"
] | 64 | 2015-03-06T00:30:56.000Z | 2022-03-24T13:26:53.000Z | pkgs/libs/mesa/src/src/glut/dos/state.c | manggoguy/parsec-modified | d14edfb62795805c84a4280d67b50cca175b95af | [
"BSD-3-Clause"
] | 12 | 2020-12-15T08:30:19.000Z | 2022-03-13T03:54:24.000Z | pkgs/libs/mesa/src/src/glut/dos/state.c | manggoguy/parsec-modified | d14edfb62795805c84a4280d67b50cca175b95af | [
"BSD-3-Clause"
] | 40 | 2015-02-26T15:31:16.000Z | 2022-03-03T23:23:37.000Z | /*
* DOS/DJGPP Mesa Utility Toolkit
* Version: 1.0
*
* Copyright (C) 2005 Daniel Borca All Rights Reserved.
*
* 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
* DANIEL BORCA 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.
*/
#include <stdio.h>
#include "internal.h"
#define FREQUENCY 100 /* set this to zero to use the default timer */
static int timer_installed;
#if FREQUENCY
static volatile int ticks;
static void
ticks_timer (void *p)
{
(void)p;
ticks++;
} ENDOFUNC(ticks_timer)
#else
#include <time.h>
static struct timeval then;
#endif
int APIENTRY
glutGet (GLenum type)
{
switch (type) {
case GLUT_WINDOW_X:
return _glut_current->xpos;
case GLUT_WINDOW_Y:
return _glut_current->ypos;
case GLUT_WINDOW_WIDTH:
return _glut_current->width;
case GLUT_WINDOW_HEIGHT:
return _glut_current->height;
case GLUT_WINDOW_STENCIL_SIZE:
return _glut_visual.stencil;
case GLUT_WINDOW_DEPTH_SIZE:
return _glut_visual.depth;
case GLUT_WINDOW_RGBA:
return !(_glut_default.mode & GLUT_INDEX);
case GLUT_WINDOW_COLORMAP_SIZE:
return (_glut_default.mode & GLUT_INDEX) ? (256 - RESERVED_COLORS) : 0;
case GLUT_SCREEN_WIDTH:
return _glut_visual.geometry[0];
case GLUT_SCREEN_HEIGHT:
return _glut_visual.geometry[1];
case GLUT_INIT_WINDOW_X:
return _glut_default.x;
case GLUT_INIT_WINDOW_Y:
return _glut_default.y;
case GLUT_INIT_WINDOW_WIDTH:
return _glut_default.width;
case GLUT_INIT_WINDOW_HEIGHT:
return _glut_default.height;
case GLUT_INIT_DISPLAY_MODE:
return _glut_default.mode;
case GLUT_ELAPSED_TIME:
#if FREQUENCY
if (!timer_installed) {
timer_installed = GL_TRUE;
LOCKDATA(ticks);
LOCKFUNC(ticks_timer);
pc_install_int(ticks_timer, NULL, FREQUENCY);
}
return ticks * 1000 / FREQUENCY;
#else
if (!timer_installed) {
timer_installed = GL_TRUE;
gettimeofday(&then, NULL);
return 0;
} else {
struct timeval now;
gettimeofday(&now, NULL);
return (now.tv_usec - then.tv_usec) / 1000 +
(now.tv_sec - then.tv_sec) * 1000;
}
#endif
default:
return -1;
}
}
int APIENTRY
glutDeviceGet (GLenum type)
{
switch (type) {
case GLUT_HAS_KEYBOARD:
return GL_TRUE;
case GLUT_HAS_MOUSE:
return (_glut_mouse != 0);
case GLUT_NUM_MOUSE_BUTTONS:
return _glut_mouse;
case GLUT_HAS_SPACEBALL:
case GLUT_HAS_DIAL_AND_BUTTON_BOX:
case GLUT_HAS_TABLET:
return GL_FALSE;
case GLUT_NUM_SPACEBALL_BUTTONS:
case GLUT_NUM_BUTTON_BOX_BUTTONS:
case GLUT_NUM_DIALS:
case GLUT_NUM_TABLET_BUTTONS:
return 0;
default:
return -1;
}
}
int APIENTRY
glutGetModifiers (void)
{
int mod = 0;
int shifts = pc_keyshifts();
if (shifts & (KB_SHIFT_FLAG | KB_CAPSLOCK_FLAG)) {
mod |= GLUT_ACTIVE_SHIFT;
}
if (shifts & KB_ALT_FLAG) {
mod |= GLUT_ACTIVE_ALT;
}
if (shifts & KB_CTRL_FLAG) {
mod |= GLUT_ACTIVE_CTRL;
}
return mod;
}
void APIENTRY
glutReportErrors (void)
{
/* reports all the OpenGL errors that happened till now */
}
/* GAME MODE
* Hack alert: incomplete... what is GameMode, anyway?
*/
static GLint game;
static GLboolean game_possible;
static GLboolean game_active;
static GLuint game_width;
static GLuint game_height;
static GLuint game_bpp;
static GLuint game_refresh;
void APIENTRY
glutGameModeString (const char *string)
{
if (sscanf(string, "%ux%u:%u@%u", &game_width, &game_height, &game_bpp, &game_refresh) == 4) {
game_possible = GL_TRUE;
}
}
int APIENTRY
glutGameModeGet (GLenum mode)
{
switch (mode) {
case GLUT_GAME_MODE_ACTIVE:
return game_active;
case GLUT_GAME_MODE_POSSIBLE:
return game_possible && !_glut_current;
case GLUT_GAME_MODE_WIDTH:
return game_active ? (int)game_width : -1;
case GLUT_GAME_MODE_HEIGHT:
return game_active ? (int)game_height : -1;
case GLUT_GAME_MODE_PIXEL_DEPTH:
return game_active ? (int)game_bpp : -1;
case GLUT_GAME_MODE_REFRESH_RATE:
return game_active ? (int)game_refresh : -1;
default:
return -1;
}
}
int APIENTRY
glutEnterGameMode (void)
{
if (glutGameModeGet(GLUT_GAME_MODE_POSSIBLE)) {
_glut_visual.bpp = game_bpp;
_glut_visual.refresh = game_refresh;
glutInitWindowSize(game_width, game_height);
if ((game = glutCreateWindow("<game>")) > 0) {
game_active = GL_TRUE;
}
return game;
} else {
return 0;
}
}
void GLUTAPIENTRY
glutLeaveGameMode (void)
{
if (glutGameModeGet(GLUT_GAME_MODE_ACTIVE)) {
game_active = GL_FALSE;
glutDestroyWindow(game);
}
}
| 24.991632 | 97 | 0.664323 | [
"geometry"
] |
b0de81e13a220429377a58840ef7aa186b6ba4ef | 1,689 | h | C | src/util/bet_reader.h | lucasnr/keno-cpp | 8d8042e70b97af58362d70783db7af7bef47e07e | [
"MIT"
] | null | null | null | src/util/bet_reader.h | lucasnr/keno-cpp | 8d8042e70b97af58362d70783db7af7bef47e07e | [
"MIT"
] | null | null | null | src/util/bet_reader.h | lucasnr/keno-cpp | 8d8042e70b97af58362d70783db7af7bef47e07e | [
"MIT"
] | null | null | null | #include <fstream>
#include <iomanip>
#include <sstream>
#include "../model/KenoBet.h"
#include "./message_util.h"
#include "./string_utils.h"
/**
* @param filename The name of the file to be read
* @param bet The bet object to set the contents of the file
* @return The number of rounds, or 0 if the file is somehow not valid
*/
unsigned int readKenoBetFile(const string filename, KenoBet* bet) {
ifstream file(filename);
if (!file.good()) {
message::danger("The provided bet file was not found");
file.close();
return 0;
}
string message =
"Preparing to read bet file [" + filename + "], please wait...";
stringstream separator;
separator << setw(message.length()) << setfill('-') << "";
message::info(message);
message::info(separator.str());
cash_type wage;
unsigned int rounds = 0;
bool bWage = false, bRounds = false;
string line, spots;
while (getline(file, line)) {
if (line.empty()) continue;
if (!bWage) {
bWage = true;
wage = atof(trim(line).c_str());
continue;
}
if (!bRounds) {
bRounds = true;
rounds = atoi(trim(line).c_str());
continue;
}
spots = trim(line);
}
file.close();
vector<string> vSpots = split(spots, ' ');
if (wage <= 0 || vSpots.size() == 0 || rounds <= 0) {
message::danger("Error reading bet file!");
return 0;
}
bet->set_wage(wage);
for (size_t i = 0; i < vSpots.size(); i++) {
auto spot = atoi(vSpots[i].c_str());
bet->add_number(spot);
}
if (bet->get_spots().empty()) {
message::danger("Error reading bet file!");
return 0;
}
message::success("Bet successfully read!");
return rounds;
}
| 22.824324 | 70 | 0.609828 | [
"object",
"vector",
"model"
] |
b0f126c03ee94aa4d8c58a71b13b26073434e555 | 1,722 | h | C | wrappers/7.0.0/vtkArrayNormWrap.h | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/7.0.0/vtkArrayNormWrap.h | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/7.0.0/vtkArrayNormWrap.h | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#ifndef NATIVE_EXTENSION_VTK_VTKARRAYNORMWRAP_H
#define NATIVE_EXTENSION_VTK_VTKARRAYNORMWRAP_H
#include <nan.h>
#include <vtkSmartPointer.h>
#include <vtkArrayNorm.h>
#include "vtkArrayDataAlgorithmWrap.h"
#include "../../plus/plus.h"
class VtkArrayNormWrap : public VtkArrayDataAlgorithmWrap
{
public:
using Nan::ObjectWrap::Wrap;
static void Init(v8::Local<v8::Object> exports);
static void InitPtpl();
static void ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info);
VtkArrayNormWrap(vtkSmartPointer<vtkArrayNorm>);
VtkArrayNormWrap();
~VtkArrayNormWrap( );
static Nan::Persistent<v8::FunctionTemplate> ptpl;
private:
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetDimension(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetInvert(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetL(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetDimension(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetInvert(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetL(const Nan::FunctionCallbackInfo<v8::Value>& info);
#ifdef VTK_NODE_PLUS_VTKARRAYNORMWRAP_CLASSDEF
VTK_NODE_PLUS_VTKARRAYNORMWRAP_CLASSDEF
#endif
};
#endif
| 34.44 | 77 | 0.773519 | [
"object"
] |
b0f186cc627220546c3f0558d0440c3695fa48d9 | 46,189 | c | C | common/usbc/usb_prl_sm.c | SiliconMitus39/Emb_Contr | 0aa1ab988d902380f449b274ca9a05f2aa3d5539 | [
"BSD-3-Clause"
] | null | null | null | common/usbc/usb_prl_sm.c | SiliconMitus39/Emb_Contr | 0aa1ab988d902380f449b274ca9a05f2aa3d5539 | [
"BSD-3-Clause"
] | null | null | null | common/usbc/usb_prl_sm.c | SiliconMitus39/Emb_Contr | 0aa1ab988d902380f449b274ca9a05f2aa3d5539 | [
"BSD-3-Clause"
] | 1 | 2021-05-27T03:14:47.000Z | 2021-05-27T03:14:47.000Z | /* Copyright 2019 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "battery.h"
#include "battery_smart.h"
#include "board.h"
#include "charge_manager.h"
#include "charge_state.h"
#include "chipset.h"
#include "common.h"
#include "console.h"
#include "ec_commands.h"
#include "gpio.h"
#include "hooks.h"
#include "host_command.h"
#include "registers.h"
#include "system.h"
#include "task.h"
#include "timer.h"
#include "tcpm.h"
#include "util.h"
#include "usb_charge.h"
#include "usb_mux.h"
#include "usb_pd.h"
#include "usb_pe_sm.h"
#include "usb_prl_sm.h"
#include "usb_tc_sm.h"
#include "usb_emsg.h"
#include "usb_sm.h"
#include "vpd_api.h"
#include "version.h"
#define RCH_SET_FLAG(port, flag) atomic_or(&rch[port].flags, (flag))
#define RCH_CLR_FLAG(port, flag) atomic_clear(&rch[port].flags, (flag))
#define RCH_CHK_FLAG(port, flag) (rch[port].flags & (flag))
#define TCH_SET_FLAG(port, flag) atomic_or(&tch[port].flags, (flag))
#define TCH_CLR_FLAG(port, flag) atomic_clear(&tch[port].flags, (flag))
#define TCH_CHK_FLAG(port, flag) (tch[port].flags & (flag))
#define PRL_TX_SET_FLAG(port, flag) atomic_or(&prl_tx[port].flags, (flag))
#define PRL_TX_CLR_FLAG(port, flag) atomic_clear(&prl_tx[port].flags, (flag))
#define PRL_TX_CHK_FLAG(port, flag) (prl_tx[port].flags & (flag))
#define PRL_HR_SET_FLAG(port, flag) atomic_or(&prl_hr[port].flags, (flag))
#define PRL_HR_CLR_FLAG(port, flag) atomic_clear(&prl_hr[port].flags, (flag))
#define PRL_HR_CHK_FLAG(port, flag) (prl_hr[port].flags & (flag))
#define PDMSG_SET_FLAG(port, flag) atomic_or(&pdmsg[port].flags, (flag))
#define PDMSG_CLR_FLAG(port, flag) atomic_clear(&pdmsg[port].flags, (flag))
#define PDMSG_CHK_FLAG(port, flag) (pdmsg[port].flags & (flag))
/* Protocol Layer Flags */
/*
* NOTE:
* These flags are used in multiple state machines and could have
* different meanings in each state machine.
*/
/* Flag to note message transmission completed */
#define PRL_FLAGS_TX_COMPLETE BIT(0)
/* Flag to note an AMS is being started by PE */
#define PRL_FLAGS_START_AMS BIT(1)
/* Flag to note an AMS is being stopped by PE */
#define PRL_FLAGS_END_AMS BIT(2)
/* Flag to note transmission error occurred */
#define PRL_FLAGS_TX_ERROR BIT(3)
/* Flag to note PE triggered a hard reset */
#define PRL_FLAGS_PE_HARD_RESET BIT(4)
/* Flag to note hard reset has completed */
#define PRL_FLAGS_HARD_RESET_COMPLETE BIT(5)
/* Flag to note port partner sent a hard reset */
#define PRL_FLAGS_PORT_PARTNER_HARD_RESET BIT(6)
/* Flag to note a message transmission has been requested */
#define PRL_FLAGS_MSG_XMIT BIT(7)
/* Flag to note a message was received */
#define PRL_FLAGS_MSG_RECEIVED BIT(8)
/* Flag to note aborting current TX message, not currently set */
#define PRL_FLAGS_ABORT BIT(9)
/* Flag to note current TX message uses chunking */
#define PRL_FLAGS_CHUNKING BIT(10)
/* PD counter definitions */
#define PD_MESSAGE_ID_COUNT 7
static enum sm_local_state local_state[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Protocol Transmit States (Section 6.11.2.2) */
enum usb_prl_tx_state {
PRL_TX_PHY_LAYER_RESET,
PRL_TX_WAIT_FOR_MESSAGE_REQUEST,
PRL_TX_LAYER_RESET_FOR_TRANSMIT,
PRL_TX_WAIT_FOR_PHY_RESPONSE,
PRL_TX_SRC_SOURCE_TX,
PRL_TX_SNK_START_AMS,
PRL_TX_SRC_PENDING,
PRL_TX_SNK_PENDING,
PRL_TX_DISCARD_MESSAGE,
};
/* Protocol Hard Reset States (Section 6.11.2.4) */
enum usb_prl_hr_state {
PRL_HR_WAIT_FOR_REQUEST,
PRL_HR_RESET_LAYER,
PRL_HR_WAIT_FOR_PHY_HARD_RESET_COMPLETE,
PRL_HR_WAIT_FOR_PE_HARD_RESET_COMPLETE,
};
/* Chunked Rx states (Section 6.11.2.1.2) */
enum usb_rch_state {
RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER,
RCH_PASS_UP_MESSAGE,
RCH_PROCESSING_EXTENDED_MESSAGE,
RCH_REQUESTING_CHUNK,
RCH_WAITING_CHUNK,
RCH_REPORT_ERROR,
};
/* Chunked Tx states (Section 6.11.2.1.3) */
enum usb_tch_state {
TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE,
TCH_WAIT_FOR_TRANSMISSION_COMPLETE,
TCH_CONSTRUCT_CHUNKED_MESSAGE,
TCH_SENDING_CHUNKED_MESSAGE,
TCH_WAIT_CHUNK_REQUEST,
TCH_MESSAGE_RECEIVED,
TCH_MESSAGE_SENT,
TCH_REPORT_ERROR,
};
/* Forward declare full list of states. Index by above enums. */
static const struct usb_state prl_tx_states[];
static const struct usb_state prl_hr_states[];
static const struct usb_state rch_states[];
static const struct usb_state tch_states[];
/* Chunked Rx State Machine Object */
static struct rx_chunked {
/* state machine context */
struct sm_ctx ctx;
/* PRL_FLAGS */
uint32_t flags;
/* protocol timer */
uint64_t chunk_sender_response_timer;
} rch[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Chunked Tx State Machine Object */
static struct tx_chunked {
/* state machine context */
struct sm_ctx ctx;
/* state machine flags */
uint32_t flags;
/* protocol timer */
uint64_t chunk_sender_request_timer;
/* error to report when moving to tch_report_error state */
enum pe_error error;
} tch[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Message Reception State Machine Object */
static struct protocol_layer_rx {
/* message ids for all valid port partners */
int msg_id[NUM_SOP_STAR_TYPES];
} prl_rx[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Message Transmission State Machine Object */
static struct protocol_layer_tx {
/* state machine context */
struct sm_ctx ctx;
/* state machine flags */
uint32_t flags;
/* protocol timer */
uint64_t sink_tx_timer;
/* tcpc transmit timeout */
uint64_t tcpc_tx_timeout;
/* last message type we transmitted */
enum tcpm_transmit_type last_xmit_type;
/* message id counters for all 6 port partners */
uint32_t msg_id_counter[NUM_SOP_STAR_TYPES];
/* message retry counter */
uint32_t retry_counter;
/* transmit status */
int xmit_status;
} prl_tx[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Hard Reset State Machine Object */
static struct protocol_hard_reset {
/* state machine context */
struct sm_ctx ctx;
/* state machine flags */
uint32_t flags;
/* protocol timer */
uint64_t hard_reset_complete_timer;
} prl_hr[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Chunking Message Object */
static struct pd_message {
/* message status flags */
uint32_t flags;
/* SOP* */
enum tcpm_transmit_type xmit_type;
/* type of message */
uint8_t msg_type;
/* extended message */
uint8_t ext;
/* PD revision */
enum pd_rev_type rev[NUM_SOP_STAR_TYPES];
/* Number of 32-bit objects in chk_buf */
uint16_t data_objs;
/* temp chunk buffer */
uint32_t chk_buf[7];
uint32_t chunk_number_expected;
uint32_t num_bytes_received;
uint32_t chunk_number_to_send;
uint32_t send_offset;
} pdmsg[CONFIG_USB_PD_PORT_MAX_COUNT];
struct extended_msg emsg[CONFIG_USB_PD_PORT_MAX_COUNT];
/* Common Protocol Layer Message Transmission */
static void prl_tx_construct_message(int port);
static void prl_rx_wait_for_phy_message(const int port, int evt);
/* Set the protocol transmit statemachine to a new state. */
static void set_state_prl_tx(const int port,
const enum usb_prl_tx_state new_state)
{
set_state(port, &prl_tx[port].ctx, &prl_tx_states[new_state]);
}
/* Get the protocol transmit statemachine's current state. */
test_export_static enum usb_prl_tx_state prl_tx_get_state(const int port)
{
return prl_tx[port].ctx.current - &prl_tx_states[0];
}
/* Set the hard reset statemachine to a new state. */
static void set_state_prl_hr(const int port,
const enum usb_prl_hr_state new_state)
{
set_state(port, &prl_hr[port].ctx, &prl_hr_states[new_state]);
}
#ifdef TEST_BUILD
/* Get the hard reset statemachine's current state. */
enum usb_prl_hr_state prl_hr_get_state(const int port)
{
return prl_hr[port].ctx.current - &prl_hr_states[0];
}
#endif
/* Set the chunked Rx statemachine to a new state. */
static void set_state_rch(const int port, const enum usb_rch_state new_state)
{
set_state(port, &rch[port].ctx, &rch_states[new_state]);
}
/* Get the chunked Rx statemachine's current state. */
test_export_static enum usb_rch_state rch_get_state(const int port)
{
return rch[port].ctx.current - &rch_states[0];
}
/* Set the chunked Tx statemachine to a new state. */
static void set_state_tch(const int port, const enum usb_tch_state new_state)
{
set_state(port, &tch[port].ctx, &tch_states[new_state]);
}
/* Get the chunked Tx statemachine's current state. */
test_export_static enum usb_tch_state tch_get_state(const int port)
{
return tch[port].ctx.current - &tch_states[0];
}
void pd_transmit_complete(int port, int status)
{
prl_tx[port].xmit_status = status;
}
void pd_execute_hard_reset(int port)
{
/* Only allow async. function calls when state machine is running */
if (!prl_is_running(port))
return;
PRL_HR_SET_FLAG(port, PRL_FLAGS_PORT_PARTNER_HARD_RESET);
set_state_prl_hr(port, PRL_HR_RESET_LAYER);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
void prl_execute_hard_reset(int port)
{
/* Only allow async. function calls when state machine is running */
if (!prl_is_running(port))
return;
PRL_HR_SET_FLAG(port, PRL_FLAGS_PE_HARD_RESET);
set_state_prl_hr(port, PRL_HR_RESET_LAYER);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
int prl_is_running(int port)
{
return local_state[port] == SM_RUN;
}
static void prl_init(int port)
{
int i;
const struct sm_ctx cleared = {};
prl_tx[port].flags = 0;
prl_tx[port].last_xmit_type = TCPC_TX_SOP;
prl_tx[port].xmit_status = TCPC_TX_UNSET;
tch[port].flags = 0;
rch[port].flags = 0;
/*
* Initialize to highest revision supported. If the port or cable
* partner doesn't support this revision, the Protocol Engine will
* lower this value to the revision supported by the partner.
*/
pdmsg[port].rev[TCPC_TX_SOP] = PD_REV30;
pdmsg[port].rev[TCPC_TX_SOP_PRIME] = PD_REV30;
pdmsg[port].rev[TCPC_TX_SOP_PRIME_PRIME] = PD_REV30;
pdmsg[port].rev[TCPC_TX_SOP_DEBUG_PRIME] = PD_REV30;
pdmsg[port].rev[TCPC_TX_SOP_DEBUG_PRIME_PRIME] = PD_REV30;
pdmsg[port].flags = 0;
prl_hr[port].flags = 0;
for (i = 0; i < NUM_SOP_STAR_TYPES; i++) {
prl_rx[port].msg_id[i] = -1;
prl_tx[port].msg_id_counter[i] = 0;
}
/* Clear state machines and set initial states */
prl_tx[port].ctx = cleared;
set_state_prl_tx(port, PRL_TX_PHY_LAYER_RESET);
rch[port].ctx = cleared;
set_state_rch(port, RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER);
tch[port].ctx = cleared;
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
prl_hr[port].ctx = cleared;
set_state_prl_hr(port, PRL_HR_WAIT_FOR_REQUEST);
}
void prl_start_ams(int port)
{
PRL_TX_SET_FLAG(port, PRL_FLAGS_START_AMS);
}
void prl_end_ams(int port)
{
PRL_TX_SET_FLAG(port, PRL_FLAGS_END_AMS);
}
void prl_hard_reset_complete(int port)
{
PRL_HR_SET_FLAG(port, PRL_FLAGS_HARD_RESET_COMPLETE);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
void prl_send_ctrl_msg(int port,
enum tcpm_transmit_type type,
enum pd_ctrl_msg_type msg)
{
pdmsg[port].xmit_type = type;
pdmsg[port].msg_type = msg;
pdmsg[port].ext = 0;
emsg[port].len = 0;
TCH_SET_FLAG(port, PRL_FLAGS_MSG_XMIT);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
void prl_send_data_msg(int port,
enum tcpm_transmit_type type,
enum pd_data_msg_type msg)
{
pdmsg[port].xmit_type = type;
pdmsg[port].msg_type = msg;
pdmsg[port].ext = 0;
TCH_SET_FLAG(port, PRL_FLAGS_MSG_XMIT);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
void prl_send_ext_data_msg(int port,
enum tcpm_transmit_type type,
enum pd_ext_msg_type msg)
{
pdmsg[port].xmit_type = type;
pdmsg[port].msg_type = msg;
pdmsg[port].ext = 1;
TCH_SET_FLAG(port, PRL_FLAGS_MSG_XMIT);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
void prl_reset(int port)
{
local_state[port] = SM_INIT;
}
void prl_run(int port, int evt, int en)
{
switch (local_state[port]) {
case SM_PAUSED:
if (!en)
break;
/* fall through */
case SM_INIT:
prl_init(port);
local_state[port] = SM_RUN;
/* fall through */
case SM_RUN:
if (!en) {
/* Disable RX */
if (IS_ENABLED(CONFIG_USB_TYPEC_CTVPD) ||
IS_ENABLED(CONFIG_USB_TYPEC_VPD))
vpd_rx_enable(0);
else
tcpm_set_rx_enable(port, 0);
local_state[port] = SM_PAUSED;
break;
}
/* Run Protocol Layer Message Reception */
prl_rx_wait_for_phy_message(port, evt);
/* Run RX Chunked state machine */
run_state(port, &rch[port].ctx);
/* Run TX Chunked state machine */
run_state(port, &tch[port].ctx);
/* Run Protocol Layer Message Transmission state machine */
run_state(port, &prl_tx[port].ctx);
/* Run Protocol Layer Hard Reset state machine */
run_state(port, &prl_hr[port].ctx);
break;
}
}
void prl_set_rev(int port, enum tcpm_transmit_type type,
enum pd_rev_type rev)
{
pdmsg[port].rev[type] = rev;
}
enum pd_rev_type prl_get_rev(int port, enum tcpm_transmit_type type)
{
return pdmsg[port].rev[type];
}
/* Common Protocol Layer Message Transmission */
static void prl_tx_phy_layer_reset_entry(const int port)
{
if (IS_ENABLED(CONFIG_USB_TYPEC_CTVPD)
|| IS_ENABLED(CONFIG_USB_TYPEC_VPD)) {
vpd_rx_enable(1);
} else {
tcpm_init(port);
tcpm_clear_pending_messages(port);
tcpm_set_rx_enable(port, 1);
}
}
static void prl_tx_phy_layer_reset_run(const int port)
{
set_state_prl_tx(port, PRL_TX_WAIT_FOR_MESSAGE_REQUEST);
}
static void prl_tx_wait_for_message_request_entry(const int port)
{
/* Reset RetryCounter */
prl_tx[port].retry_counter = 0;
}
static void prl_tx_wait_for_message_request_run(const int port)
{
if ((prl_get_rev(port, pdmsg[port].xmit_type) == PD_REV30) &&
PRL_TX_CHK_FLAG(port,
(PRL_FLAGS_START_AMS | PRL_FLAGS_END_AMS))) {
if (tc_get_power_role(port) == PD_ROLE_SOURCE) {
/*
* Start of SRC AMS notification received from
* Policy Engine
*/
if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_START_AMS)) {
PRL_TX_CLR_FLAG(port, PRL_FLAGS_START_AMS);
set_state_prl_tx(port, PRL_TX_SRC_SOURCE_TX);
return;
}
/*
* End of SRC AMS notification received from
* Policy Engine
*/
else if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_END_AMS)) {
/* Set Rp = SinkTxOk */
tcpm_select_rp_value(port, SINK_TX_OK);
tcpm_set_cc(port, TYPEC_CC_RP);
prl_tx[port].retry_counter = 0;
/* PRL_FLAGS_END AMS is cleared here */
prl_tx[port].flags = 0;
}
} else {
/*
* Start of SNK AMS notification received from
* Policy Engine
*/
if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_START_AMS)) {
PRL_TX_CLR_FLAG(port, PRL_FLAGS_START_AMS);
/*
* First Message in AMS notification
* received from Policy Engine.
*/
set_state_prl_tx(port, PRL_TX_SNK_START_AMS);
return;
}
/*
* End of SNK AMS notification received from
* Policy Engine
*/
else if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_END_AMS)) {
prl_tx[port].retry_counter = 0;
/* PRL_FLAGS_END AMS is cleared here */
prl_tx[port].flags = 0;
}
}
} else if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_MSG_XMIT)) {
PRL_TX_CLR_FLAG(port, PRL_FLAGS_MSG_XMIT);
/*
* Soft Reset Message Message pending
*/
if ((pdmsg[port].msg_type == PD_CTRL_SOFT_RESET) &&
(emsg[port].len == 0)) {
set_state_prl_tx(port, PRL_TX_LAYER_RESET_FOR_TRANSMIT);
}
/*
* Message pending (except Soft Reset)
*/
else {
/* NOTE: PRL_TX_Construct_Message State embedded here */
prl_tx_construct_message(port);
set_state_prl_tx(port, PRL_TX_WAIT_FOR_PHY_RESPONSE);
}
return;
}
}
static void increment_msgid_counter(int port)
{
/* If the last message wasn't an SOP* message, no need to increment */
if (prl_tx[port].last_xmit_type >= NUM_SOP_STAR_TYPES)
return;
prl_tx[port].msg_id_counter[prl_tx[port].last_xmit_type] =
(prl_tx[port].msg_id_counter[prl_tx[port].last_xmit_type] + 1) &
PD_MESSAGE_ID_COUNT;
}
/*
* PrlTxDiscard
*/
static void prl_tx_discard_message_entry(const int port)
{
/* Increment msgidCounter */
increment_msgid_counter(port);
set_state_prl_tx(port, PRL_TX_PHY_LAYER_RESET);
}
/*
* PrlTxSrcSourceTx
*/
static void prl_tx_src_source_tx_entry(const int port)
{
/* Set Rp = SinkTxNG */
tcpm_select_rp_value(port, SINK_TX_NG);
tcpm_set_cc(port, TYPEC_CC_RP);
}
static void prl_tx_src_source_tx_run(const int port)
{
if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_MSG_XMIT)) {
PRL_TX_CLR_FLAG(port, PRL_FLAGS_MSG_XMIT);
set_state_prl_tx(port, PRL_TX_SRC_PENDING);
}
}
/*
* PrlTxSnkStartAms
*/
static void prl_tx_snk_start_ams_run(const int port)
{
if (PRL_TX_CHK_FLAG(port, PRL_FLAGS_MSG_XMIT)) {
PRL_TX_CLR_FLAG(port, PRL_FLAGS_MSG_XMIT);
set_state_prl_tx(port, PRL_TX_SNK_PENDING);
}
}
/*
* PrlTxLayerResetForTransmit
*/
static void prl_tx_layer_reset_for_transmit_entry(const int port)
{
int i;
/* Reset MessageIdCounters */
for (i = 0; i < NUM_SOP_STAR_TYPES; i++)
prl_tx[port].msg_id_counter[i] = 0;
}
static void prl_tx_layer_reset_for_transmit_run(const int port)
{
/* NOTE: PRL_Tx_Construct_Message State embedded here */
prl_tx_construct_message(port);
set_state_prl_tx(port, PRL_TX_WAIT_FOR_PHY_RESPONSE);
}
static uint32_t get_sop_star_header(const int port)
{
const int is_sop_packet = pdmsg[port].xmit_type == TCPC_TX_SOP;
/* SOP vs SOP'/SOP" headers are different. Replace fields as needed */
return PD_HEADER(
pdmsg[port].msg_type,
is_sop_packet ?
tc_get_power_role(port) : tc_get_cable_plug(port),
is_sop_packet ?
tc_get_data_role(port) : 0,
prl_tx[port].msg_id_counter[pdmsg[port].xmit_type],
pdmsg[port].data_objs,
pdmsg[port].rev[pdmsg[port].xmit_type],
pdmsg[port].ext);
}
static void prl_tx_construct_message(const int port)
{
/* The header is unused for hard reset, etc. */
const uint32_t header = pdmsg[port].xmit_type < NUM_SOP_STAR_TYPES ?
get_sop_star_header(port) : 0;
/* Save SOP* so the correct msg_id_counter can be incremented */
prl_tx[port].last_xmit_type = pdmsg[port].xmit_type;
/*
* These flags could be set if this function is called before the
* Policy Engine is informed of the previous transmission. Clear the
* flags so that this message can be sent.
*/
prl_tx[port].xmit_status = TCPC_TX_UNSET;
PDMSG_CLR_FLAG(port, PRL_FLAGS_TX_COMPLETE);
/* Pass message to PHY Layer */
tcpm_transmit(port, pdmsg[port].xmit_type, header,
pdmsg[port].chk_buf);
}
/*
* PrlTxWaitForPhyResponse
*/
static void prl_tx_wait_for_phy_response_entry(const int port)
{
prl_tx[port].tcpc_tx_timeout = get_time().val + PD_T_TCPC_TX_TIMEOUT;
}
static void prl_tx_wait_for_phy_response_run(const int port)
{
/* Wait until TX is complete */
/*
* NOTE: The TCPC will set xmit_status to TCPC_TX_COMPLETE_DISCARDED
* when a GoodCRC containing an incorrect MessageID is received.
* This condition satifies the PRL_Tx_Match_MessageID state
* requirement.
*/
if (get_time().val > prl_tx[port].tcpc_tx_timeout ||
prl_tx[port].xmit_status == TCPC_TX_COMPLETE_FAILED ||
prl_tx[port].xmit_status == TCPC_TX_COMPLETE_DISCARDED) {
/* NOTE: PRL_Tx_Check_RetryCounter State embedded here. */
/* Increment check RetryCounter */
prl_tx[port].retry_counter++;
/*
* (RetryCounter > nRetryCount) | Large Extended Message
*/
if (prl_tx[port].retry_counter > N_RETRY_COUNT ||
(pdmsg[port].ext &&
PD_EXT_HEADER_DATA_SIZE(GET_EXT_HEADER(
pdmsg[port].chk_buf[0]) > 26))) {
/*
* NOTE: PRL_Tx_Transmission_Error State embedded
* here.
*/
/*
* State tch_wait_for_transmission_complete will
* inform policy engine of error
*/
PDMSG_SET_FLAG(port, PRL_FLAGS_TX_ERROR);
/* Increment message id counter */
increment_msgid_counter(port);
set_state_prl_tx(port, PRL_TX_WAIT_FOR_MESSAGE_REQUEST);
} else {
/*
* NOTE: PRL_TX_Construct_Message State embedded
* here.
*/
/* Try to resend the message. */
prl_tx_construct_message(port);
}
} else if (prl_tx[port].xmit_status == TCPC_TX_COMPLETE_SUCCESS) {
/* NOTE: PRL_TX_Message_Sent State embedded here. */
/* Increment messageId counter */
increment_msgid_counter(port);
/* Inform Policy Engine Message was sent */
PDMSG_SET_FLAG(port, PRL_FLAGS_TX_COMPLETE);
/*
* This event reduces the time of informing the policy engine of
* the transmission by one state machine cycle
*/
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
set_state_prl_tx(port, PRL_TX_WAIT_FOR_MESSAGE_REQUEST);
}
}
static void prl_tx_wait_for_phy_response_exit(const int port)
{
prl_tx[port].xmit_status = TCPC_TX_UNSET;
}
/* Source Protocol Layer Message Transmission */
/*
* PrlTxSrcPending
*/
static void prl_tx_src_pending_entry(const int port)
{
/* Start SinkTxTimer */
prl_tx[port].sink_tx_timer = get_time().val + PD_T_SINK_TX;
}
static void prl_tx_src_pending_run(const int port)
{
if (get_time().val > prl_tx[port].sink_tx_timer) {
/*
* Soft Reset Message pending &
* SinkTxTimer timeout
*/
if ((emsg[port].len == 0) &&
(pdmsg[port].msg_type == PD_CTRL_SOFT_RESET)) {
set_state_prl_tx(port, PRL_TX_LAYER_RESET_FOR_TRANSMIT);
}
/* Message pending (except Soft Reset) &
* SinkTxTimer timeout
*/
else {
prl_tx_construct_message(port);
set_state_prl_tx(port, PRL_TX_WAIT_FOR_PHY_RESPONSE);
}
return;
}
}
/*
* PrlTxSnkPending
*/
static void prl_tx_snk_pending_run(const int port)
{
enum tcpc_cc_voltage_status cc1, cc2;
tcpm_get_cc(port, &cc1, &cc2);
if (cc1 == TYPEC_CC_VOLT_RP_3_0 || cc2 == TYPEC_CC_VOLT_RP_3_0) {
/*
* Soft Reset Message Message pending &
* Rp = SinkTxOk
*/
if ((pdmsg[port].msg_type == PD_CTRL_SOFT_RESET) &&
(emsg[port].len == 0)) {
set_state_prl_tx(port, PRL_TX_LAYER_RESET_FOR_TRANSMIT);
}
/*
* Message pending (except Soft Reset) &
* Rp = SinkTxOk
*/
else {
prl_tx_construct_message(port);
set_state_prl_tx(port, PRL_TX_WAIT_FOR_PHY_RESPONSE);
}
return;
}
}
/* Hard Reset Operation */
static void prl_hr_wait_for_request_entry(const int port)
{
prl_hr[port].flags = 0;
}
static void prl_hr_wait_for_request_run(const int port)
{
if (PRL_HR_CHK_FLAG(port, PRL_FLAGS_PE_HARD_RESET |
PRL_FLAGS_PORT_PARTNER_HARD_RESET))
set_state_prl_hr(port, PRL_HR_RESET_LAYER);
}
/*
* PrlHrResetLayer
*/
static void prl_hr_reset_layer_entry(const int port)
{
int i;
/* reset messageIDCounters */
for (i = 0; i < NUM_SOP_STAR_TYPES; i++)
prl_tx[port].msg_id_counter[i] = 0;
/*
* Protocol Layer message transmission transitions to
* PRL_Tx_Wait_For_Message_Request state.
*/
set_state_prl_tx(port, PRL_TX_WAIT_FOR_MESSAGE_REQUEST);
tch[port].flags = 0;
rch[port].flags = 0;
pdmsg[port].flags = 0;
/* Reset message ids */
for (i = 0; i < NUM_SOP_STAR_TYPES; i++) {
prl_rx[port].msg_id[i] = -1;
prl_tx[port].msg_id_counter[i] = 0;
}
/* Disable RX */
if (IS_ENABLED(CONFIG_USB_TYPEC_CTVPD) ||
IS_ENABLED(CONFIG_USB_TYPEC_VPD))
vpd_rx_enable(0);
else
tcpm_set_rx_enable(port, 0);
return;
}
static void prl_hr_reset_layer_run(const int port)
{
/*
* Protocol Layer reset Complete &
* Hard Reset was initiated by Policy Engine
*/
if (PRL_HR_CHK_FLAG(port, PRL_FLAGS_PE_HARD_RESET)) {
/* Request PHY to perform a Hard Reset */
prl_send_ctrl_msg(port, TCPC_TX_HARD_RESET, 0);
set_state_prl_hr(port, PRL_HR_WAIT_FOR_PHY_HARD_RESET_COMPLETE);
}
/*
* Protocol Layer reset complete &
* Hard Reset was initiated by Port Partner
*/
else {
/* Inform Policy Engine of the Hard Reset */
pe_got_hard_reset(port);
set_state_prl_hr(port, PRL_HR_WAIT_FOR_PE_HARD_RESET_COMPLETE);
}
}
/*
* PrlHrWaitForPhyHardResetComplete
*/
static void prl_hr_wait_for_phy_hard_reset_complete_entry(const int port)
{
/* Start HardResetCompleteTimer */
prl_hr[port].hard_reset_complete_timer =
get_time().val + PD_T_PS_HARD_RESET;
}
static void prl_hr_wait_for_phy_hard_reset_complete_run(const int port)
{
/*
* Wait for hard reset from PHY
* or timeout
*/
if (PDMSG_CHK_FLAG(port, PRL_FLAGS_TX_COMPLETE) ||
(get_time().val > prl_hr[port].hard_reset_complete_timer)) {
/* PRL_HR_PHY_Hard_Reset_Requested */
/* Inform Policy Engine Hard Reset was sent */
pe_hard_reset_sent(port);
set_state_prl_hr(port, PRL_HR_WAIT_FOR_PE_HARD_RESET_COMPLETE);
return;
}
}
/*
* PrlHrWaitForPeHardResetComplete
*/
static void prl_hr_wait_for_pe_hard_reset_complete_run(const int port)
{
/*
* Wait for Hard Reset complete indication from Policy Engine
*/
if (PRL_HR_CHK_FLAG(port, PRL_FLAGS_HARD_RESET_COMPLETE))
set_state_prl_hr(port, PRL_HR_WAIT_FOR_REQUEST);
}
static void prl_hr_wait_for_pe_hard_reset_complete_exit(const int port)
{
/* Exit from Hard Reset */
set_state_prl_tx(port, PRL_TX_PHY_LAYER_RESET);
set_state_rch(port, RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER);
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
}
static void copy_chunk_to_ext(int port)
{
/* Calculate number of bytes */
pdmsg[port].num_bytes_received = (PD_HEADER_CNT(emsg[port].header) * 4);
/* Copy chunk into extended message */
memcpy((uint8_t *)emsg[port].buf, (uint8_t *)pdmsg[port].chk_buf,
pdmsg[port].num_bytes_received);
/* Set extended message length */
emsg[port].len = pdmsg[port].num_bytes_received;
}
/*
* Chunked Rx State Machine
*/
/*
* RchWaitForMessageFromProtocolLayer
*/
static void rch_wait_for_message_from_protocol_layer_entry(const int port)
{
/* Clear Abort flag */
PDMSG_CLR_FLAG(port, PRL_FLAGS_ABORT);
/* All Messages are chunked */
rch[port].flags = PRL_FLAGS_CHUNKING;
}
static void rch_wait_for_message_from_protocol_layer_run(const int port)
{
if (RCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
RCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
/*
* Are we communicating with a PD3.0 device and is
* this an extended message?
*/
if (prl_get_rev(port, pdmsg[port].xmit_type) == PD_REV30 &&
PD_HEADER_EXT(emsg[port].header)) {
uint16_t exhdr = GET_EXT_HEADER(*pdmsg[port].chk_buf);
uint8_t chunked = PD_EXT_HEADER_CHUNKED(exhdr);
/*
* Received Extended Message &
* (Chunking = 1 & Chunked = 1)
*/
if ((RCH_CHK_FLAG(port, PRL_FLAGS_CHUNKING)) &&
chunked) {
/*
* RCH_Processing_Extended_Message first chunk
* entry processing embedded here
*
* This is the first chunk:
* Set Chunk_number_expected = 0 and
* Num_Bytes_Received = 0
*/
pdmsg[port].chunk_number_expected = 0;
pdmsg[port].num_bytes_received = 0;
pdmsg[port].msg_type =
PD_HEADER_TYPE(emsg[port].header);
set_state_rch(port,
RCH_PROCESSING_EXTENDED_MESSAGE);
}
/*
* (Received Extended Message &
* (Chunking = 0 & Chunked = 0))
*/
else if (!RCH_CHK_FLAG(port, PRL_FLAGS_CHUNKING) &&
!chunked) {
/* Copy chunk to extended buffer */
copy_chunk_to_ext(port);
set_state_rch(port, RCH_PASS_UP_MESSAGE);
}
/*
* Chunked != Chunking
*/
else {
set_state_rch(port, RCH_REPORT_ERROR);
}
}
/*
* Received Non-Extended Message
*/
else if (!PD_HEADER_EXT(emsg[port].header)) {
/* Copy chunk to extended buffer */
copy_chunk_to_ext(port);
set_state_rch(port, RCH_PASS_UP_MESSAGE);
}
/*
* Received an Extended Message while communicating at a
* revision lower than PD3.0
*/
else {
set_state_rch(port, RCH_REPORT_ERROR);
}
}
}
/*
* RchPassUpMessage
*/
static void rch_pass_up_message_entry(const int port)
{
/* Pass Message to Policy Engine */
pe_message_received(port);
set_state_rch(port, RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER);
}
/*
* RchProcessingExtendedMessage
*/
static void rch_processing_extended_message_run(const int port)
{
uint16_t exhdr = GET_EXT_HEADER(pdmsg[port].chk_buf[0]);
uint8_t chunk_num = PD_EXT_HEADER_CHUNK_NUM(exhdr);
uint32_t data_size = PD_EXT_HEADER_DATA_SIZE(exhdr);
uint32_t byte_num;
/*
* Abort Flag Set
*/
if (PDMSG_CHK_FLAG(port, PRL_FLAGS_ABORT))
set_state_rch(port, RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER);
/*
* If expected Chunk Number:
* Append data to Extended_Message_Buffer
* Increment Chunk_number_Expected
* Adjust Num Bytes Received
*/
else if (chunk_num == pdmsg[port].chunk_number_expected) {
byte_num = data_size - pdmsg[port].num_bytes_received;
if (byte_num > 25)
byte_num = 26;
/* Make sure extended message buffer does not overflow */
if (pdmsg[port].num_bytes_received +
byte_num > EXTENDED_BUFFER_SIZE) {
set_state_rch(port, RCH_REPORT_ERROR);
return;
}
/* Append data */
/* Add 2 to chk_buf to skip over extended message header */
memcpy(((uint8_t *)emsg[port].buf +
pdmsg[port].num_bytes_received),
(uint8_t *)pdmsg[port].chk_buf + 2, byte_num);
/* increment chunk number expected */
pdmsg[port].chunk_number_expected++;
/* adjust num bytes received */
pdmsg[port].num_bytes_received += byte_num;
/* Was that the last chunk? */
if (pdmsg[port].num_bytes_received >= data_size) {
emsg[port].len = pdmsg[port].num_bytes_received;
/* Pass Message to Policy Engine */
set_state_rch(port, RCH_PASS_UP_MESSAGE);
}
/*
* Message not Complete
*/
else
set_state_rch(port, RCH_REQUESTING_CHUNK);
}
/*
* Unexpected Chunk Number
*/
else
set_state_rch(port, RCH_REPORT_ERROR);
}
/*
* RchRequestingChunk
*/
static void rch_requesting_chunk_entry(const int port)
{
/*
* Send Chunk Request to Protocol Layer
* with chunk number = Chunk_Number_Expected
*/
pdmsg[port].chk_buf[0] = PD_EXT_HEADER(
pdmsg[port].chunk_number_expected,
1, /* Request Chunk */
0 /* Data Size */
);
pdmsg[port].data_objs = 1;
pdmsg[port].ext = 1;
PRL_TX_SET_FLAG(port, PRL_FLAGS_MSG_XMIT);
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_TX, 0);
}
static void rch_requesting_chunk_run(const int port)
{
/*
* Message Transmitted received from Protocol Layer
*/
if (PDMSG_CHK_FLAG(port, PRL_FLAGS_TX_COMPLETE)) {
PDMSG_CLR_FLAG(port, PRL_FLAGS_TX_COMPLETE);
set_state_rch(port, RCH_WAITING_CHUNK);
}
/*
* Transmission Error from Protocol Layer or
* Message Received From Protocol Layer
*/
else if (RCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED) ||
PDMSG_CHK_FLAG(port, PRL_FLAGS_TX_ERROR)) {
/*
* Leave PRL_FLAGS_MSG_RECEIVED flag set. It'll be
* cleared in rch_report_error state
*/
set_state_rch(port, RCH_REPORT_ERROR);
}
}
/*
* RchWaitingChunk
*/
static void rch_waiting_chunk_entry(const int port)
{
/*
* Start ChunkSenderResponseTimer
*/
rch[port].chunk_sender_response_timer =
get_time().val + PD_T_CHUNK_SENDER_RESPONSE;
}
static void rch_waiting_chunk_run(const int port)
{
if (RCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
/*
* Leave PRL_FLAGS_MSG_RECEIVED flag set just in case an error
* is detected. If an error is detected, PRL_FLAGS_MSG_RECEIVED
* will be cleared in rch_report_error state.
*/
if (PD_HEADER_EXT(emsg[port].header)) {
uint16_t exhdr = GET_EXT_HEADER(pdmsg[port].chk_buf[0]);
/*
* Other Message Received from Protocol Layer
*/
if (PD_EXT_HEADER_REQ_CHUNK(exhdr) ||
!PD_EXT_HEADER_CHUNKED(exhdr)) {
set_state_rch(port, RCH_REPORT_ERROR);
}
/*
* Chunk response Received from Protocol Layer
*/
else {
/*
* No error wad detected, so clear
* PRL_FLAGS_MSG_RECEIVED flag.
*/
RCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
set_state_rch(port,
RCH_PROCESSING_EXTENDED_MESSAGE);
}
}
}
/*
* ChunkSenderResponseTimer Timeout
*/
else if (get_time().val > rch[port].chunk_sender_response_timer) {
set_state_rch(port, RCH_REPORT_ERROR);
}
}
/*
* RchReportError
*/
static void rch_report_error_entry(const int port)
{
/*
* If the state was entered because a message was received,
* this message is passed to the Policy Engine.
*/
if (RCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
RCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
/* Copy chunk to extended buffer */
copy_chunk_to_ext(port);
/* Pass Message to Policy Engine */
pe_message_received(port);
/* Report error */
pe_report_error(port, ERR_RCH_MSG_REC);
} else {
/* Report error */
pe_report_error(port, ERR_RCH_CHUNKED);
}
}
static void rch_report_error_run(const int port)
{
set_state_rch(port, RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER);
}
/*
* Chunked Tx State Machine
*/
/*
* TchWaitForMessageRequestFromPe
*/
static void tch_wait_for_message_request_from_pe_entry(const int port)
{
/* Clear Abort flag */
PDMSG_CLR_FLAG(port, PRL_FLAGS_ABORT);
/* All Messages are chunked */
tch[port].flags = PRL_FLAGS_CHUNKING;
}
static void tch_wait_for_message_request_from_pe_run(const int port)
{
/*
* Any message received and not in state TCH_Wait_Chunk_Request
*/
if (TCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
TCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
set_state_tch(port, TCH_MESSAGE_RECEIVED);
} else if (TCH_CHK_FLAG(port, PRL_FLAGS_MSG_XMIT)) {
TCH_CLR_FLAG(port, PRL_FLAGS_MSG_XMIT);
/*
* Rx Chunking State != RCH_Wait_For_Message_From_Protocol_Layer
* & Abort Supported
*
* Discard the Message
*/
if (rch_get_state(port) !=
RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER) {
tch[port].error = ERR_TCH_XMIT;
set_state_tch(port, TCH_REPORT_ERROR);
} else {
/*
* Extended Message Request & Chunking
*/
if (prl_get_rev(port, pdmsg[port].xmit_type) == PD_REV30
&& pdmsg[port].ext &&
TCH_CHK_FLAG(port, PRL_FLAGS_CHUNKING)) {
/*
* NOTE: TCH_Prepare_To_Send_Chunked_Message
* embedded here.
*/
pdmsg[port].send_offset = 0;
pdmsg[port].chunk_number_to_send = 0;
set_state_tch(port,
TCH_CONSTRUCT_CHUNKED_MESSAGE);
} else
/*
* Non-Extended Message Request
*/
{
/* Make sure buffer doesn't overflow */
if (emsg[port].len > BUFFER_SIZE) {
tch[port].error = ERR_TCH_XMIT;
set_state_tch(port, TCH_REPORT_ERROR);
return;
}
/* NOTE: TCH_Pass_Down_Message embedded here */
/* Copy message to chunked buffer */
memset((uint8_t *)pdmsg[port].chk_buf,
0, BUFFER_SIZE);
memcpy((uint8_t *)pdmsg[port].chk_buf,
(uint8_t *)emsg[port].buf,
emsg[port].len);
/*
* Pad length to 4-byte boundery and
* convert to number of 32-bit objects.
* Since the value is shifted right by 2,
* no need to explicitly clear the lower
* 2-bits.
*/
pdmsg[port].data_objs =
(emsg[port].len + 3) >> 2;
/* Pass Message to Protocol Layer */
PRL_TX_SET_FLAG(port, PRL_FLAGS_MSG_XMIT);
set_state_tch(port,
TCH_WAIT_FOR_TRANSMISSION_COMPLETE);
}
}
}
}
/*
* TchWaitForTransmissionComplete
*/
static void tch_wait_for_transmission_complete_run(const int port)
{
/*
* Inform Policy Engine that Message was sent.
*/
if (PDMSG_CHK_FLAG(port, PRL_FLAGS_TX_COMPLETE)) {
PDMSG_CLR_FLAG(port, PRL_FLAGS_TX_COMPLETE);
set_state_tch(port, TCH_MESSAGE_SENT);
}
/*
* Inform Policy Engine of Tx Error
*/
else if (PDMSG_CHK_FLAG(port, PRL_FLAGS_TX_ERROR)) {
PDMSG_CLR_FLAG(port, PRL_FLAGS_TX_ERROR);
tch[port].error = ERR_TCH_XMIT;
set_state_tch(port, TCH_REPORT_ERROR);
}
}
/*
* TchConstructChunkedMessage
*/
static void tch_construct_chunked_message_entry(const int port)
{
uint16_t *ext_hdr;
uint8_t *data;
uint16_t num;
/*
* Any message received and not in state TCH_Wait_Chunk_Request
*/
if (TCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
TCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
set_state_tch(port, TCH_MESSAGE_RECEIVED);
return;
}
/* Prepare to copy chunk into chk_buf */
ext_hdr = (uint16_t *)pdmsg[port].chk_buf;
data = ((uint8_t *)pdmsg[port].chk_buf + 2);
num = emsg[port].len - pdmsg[port].send_offset;
if (num > 26)
num = 26;
/* Set the chunks extended header */
*ext_hdr = PD_EXT_HEADER(pdmsg[port].chunk_number_to_send,
0, /* Chunk Request */
emsg[port].len);
/* Copy the message chunk into chk_buf */
memset(data, 0, 28);
memcpy(data, emsg[port].buf + pdmsg[port].send_offset, num);
pdmsg[port].send_offset += num;
/*
* Add in 2 bytes for extended header
* pad out to 4-byte boundary
* convert to number of 4-byte words
* Since the value is shifted right by 2,
* no need to explicitly clear the lower
* 2-bits.
*/
pdmsg[port].data_objs = (num + 2 + 3) >> 2;
/* Pass message chunk to Protocol Layer */
PRL_TX_SET_FLAG(port, PRL_FLAGS_MSG_XMIT);
}
static void tch_construct_chunked_message_run(const int port)
{
if (PDMSG_CHK_FLAG(port, PRL_FLAGS_ABORT))
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
else
set_state_tch(port, TCH_SENDING_CHUNKED_MESSAGE);
}
/*
* TchSendingChunkedMessage
*/
static void tch_sending_chunked_message_run(const int port)
{
/*
* Transmission Error
*/
if (PDMSG_CHK_FLAG(port, PRL_FLAGS_TX_ERROR)) {
tch[port].error = ERR_TCH_XMIT;
set_state_tch(port, TCH_REPORT_ERROR);
}
/*
* Message Transmitted from Protocol Layer &
* Last Chunk
*/
else if (emsg[port].len == pdmsg[port].send_offset) {
set_state_tch(port, TCH_MESSAGE_SENT);
}
/*
* Any message received and not in state TCH_Wait_Chunk_Request
*/
else if (TCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
TCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
set_state_tch(port, TCH_MESSAGE_RECEIVED);
}
/*
* Message Transmitted from Protocol Layer &
* Not Last Chunk
*/
else
set_state_tch(port, TCH_WAIT_CHUNK_REQUEST);
}
/*
* TchWaitChunkRequest
*/
static void tch_wait_chunk_request_entry(const int port)
{
/* Increment Chunk Number to Send */
pdmsg[port].chunk_number_to_send++;
/* Start Chunk Sender Request Timer */
tch[port].chunk_sender_request_timer =
get_time().val + PD_T_CHUNK_SENDER_REQUEST;
}
static void tch_wait_chunk_request_run(const int port)
{
if (TCH_CHK_FLAG(port, PRL_FLAGS_MSG_RECEIVED)) {
TCH_CLR_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
if (PD_HEADER_EXT(emsg[port].header)) {
uint16_t exthdr;
exthdr = GET_EXT_HEADER(pdmsg[port].chk_buf[0]);
if (PD_EXT_HEADER_REQ_CHUNK(exthdr)) {
/*
* Chunk Request Received &
* Chunk Number = Chunk Number to Send
*/
if (PD_EXT_HEADER_CHUNK_NUM(exthdr) ==
pdmsg[port].chunk_number_to_send) {
set_state_tch(port,
TCH_CONSTRUCT_CHUNKED_MESSAGE);
}
/*
* Chunk Request Received &
* Chunk Number != Chunk Number to Send
*/
else {
tch[port].error = ERR_TCH_CHUNKED;
set_state_tch(port, TCH_REPORT_ERROR);
}
return;
}
}
/*
* Other message received
*/
set_state_tch(port, TCH_MESSAGE_RECEIVED);
}
/*
* ChunkSenderRequestTimer timeout
*/
else if (get_time().val >=
tch[port].chunk_sender_request_timer) {
set_state_tch(port, TCH_MESSAGE_SENT);
}
}
/*
* TchMessageReceived
*/
static void tch_message_received_entry(const int port)
{
/* Pass message to chunked Rx */
RCH_SET_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
}
static void tch_message_received_run(const int port)
{
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
}
/*
* TchMessageSent
*/
static void tch_message_sent_entry(const int port)
{
/* Tell PE message was sent */
pe_message_sent(port);
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
}
/*
* TchReportError
*/
static void tch_report_error_entry(const int port)
{
/* Report Error To Policy Engine */
pe_report_error(port, tch[port].error);
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
}
/*
* Protocol Layer Message Reception State Machine
*/
static void prl_rx_wait_for_phy_message(const int port, int evt)
{
uint32_t header;
uint8_t type;
uint8_t cnt;
uint8_t sop;
int8_t msid;
/* If we don't have any message, just stop processing now. */
if (!tcpm_has_pending_message(port) ||
tcpm_dequeue_message(port, pdmsg[port].chk_buf, &header))
return;
emsg[port].header = header;
type = PD_HEADER_TYPE(header);
cnt = PD_HEADER_CNT(header);
msid = PD_HEADER_ID(header);
sop = PD_HEADER_GET_SOP(header);
/*
* Ignore messages sent to the cable from our
* port partner if we aren't Vconn powered device.
*/
if (!IS_ENABLED(CONFIG_USB_TYPEC_CTVPD) &&
!IS_ENABLED(CONFIG_USB_TYPEC_VPD) &&
PD_HEADER_GET_SOP(header) != PD_MSG_SOP &&
PD_HEADER_PROLE(header) == PD_PLUG_FROM_DFP_UFP)
return;
if (cnt == 0 && type == PD_CTRL_SOFT_RESET) {
int i;
for (i = 0; i < NUM_SOP_STAR_TYPES; i++) {
/* Clear MessageIdCounter */
prl_tx[port].msg_id_counter[i] = 0;
/* Clear stored MessageID value */
prl_rx[port].msg_id[i] = -1;
}
/* Inform Policy Engine of Soft Reset */
pe_got_soft_reset(port);
/* Soft Reset occurred */
set_state_prl_tx(port, PRL_TX_PHY_LAYER_RESET);
set_state_rch(port, RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER);
set_state_tch(port, TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE);
}
/*
* Ignore if this is a duplicate message. Stop processing.
*/
if (prl_rx[port].msg_id[sop] == msid)
return;
/*
* Discard any pending tx message if this is
* not a ping message
*/
if (prl_get_rev(port, pdmsg[port].xmit_type) == PD_REV30 &&
(cnt == 0) && type != PD_CTRL_PING) {
if (prl_tx_get_state(port) == PRL_TX_SRC_PENDING ||
prl_tx_get_state(port) == PRL_TX_SNK_PENDING)
set_state_prl_tx(port, PRL_TX_DISCARD_MESSAGE);
}
/* Store Message Id */
prl_rx[port].msg_id[sop] = msid;
/* RTR Chunked Message Router States. */
/*
* Received Ping from Protocol Layer
*/
if (cnt == 0 && type == PD_CTRL_PING) {
/* NOTE: RTR_PING State embedded here. */
emsg[port].len = 0;
pe_message_received(port);
return;
}
/*
* Message (not Ping) Received from
* Protocol Layer & Doing Tx Chunks
*/
else if (tch_get_state(port) != TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE &&
tch_get_state(port) != TCH_WAIT_FOR_TRANSMISSION_COMPLETE) {
/* NOTE: RTR_TX_CHUNKS State embedded here. */
/*
* Send Message to Tx Chunk
* Chunk State Machine
*/
TCH_SET_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
}
/*
* Message (not Ping) Received from
* Protocol Layer & Not Doing Tx Chunks
*/
else {
/* NOTE: RTR_RX_CHUNKS State embedded here. */
/*
* Send Message to Rx
* Chunk State Machine
*/
RCH_SET_FLAG(port, PRL_FLAGS_MSG_RECEIVED);
}
task_set_event(PD_PORT_TO_TASK_ID(port), PD_EVENT_SM, 0);
}
/* All necessary Protocol Transmit States (Section 6.11.2.2) */
static const struct usb_state prl_tx_states[] = {
[PRL_TX_PHY_LAYER_RESET] = {
.entry = prl_tx_phy_layer_reset_entry,
.run = prl_tx_phy_layer_reset_run,
},
[PRL_TX_WAIT_FOR_MESSAGE_REQUEST] = {
.entry = prl_tx_wait_for_message_request_entry,
.run = prl_tx_wait_for_message_request_run,
},
[PRL_TX_LAYER_RESET_FOR_TRANSMIT] = {
.entry = prl_tx_layer_reset_for_transmit_entry,
.run = prl_tx_layer_reset_for_transmit_run,
},
[PRL_TX_WAIT_FOR_PHY_RESPONSE] = {
.entry = prl_tx_wait_for_phy_response_entry,
.run = prl_tx_wait_for_phy_response_run,
.exit = prl_tx_wait_for_phy_response_exit,
},
[PRL_TX_SRC_SOURCE_TX] = {
.entry = prl_tx_src_source_tx_entry,
.run = prl_tx_src_source_tx_run,
},
[PRL_TX_SNK_START_AMS] = {
.run = prl_tx_snk_start_ams_run,
},
[PRL_TX_SRC_PENDING] = {
.entry = prl_tx_src_pending_entry,
.run = prl_tx_src_pending_run,
},
[PRL_TX_SNK_PENDING] = {
.run = prl_tx_snk_pending_run,
},
[PRL_TX_DISCARD_MESSAGE] = {
.entry = prl_tx_discard_message_entry,
},
};
/* All necessary Protocol Hard Reset States (Section 6.11.2.4) */
static const struct usb_state prl_hr_states[] = {
[PRL_HR_WAIT_FOR_REQUEST] = {
.entry = prl_hr_wait_for_request_entry,
.run = prl_hr_wait_for_request_run,
},
[PRL_HR_RESET_LAYER] = {
.entry = prl_hr_reset_layer_entry,
.run = prl_hr_reset_layer_run,
},
[PRL_HR_WAIT_FOR_PHY_HARD_RESET_COMPLETE] = {
.entry = prl_hr_wait_for_phy_hard_reset_complete_entry,
.run = prl_hr_wait_for_phy_hard_reset_complete_run,
},
[PRL_HR_WAIT_FOR_PE_HARD_RESET_COMPLETE] = {
.run = prl_hr_wait_for_pe_hard_reset_complete_run,
.exit = prl_hr_wait_for_pe_hard_reset_complete_exit,
},
};
/* All necessary Chunked Rx states (Section 6.11.2.1.2) */
static const struct usb_state rch_states[] = {
[RCH_WAIT_FOR_MESSAGE_FROM_PROTOCOL_LAYER] = {
.entry = rch_wait_for_message_from_protocol_layer_entry,
.run = rch_wait_for_message_from_protocol_layer_run,
},
[RCH_PASS_UP_MESSAGE] = {
.entry = rch_pass_up_message_entry,
},
[RCH_PROCESSING_EXTENDED_MESSAGE] = {
.run = rch_processing_extended_message_run,
},
[RCH_REQUESTING_CHUNK] = {
.entry = rch_requesting_chunk_entry,
.run = rch_requesting_chunk_run,
},
[RCH_WAITING_CHUNK] = {
.entry = rch_waiting_chunk_entry,
.run = rch_waiting_chunk_run,
},
[RCH_REPORT_ERROR] = {
.entry = rch_report_error_entry,
.run = rch_report_error_run,
},
};
/* All necessary Chunked Tx states (Section 6.11.2.1.3) */
static const struct usb_state tch_states[] = {
[TCH_WAIT_FOR_MESSAGE_REQUEST_FROM_PE] = {
.entry = tch_wait_for_message_request_from_pe_entry,
.run = tch_wait_for_message_request_from_pe_run,
},
[TCH_WAIT_FOR_TRANSMISSION_COMPLETE] = {
.run = tch_wait_for_transmission_complete_run,
},
[TCH_CONSTRUCT_CHUNKED_MESSAGE] = {
.entry = tch_construct_chunked_message_entry,
.run = tch_construct_chunked_message_run,
},
[TCH_SENDING_CHUNKED_MESSAGE] = {
.run = tch_sending_chunked_message_run,
},
[TCH_WAIT_CHUNK_REQUEST] = {
.entry = tch_wait_chunk_request_entry,
.run = tch_wait_chunk_request_run,
},
[TCH_MESSAGE_RECEIVED] = {
.entry = tch_message_received_entry,
.run = tch_message_received_run,
},
[TCH_MESSAGE_SENT] = {
.entry = tch_message_sent_entry,
},
[TCH_REPORT_ERROR] = {
.entry = tch_report_error_entry,
},
};
#ifdef TEST_BUILD
const struct test_sm_data test_prl_sm_data[] = {
{
.base = prl_tx_states,
.size = ARRAY_SIZE(prl_tx_states),
},
{
.base = prl_hr_states,
.size = ARRAY_SIZE(prl_hr_states),
},
{
.base = rch_states,
.size = ARRAY_SIZE(rch_states),
},
{
.base = tch_states,
.size = ARRAY_SIZE(tch_states),
},
};
const int test_prl_sm_data_size = ARRAY_SIZE(test_prl_sm_data);
#endif
| 26.03664 | 77 | 0.722834 | [
"object"
] |
b0f1da2de78a962cb33878646b0069519ec9bc6e | 2,021 | c | C | src/ndsave.c | ymei/NetDAQ | f4360fecf505484467b39c19acdc05c89065690d | [
"BSD-3-Clause"
] | null | null | null | src/ndsave.c | ymei/NetDAQ | f4360fecf505484467b39c19acdc05c89065690d | [
"BSD-3-Clause"
] | null | null | null | src/ndsave.c | ymei/NetDAQ | f4360fecf505484467b39c19acdc05c89065690d | [
"BSD-3-Clause"
] | null | null | null | /** \file
* NetDAQ saving data to file from shared memory.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include "common.h"
#include "ipc.h"
/** Parameters settable from commandline */
typedef struct param
{
char *shmName; //!< shared memory object name, system-wide.
} param_t;
param_t paramDefault = {
.shmName = SHM_NAME,
};
void print_usage(const param_t *pm, FILE *s)
{
fprintf(s, "Usage:\n");
fprintf(s, " -n shmName [\"%s\"]: Shared memory object name, system-wide.\n", pm->shmName);
}
int main(int argc, char **argv)
{
int shmfd;
void *shmp;
shm_sync_t *ssv;
size_t pageSize, shmSize;
param_t pm;
int optC = 0;
// parse switches
memcpy(&pm, ¶mDefault, sizeof(pm));
while ((optC = getopt(argc, argv, "n:")) != -1) {
switch (optC) {
case 'n':
pm.shmName = optarg;
break;
default:
print_usage(&pm, stderr);
return EXIT_FAILURE;
break;
}
}
argc -= optind;
argv += optind;
pageSize = get_system_pagesize();
shmfd = shm_connect(pm.shmName, &shmp, &shmSize, &ssv);
if (shmfd<0 || shmp==NULL) return EXIT_FAILURE;
close(shmfd); // Can be closed immediately after mmap.
fprintf(stderr, "System pagesize: %zd bytes.\n", pageSize);
fprintf(stderr, "Shared memory element size: %zd bytes.\n", ssv->elemSize);
fprintf(stderr, "Shared memory SegLen: %zd, nSeg: %zd, total size: %zd bytes.\n",
ssv->segLen, ssv->nSeg, shmSize);
fprintf(stderr, "Shared memory sync variables in the last %d page.\n", SHM_SYNC_NPAGE);
shm_consumer_init(ssv);
SHM_ELEM_TYPE *p;
for (int i=0;;i++) {
if ((p = shm_acquire_next_segment_sync(shmp, ssv, SHM_SEG_READ))) {
printf("0x%08x %2td %2td %d\n", *p,
atomic_load(&ssv->iRd), atomic_load(&ssv->iWr), i);
}
}
return EXIT_SUCCESS;
}
| 26.592105 | 100 | 0.59525 | [
"object"
] |
b0f7417538b5a3c8ed0341e952ff75fb6ed040a0 | 6,472 | h | C | quisp/test_utils/StaticEnv.h | TSarkar99/quisp | 1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da | [
"BSD-3-Clause"
] | 47 | 2020-03-13T08:40:53.000Z | 2022-03-30T06:50:10.000Z | quisp/test_utils/StaticEnv.h | TSarkar99/quisp | 1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da | [
"BSD-3-Clause"
] | 236 | 2020-03-13T07:19:33.000Z | 2022-03-21T07:38:23.000Z | quisp/test_utils/StaticEnv.h | TSarkar99/quisp | 1c954eb20f8bf098a68e0e93caf2f7bfd7fa28da | [
"BSD-3-Clause"
] | 18 | 2020-03-14T02:16:20.000Z | 2021-11-25T12:50:41.000Z | #pragma once
#include <omnetpp.h>
#include "Configuration.h"
namespace quisp_test {
namespace env {
using namespace omnetpp;
/**
* \brief cEnvir implementation for unit testing based on OMNeT++'s StaticEnv.
* \see https://github.com/omnetpp/omnetpp/blob/308b3b2b4c060b165911237a9bd9470ea010d34c/src/sim/csimulation.cc#L728
*/
class StaticEnv : public omnetpp::cEnvir {
protected:
void unsupported() const { throw std::runtime_error("StaticEnv: Unsupported method called"); }
void alert(const char *msg) override { ::printf("\n<!> %s\n\n", msg); }
bool askYesNo(const char *msg) override {
unsupported();
return false;
}
public:
StaticEnv();
~StaticEnv() {}
// eventlog callback interface
void objectDeleted(cObject *object) override {}
void simulationEvent(cEvent *event) override {}
void messageScheduled(cMessage *msg) override {}
void messageCancelled(cMessage *msg) override {}
void beginSend(cMessage *msg) override {}
void messageSendDirect(cMessage *msg, cGate *toGate, simtime_t propagationDelay, simtime_t transmissionDelay) override {}
void messageSendHop(cMessage *msg, cGate *srcGate) override {}
void messageSendHop(cMessage *msg, cGate *srcGate, simtime_t propagationDelay, simtime_t transmissionDelay, bool discard) override {}
void endSend(cMessage *msg) override {}
void messageCreated(cMessage *msg) override {}
void messageCloned(cMessage *msg, cMessage *clone) override {}
void messageDeleted(cMessage *msg) override {}
void moduleReparented(cModule *module, cModule *oldparent, int oldId) override {}
void componentMethodBegin(cComponent *from, cComponent *to, const char *methodFmt, va_list va, bool silent) override {}
void componentMethodEnd() override {}
void moduleCreated(cModule *newmodule) override {}
void moduleDeleted(cModule *module) override {}
void gateCreated(cGate *newgate) override {}
void gateDeleted(cGate *gate) override {}
void connectionCreated(cGate *srcgate) override {}
void connectionDeleted(cGate *srcgate) override {}
void displayStringChanged(cComponent *component) override {}
void undisposedObject(cObject *obj) override;
void log(cLogEntry *entry) override {}
// configuration, model parameters
void preconfigure(cComponent *component) override {}
void configure(cComponent *component) override {}
void readParameter(cPar *parameter) override { unsupported(); }
bool isModuleLocal(cModule *parentmod, const char *modname, int index) override { return true; }
cXMLElement *getXMLDocument(const char *filename, const char *xpath = nullptr) override {
unsupported();
return nullptr;
}
cXMLElement *getParsedXMLString(const char *content, const char *xpath = nullptr) override {
unsupported();
return nullptr;
}
void forgetXMLDocument(const char *filename) override {}
void forgetParsedXMLString(const char *content) override {}
void flushXMLDocumentCache() override {}
void flushXMLParsedContentCache() override {}
unsigned getExtraStackForEnvir() const override { return 0; }
cConfiguration *getConfig() override;
std::string resolveResourcePath(const char *fileName, cComponentType *context) override { return ""; }
bool isGUI() const override { return false; }
bool isExpressMode() const override { return false; }
// UI functions (see also protected ones)
void bubble(cComponent *component, const char *text) override {}
std::string gets(const char *prompt, const char *defaultreply = nullptr) override;
cEnvir &flush() {
::fflush(stdout);
return *this;
}
// RNGs
int getNumRNGs() const override { return 0; }
cRNG *getRNG(int k) override;
// output vectors
void *registerOutputVector(const char *modulename, const char *vectorname) override { return nullptr; }
void deregisterOutputVector(void *vechandle) override {}
void setVectorAttribute(void *vechandle, const char *name, const char *value) override {}
bool recordInOutputVector(void *vechandle, simtime_t t, double value) override { return false; }
// output scalars
void recordScalar(cComponent *component, const char *name, double value, opp_string_map *attributes = nullptr) override {}
void recordStatistic(cComponent *component, const char *name, cStatistic *statistic, opp_string_map *attributes = nullptr) override {}
void addResultRecorders(cComponent *component, simsignal_t signal, const char *statisticName, cProperty *statisticTemplateProperty) override {}
// snapshot file
virtual std::ostream *getStreamForSnapshot() override {
unsupported();
return nullptr;
}
void releaseStreamForSnapshot(std::ostream *os) override { unsupported(); }
// misc
int getArgCount() const override {
unsupported();
return 0;
}
char **getArgVector() const override {
unsupported();
return nullptr;
}
int getParsimProcId() const override { return 0; }
int getParsimNumPartitions() const override { return 1; }
unsigned long getUniqueNumber() override {
unsupported();
return 0;
}
bool idle() override { return false; }
void refOsgNode(osg::Node *scene) override {}
void unrefOsgNode(osg::Node *scene) override {}
bool ensureDebugger(cRuntimeError *) override { return false; }
void getImageSize(const char *imageName, double &outWidth, double &outHeight) override { unsupported(); }
void getTextExtent(const cFigure::Font &font, const char *text, double &outWidth, double &outHeight, double &outAscent) override { unsupported(); }
void appendToImagePath(const char *directory) override { unsupported(); }
void loadImage(const char *fileName, const char *imageName = nullptr) override { unsupported(); }
cFigure::Rectangle getSubmoduleBounds(const cModule *submodule) override { return cFigure::Rectangle(NAN, NAN, NAN, NAN); }
double getZoomLevel(const cModule *module) override { return NAN; }
double getAnimationTime() const override { return 0; }
double getAnimationSpeed() const override { return 0; }
double getRemainingAnimationHoldTime() const override { return 0; }
// lifecycle listeners
void addLifecycleListener(cISimulationLifecycleListener *listener) override {}
void removeLifecycleListener(cISimulationLifecycleListener *listener) override {}
void notifyLifecycleListeners(SimulationLifecycleEventType eventType, cObject *details) override {}
cSimulation *newSimulation();
void resetSimulation();
cRNG *rng = nullptr;
};
} // namespace env
} // namespace quisp_test
| 43.146667 | 149 | 0.745828 | [
"object",
"model"
] |
b0f7e166817788e421f126e8378fbc7fef47f496 | 6,691 | h | C | PinGUI/GUIManager.h | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 60 | 2017-04-16T15:31:13.000Z | 2021-12-22T19:01:07.000Z | PinGUI/GUIManager.h | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 4 | 2017-02-14T19:05:21.000Z | 2020-07-16T10:04:27.000Z | PinGUI/GUIManager.h | Pinsius/PinGUI | eb1d39937e28c7f0a030f3dcd61e3d1a67c1feb1 | [
"Zlib"
] | 20 | 2017-02-15T19:07:17.000Z | 2021-12-22T19:01:07.000Z | #ifndef GUIMANAGER_H
#define GUIMANAGER_H
/**
PinGUI
Copyright (c) 2017 Lubomir Barantal <l.pinsius@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
**/
#include <iostream>
#include <algorithm>
#include <typeinfo>
#include "TextManager/TextManager.h"
#include "stuff.h"
#include "GUI_Cursor.h"
#include "GUI_CollisionManager.cpp"
#include "GUI_ColorManager.h"
#include "CameraManager.h"
#include "VBO_Manager.h"
#include <memory>
/*** GUI ELEMENTS ***/
#include "GUI_Elements/ClipBoard.h"
#include "GUI_Elements/ArrowBoard.h"
#include "GUI_Elements/VolumeBoard.h"
#include "GUI_Elements/CrossBox.h"
#include "GUI_Elements/ComboBox.h"
#include "GUI_Elements/Image.h"
#include "GUI_Elements/Button.h"
#define BUTTON_TYPES 2
//For allocation of new VBO´s
#define VBO_ALLOCATION_LIMIT 1000
class Window;
class GUIManager
{
private:
//OpenGL stuff
std::unique_ptr<VBO_Manager> _vboMANAGER;
//Vector of vectors for each kind of button type
std::vector<vboData> _vboDATA;
//Storage place for clipboards
std::vector<std::shared_ptr<GUI_Element>> _ELEMENTS;
//TextManager that belongs to the current GUIManager(GM)
std::shared_ptr<TextManager> _texter;
//Pointer to an element which is currently in manipulating mod
GUI_Element* _manipulatingElement;
std::shared_ptr<GUI_Element> _collidingElement;
//Bool for update state
bool _needUpdate;
bool _moved;
//Bool for manipulating mod
bool _manipulatingMod;
PinGUI::basicPointer _function;
/**
Methods
**/
void loadVBO();
void updateVBO();
//Rendering methods - for each button type
void renderElements(); //Clipboards are first because sometime i want to put the text over the clipboard
void renderText();
//Method for checking the collisions
void checkCollisions();
void checkAimingElements();
public:
GUIManager();
GUIManager(std::shared_ptr<TextManager> texter);
~GUIManager();
//Making methods
void createClipBoard(GUIPos x, GUIPos y, clipboard_type type, int maxSize, element_shape shape = ROUNDED, unsigned int adjTextSize = 0);
void createClipBoard(GUIPos x, GUIPos y, clipboard_type type, int maxSize, int width, element_shape shape = ROUNDED, unsigned int adjTextSize = 0);
void createClipBoard(GUIPos x, GUIPos y, clipboard_type type, int* var, int maxSize, bool negativeInput = true, element_shape shape = ROUNDED);
void createClipBoard(GUIPos x, GUIPos y, clipboard_type type, float* var, int maxSize, bool negativeInput = true, element_shape shape = ROUNDED);
void createClipBoard(GUIPos x, GUIPos y, clipboard_type type, std::string* var, int maxSize, element_shape shape = ROUNDED);
void createComboBox(GUIPos x, GUIPos y, std::vector<std::string> items, int maxNumOfItems);
void createComboBox(GUIPos x, GUIPos y, std::vector<std::string> items, int maxSize, int maxNumOfItems);
void createArrowBoard(GUIPos x, GUIPos y, int* var, int maxSize, bool clickable = true, int minSize = 0, PinGUI::manipulationState state = PinGUI::HORIZONTAL);
void createArrowBoard(GUIPos x, GUIPos y, float* var, int maxSize, bool clickable = true, int minSize = 0, PinGUI::manipulationState state = PinGUI::HORIZONTAL);
void createVolumeBoard(GUIPos x, GUIPos y, bool clickable, int* var, int maxSize);
void createVolumeBoard(GUIPos x, GUIPos y, bool clickable, float* var, int maxSize);
void createCheckBox(GUIPos x, GUIPos y, bool* var);
void createImage(SDL_Surface* imageSurface, GUIPos x, GUIPos y);
void createImage(SDL_Surface* imageSurface, GUIPos x, GUIPos y, int width, int height);
void createButton(GUIPos x, GUIPos y, std::string name, PinGUI::basicPointer f);
void createButton(GUIPos x, GUIPos y, std::string name, PinGUI::basicPointer f, int maxSize);
void createWindowButton(GUIPos x, GUIPos y, std::string name, std::shared_ptr<Window> window);
void createWindowButton(GUIPos x, GUIPos y, std::string name, std::shared_ptr<Window> window, int maxSize);
void createIconButton(GUIPos x, GUIPos y, SDL_Surface* iconSurface, PinGUI::basicPointer f);
void createIconButton(GUIPos x, GUIPos y, SDL_Surface* iconSurface, float width, float height, PinGUI::basicPointer f);
void moveGUI(PinGUI::Vector2<GUIPos> vect, bool croppedMovement = false);
void moveGUITo(PinGUI::Vector2<GUIPos> vect);
void cropGUI(PinGUI::Rect& rect);
void putElement(std::shared_ptr<GUI_Element> object);
void putElementAtStart(std::shared_ptr<GUI_Element> object);
void withdrawElement(std::shared_ptr<GUI_Element> object);
//Rendering method
void render();
//Update method
void update(bool allowCollision = true);
void checkCrop();
void doCrop();
/** GETTERS SETTERS **/
clipboardData getClipboardData();
std::vector<std::shared_ptr<GUI_Element>>* getElementVector();
std::shared_ptr<TextManager> getTextManager();
bool* getUpdateBool();
bool getUpdate();
std::size_t getGUISize();
std::shared_ptr<GUI_Element> getGuiElement(unsigned int position = 0);
std::shared_ptr<GUI_Element> getLastGuiElement();
std::shared_ptr<GUI_Element> getCollidingElement();
void setUpdate(bool state);
void setFunction(PinGUI::basicPointer f);
void normalizeElements(float x, float y);
};
#endif // GUIMANAGER_H
| 36.763736 | 170 | 0.679868 | [
"render",
"object",
"shape",
"vector"
] |
7c056aa89121e96ea0f3bbc957875355ef3fcf65 | 5,995 | h | C | src/Tab Strip/CTTabStripController.h | typcn/chromium-tabs | 42c3d1a43bf2cfd385da0c99f01724063004773d | [
"BSD-3-Clause",
"MIT"
] | 19 | 2015-09-07T00:48:32.000Z | 2020-08-09T15:34:40.000Z | src/Tab Strip/CTTabStripController.h | typcn/chromium-tabs | 42c3d1a43bf2cfd385da0c99f01724063004773d | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/Tab Strip/CTTabStripController.h | typcn/chromium-tabs | 42c3d1a43bf2cfd385da0c99f01724063004773d | [
"BSD-3-Clause",
"MIT"
] | 6 | 2015-09-04T16:01:52.000Z | 2019-01-26T01:06:37.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-chromium file.
#pragma once
#import <Cocoa/Cocoa.h>
#import "CTTabControllerTarget.h"
#import "URLDropTarget.h"
@class NewTabButton;
@class CTTabContentsController;
@class CTTabView;
@class CTTabStripView;
@class CTTabContents;
@class CTBrowser;
@class CTTabStripModel;
// A class that handles managing the tab strip in a browser window. It uses
// a supporting C++ bridge object to register for notifications from the
// TabStripModel. The Obj-C part of this class handles drag and drop and all
// the other Cocoa-y aspects.
//
// For a full description of the design, see
// http://www.chromium.org/developers/design-documents/tab-strip-mac
@interface CTTabStripController : NSObject<CTTabControllerTarget, URLDropTargetController>
@property(nonatomic) CGFloat indentForControls;
// Show or hide the new tab button. The button is hidden immediately, but
// waits until the next call to |-layoutTabs| to show it again.
@property(nonatomic, assign) BOOL showsNewTabButton;
// Ensure that the new tab button is never shown if set.
@property(nonatomic, assign) BOOL disableNewTabButton;
// Initialize the controller with a view and browser that contains
// everything else we'll need. |switchView| is the view whose contents get
// "switched" every time the user switches tabs. The children of this view
// will be released, so if you want them to stay around, make sure
// you have retained them.
- (id)initWithView:(CTTabStripView*)view
switchView:(NSView*)switchView
browser:(CTBrowser*)browser;
// Return the view for the currently active tab.
- (NSView*)activeTabView;
// Set the frame of the active tab, also updates the internal frame dict.
- (void)setFrameOfActiveTab:(NSRect)frame;
// Move the given tab at index |from| in this window to the location of the
// current placeholder.
- (void)moveTabFromIndex:(NSInteger)from;
// Drop a given CTTabContents at the location of the current placeholder. If there
// is no placeholder, it will go at the end. Used when dragging from another
// window when we don't have access to the CTTabContents as part of our strip.
// |frame| is in the coordinate system of the tab strip view and represents
// where the user dropped the new tab so it can be animated into its correct
// location when the tab is added to the model. If the tab was pinned in its
// previous window, setting |pinned| to YES will propagate that state to the
// new window. Mini-tabs are either app or pinned tabs; the app state is stored
// by the |contents|, but the |pinned| state is the caller's responsibility.
- (void)dropTabContents:(CTTabContents*)contents
withFrame:(NSRect)frame
asPinnedTab:(BOOL)pinned;
// Returns the index of the subview |view|. Returns -1 if not present. Takes
// closing tabs into account such that this index will correctly match the tab
// model. If |view| is in the process of closing, returns -1, as closing tabs
// are no longer in the model.
- (NSInteger)modelIndexForTabView:(NSView*)view;
// Return the view at a given index.
- (NSView*)viewAtIndex:(NSUInteger)index;
// Return the number of tab views in the tab strip. It's same as number of tabs
// in the model, except when a tab is closing, which will be counted in views
// count, but no longer in the model.
- (NSUInteger)viewsCount;
// Set the placeholder for a dragged tab, allowing the |frame| and |strechiness|
// to be specified. This causes this tab to be rendered in an arbitrary position
- (void)insertPlaceholderForTab:(CTTabView*)tab
frame:(NSRect)frame;
// Returns whether or not |tab| can still be fully seen in the tab strip or if
// its current position would cause it be obscured by things such as the edge
// of the window or the window decorations. Returns YES only if the entire tab
// is visible.
- (BOOL)isTabFullyVisible:(CTTabView*)tab;
// Force the tabs to rearrange themselves to reflect the current model.
- (void)layoutTabs;
- (void)layoutTabsWithoutAnimation;
// Are we in rapid (tab) closure mode? I.e., is a full layout deferred (while
// the user closes tabs)? Needed to overcome missing clicks during rapid tab
// closure.
- (BOOL)inRapidClosureMode;
// Returns YES if the user is allowed to drag tabs on the strip at this moment.
// For example, this returns NO if there are any pending tab close animtations.
- (BOOL)tabDraggingAllowed;
// Default height for tabs.
+ (CGFloat)defaultTabHeight;
// Default indentation for tabs (see |indentForControls_|).
+ (CGFloat)defaultIndentForControls;
// Returns the (lazily created) window sheet controller of this window. Used
// for the per-tab sheets.
//- (GTMWindowSheetController*)sheetController;
// Destroys the window sheet controller of this window, if it exists. The sheet
// controller can be recreated by a subsequent call to |-sheetController|. Must
// not be called if any sheets are currently open.
// TODO(viettrungluu): This is temporary code needed to allow sheets to work
// (read: not crash) in fullscreen mode. Once GTMWindowSheetController is
// modified to support moving sheets between windows, this code can go away.
// http://crbug.com/19093.
//- (void)destroySheetController;
// Returns the currently active CTTabContentsController.
- (CTTabContentsController*)activeTabContentsController;
// See comments in browser_window_controller.h for documentation about these
// functions.
//- (void)attachConstrainedWindow:(ConstrainedWindowMac*)window;
//- (void)removeConstrainedWindow:(ConstrainedWindowMac*)window;
//- (void)updateDevToolsForContents:(CTTabContents*)contents;
-(CTTabContentsController*)tabContentsControllerForTabContents:(CTTabContents*)contents;
@end
// Notification sent when the number of tabs changes. The object will be this
// controller.
extern NSString* const kTabStripNumberOfTabsChanged;
| 41.631944 | 90 | 0.759466 | [
"object",
"model"
] |
7c06bf3455330fb84f6b2b5daa2a4fdb5c1a3d67 | 114,289 | c | C | src/freedreno/ir3/ir3_compiler_nir.c | pundiramit/external-mesa3d | c342483c57fa185ff67bd5ab7d82cb884e42684e | [
"MIT"
] | null | null | null | src/freedreno/ir3/ir3_compiler_nir.c | pundiramit/external-mesa3d | c342483c57fa185ff67bd5ab7d82cb884e42684e | [
"MIT"
] | null | null | null | src/freedreno/ir3/ir3_compiler_nir.c | pundiramit/external-mesa3d | c342483c57fa185ff67bd5ab7d82cb884e42684e | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2015 Rob Clark <robclark@freedesktop.org>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) 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.
*
* Authors:
* Rob Clark <robclark@freedesktop.org>
*/
#include <stdarg.h>
#include "util/u_string.h"
#include "util/u_memory.h"
#include "util/u_math.h"
#include "ir3_compiler.h"
#include "ir3_image.h"
#include "ir3_shader.h"
#include "ir3_nir.h"
#include "instr-a3xx.h"
#include "ir3.h"
#include "ir3_context.h"
void
ir3_handle_bindless_cat6(struct ir3_instruction *instr, nir_src rsrc)
{
nir_intrinsic_instr *intrin = ir3_bindless_resource(rsrc);
if (!intrin)
return;
instr->flags |= IR3_INSTR_B;
instr->cat6.base = nir_intrinsic_desc_set(intrin);
}
static struct ir3_instruction *
create_input(struct ir3_context *ctx, unsigned compmask)
{
struct ir3_instruction *in;
in = ir3_instr_create(ctx->in_block, OPC_META_INPUT, 1);
in->input.sysval = ~0;
__ssa_dst(in)->wrmask = compmask;
array_insert(ctx->ir, ctx->ir->inputs, in);
return in;
}
static struct ir3_instruction *
create_frag_input(struct ir3_context *ctx, struct ir3_instruction *coord, unsigned n)
{
struct ir3_block *block = ctx->block;
struct ir3_instruction *instr;
/* packed inloc is fixed up later: */
struct ir3_instruction *inloc = create_immed(block, n);
if (coord) {
instr = ir3_BARY_F(block, inloc, 0, coord, 0);
} else if (ctx->compiler->flat_bypass) {
instr = ir3_LDLV(block, inloc, 0, create_immed(block, 1), 0);
instr->cat6.type = TYPE_U32;
instr->cat6.iim_val = 1;
} else {
instr = ir3_BARY_F(block, inloc, 0, ctx->ij[IJ_PERSP_PIXEL], 0);
instr->regs[2]->wrmask = 0x3;
}
return instr;
}
static struct ir3_instruction *
create_driver_param(struct ir3_context *ctx, enum ir3_driver_param dp)
{
/* first four vec4 sysval's reserved for UBOs: */
/* NOTE: dp is in scalar, but there can be >4 dp components: */
struct ir3_const_state *const_state = ir3_const_state(ctx->so);
unsigned n = const_state->offsets.driver_param;
unsigned r = regid(n + dp / 4, dp % 4);
return create_uniform(ctx->block, r);
}
/*
* Adreno's comparisons produce a 1 for true and 0 for false, in either 16 or
* 32-bit registers. We use NIR's 1-bit integers to represent bools, and
* trust that we will only see and/or/xor on those 1-bit values, so we can
* safely store NIR i1s in a 32-bit reg while always containing either a 1 or
* 0.
*/
/*
* alu/sfu instructions:
*/
static struct ir3_instruction *
create_cov(struct ir3_context *ctx, struct ir3_instruction *src,
unsigned src_bitsize, nir_op op)
{
type_t src_type, dst_type;
switch (op) {
case nir_op_f2f32:
case nir_op_f2f16_rtne:
case nir_op_f2f16_rtz:
case nir_op_f2f16:
case nir_op_f2i32:
case nir_op_f2i16:
case nir_op_f2i8:
case nir_op_f2u32:
case nir_op_f2u16:
case nir_op_f2u8:
switch (src_bitsize) {
case 32:
src_type = TYPE_F32;
break;
case 16:
src_type = TYPE_F16;
break;
default:
ir3_context_error(ctx, "invalid src bit size: %u", src_bitsize);
}
break;
case nir_op_i2f32:
case nir_op_i2f16:
case nir_op_i2i32:
case nir_op_i2i16:
case nir_op_i2i8:
switch (src_bitsize) {
case 32:
src_type = TYPE_S32;
break;
case 16:
src_type = TYPE_S16;
break;
case 8:
src_type = TYPE_S8;
break;
default:
ir3_context_error(ctx, "invalid src bit size: %u", src_bitsize);
}
break;
case nir_op_u2f32:
case nir_op_u2f16:
case nir_op_u2u32:
case nir_op_u2u16:
case nir_op_u2u8:
switch (src_bitsize) {
case 32:
src_type = TYPE_U32;
break;
case 16:
src_type = TYPE_U16;
break;
case 8:
src_type = TYPE_U8;
break;
default:
ir3_context_error(ctx, "invalid src bit size: %u", src_bitsize);
}
break;
case nir_op_b2f16:
case nir_op_b2f32:
case nir_op_b2i8:
case nir_op_b2i16:
case nir_op_b2i32:
src_type = TYPE_U32;
break;
default:
ir3_context_error(ctx, "invalid conversion op: %u", op);
}
switch (op) {
case nir_op_f2f32:
case nir_op_i2f32:
case nir_op_u2f32:
case nir_op_b2f32:
dst_type = TYPE_F32;
break;
case nir_op_f2f16_rtne:
case nir_op_f2f16_rtz:
case nir_op_f2f16:
case nir_op_i2f16:
case nir_op_u2f16:
case nir_op_b2f16:
dst_type = TYPE_F16;
break;
case nir_op_f2i32:
case nir_op_i2i32:
case nir_op_b2i32:
dst_type = TYPE_S32;
break;
case nir_op_f2i16:
case nir_op_i2i16:
case nir_op_b2i16:
dst_type = TYPE_S16;
break;
case nir_op_f2i8:
case nir_op_i2i8:
case nir_op_b2i8:
dst_type = TYPE_S8;
break;
case nir_op_f2u32:
case nir_op_u2u32:
dst_type = TYPE_U32;
break;
case nir_op_f2u16:
case nir_op_u2u16:
dst_type = TYPE_U16;
break;
case nir_op_f2u8:
case nir_op_u2u8:
dst_type = TYPE_U8;
break;
default:
ir3_context_error(ctx, "invalid conversion op: %u", op);
}
if (src_type == dst_type)
return src;
struct ir3_instruction *cov =
ir3_COV(ctx->block, src, src_type, dst_type);
if (op == nir_op_f2f16_rtne)
cov->regs[0]->flags |= IR3_REG_EVEN;
return cov;
}
static void
emit_alu(struct ir3_context *ctx, nir_alu_instr *alu)
{
const nir_op_info *info = &nir_op_infos[alu->op];
struct ir3_instruction **dst, *src[info->num_inputs];
unsigned bs[info->num_inputs]; /* bit size */
struct ir3_block *b = ctx->block;
unsigned dst_sz, wrmask;
type_t dst_type = nir_dest_bit_size(alu->dest.dest) == 16 ?
TYPE_U16 : TYPE_U32;
if (alu->dest.dest.is_ssa) {
dst_sz = alu->dest.dest.ssa.num_components;
wrmask = (1 << dst_sz) - 1;
} else {
dst_sz = alu->dest.dest.reg.reg->num_components;
wrmask = alu->dest.write_mask;
}
dst = ir3_get_dst(ctx, &alu->dest.dest, dst_sz);
/* Vectors are special in that they have non-scalarized writemasks,
* and just take the first swizzle channel for each argument in
* order into each writemask channel.
*/
if ((alu->op == nir_op_vec2) ||
(alu->op == nir_op_vec3) ||
(alu->op == nir_op_vec4)) {
for (int i = 0; i < info->num_inputs; i++) {
nir_alu_src *asrc = &alu->src[i];
compile_assert(ctx, !asrc->abs);
compile_assert(ctx, !asrc->negate);
src[i] = ir3_get_src(ctx, &asrc->src)[asrc->swizzle[0]];
if (!src[i])
src[i] = create_immed_typed(ctx->block, 0, dst_type);
dst[i] = ir3_MOV(b, src[i], dst_type);
}
ir3_put_dst(ctx, &alu->dest.dest);
return;
}
/* We also get mov's with more than one component for mov's so
* handle those specially:
*/
if (alu->op == nir_op_mov) {
nir_alu_src *asrc = &alu->src[0];
struct ir3_instruction *const *src0 = ir3_get_src(ctx, &asrc->src);
for (unsigned i = 0; i < dst_sz; i++) {
if (wrmask & (1 << i)) {
dst[i] = ir3_MOV(b, src0[asrc->swizzle[i]], dst_type);
} else {
dst[i] = NULL;
}
}
ir3_put_dst(ctx, &alu->dest.dest);
return;
}
/* General case: We can just grab the one used channel per src. */
for (int i = 0; i < info->num_inputs; i++) {
unsigned chan = ffs(alu->dest.write_mask) - 1;
nir_alu_src *asrc = &alu->src[i];
compile_assert(ctx, !asrc->abs);
compile_assert(ctx, !asrc->negate);
src[i] = ir3_get_src(ctx, &asrc->src)[asrc->swizzle[chan]];
bs[i] = nir_src_bit_size(asrc->src);
compile_assert(ctx, src[i]);
}
switch (alu->op) {
case nir_op_f2f32:
case nir_op_f2f16_rtne:
case nir_op_f2f16_rtz:
case nir_op_f2f16:
case nir_op_f2i32:
case nir_op_f2i16:
case nir_op_f2i8:
case nir_op_f2u32:
case nir_op_f2u16:
case nir_op_f2u8:
case nir_op_i2f32:
case nir_op_i2f16:
case nir_op_i2i32:
case nir_op_i2i16:
case nir_op_i2i8:
case nir_op_u2f32:
case nir_op_u2f16:
case nir_op_u2u32:
case nir_op_u2u16:
case nir_op_u2u8:
case nir_op_b2f16:
case nir_op_b2f32:
case nir_op_b2i8:
case nir_op_b2i16:
case nir_op_b2i32:
dst[0] = create_cov(ctx, src[0], bs[0], alu->op);
break;
case nir_op_fquantize2f16:
dst[0] = create_cov(ctx,
create_cov(ctx, src[0], 32, nir_op_f2f16),
16, nir_op_f2f32);
break;
case nir_op_f2b1:
dst[0] = ir3_CMPS_F(b,
src[0], 0,
create_immed_typed(b, 0, bs[0] == 16 ? TYPE_F16 : TYPE_F32), 0);
dst[0]->cat2.condition = IR3_COND_NE;
break;
case nir_op_i2b1:
/* i2b1 will appear when translating from nir_load_ubo or
* nir_intrinsic_load_ssbo, where any non-zero value is true.
*/
dst[0] = ir3_CMPS_S(b, src[0], 0, create_immed(b, 0), 0);
dst[0]->cat2.condition = IR3_COND_NE;
break;
case nir_op_b2b1:
/* b2b1 will appear when translating from
*
* - nir_intrinsic_load_shared of a 32-bit 0/~0 value.
* - nir_intrinsic_load_constant of a 32-bit 0/~0 value
*
* A negate can turn those into a 1 or 0 for us.
*/
dst[0] = ir3_ABSNEG_S(b, src[0], IR3_REG_SNEG);
break;
case nir_op_b2b32:
/* b2b32 will appear when converting our 1-bit bools to a store_shared
* argument.
*
* A negate can turn those into a ~0 for us.
*/
dst[0] = ir3_ABSNEG_S(b, src[0], IR3_REG_SNEG);
break;
case nir_op_fneg:
dst[0] = ir3_ABSNEG_F(b, src[0], IR3_REG_FNEG);
break;
case nir_op_fabs:
dst[0] = ir3_ABSNEG_F(b, src[0], IR3_REG_FABS);
break;
case nir_op_fmax:
dst[0] = ir3_MAX_F(b, src[0], 0, src[1], 0);
break;
case nir_op_fmin:
dst[0] = ir3_MIN_F(b, src[0], 0, src[1], 0);
break;
case nir_op_fsat:
/* if there is just a single use of the src, and it supports
* (sat) bit, we can just fold the (sat) flag back to the
* src instruction and create a mov. This is easier for cp
* to eliminate.
*
* NOTE: a3xx definitely seen not working with flat bary.f. Same test
* uses ldlv on a4xx+, so not definitive. Seems rare enough to apply
* everywhere.
*
* TODO probably opc_cat==4 is ok too
*/
if (alu->src[0].src.is_ssa &&
src[0]->opc != OPC_BARY_F &&
(list_length(&alu->src[0].src.ssa->uses) == 1) &&
((opc_cat(src[0]->opc) == 2) || (opc_cat(src[0]->opc) == 3))) {
src[0]->flags |= IR3_INSTR_SAT;
dst[0] = ir3_MOV(b, src[0], dst_type);
} else {
/* otherwise generate a max.f that saturates.. blob does
* similar (generating a cat2 mov using max.f)
*/
dst[0] = ir3_MAX_F(b, src[0], 0, src[0], 0);
dst[0]->flags |= IR3_INSTR_SAT;
}
break;
case nir_op_fmul:
dst[0] = ir3_MUL_F(b, src[0], 0, src[1], 0);
break;
case nir_op_fadd:
dst[0] = ir3_ADD_F(b, src[0], 0, src[1], 0);
break;
case nir_op_fsub:
dst[0] = ir3_ADD_F(b, src[0], 0, src[1], IR3_REG_FNEG);
break;
case nir_op_ffma:
dst[0] = ir3_MAD_F32(b, src[0], 0, src[1], 0, src[2], 0);
break;
case nir_op_fddx:
case nir_op_fddx_coarse:
dst[0] = ir3_DSX(b, src[0], 0);
dst[0]->cat5.type = TYPE_F32;
break;
case nir_op_fddx_fine:
dst[0] = ir3_DSXPP_MACRO(b, src[0], 0);
dst[0]->cat5.type = TYPE_F32;
break;
case nir_op_fddy:
case nir_op_fddy_coarse:
dst[0] = ir3_DSY(b, src[0], 0);
dst[0]->cat5.type = TYPE_F32;
break;
break;
case nir_op_fddy_fine:
dst[0] = ir3_DSYPP_MACRO(b, src[0], 0);
dst[0]->cat5.type = TYPE_F32;
break;
case nir_op_flt:
dst[0] = ir3_CMPS_F(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_LT;
break;
case nir_op_fge:
dst[0] = ir3_CMPS_F(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_GE;
break;
case nir_op_feq:
dst[0] = ir3_CMPS_F(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_EQ;
break;
case nir_op_fneu:
dst[0] = ir3_CMPS_F(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_NE;
break;
case nir_op_fceil:
dst[0] = ir3_CEIL_F(b, src[0], 0);
break;
case nir_op_ffloor:
dst[0] = ir3_FLOOR_F(b, src[0], 0);
break;
case nir_op_ftrunc:
dst[0] = ir3_TRUNC_F(b, src[0], 0);
break;
case nir_op_fround_even:
dst[0] = ir3_RNDNE_F(b, src[0], 0);
break;
case nir_op_fsign:
dst[0] = ir3_SIGN_F(b, src[0], 0);
break;
case nir_op_fsin:
dst[0] = ir3_SIN(b, src[0], 0);
break;
case nir_op_fcos:
dst[0] = ir3_COS(b, src[0], 0);
break;
case nir_op_frsq:
dst[0] = ir3_RSQ(b, src[0], 0);
break;
case nir_op_frcp:
dst[0] = ir3_RCP(b, src[0], 0);
break;
case nir_op_flog2:
dst[0] = ir3_LOG2(b, src[0], 0);
break;
case nir_op_fexp2:
dst[0] = ir3_EXP2(b, src[0], 0);
break;
case nir_op_fsqrt:
dst[0] = ir3_SQRT(b, src[0], 0);
break;
case nir_op_iabs:
dst[0] = ir3_ABSNEG_S(b, src[0], IR3_REG_SABS);
break;
case nir_op_iadd:
dst[0] = ir3_ADD_U(b, src[0], 0, src[1], 0);
break;
case nir_op_iand:
dst[0] = ir3_AND_B(b, src[0], 0, src[1], 0);
break;
case nir_op_imax:
dst[0] = ir3_MAX_S(b, src[0], 0, src[1], 0);
break;
case nir_op_umax:
dst[0] = ir3_MAX_U(b, src[0], 0, src[1], 0);
break;
case nir_op_imin:
dst[0] = ir3_MIN_S(b, src[0], 0, src[1], 0);
break;
case nir_op_umin:
dst[0] = ir3_MIN_U(b, src[0], 0, src[1], 0);
break;
case nir_op_umul_low:
dst[0] = ir3_MULL_U(b, src[0], 0, src[1], 0);
break;
case nir_op_imadsh_mix16:
dst[0] = ir3_MADSH_M16(b, src[0], 0, src[1], 0, src[2], 0);
break;
case nir_op_imad24_ir3:
dst[0] = ir3_MAD_S24(b, src[0], 0, src[1], 0, src[2], 0);
break;
case nir_op_imul24:
dst[0] = ir3_MUL_S24(b, src[0], 0, src[1], 0);
break;
case nir_op_ineg:
dst[0] = ir3_ABSNEG_S(b, src[0], IR3_REG_SNEG);
break;
case nir_op_inot:
if (bs[0] == 1) {
dst[0] = ir3_SUB_U(b, create_immed(ctx->block, 1), 0, src[0], 0);
} else {
dst[0] = ir3_NOT_B(b, src[0], 0);
}
break;
case nir_op_ior:
dst[0] = ir3_OR_B(b, src[0], 0, src[1], 0);
break;
case nir_op_ishl:
dst[0] = ir3_SHL_B(b, src[0], 0, src[1], 0);
break;
case nir_op_ishr:
dst[0] = ir3_ASHR_B(b, src[0], 0, src[1], 0);
break;
case nir_op_isub:
dst[0] = ir3_SUB_U(b, src[0], 0, src[1], 0);
break;
case nir_op_ixor:
dst[0] = ir3_XOR_B(b, src[0], 0, src[1], 0);
break;
case nir_op_ushr:
dst[0] = ir3_SHR_B(b, src[0], 0, src[1], 0);
break;
case nir_op_ilt:
dst[0] = ir3_CMPS_S(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_LT;
break;
case nir_op_ige:
dst[0] = ir3_CMPS_S(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_GE;
break;
case nir_op_ieq:
dst[0] = ir3_CMPS_S(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_EQ;
break;
case nir_op_ine:
dst[0] = ir3_CMPS_S(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_NE;
break;
case nir_op_ult:
dst[0] = ir3_CMPS_U(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_LT;
break;
case nir_op_uge:
dst[0] = ir3_CMPS_U(b, src[0], 0, src[1], 0);
dst[0]->cat2.condition = IR3_COND_GE;
break;
case nir_op_bcsel: {
struct ir3_instruction *cond = src[0];
/* If src[0] is a negation (likely as a result of an ir3_b2n(cond)),
* we can ignore that and use original cond, since the nonzero-ness of
* cond stays the same.
*/
if (cond->opc == OPC_ABSNEG_S &&
cond->flags == 0 &&
(cond->regs[1]->flags & (IR3_REG_SNEG | IR3_REG_SABS)) == IR3_REG_SNEG) {
cond = cond->regs[1]->instr;
}
compile_assert(ctx, bs[1] == bs[2]);
/* The condition's size has to match the other two arguments' size, so
* convert down if necessary.
*/
if (bs[1] == 16) {
struct hash_entry *prev_entry =
_mesa_hash_table_search(ctx->sel_cond_conversions, src[0]);
if (prev_entry) {
cond = prev_entry->data;
} else {
cond = ir3_COV(b, cond, TYPE_U32, TYPE_U16);
_mesa_hash_table_insert(ctx->sel_cond_conversions, src[0], cond);
}
}
if (bs[1] != 16)
dst[0] = ir3_SEL_B32(b, src[1], 0, cond, 0, src[2], 0);
else
dst[0] = ir3_SEL_B16(b, src[1], 0, cond, 0, src[2], 0);
break;
}
case nir_op_bit_count: {
// TODO, we need to do this 16b at a time on a5xx+a6xx.. need to
// double check on earlier gen's. Once half-precision support is
// in place, this should probably move to a NIR lowering pass:
struct ir3_instruction *hi, *lo;
hi = ir3_COV(b, ir3_SHR_B(b, src[0], 0, create_immed(b, 16), 0),
TYPE_U32, TYPE_U16);
lo = ir3_COV(b, src[0], TYPE_U32, TYPE_U16);
hi = ir3_CBITS_B(b, hi, 0);
lo = ir3_CBITS_B(b, lo, 0);
// TODO maybe the builders should default to making dst half-precision
// if the src's were half precision, to make this less awkward.. otoh
// we should probably just do this lowering in NIR.
hi->regs[0]->flags |= IR3_REG_HALF;
lo->regs[0]->flags |= IR3_REG_HALF;
dst[0] = ir3_ADD_S(b, hi, 0, lo, 0);
dst[0]->regs[0]->flags |= IR3_REG_HALF;
dst[0] = ir3_COV(b, dst[0], TYPE_U16, TYPE_U32);
break;
}
case nir_op_ifind_msb: {
struct ir3_instruction *cmp;
dst[0] = ir3_CLZ_S(b, src[0], 0);
cmp = ir3_CMPS_S(b, dst[0], 0, create_immed(b, 0), 0);
cmp->cat2.condition = IR3_COND_GE;
dst[0] = ir3_SEL_B32(b,
ir3_SUB_U(b, create_immed(b, 31), 0, dst[0], 0), 0,
cmp, 0, dst[0], 0);
break;
}
case nir_op_ufind_msb:
dst[0] = ir3_CLZ_B(b, src[0], 0);
dst[0] = ir3_SEL_B32(b,
ir3_SUB_U(b, create_immed(b, 31), 0, dst[0], 0), 0,
src[0], 0, dst[0], 0);
break;
case nir_op_find_lsb:
dst[0] = ir3_BFREV_B(b, src[0], 0);
dst[0] = ir3_CLZ_B(b, dst[0], 0);
break;
case nir_op_bitfield_reverse:
dst[0] = ir3_BFREV_B(b, src[0], 0);
break;
default:
ir3_context_error(ctx, "Unhandled ALU op: %s\n",
nir_op_infos[alu->op].name);
break;
}
if (nir_alu_type_get_base_type(info->output_type) == nir_type_bool) {
assert(nir_dest_bit_size(alu->dest.dest) == 1 ||
alu->op == nir_op_b2b32);
assert(dst_sz == 1);
} else {
/* 1-bit values stored in 32-bit registers are only valid for certain
* ALU ops.
*/
switch (alu->op) {
case nir_op_iand:
case nir_op_ior:
case nir_op_ixor:
case nir_op_inot:
case nir_op_bcsel:
break;
default:
compile_assert(ctx, nir_dest_bit_size(alu->dest.dest) != 1);
}
}
ir3_put_dst(ctx, &alu->dest.dest);
}
static void
emit_intrinsic_load_ubo_ldc(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
unsigned ncomp = intr->num_components;
struct ir3_instruction *offset = ir3_get_src(ctx, &intr->src[1])[0];
struct ir3_instruction *idx = ir3_get_src(ctx, &intr->src[0])[0];
struct ir3_instruction *ldc = ir3_LDC(b, idx, 0, offset, 0);
ldc->regs[0]->wrmask = MASK(ncomp);
ldc->cat6.iim_val = ncomp;
ldc->cat6.d = nir_intrinsic_component(intr);
ldc->cat6.type = TYPE_U32;
ir3_handle_bindless_cat6(ldc, intr->src[0]);
if (ldc->flags & IR3_INSTR_B)
ctx->so->bindless_ubo = true;
ir3_split_dest(b, dst, ldc, 0, ncomp);
}
/* handles direct/indirect UBO reads: */
static void
emit_intrinsic_load_ubo(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *base_lo, *base_hi, *addr, *src0, *src1;
const struct ir3_const_state *const_state = ir3_const_state(ctx->so);
unsigned ubo = regid(const_state->offsets.ubo, 0);
const unsigned ptrsz = ir3_pointer_size(ctx->compiler);
int off = 0;
/* First src is ubo index, which could either be an immed or not: */
src0 = ir3_get_src(ctx, &intr->src[0])[0];
if (is_same_type_mov(src0) &&
(src0->regs[1]->flags & IR3_REG_IMMED)) {
base_lo = create_uniform(b, ubo + (src0->regs[1]->iim_val * ptrsz));
base_hi = create_uniform(b, ubo + (src0->regs[1]->iim_val * ptrsz) + 1);
} else {
base_lo = create_uniform_indirect(b, ubo, TYPE_U32, ir3_get_addr0(ctx, src0, ptrsz));
base_hi = create_uniform_indirect(b, ubo + 1, TYPE_U32, ir3_get_addr0(ctx, src0, ptrsz));
/* NOTE: since relative addressing is used, make sure constlen is
* at least big enough to cover all the UBO addresses, since the
* assembler won't know what the max address reg is.
*/
ctx->so->constlen = MAX2(ctx->so->constlen,
const_state->offsets.ubo + (ctx->s->info.num_ubos * ptrsz));
}
/* note: on 32bit gpu's base_hi is ignored and DCE'd */
addr = base_lo;
if (nir_src_is_const(intr->src[1])) {
off += nir_src_as_uint(intr->src[1]);
} else {
/* For load_ubo_indirect, second src is indirect offset: */
src1 = ir3_get_src(ctx, &intr->src[1])[0];
/* and add offset to addr: */
addr = ir3_ADD_S(b, addr, 0, src1, 0);
}
/* if offset is to large to encode in the ldg, split it out: */
if ((off + (intr->num_components * 4)) > 1024) {
/* split out the minimal amount to improve the odds that
* cp can fit the immediate in the add.s instruction:
*/
unsigned off2 = off + (intr->num_components * 4) - 1024;
addr = ir3_ADD_S(b, addr, 0, create_immed(b, off2), 0);
off -= off2;
}
if (ptrsz == 2) {
struct ir3_instruction *carry;
/* handle 32b rollover, ie:
* if (addr < base_lo)
* base_hi++
*/
carry = ir3_CMPS_U(b, addr, 0, base_lo, 0);
carry->cat2.condition = IR3_COND_LT;
base_hi = ir3_ADD_S(b, base_hi, 0, carry, 0);
addr = ir3_create_collect(ctx, (struct ir3_instruction*[]){ addr, base_hi }, 2);
}
for (int i = 0; i < intr->num_components; i++) {
struct ir3_instruction *load =
ir3_LDG(b, addr, 0,
create_immed(b, off + i * 4), 0,
create_immed(b, 1), 0); /* num components */
load->cat6.type = TYPE_U32;
dst[i] = load;
}
}
/* src[] = { block_index } */
static void
emit_intrinsic_ssbo_size(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
if (ir3_bindless_resource(intr->src[0])) {
struct ir3_block *b = ctx->block;
struct ir3_instruction *ibo = ir3_ssbo_to_ibo(ctx, intr->src[0]);
struct ir3_instruction *resinfo = ir3_RESINFO(b, ibo, 0);
resinfo->cat6.iim_val = 1;
resinfo->cat6.d = 1;
resinfo->cat6.type = TYPE_U32;
resinfo->cat6.typed = false;
/* resinfo has no writemask and always writes out 3 components */
resinfo->regs[0]->wrmask = MASK(3);
ir3_handle_bindless_cat6(resinfo, intr->src[0]);
struct ir3_instruction *resinfo_dst;
ir3_split_dest(b, &resinfo_dst, resinfo, 0, 1);
/* Unfortunately resinfo returns the array length, i.e. in dwords,
* while NIR expects us to return the size in bytes.
*
* TODO: fix this in NIR.
*/
*dst = ir3_SHL_B(b, resinfo_dst, 0, create_immed(b, 2), 0);
return;
}
/* SSBO size stored as a const starting at ssbo_sizes: */
const struct ir3_const_state *const_state = ir3_const_state(ctx->so);
unsigned blk_idx = nir_src_as_uint(intr->src[0]);
unsigned idx = regid(const_state->offsets.ssbo_sizes, 0) +
const_state->ssbo_size.off[blk_idx];
debug_assert(const_state->ssbo_size.mask & (1 << blk_idx));
dst[0] = create_uniform(ctx->block, idx);
}
/* src[] = { offset }. const_index[] = { base } */
static void
emit_intrinsic_load_shared(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *ldl, *offset;
unsigned base;
offset = ir3_get_src(ctx, &intr->src[0])[0];
base = nir_intrinsic_base(intr);
ldl = ir3_LDL(b, offset, 0,
create_immed(b, base), 0,
create_immed(b, intr->num_components), 0);
ldl->cat6.type = utype_dst(intr->dest);
ldl->regs[0]->wrmask = MASK(intr->num_components);
ldl->barrier_class = IR3_BARRIER_SHARED_R;
ldl->barrier_conflict = IR3_BARRIER_SHARED_W;
ir3_split_dest(b, dst, ldl, 0, intr->num_components);
}
/* src[] = { value, offset }. const_index[] = { base, write_mask } */
static void
emit_intrinsic_store_shared(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *stl, *offset;
struct ir3_instruction * const *value;
unsigned base, wrmask, ncomp;
value = ir3_get_src(ctx, &intr->src[0]);
offset = ir3_get_src(ctx, &intr->src[1])[0];
base = nir_intrinsic_base(intr);
wrmask = nir_intrinsic_write_mask(intr);
ncomp = ffs(~wrmask) - 1;
assert(wrmask == BITFIELD_MASK(intr->num_components));
stl = ir3_STL(b, offset, 0,
ir3_create_collect(ctx, value, ncomp), 0,
create_immed(b, ncomp), 0);
stl->cat6.dst_offset = base;
stl->cat6.type = utype_src(intr->src[0]);
stl->barrier_class = IR3_BARRIER_SHARED_W;
stl->barrier_conflict = IR3_BARRIER_SHARED_R | IR3_BARRIER_SHARED_W;
array_insert(b, b->keeps, stl);
}
/* src[] = { offset }. const_index[] = { base } */
static void
emit_intrinsic_load_shared_ir3(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *load, *offset;
unsigned base;
offset = ir3_get_src(ctx, &intr->src[0])[0];
base = nir_intrinsic_base(intr);
load = ir3_LDLW(b, offset, 0,
create_immed(b, base), 0,
create_immed(b, intr->num_components), 0);
/* for a650, use LDL for tess ctrl inputs: */
if (ctx->so->type == MESA_SHADER_TESS_CTRL && ctx->compiler->tess_use_shared)
load->opc = OPC_LDL;
load->cat6.type = utype_dst(intr->dest);
load->regs[0]->wrmask = MASK(intr->num_components);
load->barrier_class = IR3_BARRIER_SHARED_R;
load->barrier_conflict = IR3_BARRIER_SHARED_W;
ir3_split_dest(b, dst, load, 0, intr->num_components);
}
/* src[] = { value, offset }. const_index[] = { base } */
static void
emit_intrinsic_store_shared_ir3(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *store, *offset;
struct ir3_instruction * const *value;
value = ir3_get_src(ctx, &intr->src[0]);
offset = ir3_get_src(ctx, &intr->src[1])[0];
store = ir3_STLW(b, offset, 0,
ir3_create_collect(ctx, value, intr->num_components), 0,
create_immed(b, intr->num_components), 0);
/* for a650, use STL for vertex outputs used by tess ctrl shader: */
if (ctx->so->type == MESA_SHADER_VERTEX && ctx->so->key.tessellation &&
ctx->compiler->tess_use_shared)
store->opc = OPC_STL;
store->cat6.dst_offset = nir_intrinsic_base(intr);
store->cat6.type = utype_src(intr->src[0]);
store->barrier_class = IR3_BARRIER_SHARED_W;
store->barrier_conflict = IR3_BARRIER_SHARED_R | IR3_BARRIER_SHARED_W;
array_insert(b, b->keeps, store);
}
/*
* CS shared variable atomic intrinsics
*
* All of the shared variable atomic memory operations read a value from
* memory, compute a new value using one of the operations below, write the
* new value to memory, and return the original value read.
*
* All operations take 2 sources except CompSwap that takes 3. These
* sources represent:
*
* 0: The offset into the shared variable storage region that the atomic
* operation will operate on.
* 1: The data parameter to the atomic function (i.e. the value to add
* in shared_atomic_add, etc).
* 2: For CompSwap only: the second data parameter.
*/
static struct ir3_instruction *
emit_intrinsic_atomic_shared(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *atomic, *src0, *src1;
type_t type = TYPE_U32;
src0 = ir3_get_src(ctx, &intr->src[0])[0]; /* offset */
src1 = ir3_get_src(ctx, &intr->src[1])[0]; /* value */
switch (intr->intrinsic) {
case nir_intrinsic_shared_atomic_add:
atomic = ir3_ATOMIC_ADD(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_imin:
atomic = ir3_ATOMIC_MIN(b, src0, 0, src1, 0);
type = TYPE_S32;
break;
case nir_intrinsic_shared_atomic_umin:
atomic = ir3_ATOMIC_MIN(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_imax:
atomic = ir3_ATOMIC_MAX(b, src0, 0, src1, 0);
type = TYPE_S32;
break;
case nir_intrinsic_shared_atomic_umax:
atomic = ir3_ATOMIC_MAX(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_and:
atomic = ir3_ATOMIC_AND(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_or:
atomic = ir3_ATOMIC_OR(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_xor:
atomic = ir3_ATOMIC_XOR(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_exchange:
atomic = ir3_ATOMIC_XCHG(b, src0, 0, src1, 0);
break;
case nir_intrinsic_shared_atomic_comp_swap:
/* for cmpxchg, src1 is [ui]vec2(data, compare): */
src1 = ir3_create_collect(ctx, (struct ir3_instruction*[]){
ir3_get_src(ctx, &intr->src[2])[0],
src1,
}, 2);
atomic = ir3_ATOMIC_CMPXCHG(b, src0, 0, src1, 0);
break;
default:
unreachable("boo");
}
atomic->cat6.iim_val = 1;
atomic->cat6.d = 1;
atomic->cat6.type = type;
atomic->barrier_class = IR3_BARRIER_SHARED_W;
atomic->barrier_conflict = IR3_BARRIER_SHARED_R | IR3_BARRIER_SHARED_W;
/* even if nothing consume the result, we can't DCE the instruction: */
array_insert(b, b->keeps, atomic);
return atomic;
}
/* src[] = { offset }. */
static void
emit_intrinsic_load_scratch(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *ldp, *offset;
offset = ir3_get_src(ctx, &intr->src[0])[0];
ldp = ir3_LDP(b, offset, 0,
create_immed(b, 0), 0,
create_immed(b, intr->num_components), 0);
ldp->cat6.type = utype_dst(intr->dest);
ldp->regs[0]->wrmask = MASK(intr->num_components);
ldp->barrier_class = IR3_BARRIER_PRIVATE_R;
ldp->barrier_conflict = IR3_BARRIER_PRIVATE_W;
ir3_split_dest(b, dst, ldp, 0, intr->num_components);
}
/* src[] = { value, offset }. const_index[] = { write_mask } */
static void
emit_intrinsic_store_scratch(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *stp, *offset;
struct ir3_instruction * const *value;
unsigned wrmask, ncomp;
value = ir3_get_src(ctx, &intr->src[0]);
offset = ir3_get_src(ctx, &intr->src[1])[0];
wrmask = nir_intrinsic_write_mask(intr);
ncomp = ffs(~wrmask) - 1;
assert(wrmask == BITFIELD_MASK(intr->num_components));
stp = ir3_STP(b, offset, 0,
ir3_create_collect(ctx, value, ncomp), 0,
create_immed(b, ncomp), 0);
stp->cat6.dst_offset = 0;
stp->cat6.type = utype_src(intr->src[0]);
stp->barrier_class = IR3_BARRIER_PRIVATE_W;
stp->barrier_conflict = IR3_BARRIER_PRIVATE_R | IR3_BARRIER_PRIVATE_W;
array_insert(b, b->keeps, stp);
}
struct tex_src_info {
/* For prefetch */
unsigned tex_base, samp_base, tex_idx, samp_idx;
/* For normal tex instructions */
unsigned base, combined_idx, a1_val, flags;
struct ir3_instruction *samp_tex;
};
/* TODO handle actual indirect/dynamic case.. which is going to be weird
* to handle with the image_mapping table..
*/
static struct tex_src_info
get_image_samp_tex_src(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_block *b = ctx->block;
struct tex_src_info info = { 0 };
nir_intrinsic_instr *bindless_tex = ir3_bindless_resource(intr->src[0]);
ctx->so->bindless_tex = true;
if (bindless_tex) {
/* Bindless case */
info.flags |= IR3_INSTR_B;
/* Gather information required to determine which encoding to
* choose as well as for prefetch.
*/
info.tex_base = nir_intrinsic_desc_set(bindless_tex);
bool tex_const = nir_src_is_const(bindless_tex->src[0]);
if (tex_const)
info.tex_idx = nir_src_as_uint(bindless_tex->src[0]);
info.samp_idx = 0;
/* Choose encoding. */
if (tex_const && info.tex_idx < 256) {
if (info.tex_idx < 16) {
/* Everything fits within the instruction */
info.base = info.tex_base;
info.combined_idx = info.samp_idx | (info.tex_idx << 4);
} else {
info.base = info.tex_base;
info.a1_val = info.tex_idx << 3;
info.combined_idx = 0;
info.flags |= IR3_INSTR_A1EN;
}
info.samp_tex = NULL;
} else {
info.flags |= IR3_INSTR_S2EN;
info.base = info.tex_base;
/* Note: the indirect source is now a vec2 instead of hvec2 */
struct ir3_instruction *texture, *sampler;
texture = ir3_get_src(ctx, &intr->src[0])[0];
sampler = create_immed(b, 0);
info.samp_tex = ir3_create_collect(ctx, (struct ir3_instruction*[]){
texture,
sampler,
}, 2);
}
} else {
info.flags |= IR3_INSTR_S2EN;
unsigned slot = nir_src_as_uint(intr->src[0]);
unsigned tex_idx = ir3_image_to_tex(&ctx->so->image_mapping, slot);
struct ir3_instruction *texture, *sampler;
texture = create_immed_typed(ctx->block, tex_idx, TYPE_U16);
sampler = create_immed_typed(ctx->block, tex_idx, TYPE_U16);
info.samp_tex = ir3_create_collect(ctx, (struct ir3_instruction*[]){
sampler,
texture,
}, 2);
}
return info;
}
static struct ir3_instruction *
emit_sam(struct ir3_context *ctx, opc_t opc, struct tex_src_info info,
type_t type, unsigned wrmask, struct ir3_instruction *src0,
struct ir3_instruction *src1)
{
struct ir3_instruction *sam, *addr;
if (info.flags & IR3_INSTR_A1EN) {
addr = ir3_get_addr1(ctx, info.a1_val);
}
sam = ir3_SAM(ctx->block, opc, type, 0b1111, info.flags,
info.samp_tex, src0, src1);
if (info.flags & IR3_INSTR_A1EN) {
ir3_instr_set_address(sam, addr);
}
if (info.flags & IR3_INSTR_B) {
sam->cat5.tex_base = info.base;
sam->cat5.samp = info.combined_idx;
}
return sam;
}
/* src[] = { deref, coord, sample_index }. const_index[] = {} */
static void
emit_intrinsic_load_image(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
struct tex_src_info info = get_image_samp_tex_src(ctx, intr);
struct ir3_instruction *sam;
struct ir3_instruction * const *src0 = ir3_get_src(ctx, &intr->src[1]);
struct ir3_instruction *coords[4];
unsigned flags, ncoords = ir3_get_image_coords(intr, &flags);
type_t type = ir3_get_type_for_image_intrinsic(intr);
/* hmm, this seems a bit odd, but it is what blob does and (at least
* a5xx) just faults on bogus addresses otherwise:
*/
if (flags & IR3_INSTR_3D) {
flags &= ~IR3_INSTR_3D;
flags |= IR3_INSTR_A;
}
info.flags |= flags;
for (unsigned i = 0; i < ncoords; i++)
coords[i] = src0[i];
if (ncoords == 1)
coords[ncoords++] = create_immed(b, 0);
sam = emit_sam(ctx, OPC_ISAM, info, type, 0b1111,
ir3_create_collect(ctx, coords, ncoords), NULL);
sam->barrier_class = IR3_BARRIER_IMAGE_R;
sam->barrier_conflict = IR3_BARRIER_IMAGE_W;
ir3_split_dest(b, dst, sam, 0, 4);
}
/* A4xx version of image_size, see ir3_a6xx.c for newer resinfo version. */
void
emit_intrinsic_image_size_tex(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
struct ir3_block *b = ctx->block;
struct tex_src_info info = get_image_samp_tex_src(ctx, intr);
struct ir3_instruction *sam, *lod;
unsigned flags, ncoords = ir3_get_image_coords(intr, &flags);
type_t dst_type = nir_dest_bit_size(intr->dest) == 16 ?
TYPE_U16 : TYPE_U32;
info.flags |= flags;
assert(nir_src_as_uint(intr->src[1]) == 0);
lod = create_immed(b, 0);
sam = emit_sam(ctx, OPC_GETSIZE, info, dst_type, 0b1111, lod, NULL);
/* Array size actually ends up in .w rather than .z. This doesn't
* matter for miplevel 0, but for higher mips the value in z is
* minified whereas w stays. Also, the value in TEX_CONST_3_DEPTH is
* returned, which means that we have to add 1 to it for arrays for
* a3xx.
*
* Note use a temporary dst and then copy, since the size of the dst
* array that is passed in is based on nir's understanding of the
* result size, not the hardware's
*/
struct ir3_instruction *tmp[4];
ir3_split_dest(b, tmp, sam, 0, 4);
/* get_size instruction returns size in bytes instead of texels
* for imageBuffer, so we need to divide it by the pixel size
* of the image format.
*
* TODO: This is at least true on a5xx. Check other gens.
*/
if (nir_intrinsic_image_dim(intr) == GLSL_SAMPLER_DIM_BUF) {
/* Since all the possible values the divisor can take are
* power-of-two (4, 8, or 16), the division is implemented
* as a shift-right.
* During shader setup, the log2 of the image format's
* bytes-per-pixel should have been emitted in 2nd slot of
* image_dims. See ir3_shader::emit_image_dims().
*/
const struct ir3_const_state *const_state =
ir3_const_state(ctx->so);
unsigned cb = regid(const_state->offsets.image_dims, 0) +
const_state->image_dims.off[nir_src_as_uint(intr->src[0])];
struct ir3_instruction *aux = create_uniform(b, cb + 1);
tmp[0] = ir3_SHR_B(b, tmp[0], 0, aux, 0);
}
for (unsigned i = 0; i < ncoords; i++)
dst[i] = tmp[i];
if (flags & IR3_INSTR_A) {
if (ctx->compiler->levels_add_one) {
dst[ncoords-1] = ir3_ADD_U(b, tmp[3], 0, create_immed(b, 1), 0);
} else {
dst[ncoords-1] = ir3_MOV(b, tmp[3], TYPE_U32);
}
}
}
static void
emit_intrinsic_barrier(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction *barrier;
switch (intr->intrinsic) {
case nir_intrinsic_control_barrier:
barrier = ir3_BAR(b);
barrier->cat7.g = true;
barrier->cat7.l = true;
barrier->flags = IR3_INSTR_SS | IR3_INSTR_SY;
barrier->barrier_class = IR3_BARRIER_EVERYTHING;
break;
case nir_intrinsic_memory_barrier:
barrier = ir3_FENCE(b);
barrier->cat7.g = true;
barrier->cat7.r = true;
barrier->cat7.w = true;
barrier->cat7.l = true;
barrier->barrier_class = IR3_BARRIER_IMAGE_W |
IR3_BARRIER_BUFFER_W;
barrier->barrier_conflict =
IR3_BARRIER_IMAGE_R | IR3_BARRIER_IMAGE_W |
IR3_BARRIER_BUFFER_R | IR3_BARRIER_BUFFER_W;
break;
case nir_intrinsic_memory_barrier_buffer:
barrier = ir3_FENCE(b);
barrier->cat7.g = true;
barrier->cat7.r = true;
barrier->cat7.w = true;
barrier->barrier_class = IR3_BARRIER_BUFFER_W;
barrier->barrier_conflict = IR3_BARRIER_BUFFER_R |
IR3_BARRIER_BUFFER_W;
break;
case nir_intrinsic_memory_barrier_image:
// TODO double check if this should have .g set
barrier = ir3_FENCE(b);
barrier->cat7.g = true;
barrier->cat7.r = true;
barrier->cat7.w = true;
barrier->barrier_class = IR3_BARRIER_IMAGE_W;
barrier->barrier_conflict = IR3_BARRIER_IMAGE_R |
IR3_BARRIER_IMAGE_W;
break;
case nir_intrinsic_memory_barrier_shared:
barrier = ir3_FENCE(b);
barrier->cat7.g = true;
barrier->cat7.l = true;
barrier->cat7.r = true;
barrier->cat7.w = true;
barrier->barrier_class = IR3_BARRIER_SHARED_W;
barrier->barrier_conflict = IR3_BARRIER_SHARED_R |
IR3_BARRIER_SHARED_W;
break;
case nir_intrinsic_group_memory_barrier:
barrier = ir3_FENCE(b);
barrier->cat7.g = true;
barrier->cat7.l = true;
barrier->cat7.r = true;
barrier->cat7.w = true;
barrier->barrier_class = IR3_BARRIER_SHARED_W |
IR3_BARRIER_IMAGE_W |
IR3_BARRIER_BUFFER_W;
barrier->barrier_conflict =
IR3_BARRIER_SHARED_R | IR3_BARRIER_SHARED_W |
IR3_BARRIER_IMAGE_R | IR3_BARRIER_IMAGE_W |
IR3_BARRIER_BUFFER_R | IR3_BARRIER_BUFFER_W;
break;
default:
unreachable("boo");
}
/* make sure barrier doesn't get DCE'd */
array_insert(b, b->keeps, barrier);
}
static void add_sysval_input_compmask(struct ir3_context *ctx,
gl_system_value slot, unsigned compmask,
struct ir3_instruction *instr)
{
struct ir3_shader_variant *so = ctx->so;
unsigned n = so->inputs_count++;
assert(instr->opc == OPC_META_INPUT);
instr->input.inidx = n;
instr->input.sysval = slot;
so->inputs[n].sysval = true;
so->inputs[n].slot = slot;
so->inputs[n].compmask = compmask;
so->total_in++;
}
static struct ir3_instruction *
create_sysval_input(struct ir3_context *ctx, gl_system_value slot,
unsigned compmask)
{
assert(compmask);
struct ir3_instruction *sysval = create_input(ctx, compmask);
add_sysval_input_compmask(ctx, slot, compmask, sysval);
return sysval;
}
static struct ir3_instruction *
get_barycentric(struct ir3_context *ctx, enum ir3_bary bary)
{
static const gl_system_value sysval_base = SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL;
STATIC_ASSERT(sysval_base + IJ_PERSP_PIXEL == SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL);
STATIC_ASSERT(sysval_base + IJ_PERSP_SAMPLE == SYSTEM_VALUE_BARYCENTRIC_PERSP_SAMPLE);
STATIC_ASSERT(sysval_base + IJ_PERSP_CENTROID == SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTROID);
STATIC_ASSERT(sysval_base + IJ_PERSP_SIZE == SYSTEM_VALUE_BARYCENTRIC_PERSP_SIZE);
STATIC_ASSERT(sysval_base + IJ_LINEAR_PIXEL == SYSTEM_VALUE_BARYCENTRIC_LINEAR_PIXEL);
STATIC_ASSERT(sysval_base + IJ_LINEAR_CENTROID == SYSTEM_VALUE_BARYCENTRIC_LINEAR_CENTROID);
STATIC_ASSERT(sysval_base + IJ_LINEAR_SAMPLE == SYSTEM_VALUE_BARYCENTRIC_LINEAR_SAMPLE);
if (!ctx->ij[bary]) {
struct ir3_instruction *xy[2];
struct ir3_instruction *ij;
ij = create_sysval_input(ctx, sysval_base + bary, 0x3);
ir3_split_dest(ctx->block, xy, ij, 0, 2);
ctx->ij[bary] = ir3_create_collect(ctx, xy, 2);
}
return ctx->ij[bary];
}
/* TODO: make this a common NIR helper?
* there is a nir_system_value_from_intrinsic but it takes nir_intrinsic_op so it
* can't be extended to work with this
*/
static gl_system_value
nir_intrinsic_barycentric_sysval(nir_intrinsic_instr *intr)
{
enum glsl_interp_mode interp_mode = nir_intrinsic_interp_mode(intr);
gl_system_value sysval;
switch (intr->intrinsic) {
case nir_intrinsic_load_barycentric_pixel:
if (interp_mode == INTERP_MODE_NOPERSPECTIVE)
sysval = SYSTEM_VALUE_BARYCENTRIC_LINEAR_PIXEL;
else
sysval = SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL;
break;
case nir_intrinsic_load_barycentric_centroid:
if (interp_mode == INTERP_MODE_NOPERSPECTIVE)
sysval = SYSTEM_VALUE_BARYCENTRIC_LINEAR_CENTROID;
else
sysval = SYSTEM_VALUE_BARYCENTRIC_PERSP_CENTROID;
break;
case nir_intrinsic_load_barycentric_sample:
if (interp_mode == INTERP_MODE_NOPERSPECTIVE)
sysval = SYSTEM_VALUE_BARYCENTRIC_LINEAR_SAMPLE;
else
sysval = SYSTEM_VALUE_BARYCENTRIC_PERSP_SAMPLE;
break;
default:
unreachable("invalid barycentric intrinsic");
}
return sysval;
}
static void
emit_intrinsic_barycentric(struct ir3_context *ctx, nir_intrinsic_instr *intr,
struct ir3_instruction **dst)
{
gl_system_value sysval = nir_intrinsic_barycentric_sysval(intr);
if (!ctx->so->key.msaa) {
if (sysval == SYSTEM_VALUE_BARYCENTRIC_PERSP_SAMPLE)
sysval = SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL;
if (sysval == SYSTEM_VALUE_BARYCENTRIC_LINEAR_SAMPLE)
sysval = SYSTEM_VALUE_BARYCENTRIC_LINEAR_PIXEL;
}
enum ir3_bary bary = sysval - SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL;
struct ir3_instruction *ij = get_barycentric(ctx, bary);
ir3_split_dest(ctx->block, dst, ij, 0, 2);
}
static struct ir3_instruction *
get_frag_coord(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
if (!ctx->frag_coord) {
struct ir3_block *b = ctx->in_block;
struct ir3_instruction *xyzw[4];
struct ir3_instruction *hw_frag_coord;
hw_frag_coord = create_sysval_input(ctx, SYSTEM_VALUE_FRAG_COORD, 0xf);
ir3_split_dest(b, xyzw, hw_frag_coord, 0, 4);
/* for frag_coord.xy, we get unsigned values.. we need
* to subtract (integer) 8 and divide by 16 (right-
* shift by 4) then convert to float:
*
* sub.s tmp, src, 8
* shr.b tmp, tmp, 4
* mov.u32f32 dst, tmp
*
*/
for (int i = 0; i < 2; i++) {
xyzw[i] = ir3_COV(b, xyzw[i], TYPE_U32, TYPE_F32);
xyzw[i] = ir3_MUL_F(b, xyzw[i], 0, create_immed(b, fui(1.0 / 16.0)), 0);
}
ctx->frag_coord = ir3_create_collect(ctx, xyzw, 4);
}
ctx->so->fragcoord_compmask |=
nir_ssa_def_components_read(&intr->dest.ssa);
return ctx->frag_coord;
}
static void setup_input(struct ir3_context *ctx, nir_intrinsic_instr *intr);
static void setup_output(struct ir3_context *ctx, nir_intrinsic_instr *intr);
static void
emit_intrinsic(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
const nir_intrinsic_info *info = &nir_intrinsic_infos[intr->intrinsic];
struct ir3_instruction **dst;
struct ir3_instruction * const *src;
struct ir3_block *b = ctx->block;
unsigned dest_components = nir_intrinsic_dest_components(intr);
int idx;
if (info->has_dest) {
dst = ir3_get_dst(ctx, &intr->dest, dest_components);
} else {
dst = NULL;
}
const struct ir3_const_state *const_state = ir3_const_state(ctx->so);
const unsigned primitive_param = const_state->offsets.primitive_param * 4;
const unsigned primitive_map = const_state->offsets.primitive_map * 4;
switch (intr->intrinsic) {
case nir_intrinsic_load_uniform:
idx = nir_intrinsic_base(intr);
if (nir_src_is_const(intr->src[0])) {
idx += nir_src_as_uint(intr->src[0]);
for (int i = 0; i < dest_components; i++) {
dst[i] = create_uniform_typed(b, idx + i,
nir_dest_bit_size(intr->dest) == 16 ? TYPE_F16 : TYPE_F32);
}
} else {
src = ir3_get_src(ctx, &intr->src[0]);
for (int i = 0; i < dest_components; i++) {
dst[i] = create_uniform_indirect(b, idx + i,
nir_dest_bit_size(intr->dest) == 16 ? TYPE_F16 : TYPE_F32,
ir3_get_addr0(ctx, src[0], 1));
}
/* NOTE: if relative addressing is used, we set
* constlen in the compiler (to worst-case value)
* since we don't know in the assembler what the max
* addr reg value can be:
*/
ctx->so->constlen = MAX2(ctx->so->constlen,
const_state->ubo_state.size / 16);
}
break;
case nir_intrinsic_load_vs_primitive_stride_ir3:
dst[0] = create_uniform(b, primitive_param + 0);
break;
case nir_intrinsic_load_vs_vertex_stride_ir3:
dst[0] = create_uniform(b, primitive_param + 1);
break;
case nir_intrinsic_load_hs_patch_stride_ir3:
dst[0] = create_uniform(b, primitive_param + 2);
break;
case nir_intrinsic_load_patch_vertices_in:
dst[0] = create_uniform(b, primitive_param + 3);
break;
case nir_intrinsic_load_tess_param_base_ir3:
dst[0] = create_uniform(b, primitive_param + 4);
dst[1] = create_uniform(b, primitive_param + 5);
break;
case nir_intrinsic_load_tess_factor_base_ir3:
dst[0] = create_uniform(b, primitive_param + 6);
dst[1] = create_uniform(b, primitive_param + 7);
break;
case nir_intrinsic_load_primitive_location_ir3:
idx = nir_intrinsic_driver_location(intr);
dst[0] = create_uniform(b, primitive_map + idx);
break;
case nir_intrinsic_load_gs_header_ir3:
dst[0] = ctx->gs_header;
break;
case nir_intrinsic_load_tcs_header_ir3:
dst[0] = ctx->tcs_header;
break;
case nir_intrinsic_load_primitive_id:
dst[0] = ctx->primitive_id;
break;
case nir_intrinsic_load_tess_coord:
if (!ctx->tess_coord) {
ctx->tess_coord =
create_sysval_input(ctx, SYSTEM_VALUE_TESS_COORD, 0x3);
}
ir3_split_dest(b, dst, ctx->tess_coord, 0, 2);
/* Unused, but ir3_put_dst() below wants to free something */
dst[2] = create_immed(b, 0);
break;
case nir_intrinsic_end_patch_ir3:
assert(ctx->so->type == MESA_SHADER_TESS_CTRL);
struct ir3_instruction *end = ir3_PREDE(b);
array_insert(b, b->keeps, end);
end->barrier_class = IR3_BARRIER_EVERYTHING;
end->barrier_conflict = IR3_BARRIER_EVERYTHING;
break;
case nir_intrinsic_store_global_ir3: {
struct ir3_instruction *value, *addr, *offset;
unsigned ncomp = nir_intrinsic_src_components(intr, 0);
addr = ir3_create_collect(ctx, (struct ir3_instruction*[]){
ir3_get_src(ctx, &intr->src[1])[0],
ir3_get_src(ctx, &intr->src[1])[1]
}, 2);
offset = ir3_get_src(ctx, &intr->src[2])[0];
value = ir3_create_collect(ctx, ir3_get_src(ctx, &intr->src[0]), ncomp);
struct ir3_instruction *stg =
ir3_STG_G(ctx->block, addr, 0, value, 0,
create_immed(ctx->block, ncomp), 0, offset, 0);
stg->cat6.type = TYPE_U32;
stg->cat6.iim_val = 1;
array_insert(b, b->keeps, stg);
stg->barrier_class = IR3_BARRIER_BUFFER_W;
stg->barrier_conflict = IR3_BARRIER_BUFFER_R | IR3_BARRIER_BUFFER_W;
break;
}
case nir_intrinsic_load_global_ir3: {
struct ir3_instruction *addr, *offset;
addr = ir3_create_collect(ctx, (struct ir3_instruction*[]){
ir3_get_src(ctx, &intr->src[0])[0],
ir3_get_src(ctx, &intr->src[0])[1]
}, 2);
offset = ir3_get_src(ctx, &intr->src[1])[0];
struct ir3_instruction *load =
ir3_LDG(b, addr, 0, offset, 0,
create_immed(ctx->block, dest_components), 0);
load->cat6.type = TYPE_U32;
load->regs[0]->wrmask = MASK(dest_components);
load->barrier_class = IR3_BARRIER_BUFFER_R;
load->barrier_conflict = IR3_BARRIER_BUFFER_W;
ir3_split_dest(b, dst, load, 0, dest_components);
break;
}
case nir_intrinsic_load_ubo:
emit_intrinsic_load_ubo(ctx, intr, dst);
break;
case nir_intrinsic_load_ubo_vec4:
emit_intrinsic_load_ubo_ldc(ctx, intr, dst);
break;
case nir_intrinsic_load_frag_coord:
ir3_split_dest(b, dst, get_frag_coord(ctx, intr), 0, 4);
break;
case nir_intrinsic_load_sample_pos_from_id: {
/* NOTE: blob seems to always use TYPE_F16 and then cov.f16f32,
* but that doesn't seem necessary.
*/
struct ir3_instruction *offset =
ir3_RGETPOS(b, ir3_get_src(ctx, &intr->src[0])[0], 0);
offset->regs[0]->wrmask = 0x3;
offset->cat5.type = TYPE_F32;
ir3_split_dest(b, dst, offset, 0, 2);
break;
}
case nir_intrinsic_load_size_ir3:
if (!ctx->ij[IJ_PERSP_SIZE]) {
ctx->ij[IJ_PERSP_SIZE] =
create_sysval_input(ctx, SYSTEM_VALUE_BARYCENTRIC_PERSP_SIZE, 0x1);
}
dst[0] = ctx->ij[IJ_PERSP_SIZE];
break;
case nir_intrinsic_load_barycentric_centroid:
case nir_intrinsic_load_barycentric_sample:
case nir_intrinsic_load_barycentric_pixel:
emit_intrinsic_barycentric(ctx, intr, dst);
break;
case nir_intrinsic_load_interpolated_input:
case nir_intrinsic_load_input:
setup_input(ctx, intr);
break;
/* All SSBO intrinsics should have been lowered by 'lower_io_offsets'
* pass and replaced by an ir3-specifc version that adds the
* dword-offset in the last source.
*/
case nir_intrinsic_load_ssbo_ir3:
ctx->funcs->emit_intrinsic_load_ssbo(ctx, intr, dst);
break;
case nir_intrinsic_store_ssbo_ir3:
if ((ctx->so->type == MESA_SHADER_FRAGMENT) &&
!ctx->s->info.fs.early_fragment_tests)
ctx->so->no_earlyz = true;
ctx->funcs->emit_intrinsic_store_ssbo(ctx, intr);
break;
case nir_intrinsic_get_ssbo_size:
emit_intrinsic_ssbo_size(ctx, intr, dst);
break;
case nir_intrinsic_ssbo_atomic_add_ir3:
case nir_intrinsic_ssbo_atomic_imin_ir3:
case nir_intrinsic_ssbo_atomic_umin_ir3:
case nir_intrinsic_ssbo_atomic_imax_ir3:
case nir_intrinsic_ssbo_atomic_umax_ir3:
case nir_intrinsic_ssbo_atomic_and_ir3:
case nir_intrinsic_ssbo_atomic_or_ir3:
case nir_intrinsic_ssbo_atomic_xor_ir3:
case nir_intrinsic_ssbo_atomic_exchange_ir3:
case nir_intrinsic_ssbo_atomic_comp_swap_ir3:
if ((ctx->so->type == MESA_SHADER_FRAGMENT) &&
!ctx->s->info.fs.early_fragment_tests)
ctx->so->no_earlyz = true;
dst[0] = ctx->funcs->emit_intrinsic_atomic_ssbo(ctx, intr);
break;
case nir_intrinsic_load_shared:
emit_intrinsic_load_shared(ctx, intr, dst);
break;
case nir_intrinsic_store_shared:
emit_intrinsic_store_shared(ctx, intr);
break;
case nir_intrinsic_shared_atomic_add:
case nir_intrinsic_shared_atomic_imin:
case nir_intrinsic_shared_atomic_umin:
case nir_intrinsic_shared_atomic_imax:
case nir_intrinsic_shared_atomic_umax:
case nir_intrinsic_shared_atomic_and:
case nir_intrinsic_shared_atomic_or:
case nir_intrinsic_shared_atomic_xor:
case nir_intrinsic_shared_atomic_exchange:
case nir_intrinsic_shared_atomic_comp_swap:
dst[0] = emit_intrinsic_atomic_shared(ctx, intr);
break;
case nir_intrinsic_load_scratch:
emit_intrinsic_load_scratch(ctx, intr, dst);
break;
case nir_intrinsic_store_scratch:
emit_intrinsic_store_scratch(ctx, intr);
break;
case nir_intrinsic_image_load:
emit_intrinsic_load_image(ctx, intr, dst);
break;
case nir_intrinsic_bindless_image_load:
/* Bindless uses the IBO state, which doesn't have swizzle filled out,
* so using isam doesn't work.
*
* TODO: can we use isam if we fill out more fields?
*/
ctx->funcs->emit_intrinsic_load_image(ctx, intr, dst);
break;
case nir_intrinsic_image_store:
case nir_intrinsic_bindless_image_store:
if ((ctx->so->type == MESA_SHADER_FRAGMENT) &&
!ctx->s->info.fs.early_fragment_tests)
ctx->so->no_earlyz = true;
ctx->funcs->emit_intrinsic_store_image(ctx, intr);
break;
case nir_intrinsic_image_size:
case nir_intrinsic_bindless_image_size:
ctx->funcs->emit_intrinsic_image_size(ctx, intr, dst);
break;
case nir_intrinsic_image_atomic_add:
case nir_intrinsic_bindless_image_atomic_add:
case nir_intrinsic_image_atomic_imin:
case nir_intrinsic_bindless_image_atomic_imin:
case nir_intrinsic_image_atomic_umin:
case nir_intrinsic_bindless_image_atomic_umin:
case nir_intrinsic_image_atomic_imax:
case nir_intrinsic_bindless_image_atomic_imax:
case nir_intrinsic_image_atomic_umax:
case nir_intrinsic_bindless_image_atomic_umax:
case nir_intrinsic_image_atomic_and:
case nir_intrinsic_bindless_image_atomic_and:
case nir_intrinsic_image_atomic_or:
case nir_intrinsic_bindless_image_atomic_or:
case nir_intrinsic_image_atomic_xor:
case nir_intrinsic_bindless_image_atomic_xor:
case nir_intrinsic_image_atomic_exchange:
case nir_intrinsic_bindless_image_atomic_exchange:
case nir_intrinsic_image_atomic_comp_swap:
case nir_intrinsic_bindless_image_atomic_comp_swap:
if ((ctx->so->type == MESA_SHADER_FRAGMENT) &&
!ctx->s->info.fs.early_fragment_tests)
ctx->so->no_earlyz = true;
dst[0] = ctx->funcs->emit_intrinsic_atomic_image(ctx, intr);
break;
case nir_intrinsic_control_barrier:
case nir_intrinsic_memory_barrier:
case nir_intrinsic_group_memory_barrier:
case nir_intrinsic_memory_barrier_buffer:
case nir_intrinsic_memory_barrier_image:
case nir_intrinsic_memory_barrier_shared:
emit_intrinsic_barrier(ctx, intr);
/* note that blk ptr no longer valid, make that obvious: */
b = NULL;
break;
case nir_intrinsic_store_output:
setup_output(ctx, intr);
break;
case nir_intrinsic_load_base_vertex:
case nir_intrinsic_load_first_vertex:
if (!ctx->basevertex) {
ctx->basevertex = create_driver_param(ctx, IR3_DP_VTXID_BASE);
}
dst[0] = ctx->basevertex;
break;
case nir_intrinsic_load_draw_id:
if (!ctx->draw_id) {
ctx->draw_id = create_driver_param(ctx, IR3_DP_DRAWID);
}
dst[0] = ctx->draw_id;
break;
case nir_intrinsic_load_base_instance:
if (!ctx->base_instance) {
ctx->base_instance = create_driver_param(ctx, IR3_DP_INSTID_BASE);
}
dst[0] = ctx->base_instance;
break;
case nir_intrinsic_load_view_index:
if (!ctx->view_index) {
ctx->view_index = create_sysval_input(ctx, SYSTEM_VALUE_VIEW_INDEX, 0x1);
}
dst[0] = ctx->view_index;
break;
case nir_intrinsic_load_vertex_id_zero_base:
case nir_intrinsic_load_vertex_id:
if (!ctx->vertex_id) {
gl_system_value sv = (intr->intrinsic == nir_intrinsic_load_vertex_id) ?
SYSTEM_VALUE_VERTEX_ID : SYSTEM_VALUE_VERTEX_ID_ZERO_BASE;
ctx->vertex_id = create_sysval_input(ctx, sv, 0x1);
}
dst[0] = ctx->vertex_id;
break;
case nir_intrinsic_load_instance_id:
if (!ctx->instance_id) {
ctx->instance_id = create_sysval_input(ctx, SYSTEM_VALUE_INSTANCE_ID, 0x1);
}
dst[0] = ctx->instance_id;
break;
case nir_intrinsic_load_sample_id:
ctx->so->per_samp = true;
/* fall-thru */
case nir_intrinsic_load_sample_id_no_per_sample:
if (!ctx->samp_id) {
ctx->samp_id = create_sysval_input(ctx, SYSTEM_VALUE_SAMPLE_ID, 0x1);
ctx->samp_id->regs[0]->flags |= IR3_REG_HALF;
}
dst[0] = ir3_COV(b, ctx->samp_id, TYPE_U16, TYPE_U32);
break;
case nir_intrinsic_load_sample_mask_in:
if (!ctx->samp_mask_in) {
ctx->samp_mask_in = create_sysval_input(ctx, SYSTEM_VALUE_SAMPLE_MASK_IN, 0x1);
}
dst[0] = ctx->samp_mask_in;
break;
case nir_intrinsic_load_user_clip_plane:
idx = nir_intrinsic_ucp_id(intr);
for (int i = 0; i < dest_components; i++) {
unsigned n = idx * 4 + i;
dst[i] = create_driver_param(ctx, IR3_DP_UCP0_X + n);
}
break;
case nir_intrinsic_load_front_face:
if (!ctx->frag_face) {
ctx->so->frag_face = true;
ctx->frag_face = create_sysval_input(ctx, SYSTEM_VALUE_FRONT_FACE, 0x1);
ctx->frag_face->regs[0]->flags |= IR3_REG_HALF;
}
/* for fragface, we get -1 for back and 0 for front. However this is
* the inverse of what nir expects (where ~0 is true).
*/
dst[0] = ir3_CMPS_S(b,
ctx->frag_face, 0,
create_immed_typed(b, 0, TYPE_U16), 0);
dst[0]->cat2.condition = IR3_COND_EQ;
break;
case nir_intrinsic_load_local_invocation_id:
if (!ctx->local_invocation_id) {
ctx->local_invocation_id =
create_sysval_input(ctx, SYSTEM_VALUE_LOCAL_INVOCATION_ID, 0x7);
}
ir3_split_dest(b, dst, ctx->local_invocation_id, 0, 3);
break;
case nir_intrinsic_load_work_group_id:
if (!ctx->work_group_id) {
ctx->work_group_id =
create_sysval_input(ctx, SYSTEM_VALUE_WORK_GROUP_ID, 0x7);
ctx->work_group_id->regs[0]->flags |= IR3_REG_SHARED;
}
ir3_split_dest(b, dst, ctx->work_group_id, 0, 3);
break;
case nir_intrinsic_load_num_work_groups:
for (int i = 0; i < dest_components; i++) {
dst[i] = create_driver_param(ctx, IR3_DP_NUM_WORK_GROUPS_X + i);
}
break;
case nir_intrinsic_load_local_group_size:
for (int i = 0; i < dest_components; i++) {
dst[i] = create_driver_param(ctx, IR3_DP_LOCAL_GROUP_SIZE_X + i);
}
break;
case nir_intrinsic_discard_if:
case nir_intrinsic_discard: {
struct ir3_instruction *cond, *kill;
if (intr->intrinsic == nir_intrinsic_discard_if) {
/* conditional discard: */
src = ir3_get_src(ctx, &intr->src[0]);
cond = src[0];
} else {
/* unconditional discard: */
cond = create_immed(b, 1);
}
/* NOTE: only cmps.*.* can write p0.x: */
cond = ir3_CMPS_S(b, cond, 0, create_immed(b, 0), 0);
cond->cat2.condition = IR3_COND_NE;
/* condition always goes in predicate register: */
cond->regs[0]->num = regid(REG_P0, 0);
cond->regs[0]->flags &= ~IR3_REG_SSA;
kill = ir3_KILL(b, cond, 0);
kill->regs[1]->num = regid(REG_P0, 0);
array_insert(ctx->ir, ctx->ir->predicates, kill);
array_insert(b, b->keeps, kill);
ctx->so->has_kill = true;
break;
}
case nir_intrinsic_cond_end_ir3: {
struct ir3_instruction *cond, *kill;
src = ir3_get_src(ctx, &intr->src[0]);
cond = src[0];
/* NOTE: only cmps.*.* can write p0.x: */
cond = ir3_CMPS_S(b, cond, 0, create_immed(b, 0), 0);
cond->cat2.condition = IR3_COND_NE;
/* condition always goes in predicate register: */
cond->regs[0]->num = regid(REG_P0, 0);
kill = ir3_PREDT(b, cond, 0);
kill->barrier_class = IR3_BARRIER_EVERYTHING;
kill->barrier_conflict = IR3_BARRIER_EVERYTHING;
array_insert(ctx->ir, ctx->ir->predicates, kill);
array_insert(b, b->keeps, kill);
break;
}
case nir_intrinsic_load_shared_ir3:
emit_intrinsic_load_shared_ir3(ctx, intr, dst);
break;
case nir_intrinsic_store_shared_ir3:
emit_intrinsic_store_shared_ir3(ctx, intr);
break;
case nir_intrinsic_bindless_resource_ir3:
dst[0] = ir3_get_src(ctx, &intr->src[0])[0];
break;
default:
ir3_context_error(ctx, "Unhandled intrinsic type: %s\n",
nir_intrinsic_infos[intr->intrinsic].name);
break;
}
if (info->has_dest)
ir3_put_dst(ctx, &intr->dest);
}
static void
emit_load_const(struct ir3_context *ctx, nir_load_const_instr *instr)
{
struct ir3_instruction **dst = ir3_get_dst_ssa(ctx, &instr->def,
instr->def.num_components);
if (instr->def.bit_size == 16) {
for (int i = 0; i < instr->def.num_components; i++)
dst[i] = create_immed_typed(ctx->block,
instr->value[i].u16,
TYPE_U16);
} else {
for (int i = 0; i < instr->def.num_components; i++)
dst[i] = create_immed_typed(ctx->block,
instr->value[i].u32,
TYPE_U32);
}
}
static void
emit_undef(struct ir3_context *ctx, nir_ssa_undef_instr *undef)
{
struct ir3_instruction **dst = ir3_get_dst_ssa(ctx, &undef->def,
undef->def.num_components);
type_t type = (undef->def.bit_size == 16) ? TYPE_U16 : TYPE_U32;
/* backend doesn't want undefined instructions, so just plug
* in 0.0..
*/
for (int i = 0; i < undef->def.num_components; i++)
dst[i] = create_immed_typed(ctx->block, fui(0.0), type);
}
/*
* texture fetch/sample instructions:
*/
static type_t
get_tex_dest_type(nir_tex_instr *tex)
{
type_t type;
switch (tex->dest_type) {
case nir_type_float32:
return TYPE_F32;
case nir_type_float16:
return TYPE_F16;
case nir_type_int32:
return TYPE_S32;
case nir_type_int16:
return TYPE_S16;
case nir_type_bool32:
case nir_type_uint32:
return TYPE_U32;
case nir_type_bool16:
case nir_type_uint16:
return TYPE_U16;
case nir_type_invalid:
default:
unreachable("bad dest_type");
}
return type;
}
static void
tex_info(nir_tex_instr *tex, unsigned *flagsp, unsigned *coordsp)
{
unsigned coords = glsl_get_sampler_dim_coordinate_components(tex->sampler_dim);
unsigned flags = 0;
/* note: would use tex->coord_components.. except txs.. also,
* since array index goes after shadow ref, we don't want to
* count it:
*/
if (coords == 3)
flags |= IR3_INSTR_3D;
if (tex->is_shadow && tex->op != nir_texop_lod)
flags |= IR3_INSTR_S;
if (tex->is_array && tex->op != nir_texop_lod)
flags |= IR3_INSTR_A;
*flagsp = flags;
*coordsp = coords;
}
/* Gets the sampler/texture idx as a hvec2. Which could either be dynamic
* or immediate (in which case it will get lowered later to a non .s2en
* version of the tex instruction which encode tex/samp as immediates:
*/
static struct tex_src_info
get_tex_samp_tex_src(struct ir3_context *ctx, nir_tex_instr *tex)
{
struct ir3_block *b = ctx->block;
struct tex_src_info info = { 0 };
int texture_idx = nir_tex_instr_src_index(tex, nir_tex_src_texture_handle);
int sampler_idx = nir_tex_instr_src_index(tex, nir_tex_src_sampler_handle);
struct ir3_instruction *texture, *sampler;
if (texture_idx >= 0 || sampler_idx >= 0) {
/* Bindless case */
info.flags |= IR3_INSTR_B;
/* Gather information required to determine which encoding to
* choose as well as for prefetch.
*/
nir_intrinsic_instr *bindless_tex = NULL;
bool tex_const;
if (texture_idx >= 0) {
ctx->so->bindless_tex = true;
bindless_tex = ir3_bindless_resource(tex->src[texture_idx].src);
assert(bindless_tex);
info.tex_base = nir_intrinsic_desc_set(bindless_tex);
tex_const = nir_src_is_const(bindless_tex->src[0]);
if (tex_const)
info.tex_idx = nir_src_as_uint(bindless_tex->src[0]);
} else {
/* To simplify some of the logic below, assume the index is
* constant 0 when it's not enabled.
*/
tex_const = true;
info.tex_idx = 0;
}
nir_intrinsic_instr *bindless_samp = NULL;
bool samp_const;
if (sampler_idx >= 0) {
ctx->so->bindless_samp = true;
bindless_samp = ir3_bindless_resource(tex->src[sampler_idx].src);
assert(bindless_samp);
info.samp_base = nir_intrinsic_desc_set(bindless_samp);
samp_const = nir_src_is_const(bindless_samp->src[0]);
if (samp_const)
info.samp_idx = nir_src_as_uint(bindless_samp->src[0]);
} else {
samp_const = true;
info.samp_idx = 0;
}
/* Choose encoding. */
if (tex_const && samp_const && info.tex_idx < 256 && info.samp_idx < 256) {
if (info.tex_idx < 16 && info.samp_idx < 16 &&
(!bindless_tex || !bindless_samp || info.tex_base == info.samp_base)) {
/* Everything fits within the instruction */
info.base = info.tex_base;
info.combined_idx = info.samp_idx | (info.tex_idx << 4);
} else {
info.base = info.tex_base;
info.a1_val = info.tex_idx << 3 | info.samp_base;
info.combined_idx = info.samp_idx;
info.flags |= IR3_INSTR_A1EN;
}
info.samp_tex = NULL;
} else {
info.flags |= IR3_INSTR_S2EN;
/* In the indirect case, we only use a1.x to store the sampler
* base if it differs from the texture base.
*/
if (!bindless_tex || !bindless_samp || info.tex_base == info.samp_base) {
info.base = info.tex_base;
} else {
info.base = info.tex_base;
info.a1_val = info.samp_base;
info.flags |= IR3_INSTR_A1EN;
}
/* Note: the indirect source is now a vec2 instead of hvec2, and
* for some reason the texture and sampler are swapped.
*/
struct ir3_instruction *texture, *sampler;
if (bindless_tex) {
texture = ir3_get_src(ctx, &tex->src[texture_idx].src)[0];
} else {
texture = create_immed(b, 0);
}
if (bindless_samp) {
sampler = ir3_get_src(ctx, &tex->src[sampler_idx].src)[0];
} else {
sampler = create_immed(b, 0);
}
info.samp_tex = ir3_create_collect(ctx, (struct ir3_instruction*[]){
texture,
sampler,
}, 2);
}
} else {
info.flags |= IR3_INSTR_S2EN;
texture_idx = nir_tex_instr_src_index(tex, nir_tex_src_texture_offset);
sampler_idx = nir_tex_instr_src_index(tex, nir_tex_src_sampler_offset);
if (texture_idx >= 0) {
texture = ir3_get_src(ctx, &tex->src[texture_idx].src)[0];
texture = ir3_COV(ctx->block, texture, TYPE_U32, TYPE_U16);
} else {
/* TODO what to do for dynamic case? I guess we only need the
* max index for astc srgb workaround so maybe not a problem
* to worry about if we don't enable indirect samplers for
* a4xx?
*/
ctx->max_texture_index = MAX2(ctx->max_texture_index, tex->texture_index);
texture = create_immed_typed(ctx->block, tex->texture_index, TYPE_U16);
info.tex_idx = tex->texture_index;
}
if (sampler_idx >= 0) {
sampler = ir3_get_src(ctx, &tex->src[sampler_idx].src)[0];
sampler = ir3_COV(ctx->block, sampler, TYPE_U32, TYPE_U16);
} else {
sampler = create_immed_typed(ctx->block, tex->sampler_index, TYPE_U16);
info.samp_idx = tex->texture_index;
}
info.samp_tex = ir3_create_collect(ctx, (struct ir3_instruction*[]){
sampler,
texture,
}, 2);
}
return info;
}
static void
emit_tex(struct ir3_context *ctx, nir_tex_instr *tex)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction **dst, *sam, *src0[12], *src1[4];
struct ir3_instruction * const *coord, * const *off, * const *ddx, * const *ddy;
struct ir3_instruction *lod, *compare, *proj, *sample_index;
struct tex_src_info info = { 0 };
bool has_bias = false, has_lod = false, has_proj = false, has_off = false;
unsigned i, coords, flags, ncomp;
unsigned nsrc0 = 0, nsrc1 = 0;
type_t type;
opc_t opc = 0;
ncomp = nir_dest_num_components(tex->dest);
coord = off = ddx = ddy = NULL;
lod = proj = compare = sample_index = NULL;
dst = ir3_get_dst(ctx, &tex->dest, ncomp);
for (unsigned i = 0; i < tex->num_srcs; i++) {
switch (tex->src[i].src_type) {
case nir_tex_src_coord:
coord = ir3_get_src(ctx, &tex->src[i].src);
break;
case nir_tex_src_bias:
lod = ir3_get_src(ctx, &tex->src[i].src)[0];
has_bias = true;
break;
case nir_tex_src_lod:
lod = ir3_get_src(ctx, &tex->src[i].src)[0];
has_lod = true;
break;
case nir_tex_src_comparator: /* shadow comparator */
compare = ir3_get_src(ctx, &tex->src[i].src)[0];
break;
case nir_tex_src_projector:
proj = ir3_get_src(ctx, &tex->src[i].src)[0];
has_proj = true;
break;
case nir_tex_src_offset:
off = ir3_get_src(ctx, &tex->src[i].src);
has_off = true;
break;
case nir_tex_src_ddx:
ddx = ir3_get_src(ctx, &tex->src[i].src);
break;
case nir_tex_src_ddy:
ddy = ir3_get_src(ctx, &tex->src[i].src);
break;
case nir_tex_src_ms_index:
sample_index = ir3_get_src(ctx, &tex->src[i].src)[0];
break;
case nir_tex_src_texture_offset:
case nir_tex_src_sampler_offset:
case nir_tex_src_texture_handle:
case nir_tex_src_sampler_handle:
/* handled in get_tex_samp_src() */
break;
default:
ir3_context_error(ctx, "Unhandled NIR tex src type: %d\n",
tex->src[i].src_type);
return;
}
}
switch (tex->op) {
case nir_texop_tex_prefetch:
compile_assert(ctx, !has_bias);
compile_assert(ctx, !has_lod);
compile_assert(ctx, !compare);
compile_assert(ctx, !has_proj);
compile_assert(ctx, !has_off);
compile_assert(ctx, !ddx);
compile_assert(ctx, !ddy);
compile_assert(ctx, !sample_index);
compile_assert(ctx, nir_tex_instr_src_index(tex, nir_tex_src_texture_offset) < 0);
compile_assert(ctx, nir_tex_instr_src_index(tex, nir_tex_src_sampler_offset) < 0);
if (ctx->so->num_sampler_prefetch < ctx->prefetch_limit) {
opc = OPC_META_TEX_PREFETCH;
ctx->so->num_sampler_prefetch++;
break;
}
/* fallthru */
case nir_texop_tex: opc = has_lod ? OPC_SAML : OPC_SAM; break;
case nir_texop_txb: opc = OPC_SAMB; break;
case nir_texop_txl: opc = OPC_SAML; break;
case nir_texop_txd: opc = OPC_SAMGQ; break;
case nir_texop_txf: opc = OPC_ISAML; break;
case nir_texop_lod: opc = OPC_GETLOD; break;
case nir_texop_tg4:
/* NOTE: a4xx might need to emulate gather w/ txf (this is
* what blob does, seems gather is broken?), and a3xx did
* not support it (but probably could also emulate).
*/
switch (tex->component) {
case 0: opc = OPC_GATHER4R; break;
case 1: opc = OPC_GATHER4G; break;
case 2: opc = OPC_GATHER4B; break;
case 3: opc = OPC_GATHER4A; break;
}
break;
case nir_texop_txf_ms_fb:
case nir_texop_txf_ms: opc = OPC_ISAMM; break;
default:
ir3_context_error(ctx, "Unhandled NIR tex type: %d\n", tex->op);
return;
}
tex_info(tex, &flags, &coords);
/*
* lay out the first argument in the proper order:
* - actual coordinates first
* - shadow reference
* - array index
* - projection w
* - starting at offset 4, dpdx.xy, dpdy.xy
*
* bias/lod go into the second arg
*/
/* insert tex coords: */
for (i = 0; i < coords; i++)
src0[i] = coord[i];
nsrc0 = i;
/* scale up integer coords for TXF based on the LOD */
if (ctx->compiler->unminify_coords && (opc == OPC_ISAML)) {
assert(has_lod);
for (i = 0; i < coords; i++)
src0[i] = ir3_SHL_B(b, src0[i], 0, lod, 0);
}
if (coords == 1) {
/* hw doesn't do 1d, so we treat it as 2d with
* height of 1, and patch up the y coord.
*/
if (is_isam(opc)) {
src0[nsrc0++] = create_immed(b, 0);
} else {
src0[nsrc0++] = create_immed(b, fui(0.5));
}
}
if (tex->is_shadow && tex->op != nir_texop_lod)
src0[nsrc0++] = compare;
if (tex->is_array && tex->op != nir_texop_lod) {
struct ir3_instruction *idx = coord[coords];
/* the array coord for cube arrays needs 0.5 added to it */
if (ctx->compiler->array_index_add_half && !is_isam(opc))
idx = ir3_ADD_F(b, idx, 0, create_immed(b, fui(0.5)), 0);
src0[nsrc0++] = idx;
}
if (has_proj) {
src0[nsrc0++] = proj;
flags |= IR3_INSTR_P;
}
/* pad to 4, then ddx/ddy: */
if (tex->op == nir_texop_txd) {
while (nsrc0 < 4)
src0[nsrc0++] = create_immed(b, fui(0.0));
for (i = 0; i < coords; i++)
src0[nsrc0++] = ddx[i];
if (coords < 2)
src0[nsrc0++] = create_immed(b, fui(0.0));
for (i = 0; i < coords; i++)
src0[nsrc0++] = ddy[i];
if (coords < 2)
src0[nsrc0++] = create_immed(b, fui(0.0));
}
/* NOTE a3xx (and possibly a4xx?) might be different, using isaml
* with scaled x coord according to requested sample:
*/
if (opc == OPC_ISAMM) {
if (ctx->compiler->txf_ms_with_isaml) {
/* the samples are laid out in x dimension as
* 0 1 2 3
* x_ms = (x << ms) + sample_index;
*/
struct ir3_instruction *ms;
ms = create_immed(b, (ctx->samples >> (2 * tex->texture_index)) & 3);
src0[0] = ir3_SHL_B(b, src0[0], 0, ms, 0);
src0[0] = ir3_ADD_U(b, src0[0], 0, sample_index, 0);
opc = OPC_ISAML;
} else {
src0[nsrc0++] = sample_index;
}
}
/*
* second argument (if applicable):
* - offsets
* - lod
* - bias
*/
if (has_off | has_lod | has_bias) {
if (has_off) {
unsigned off_coords = coords;
if (tex->sampler_dim == GLSL_SAMPLER_DIM_CUBE)
off_coords--;
for (i = 0; i < off_coords; i++)
src1[nsrc1++] = off[i];
if (off_coords < 2)
src1[nsrc1++] = create_immed(b, fui(0.0));
flags |= IR3_INSTR_O;
}
if (has_lod | has_bias)
src1[nsrc1++] = lod;
}
type = get_tex_dest_type(tex);
if (opc == OPC_GETLOD)
type = TYPE_S32;
if (tex->op == nir_texop_txf_ms_fb) {
/* only expect a single txf_ms_fb per shader: */
compile_assert(ctx, !ctx->so->fb_read);
compile_assert(ctx, ctx->so->type == MESA_SHADER_FRAGMENT);
ctx->so->fb_read = true;
info.samp_tex = ir3_create_collect(ctx, (struct ir3_instruction*[]){
create_immed_typed(ctx->block, ctx->so->num_samp, TYPE_U16),
create_immed_typed(ctx->block, ctx->so->num_samp, TYPE_U16),
}, 2);
info.flags = IR3_INSTR_S2EN;
ctx->so->num_samp++;
} else {
info = get_tex_samp_tex_src(ctx, tex);
}
struct ir3_instruction *col0 = ir3_create_collect(ctx, src0, nsrc0);
struct ir3_instruction *col1 = ir3_create_collect(ctx, src1, nsrc1);
if (opc == OPC_META_TEX_PREFETCH) {
int idx = nir_tex_instr_src_index(tex, nir_tex_src_coord);
compile_assert(ctx, tex->src[idx].src.is_ssa);
sam = ir3_SAM(b, opc, type, MASK(ncomp), 0, NULL,
get_barycentric(ctx, IJ_PERSP_PIXEL), 0);
sam->prefetch.input_offset =
ir3_nir_coord_offset(tex->src[idx].src.ssa);
/* make sure not to add irrelevant flags like S2EN */
sam->flags = flags | (info.flags & IR3_INSTR_B);
sam->prefetch.tex = info.tex_idx;
sam->prefetch.samp = info.samp_idx;
sam->prefetch.tex_base = info.tex_base;
sam->prefetch.samp_base = info.samp_base;
} else {
info.flags |= flags;
sam = emit_sam(ctx, opc, info, type, MASK(ncomp), col0, col1);
}
if ((ctx->astc_srgb & (1 << tex->texture_index)) && !nir_tex_instr_is_query(tex)) {
assert(opc != OPC_META_TEX_PREFETCH);
/* only need first 3 components: */
sam->regs[0]->wrmask = 0x7;
ir3_split_dest(b, dst, sam, 0, 3);
/* we need to sample the alpha separately with a non-ASTC
* texture state:
*/
sam = ir3_SAM(b, opc, type, 0b1000, flags | info.flags,
info.samp_tex, col0, col1);
array_insert(ctx->ir, ctx->ir->astc_srgb, sam);
/* fixup .w component: */
ir3_split_dest(b, &dst[3], sam, 3, 1);
} else {
/* normal (non-workaround) case: */
ir3_split_dest(b, dst, sam, 0, ncomp);
}
/* GETLOD returns results in 4.8 fixed point */
if (opc == OPC_GETLOD) {
struct ir3_instruction *factor = create_immed(b, fui(1.0 / 256));
compile_assert(ctx, tex->dest_type == nir_type_float32);
for (i = 0; i < 2; i++) {
dst[i] = ir3_MUL_F(b, ir3_COV(b, dst[i], TYPE_S32, TYPE_F32), 0,
factor, 0);
}
}
ir3_put_dst(ctx, &tex->dest);
}
static void
emit_tex_info(struct ir3_context *ctx, nir_tex_instr *tex, unsigned idx)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction **dst, *sam;
type_t dst_type = get_tex_dest_type(tex);
struct tex_src_info info = get_tex_samp_tex_src(ctx, tex);
dst = ir3_get_dst(ctx, &tex->dest, 1);
sam = emit_sam(ctx, OPC_GETINFO, info, dst_type, 1 << idx, NULL, NULL);
/* even though there is only one component, since it ends
* up in .y/.z/.w rather than .x, we need a split_dest()
*/
ir3_split_dest(b, dst, sam, idx, 1);
/* The # of levels comes from getinfo.z. We need to add 1 to it, since
* the value in TEX_CONST_0 is zero-based.
*/
if (ctx->compiler->levels_add_one)
dst[0] = ir3_ADD_U(b, dst[0], 0, create_immed(b, 1), 0);
ir3_put_dst(ctx, &tex->dest);
}
static void
emit_tex_txs(struct ir3_context *ctx, nir_tex_instr *tex)
{
struct ir3_block *b = ctx->block;
struct ir3_instruction **dst, *sam;
struct ir3_instruction *lod;
unsigned flags, coords;
type_t dst_type = get_tex_dest_type(tex);
struct tex_src_info info = get_tex_samp_tex_src(ctx, tex);
tex_info(tex, &flags, &coords);
info.flags |= flags;
/* Actually we want the number of dimensions, not coordinates. This
* distinction only matters for cubes.
*/
if (tex->sampler_dim == GLSL_SAMPLER_DIM_CUBE)
coords = 2;
dst = ir3_get_dst(ctx, &tex->dest, 4);
int lod_idx = nir_tex_instr_src_index(tex, nir_tex_src_lod);
compile_assert(ctx, lod_idx >= 0);
lod = ir3_get_src(ctx, &tex->src[lod_idx].src)[0];
sam = emit_sam(ctx, OPC_GETSIZE, info, dst_type, 0b1111, lod, NULL);
ir3_split_dest(b, dst, sam, 0, 4);
/* Array size actually ends up in .w rather than .z. This doesn't
* matter for miplevel 0, but for higher mips the value in z is
* minified whereas w stays. Also, the value in TEX_CONST_3_DEPTH is
* returned, which means that we have to add 1 to it for arrays.
*/
if (tex->is_array) {
if (ctx->compiler->levels_add_one) {
dst[coords] = ir3_ADD_U(b, dst[3], 0, create_immed(b, 1), 0);
} else {
dst[coords] = ir3_MOV(b, dst[3], TYPE_U32);
}
}
ir3_put_dst(ctx, &tex->dest);
}
static void
emit_jump(struct ir3_context *ctx, nir_jump_instr *jump)
{
switch (jump->type) {
case nir_jump_break:
case nir_jump_continue:
case nir_jump_return:
/* I *think* we can simply just ignore this, and use the
* successor block link to figure out where we need to
* jump to for break/continue
*/
break;
default:
ir3_context_error(ctx, "Unhandled NIR jump type: %d\n", jump->type);
break;
}
}
static void
emit_instr(struct ir3_context *ctx, nir_instr *instr)
{
switch (instr->type) {
case nir_instr_type_alu:
emit_alu(ctx, nir_instr_as_alu(instr));
break;
case nir_instr_type_deref:
/* ignored, handled as part of the intrinsic they are src to */
break;
case nir_instr_type_intrinsic:
emit_intrinsic(ctx, nir_instr_as_intrinsic(instr));
break;
case nir_instr_type_load_const:
emit_load_const(ctx, nir_instr_as_load_const(instr));
break;
case nir_instr_type_ssa_undef:
emit_undef(ctx, nir_instr_as_ssa_undef(instr));
break;
case nir_instr_type_tex: {
nir_tex_instr *tex = nir_instr_as_tex(instr);
/* couple tex instructions get special-cased:
*/
switch (tex->op) {
case nir_texop_txs:
emit_tex_txs(ctx, tex);
break;
case nir_texop_query_levels:
emit_tex_info(ctx, tex, 2);
break;
case nir_texop_texture_samples:
emit_tex_info(ctx, tex, 3);
break;
default:
emit_tex(ctx, tex);
break;
}
break;
}
case nir_instr_type_jump:
emit_jump(ctx, nir_instr_as_jump(instr));
break;
case nir_instr_type_phi:
/* we have converted phi webs to regs in NIR by now */
ir3_context_error(ctx, "Unexpected NIR instruction type: %d\n", instr->type);
break;
case nir_instr_type_call:
case nir_instr_type_parallel_copy:
ir3_context_error(ctx, "Unhandled NIR instruction type: %d\n", instr->type);
break;
}
}
static struct ir3_block *
get_block(struct ir3_context *ctx, const nir_block *nblock)
{
struct ir3_block *block;
struct hash_entry *hentry;
hentry = _mesa_hash_table_search(ctx->block_ht, nblock);
if (hentry)
return hentry->data;
block = ir3_block_create(ctx->ir);
block->nblock = nblock;
_mesa_hash_table_insert(ctx->block_ht, nblock, block);
set_foreach(nblock->predecessors, sentry) {
_mesa_set_add(block->predecessors, get_block(ctx, sentry->key));
}
return block;
}
static void
emit_block(struct ir3_context *ctx, nir_block *nblock)
{
struct ir3_block *block = get_block(ctx, nblock);
for (int i = 0; i < ARRAY_SIZE(block->successors); i++) {
if (nblock->successors[i]) {
block->successors[i] =
get_block(ctx, nblock->successors[i]);
}
}
ctx->block = block;
list_addtail(&block->node, &ctx->ir->block_list);
/* re-emit addr register in each block if needed: */
for (int i = 0; i < ARRAY_SIZE(ctx->addr0_ht); i++) {
_mesa_hash_table_destroy(ctx->addr0_ht[i], NULL);
ctx->addr0_ht[i] = NULL;
}
_mesa_hash_table_u64_destroy(ctx->addr1_ht, NULL);
ctx->addr1_ht = NULL;
nir_foreach_instr (instr, nblock) {
ctx->cur_instr = instr;
emit_instr(ctx, instr);
ctx->cur_instr = NULL;
if (ctx->error)
return;
}
_mesa_hash_table_clear(ctx->sel_cond_conversions, NULL);
}
static void emit_cf_list(struct ir3_context *ctx, struct exec_list *list);
static void
emit_if(struct ir3_context *ctx, nir_if *nif)
{
struct ir3_instruction *condition = ir3_get_src(ctx, &nif->condition)[0];
ctx->block->condition = ir3_get_predicate(ctx, condition);
emit_cf_list(ctx, &nif->then_list);
emit_cf_list(ctx, &nif->else_list);
}
static void
emit_loop(struct ir3_context *ctx, nir_loop *nloop)
{
emit_cf_list(ctx, &nloop->body);
ctx->so->loops++;
}
static void
stack_push(struct ir3_context *ctx)
{
ctx->stack++;
ctx->max_stack = MAX2(ctx->max_stack, ctx->stack);
}
static void
stack_pop(struct ir3_context *ctx)
{
compile_assert(ctx, ctx->stack > 0);
ctx->stack--;
}
static void
emit_cf_list(struct ir3_context *ctx, struct exec_list *list)
{
foreach_list_typed (nir_cf_node, node, node, list) {
switch (node->type) {
case nir_cf_node_block:
emit_block(ctx, nir_cf_node_as_block(node));
break;
case nir_cf_node_if:
stack_push(ctx);
emit_if(ctx, nir_cf_node_as_if(node));
stack_pop(ctx);
break;
case nir_cf_node_loop:
stack_push(ctx);
emit_loop(ctx, nir_cf_node_as_loop(node));
stack_pop(ctx);
break;
case nir_cf_node_function:
ir3_context_error(ctx, "TODO\n");
break;
}
}
}
/* emit stream-out code. At this point, the current block is the original
* (nir) end block, and nir ensures that all flow control paths terminate
* into the end block. We re-purpose the original end block to generate
* the 'if (vtxcnt < maxvtxcnt)' condition, then append the conditional
* block holding stream-out write instructions, followed by the new end
* block:
*
* blockOrigEnd {
* p0.x = (vtxcnt < maxvtxcnt)
* // succs: blockStreamOut, blockNewEnd
* }
* blockStreamOut {
* // preds: blockOrigEnd
* ... stream-out instructions ...
* // succs: blockNewEnd
* }
* blockNewEnd {
* // preds: blockOrigEnd, blockStreamOut
* }
*/
static void
emit_stream_out(struct ir3_context *ctx)
{
struct ir3 *ir = ctx->ir;
struct ir3_stream_output_info *strmout =
&ctx->so->shader->stream_output;
struct ir3_block *orig_end_block, *stream_out_block, *new_end_block;
struct ir3_instruction *vtxcnt, *maxvtxcnt, *cond;
struct ir3_instruction *bases[IR3_MAX_SO_BUFFERS];
/* create vtxcnt input in input block at top of shader,
* so that it is seen as live over the entire duration
* of the shader:
*/
vtxcnt = create_sysval_input(ctx, SYSTEM_VALUE_VERTEX_CNT, 0x1);
maxvtxcnt = create_driver_param(ctx, IR3_DP_VTXCNT_MAX);
/* at this point, we are at the original 'end' block,
* re-purpose this block to stream-out condition, then
* append stream-out block and new-end block
*/
orig_end_block = ctx->block;
// maybe w/ store_global intrinsic, we could do this
// stuff in nir->nir pass
stream_out_block = ir3_block_create(ir);
list_addtail(&stream_out_block->node, &ir->block_list);
new_end_block = ir3_block_create(ir);
list_addtail(&new_end_block->node, &ir->block_list);
orig_end_block->successors[0] = stream_out_block;
orig_end_block->successors[1] = new_end_block;
stream_out_block->successors[0] = new_end_block;
_mesa_set_add(stream_out_block->predecessors, orig_end_block);
_mesa_set_add(new_end_block->predecessors, orig_end_block);
_mesa_set_add(new_end_block->predecessors, stream_out_block);
/* setup 'if (vtxcnt < maxvtxcnt)' condition: */
cond = ir3_CMPS_S(ctx->block, vtxcnt, 0, maxvtxcnt, 0);
cond->regs[0]->num = regid(REG_P0, 0);
cond->regs[0]->flags &= ~IR3_REG_SSA;
cond->cat2.condition = IR3_COND_LT;
/* condition goes on previous block to the conditional,
* since it is used to pick which of the two successor
* paths to take:
*/
orig_end_block->condition = cond;
/* switch to stream_out_block to generate the stream-out
* instructions:
*/
ctx->block = stream_out_block;
/* Calculate base addresses based on vtxcnt. Instructions
* generated for bases not used in following loop will be
* stripped out in the backend.
*/
for (unsigned i = 0; i < IR3_MAX_SO_BUFFERS; i++) {
const struct ir3_const_state *const_state =
ir3_const_state(ctx->so);
unsigned stride = strmout->stride[i];
struct ir3_instruction *base, *off;
base = create_uniform(ctx->block, regid(const_state->offsets.tfbo, i));
/* 24-bit should be enough: */
off = ir3_MUL_U24(ctx->block, vtxcnt, 0,
create_immed(ctx->block, stride * 4), 0);
bases[i] = ir3_ADD_S(ctx->block, off, 0, base, 0);
}
/* Generate the per-output store instructions: */
for (unsigned i = 0; i < strmout->num_outputs; i++) {
for (unsigned j = 0; j < strmout->output[i].num_components; j++) {
unsigned c = j + strmout->output[i].start_component;
struct ir3_instruction *base, *out, *stg;
base = bases[strmout->output[i].output_buffer];
out = ctx->outputs[regid(strmout->output[i].register_index, c)];
stg = ir3_STG(ctx->block, base, 0, out, 0,
create_immed(ctx->block, 1), 0);
stg->cat6.type = TYPE_U32;
stg->cat6.dst_offset = (strmout->output[i].dst_offset + j) * 4;
array_insert(ctx->block, ctx->block->keeps, stg);
}
}
/* and finally switch to the new_end_block: */
ctx->block = new_end_block;
}
static void
emit_function(struct ir3_context *ctx, nir_function_impl *impl)
{
nir_metadata_require(impl, nir_metadata_block_index);
compile_assert(ctx, ctx->stack == 0);
emit_cf_list(ctx, &impl->body);
emit_block(ctx, impl->end_block);
compile_assert(ctx, ctx->stack == 0);
/* at this point, we should have a single empty block,
* into which we emit the 'end' instruction.
*/
compile_assert(ctx, list_is_empty(&ctx->block->instr_list));
/* If stream-out (aka transform-feedback) enabled, emit the
* stream-out instructions, followed by a new empty block (into
* which the 'end' instruction lands).
*
* NOTE: it is done in this order, rather than inserting before
* we emit end_block, because NIR guarantees that all blocks
* flow into end_block, and that end_block has no successors.
* So by re-purposing end_block as the first block of stream-
* out, we guarantee that all exit paths flow into the stream-
* out instructions.
*/
if ((ctx->compiler->gpu_id < 500) &&
(ctx->so->shader->stream_output.num_outputs > 0) &&
!ctx->so->binning_pass) {
debug_assert(ctx->so->type == MESA_SHADER_VERTEX);
emit_stream_out(ctx);
}
/* Vertex shaders in a tessellation or geometry pipeline treat END as a
* NOP and has an epilogue that writes the VS outputs to local storage, to
* be read by the HS. Then it resets execution mask (chmask) and chains
* to the next shader (chsh).
*/
if ((ctx->so->type == MESA_SHADER_VERTEX &&
(ctx->so->key.has_gs || ctx->so->key.tessellation)) ||
(ctx->so->type == MESA_SHADER_TESS_EVAL && ctx->so->key.has_gs)) {
struct ir3_instruction *chmask =
ir3_CHMASK(ctx->block);
chmask->barrier_class = IR3_BARRIER_EVERYTHING;
chmask->barrier_conflict = IR3_BARRIER_EVERYTHING;
struct ir3_instruction *chsh =
ir3_CHSH(ctx->block);
chsh->barrier_class = IR3_BARRIER_EVERYTHING;
chsh->barrier_conflict = IR3_BARRIER_EVERYTHING;
} else {
ir3_END(ctx->block);
}
}
static void
setup_input(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_shader_variant *so = ctx->so;
struct ir3_instruction *coord = NULL;
if (intr->intrinsic == nir_intrinsic_load_interpolated_input)
coord = ir3_create_collect(ctx, ir3_get_src(ctx, &intr->src[0]), 2);
compile_assert(ctx, nir_src_is_const(intr->src[coord ? 1 : 0]));
unsigned frac = nir_intrinsic_component(intr);
unsigned offset = nir_src_as_uint(intr->src[coord ? 1 : 0]);
unsigned ncomp = nir_intrinsic_dest_components(intr);
unsigned n = nir_intrinsic_base(intr) + offset;
unsigned slot = nir_intrinsic_io_semantics(intr).location + offset;
unsigned compmask;
/* Inputs are loaded using ldlw or ldg for other stages. */
compile_assert(ctx, ctx->so->type == MESA_SHADER_FRAGMENT ||
ctx->so->type == MESA_SHADER_VERTEX);
if (ctx->so->type == MESA_SHADER_FRAGMENT)
compmask = BITFIELD_MASK(ncomp) << frac;
else
compmask = BITFIELD_MASK(ncomp + frac);
/* for a4xx+ rasterflat */
if (so->inputs[n].rasterflat && ctx->so->key.rasterflat)
coord = NULL;
so->total_in += util_bitcount(compmask & ~so->inputs[n].compmask);
so->inputs[n].slot = slot;
so->inputs[n].compmask |= compmask;
so->inputs_count = MAX2(so->inputs_count, n + 1);
so->inputs[n].flat = !coord;
if (ctx->so->type == MESA_SHADER_FRAGMENT) {
compile_assert(ctx, slot != VARYING_SLOT_POS);
so->inputs[n].bary = true;
for (int i = 0; i < ncomp; i++) {
unsigned idx = (n * 4) + i + frac;
ctx->last_dst[i] = create_frag_input(ctx, coord, idx);
}
} else {
struct ir3_instruction *input = NULL;
foreach_input (in, ctx->ir) {
if (in->input.inidx == n) {
input = in;
break;
}
}
if (!input) {
input = create_input(ctx, compmask);
input->input.inidx = n;
} else {
/* For aliased inputs, just append to the wrmask.. ie. if we
* first see a vec2 index at slot N, and then later a vec4,
* the wrmask of the resulting overlapped vec2 and vec4 is 0xf
*/
input->regs[0]->wrmask |= compmask;
}
for (int i = 0; i < ncomp + frac; i++) {
unsigned idx = (n * 4) + i;
compile_assert(ctx, idx < ctx->ninputs);
/* fixup the src wrmask to avoid validation fail */
if (ctx->inputs[idx] && (ctx->inputs[idx] != input)) {
ctx->inputs[idx]->regs[1]->wrmask = input->regs[0]->wrmask;
continue;
}
ir3_split_dest(ctx->block, &ctx->inputs[idx], input, i, 1);
}
for (int i = 0; i < ncomp; i++) {
unsigned idx = (n * 4) + i + frac;
ctx->last_dst[i] = ctx->inputs[idx];
}
}
}
/* Initially we assign non-packed inloc's for varyings, as we don't really
* know up-front which components will be unused. After all the compilation
* stages we scan the shader to see which components are actually used, and
* re-pack the inlocs to eliminate unneeded varyings.
*/
static void
pack_inlocs(struct ir3_context *ctx)
{
struct ir3_shader_variant *so = ctx->so;
uint8_t used_components[so->inputs_count];
memset(used_components, 0, sizeof(used_components));
/*
* First Step: scan shader to find which bary.f/ldlv remain:
*/
foreach_block (block, &ctx->ir->block_list) {
foreach_instr (instr, &block->instr_list) {
if (is_input(instr)) {
unsigned inloc = instr->regs[1]->iim_val;
unsigned i = inloc / 4;
unsigned j = inloc % 4;
compile_assert(ctx, instr->regs[1]->flags & IR3_REG_IMMED);
compile_assert(ctx, i < so->inputs_count);
used_components[i] |= 1 << j;
} else if (instr->opc == OPC_META_TEX_PREFETCH) {
for (int n = 0; n < 2; n++) {
unsigned inloc = instr->prefetch.input_offset + n;
unsigned i = inloc / 4;
unsigned j = inloc % 4;
compile_assert(ctx, i < so->inputs_count);
used_components[i] |= 1 << j;
}
}
}
}
/*
* Second Step: reassign varying inloc/slots:
*/
unsigned actual_in = 0;
unsigned inloc = 0;
/* for clip+cull distances, unused components can't be eliminated because
* they're read by fixed-function, even if there's a hole. Note that
* clip/cull distance arrays must be declared in the FS, so we can just
* use the NIR clip/cull distances to avoid reading ucp_enables in the
* shader key.
*/
unsigned clip_cull_size =
ctx->so->shader->nir->info.clip_distance_array_size +
ctx->so->shader->nir->info.cull_distance_array_size;
unsigned clip_cull_mask = MASK(clip_cull_size);
for (unsigned i = 0; i < so->inputs_count; i++) {
unsigned compmask = 0, maxcomp = 0;
so->inputs[i].inloc = inloc;
so->inputs[i].bary = false;
if (so->inputs[i].slot == VARYING_SLOT_CLIP_DIST0 ||
so->inputs[i].slot == VARYING_SLOT_CLIP_DIST1) {
if (so->inputs[i].slot == VARYING_SLOT_CLIP_DIST0)
compmask = clip_cull_mask & 0xf;
else
compmask = clip_cull_mask >> 4;
used_components[i] = compmask;
}
for (unsigned j = 0; j < 4; j++) {
if (!(used_components[i] & (1 << j)))
continue;
compmask |= (1 << j);
actual_in++;
maxcomp = j + 1;
/* at this point, since used_components[i] mask is only
* considering varyings (ie. not sysvals) we know this
* is a varying:
*/
so->inputs[i].bary = true;
}
if (so->inputs[i].bary) {
so->varying_in++;
so->inputs[i].compmask = (1 << maxcomp) - 1;
inloc += maxcomp;
}
}
/*
* Third Step: reassign packed inloc's:
*/
foreach_block (block, &ctx->ir->block_list) {
foreach_instr (instr, &block->instr_list) {
if (is_input(instr)) {
unsigned inloc = instr->regs[1]->iim_val;
unsigned i = inloc / 4;
unsigned j = inloc % 4;
instr->regs[1]->iim_val = so->inputs[i].inloc + j;
} else if (instr->opc == OPC_META_TEX_PREFETCH) {
unsigned i = instr->prefetch.input_offset / 4;
unsigned j = instr->prefetch.input_offset % 4;
instr->prefetch.input_offset = so->inputs[i].inloc + j;
}
}
}
}
static void
setup_output(struct ir3_context *ctx, nir_intrinsic_instr *intr)
{
struct ir3_shader_variant *so = ctx->so;
nir_io_semantics io = nir_intrinsic_io_semantics(intr);
compile_assert(ctx, nir_src_is_const(intr->src[1]));
unsigned offset = nir_src_as_uint(intr->src[1]);
unsigned n = nir_intrinsic_base(intr) + offset;
unsigned frac = nir_intrinsic_component(intr);
unsigned ncomp = nir_intrinsic_src_components(intr, 0);
/* For per-view variables, each user-facing slot corresponds to multiple
* views, each with a corresponding driver_location, and the offset is for
* the driver_location. To properly figure out of the slot, we'd need to
* plumb through the number of views. However, for now we only use
* per-view with gl_Position, so we assume that the variable is not an
* array or matrix (so there are no indirect accesses to the variable
* itself) and the indirect offset corresponds to the view.
*/
unsigned slot = io.location + (io.per_view ? 0 : offset);
if (ctx->so->type == MESA_SHADER_FRAGMENT) {
switch (slot) {
case FRAG_RESULT_DEPTH:
so->writes_pos = true;
break;
case FRAG_RESULT_COLOR:
if (!ctx->s->info.fs.color_is_dual_source) {
so->color0_mrt = 1;
} else {
slot = FRAG_RESULT_DATA0 + io.dual_source_blend_index;
}
break;
case FRAG_RESULT_SAMPLE_MASK:
so->writes_smask = true;
break;
case FRAG_RESULT_STENCIL:
so->writes_stencilref = true;
break;
default:
slot += io.dual_source_blend_index; /* For dual-src blend */
if (slot >= FRAG_RESULT_DATA0)
break;
ir3_context_error(ctx, "unknown FS output name: %s\n",
gl_frag_result_name(slot));
}
} else if (ctx->so->type == MESA_SHADER_VERTEX ||
ctx->so->type == MESA_SHADER_TESS_EVAL ||
ctx->so->type == MESA_SHADER_GEOMETRY) {
switch (slot) {
case VARYING_SLOT_POS:
so->writes_pos = true;
break;
case VARYING_SLOT_PSIZ:
so->writes_psize = true;
break;
case VARYING_SLOT_PRIMITIVE_ID:
case VARYING_SLOT_GS_VERTEX_FLAGS_IR3:
debug_assert(ctx->so->type == MESA_SHADER_GEOMETRY);
/* fall through */
case VARYING_SLOT_COL0:
case VARYING_SLOT_COL1:
case VARYING_SLOT_BFC0:
case VARYING_SLOT_BFC1:
case VARYING_SLOT_FOGC:
case VARYING_SLOT_CLIP_DIST0:
case VARYING_SLOT_CLIP_DIST1:
case VARYING_SLOT_CLIP_VERTEX:
case VARYING_SLOT_LAYER:
case VARYING_SLOT_VIEWPORT:
break;
default:
if (slot >= VARYING_SLOT_VAR0)
break;
if ((VARYING_SLOT_TEX0 <= slot) && (slot <= VARYING_SLOT_TEX7))
break;
ir3_context_error(ctx, "unknown %s shader output name: %s\n",
_mesa_shader_stage_to_string(ctx->so->type),
gl_varying_slot_name_for_stage(slot, ctx->so->type));
}
} else {
ir3_context_error(ctx, "unknown shader type: %d\n", ctx->so->type);
}
so->outputs_count = MAX2(so->outputs_count, n + 1);
compile_assert(ctx, so->outputs_count < ARRAY_SIZE(so->outputs));
so->outputs[n].slot = slot;
if (io.per_view)
so->outputs[n].view = offset;
for (int i = 0; i < ncomp; i++) {
unsigned idx = (n * 4) + i + frac;
compile_assert(ctx, idx < ctx->noutputs);
ctx->outputs[idx] = create_immed(ctx->block, fui(0.0));
}
/* if varying packing doesn't happen, we could end up in a situation
* with "holes" in the output, and since the per-generation code that
* sets up varying linkage registers doesn't expect to have more than
* one varying per vec4 slot, pad the holes.
*
* Note that this should probably generate a performance warning of
* some sort.
*/
for (int i = 0; i < frac; i++) {
unsigned idx = (n * 4) + i;
if (!ctx->outputs[idx]) {
ctx->outputs[idx] = create_immed(ctx->block, fui(0.0));
}
}
struct ir3_instruction * const *src = ir3_get_src(ctx, &intr->src[0]);
for (int i = 0; i < ncomp; i++) {
unsigned idx = (n * 4) + i + frac;
ctx->outputs[idx] = src[i];
}
}
static void
emit_instructions(struct ir3_context *ctx)
{
nir_function_impl *fxn = nir_shader_get_entrypoint(ctx->s);
/* some varying setup which can't be done in setup_input(): */
if (ctx->so->type == MESA_SHADER_FRAGMENT) {
nir_foreach_shader_in_variable (var, ctx->s) {
/* if any varyings have 'sample' qualifer, that triggers us
* to run in per-sample mode:
*/
if (var->data.sample)
ctx->so->per_samp = true;
/* set rasterflat flag for front/back color */
if (var->data.interpolation == INTERP_MODE_NONE) {
switch (var->data.location) {
case VARYING_SLOT_COL0:
case VARYING_SLOT_COL1:
case VARYING_SLOT_BFC0:
case VARYING_SLOT_BFC1:
ctx->so->inputs[var->data.driver_location].rasterflat = true;
break;
default:
break;
}
}
}
}
/* TODO: for GS/HS/DS, load_input isn't used. but ctx->s->num_inputs is non-zero
* likely the same for num_outputs in cases where store_output isn't used
*/
ctx->so->inputs_count = ctx->s->num_inputs;
ctx->ninputs = ctx->s->num_inputs * 4;
ctx->noutputs = ctx->s->num_outputs * 4;
ctx->inputs = rzalloc_array(ctx, struct ir3_instruction *, ctx->ninputs);
ctx->outputs = rzalloc_array(ctx, struct ir3_instruction *, ctx->noutputs);
ctx->ir = ir3_create(ctx->compiler, ctx->so);
/* Create inputs in first block: */
ctx->block = get_block(ctx, nir_start_block(fxn));
ctx->in_block = ctx->block;
/* for fragment shader, the vcoord input register is used as the
* base for bary.f varying fetch instrs:
*
* TODO defer creating ctx->ij_pixel and corresponding sysvals
* until emit_intrinsic when we know they are actually needed.
* For now, we defer creating ctx->ij_centroid, etc, since we
* only need ij_pixel for "old style" varying inputs (ie.
* tgsi_to_nir)
*/
if (ctx->so->type == MESA_SHADER_FRAGMENT) {
ctx->ij[IJ_PERSP_PIXEL] = create_input(ctx, 0x3);
}
/* Defer add_sysval_input() stuff until after setup_inputs(),
* because sysvals need to be appended after varyings:
*/
if (ctx->ij[IJ_PERSP_PIXEL]) {
add_sysval_input_compmask(ctx, SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL,
0x3, ctx->ij[IJ_PERSP_PIXEL]);
}
/* Tesselation shaders always need primitive ID for indexing the
* BO. Geometry shaders don't always need it but when they do it has be
* delivered and unclobbered in the VS. To make things easy, we always
* make room for it in VS/DS.
*/
bool has_tess = ctx->so->key.tessellation != IR3_TESS_NONE;
bool has_gs = ctx->so->key.has_gs;
switch (ctx->so->type) {
case MESA_SHADER_VERTEX:
if (has_tess) {
ctx->tcs_header = create_sysval_input(ctx, SYSTEM_VALUE_TCS_HEADER_IR3, 0x1);
ctx->primitive_id = create_sysval_input(ctx, SYSTEM_VALUE_PRIMITIVE_ID, 0x1);
} else if (has_gs) {
ctx->gs_header = create_sysval_input(ctx, SYSTEM_VALUE_GS_HEADER_IR3, 0x1);
ctx->primitive_id = create_sysval_input(ctx, SYSTEM_VALUE_PRIMITIVE_ID, 0x1);
}
break;
case MESA_SHADER_TESS_CTRL:
ctx->tcs_header = create_sysval_input(ctx, SYSTEM_VALUE_TCS_HEADER_IR3, 0x1);
ctx->primitive_id = create_sysval_input(ctx, SYSTEM_VALUE_PRIMITIVE_ID, 0x1);
break;
case MESA_SHADER_TESS_EVAL:
if (has_gs)
ctx->gs_header = create_sysval_input(ctx, SYSTEM_VALUE_GS_HEADER_IR3, 0x1);
ctx->primitive_id = create_sysval_input(ctx, SYSTEM_VALUE_PRIMITIVE_ID, 0x1);
break;
case MESA_SHADER_GEOMETRY:
ctx->gs_header = create_sysval_input(ctx, SYSTEM_VALUE_GS_HEADER_IR3, 0x1);
ctx->primitive_id = create_sysval_input(ctx, SYSTEM_VALUE_PRIMITIVE_ID, 0x1);
break;
default:
break;
}
/* Find # of samplers. Just assume that we'll be reading from images.. if
* it is write-only we don't have to count it, but after lowering derefs
* is too late to compact indices for that.
*/
ctx->so->num_samp = util_last_bit(ctx->s->info.textures_used) + ctx->s->info.num_images;
/* Save off clip+cull information. Note that in OpenGL clip planes may
* be individually enabled/disabled, so we can't use the
* clip_distance_array_size for them.
*/
ctx->so->clip_mask = ctx->so->key.ucp_enables;
ctx->so->cull_mask = MASK(ctx->s->info.cull_distance_array_size) <<
ctx->s->info.clip_distance_array_size;
ctx->so->pvtmem_size = ctx->s->scratch_size;
ctx->so->shared_size = ctx->s->shared_size;
/* NOTE: need to do something more clever when we support >1 fxn */
nir_foreach_register (reg, &fxn->registers) {
ir3_declare_array(ctx, reg);
}
/* And emit the body: */
ctx->impl = fxn;
emit_function(ctx, fxn);
}
/* Fixup tex sampler state for astc/srgb workaround instructions. We
* need to assign the tex state indexes for these after we know the
* max tex index.
*/
static void
fixup_astc_srgb(struct ir3_context *ctx)
{
struct ir3_shader_variant *so = ctx->so;
/* indexed by original tex idx, value is newly assigned alpha sampler
* state tex idx. Zero is invalid since there is at least one sampler
* if we get here.
*/
unsigned alt_tex_state[16] = {0};
unsigned tex_idx = ctx->max_texture_index + 1;
unsigned idx = 0;
so->astc_srgb.base = tex_idx;
for (unsigned i = 0; i < ctx->ir->astc_srgb_count; i++) {
struct ir3_instruction *sam = ctx->ir->astc_srgb[i];
compile_assert(ctx, sam->cat5.tex < ARRAY_SIZE(alt_tex_state));
if (alt_tex_state[sam->cat5.tex] == 0) {
/* assign new alternate/alpha tex state slot: */
alt_tex_state[sam->cat5.tex] = tex_idx++;
so->astc_srgb.orig_idx[idx++] = sam->cat5.tex;
so->astc_srgb.count++;
}
sam->cat5.tex = alt_tex_state[sam->cat5.tex];
}
}
static bool
output_slot_used_for_binning(gl_varying_slot slot)
{
return slot == VARYING_SLOT_POS || slot == VARYING_SLOT_PSIZ ||
slot == VARYING_SLOT_CLIP_DIST0 || slot == VARYING_SLOT_CLIP_DIST1;
}
static void
fixup_binning_pass(struct ir3_context *ctx)
{
struct ir3_shader_variant *so = ctx->so;
struct ir3 *ir = ctx->ir;
unsigned i, j;
/* first pass, remove unused outputs from the IR level outputs: */
for (i = 0, j = 0; i < ir->outputs_count; i++) {
struct ir3_instruction *out = ir->outputs[i];
assert(out->opc == OPC_META_COLLECT);
unsigned outidx = out->collect.outidx;
unsigned slot = so->outputs[outidx].slot;
if (output_slot_used_for_binning(slot)) {
ir->outputs[j] = ir->outputs[i];
j++;
}
}
ir->outputs_count = j;
/* second pass, cleanup the unused slots in ir3_shader_variant::outputs
* table:
*/
for (i = 0, j = 0; i < so->outputs_count; i++) {
unsigned slot = so->outputs[i].slot;
if (output_slot_used_for_binning(slot)) {
so->outputs[j] = so->outputs[i];
/* fixup outidx to point to new output table entry: */
foreach_output (out, ir) {
if (out->collect.outidx == i) {
out->collect.outidx = j;
break;
}
}
j++;
}
}
so->outputs_count = j;
}
static void
collect_tex_prefetches(struct ir3_context *ctx, struct ir3 *ir)
{
unsigned idx = 0;
/* Collect sampling instructions eligible for pre-dispatch. */
foreach_block (block, &ir->block_list) {
foreach_instr_safe (instr, &block->instr_list) {
if (instr->opc == OPC_META_TEX_PREFETCH) {
assert(idx < ARRAY_SIZE(ctx->so->sampler_prefetch));
struct ir3_sampler_prefetch *fetch =
&ctx->so->sampler_prefetch[idx];
idx++;
if (instr->flags & IR3_INSTR_B) {
fetch->cmd = IR3_SAMPLER_BINDLESS_PREFETCH_CMD;
/* In bindless mode, the index is actually the base */
fetch->tex_id = instr->prefetch.tex_base;
fetch->samp_id = instr->prefetch.samp_base;
fetch->tex_bindless_id = instr->prefetch.tex;
fetch->samp_bindless_id = instr->prefetch.samp;
} else {
fetch->cmd = IR3_SAMPLER_PREFETCH_CMD;
fetch->tex_id = instr->prefetch.tex;
fetch->samp_id = instr->prefetch.samp;
}
fetch->wrmask = instr->regs[0]->wrmask;
fetch->dst = instr->regs[0]->num;
fetch->src = instr->prefetch.input_offset;
/* These are the limits on a5xx/a6xx, we might need to
* revisit if SP_FS_PREFETCH[n] changes on later gens:
*/
assert(fetch->dst <= 0x3f);
assert(fetch->tex_id <= 0x1f);
assert(fetch->samp_id < 0xf);
ctx->so->total_in =
MAX2(ctx->so->total_in, instr->prefetch.input_offset + 2);
fetch->half_precision = !!(instr->regs[0]->flags & IR3_REG_HALF);
/* Remove the prefetch placeholder instruction: */
list_delinit(&instr->node);
}
}
}
}
int
ir3_compile_shader_nir(struct ir3_compiler *compiler,
struct ir3_shader_variant *so)
{
struct ir3_context *ctx;
struct ir3 *ir;
int ret = 0, max_bary;
bool progress;
assert(!so->ir);
ctx = ir3_context_init(compiler, so);
if (!ctx) {
DBG("INIT failed!");
ret = -1;
goto out;
}
emit_instructions(ctx);
if (ctx->error) {
DBG("EMIT failed!");
ret = -1;
goto out;
}
ir = so->ir = ctx->ir;
assert((ctx->noutputs % 4) == 0);
/* Setup IR level outputs, which are "collects" that gather
* the scalar components of outputs.
*/
for (unsigned i = 0; i < ctx->noutputs; i += 4) {
unsigned ncomp = 0;
/* figure out the # of components written:
*
* TODO do we need to handle holes, ie. if .x and .z
* components written, but .y component not written?
*/
for (unsigned j = 0; j < 4; j++) {
if (!ctx->outputs[i + j])
break;
ncomp++;
}
/* Note that in some stages, like TCS, store_output is
* lowered to memory writes, so no components of the
* are "written" from the PoV of traditional store-
* output instructions:
*/
if (!ncomp)
continue;
struct ir3_instruction *out =
ir3_create_collect(ctx, &ctx->outputs[i], ncomp);
int outidx = i / 4;
assert(outidx < so->outputs_count);
/* stash index into so->outputs[] so we can map the
* output back to slot/etc later:
*/
out->collect.outidx = outidx;
array_insert(ir, ir->outputs, out);
}
/* Set up the gs header as an output for the vertex shader so it won't
* clobber it for the tess ctrl shader.
*
* TODO this could probably be done more cleanly in a nir pass.
*/
if (ctx->so->type == MESA_SHADER_VERTEX ||
(ctx->so->key.has_gs && ctx->so->type == MESA_SHADER_TESS_EVAL)) {
if (ctx->primitive_id) {
unsigned n = so->outputs_count++;
so->outputs[n].slot = VARYING_SLOT_PRIMITIVE_ID;
struct ir3_instruction *out =
ir3_create_collect(ctx, &ctx->primitive_id, 1);
out->collect.outidx = n;
array_insert(ir, ir->outputs, out);
}
if (ctx->gs_header) {
unsigned n = so->outputs_count++;
so->outputs[n].slot = VARYING_SLOT_GS_HEADER_IR3;
struct ir3_instruction *out =
ir3_create_collect(ctx, &ctx->gs_header, 1);
out->collect.outidx = n;
array_insert(ir, ir->outputs, out);
}
if (ctx->tcs_header) {
unsigned n = so->outputs_count++;
so->outputs[n].slot = VARYING_SLOT_TCS_HEADER_IR3;
struct ir3_instruction *out =
ir3_create_collect(ctx, &ctx->tcs_header, 1);
out->collect.outidx = n;
array_insert(ir, ir->outputs, out);
}
}
/* for a6xx+, binning and draw pass VS use same VBO state, so we
* need to make sure not to remove any inputs that are used by
* the nonbinning VS.
*/
if (ctx->compiler->gpu_id >= 600 && so->binning_pass &&
so->type == MESA_SHADER_VERTEX) {
for (int i = 0; i < ctx->ninputs; i++) {
struct ir3_instruction *in = ctx->inputs[i];
if (!in)
continue;
unsigned n = i / 4;
unsigned c = i % 4;
debug_assert(n < so->nonbinning->inputs_count);
if (so->nonbinning->inputs[n].sysval)
continue;
/* be sure to keep inputs, even if only used in VS */
if (so->nonbinning->inputs[n].compmask & (1 << c))
array_insert(in->block, in->block->keeps, in);
}
}
/* at this point, for binning pass, throw away unneeded outputs: */
if (so->binning_pass && (ctx->compiler->gpu_id < 600))
fixup_binning_pass(ctx);
ir3_debug_print(ir, "AFTER: nir->ir3");
ir3_validate(ir);
do {
progress = false;
progress |= IR3_PASS(ir, ir3_cf);
progress |= IR3_PASS(ir, ir3_cp, so);
progress |= IR3_PASS(ir, ir3_dce, so);
} while (progress);
/* at this point, for binning pass, throw away unneeded outputs:
* Note that for a6xx and later, we do this after ir3_cp to ensure
* that the uniform/constant layout for BS and VS matches, so that
* we can re-use same VS_CONST state group.
*/
if (so->binning_pass && (ctx->compiler->gpu_id >= 600)) {
fixup_binning_pass(ctx);
/* cleanup the result of removing unneeded outputs: */
while (IR3_PASS(ir, ir3_dce, so)) {}
}
IR3_PASS(ir, ir3_sched_add_deps);
/* Group left/right neighbors, inserting mov's where needed to
* solve conflicts:
*/
IR3_PASS(ir, ir3_group);
/* At this point, all the dead code should be long gone: */
assert(!IR3_PASS(ir, ir3_dce, so));
ret = ir3_sched(ir);
if (ret) {
DBG("SCHED failed!");
goto out;
}
ir3_debug_print(ir, "AFTER: ir3_sched");
if (IR3_PASS(ir, ir3_cp_postsched)) {
/* cleanup the result of removing unneeded mov's: */
while (IR3_PASS(ir, ir3_dce, so)) {}
}
/* Pre-assign VS inputs on a6xx+ binning pass shader, to align
* with draw pass VS, so binning and draw pass can both use the
* same VBO state.
*
* Note that VS inputs are expected to be full precision.
*/
bool pre_assign_inputs = (ir->compiler->gpu_id >= 600) &&
(ir->type == MESA_SHADER_VERTEX) &&
so->binning_pass;
if (pre_assign_inputs) {
for (unsigned i = 0; i < ctx->ninputs; i++) {
struct ir3_instruction *instr = ctx->inputs[i];
if (!instr)
continue;
unsigned n = i / 4;
unsigned c = i % 4;
unsigned regid = so->nonbinning->inputs[n].regid + c;
instr->regs[0]->num = regid;
}
ret = ir3_ra(so, ctx->inputs, ctx->ninputs);
} else if (ctx->tcs_header) {
/* We need to have these values in the same registers between VS and TCS
* since the VS chains to TCS and doesn't get the sysvals redelivered.
*/
ctx->tcs_header->regs[0]->num = regid(0, 0);
ctx->primitive_id->regs[0]->num = regid(0, 1);
struct ir3_instruction *precolor[] = { ctx->tcs_header, ctx->primitive_id };
ret = ir3_ra(so, precolor, ARRAY_SIZE(precolor));
} else if (ctx->gs_header) {
/* We need to have these values in the same registers between producer
* (VS or DS) and GS since the producer chains to GS and doesn't get
* the sysvals redelivered.
*/
ctx->gs_header->regs[0]->num = regid(0, 0);
ctx->primitive_id->regs[0]->num = regid(0, 1);
struct ir3_instruction *precolor[] = { ctx->gs_header, ctx->primitive_id };
ret = ir3_ra(so, precolor, ARRAY_SIZE(precolor));
} else if (so->num_sampler_prefetch) {
assert(so->type == MESA_SHADER_FRAGMENT);
struct ir3_instruction *precolor[2];
int idx = 0;
foreach_input (instr, ir) {
if (instr->input.sysval != SYSTEM_VALUE_BARYCENTRIC_PERSP_PIXEL)
continue;
assert(idx < ARRAY_SIZE(precolor));
precolor[idx] = instr;
instr->regs[0]->num = idx;
idx++;
}
ret = ir3_ra(so, precolor, idx);
} else {
ret = ir3_ra(so, NULL, 0);
}
if (ret) {
DBG("RA failed!");
goto out;
}
IR3_PASS(ir, ir3_postsched, so);
if (compiler->gpu_id >= 600) {
IR3_PASS(ir, ir3_a6xx_fixup_atomic_dests, so);
}
if (so->type == MESA_SHADER_FRAGMENT)
pack_inlocs(ctx);
/*
* Fixup inputs/outputs to point to the actual registers assigned:
*
* 1) initialize to r63.x (invalid/unused)
* 2) iterate IR level inputs/outputs and update the variants
* inputs/outputs table based on the assigned registers for
* the remaining inputs/outputs.
*/
for (unsigned i = 0; i < so->inputs_count; i++)
so->inputs[i].regid = INVALID_REG;
for (unsigned i = 0; i < so->outputs_count; i++)
so->outputs[i].regid = INVALID_REG;
foreach_output (out, ir) {
assert(out->opc == OPC_META_COLLECT);
unsigned outidx = out->collect.outidx;
so->outputs[outidx].regid = out->regs[0]->num;
so->outputs[outidx].half = !!(out->regs[0]->flags & IR3_REG_HALF);
}
foreach_input (in, ir) {
assert(in->opc == OPC_META_INPUT);
unsigned inidx = in->input.inidx;
if (pre_assign_inputs && !so->inputs[inidx].sysval) {
if (VALIDREG(so->nonbinning->inputs[inidx].regid)) {
compile_assert(ctx, in->regs[0]->num ==
so->nonbinning->inputs[inidx].regid);
compile_assert(ctx, !!(in->regs[0]->flags & IR3_REG_HALF) ==
so->nonbinning->inputs[inidx].half);
}
so->inputs[inidx].regid = so->nonbinning->inputs[inidx].regid;
so->inputs[inidx].half = so->nonbinning->inputs[inidx].half;
} else {
so->inputs[inidx].regid = in->regs[0]->num;
so->inputs[inidx].half = !!(in->regs[0]->flags & IR3_REG_HALF);
}
}
if (ctx->astc_srgb)
fixup_astc_srgb(ctx);
/* We need to do legalize after (for frag shader's) the "bary.f"
* offsets (inloc) have been assigned.
*/
IR3_PASS(ir, ir3_legalize, so, &max_bary);
/* Set (ss)(sy) on first TCS and GEOMETRY instructions, since we don't
* know what we might have to wait on when coming in from VS chsh.
*/
if (so->type == MESA_SHADER_TESS_CTRL ||
so->type == MESA_SHADER_GEOMETRY ) {
foreach_block (block, &ir->block_list) {
foreach_instr (instr, &block->instr_list) {
instr->flags |= IR3_INSTR_SS | IR3_INSTR_SY;
break;
}
}
}
so->branchstack = ctx->max_stack;
/* Note that actual_in counts inputs that are not bary.f'd for FS: */
if (so->type == MESA_SHADER_FRAGMENT)
so->total_in = max_bary + 1;
/* Collect sampling instructions eligible for pre-dispatch. */
collect_tex_prefetches(ctx, ir);
if (so->type == MESA_SHADER_FRAGMENT &&
ctx->s->info.fs.needs_quad_helper_invocations)
so->need_pixlod = true;
out:
if (ret) {
if (so->ir)
ir3_destroy(so->ir);
so->ir = NULL;
}
ir3_context_free(ctx);
return ret;
}
| 29.274846 | 93 | 0.69242 | [
"geometry",
"transform"
] |
7c0c21c6514a045be170174c50383f3f2f74b5b1 | 461 | h | C | NNACommunity/NNACommunity/NNAEmotion/PostReplyTableView.h | LebenNNA/NNACommunity | 6cd8ba1098755f0d01d4d768fee00e64aae071c2 | [
"MIT"
] | 1 | 2016-03-10T16:37:33.000Z | 2016-03-10T16:37:33.000Z | NNACommunity/NNACommunity/NNAEmotion/PostReplyTableView.h | LebenNNA/NNACommunity | 6cd8ba1098755f0d01d4d768fee00e64aae071c2 | [
"MIT"
] | null | null | null | NNACommunity/NNACommunity/NNAEmotion/PostReplyTableView.h | LebenNNA/NNACommunity | 6cd8ba1098755f0d01d4d768fee00e64aae071c2 | [
"MIT"
] | null | null | null | //
// PostReplyTableView.h
// NNACommunity
//
// Created by Leben.NNA on 16/3/12.
// Copyright © 2016年 Leben.NNA. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "PostReplyModel.h"
@interface PostReplyTableView : UITableView <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *replyArr; //临时存数据演示用
- (void)setRowClicked:(void(^)(NSInteger row))handler;
- (void)loadWithModel:(PostReplyModel *)model;
@end
| 23.05 | 88 | 0.741866 | [
"model"
] |
7c0d3273c8622e26b1bdf21f116ca482bd40e3a2 | 1,190 | h | C | misc/gnuplot/GnuplotPlotElementHistogram.h | k-a-z-u/KLib | cd4d11fb68921b2ff42a6f90055447f5df9a5b1e | [
"Apache-2.0"
] | 2 | 2016-12-17T10:14:18.000Z | 2019-07-16T09:06:07.000Z | misc/gnuplot/GnuplotPlotElementHistogram.h | k-a-z-u/KLib | cd4d11fb68921b2ff42a6f90055447f5df9a5b1e | [
"Apache-2.0"
] | null | null | null | misc/gnuplot/GnuplotPlotElementHistogram.h | k-a-z-u/KLib | cd4d11fb68921b2ff42a6f90055447f5df9a5b1e | [
"Apache-2.0"
] | 3 | 2015-06-23T09:48:49.000Z | 2018-03-28T08:28:06.000Z | #ifndef GNUPLOTPLOTELEMENTHISTOGRAM_H
#define GNUPLOTPLOTELEMENTHISTOGRAM_H
#include <map>
#include "GnuplotPlotElementRaw.h"
#include "../../math/statistics/SimpleHistogram.h"
#include "attributes/GnuplotAttrStroke.h"
namespace K {
class GnuplotPlotElementHistogram : public GnuplotPlotElementRaw, public GnuplotAttrStroke {
public:
void addGeneralTo(std::stringstream& ss) const override {
ss << "set style fill solid 0.5 border lt -1\n";
}
void addHeaderTo(std::stringstream& ss, const GnuplotStringMod* mod) const override {
ss << "'-' with boxes ";
ss << attrCustom << " ";
ss << stroke.toGP();
ss << " title '" << mod->modEntryTitle(title) << "'";
}
/** add a new sample to the histogram */
void add(const SimpleHistogram& h) {
for (const auto& it : h.getFilled()) {
points.push_back(K::GnuplotPoint2(it.first, it.second));
}
}
/** remove all points */
void clear() {
points.clear();
}
/** remove the given index */
void remove(const int idx) {
points.erase(points.begin() + idx);
}
/** number of entries */
size_t size() const {
return points.size();
}
};
}
#endif // GNUPLOTPLOTELEMENTHISTOGRAM_H
| 21.25 | 93 | 0.664706 | [
"solid"
] |
7c0ef5fdaabe93a66be0dbd0f6eab9abb8eb7b5c | 10,147 | h | C | include/meanie3D/clustering/cluster_utils_impl.h | JuergenSimon/meanie3D | 776890f6b63d735153566fecc5a76c68a23ef333 | [
"MIT"
] | null | null | null | include/meanie3D/clustering/cluster_utils_impl.h | JuergenSimon/meanie3D | 776890f6b63d735153566fecc5a76c68a23ef333 | [
"MIT"
] | 5 | 2016-09-17T13:46:23.000Z | 2020-07-01T16:31:29.000Z | include/meanie3D/clustering/cluster_utils_impl.h | JuergenSimon/meanie3D | 776890f6b63d735153566fecc5a76c68a23ef333 | [
"MIT"
] | 3 | 2016-04-18T13:13:28.000Z | 2020-06-18T12:30:05.000Z | /* The MIT License (MIT)
*
* (c) Jürgen Simon 2014 (juergen.simon@uni-bonn.de)
*
* 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.
*/
#ifndef M3D_CLUSTERUTILS_IMPL_H
#define M3D_CLUSTERUTILS_IMPL_H
#include <meanie3D/defines.h>
#include <meanie3D/namespaces.h>
#include <meanie3D/utils.h>
#include <boost/progress.hpp>
namespace m3D {
template<typename T>
ClusterUtils<T>::ClusterUtils(float merge_threshold)
: m_merge_threshold(merge_threshold) {
}
template<typename T>
void
ClusterUtils<T>::filter_with_previous_clusters(typename ClusterList<T>::ptr previous,
typename ClusterList<T>::ptr current,
CoordinateSystem <T> *coord_system,
WeightFunction <T> *weight_function,
const Verbosity verbosity) {
using utils::SimpleMatrix;
using namespace utils::vectors;
if (verbosity >= VerbosityNormal) {
cout << endl << "Filtering with previous results ..." << endl;
start_timer();
}
// sanity check
if (current->clusters.size() == 0 || previous->clusters.size() == 0) {
if (verbosity >= VerbosityNormal) {
cout << "Nothing to do." << endl;
return;
}
}
// Provide index for overlap calculations
ClusterIndex<T> index_of_previous(previous->clusters, coord_system->get_dimension_sizes());
size_t new_count = current->clusters.size();
size_t old_count = previous->clusters.size();
id_t current_id = current->clusters[current->clusters.size() - 1]->id;
typename SimpleMatrix<T>::matrix_t coverOldByNew = SimpleMatrix<T>::create_matrix(new_count, old_count);
typename SimpleMatrix<T>::matrix_t coverNewByOld = SimpleMatrix<T>::create_matrix(new_count, old_count);
// compute overlap
size_t n, m;
boost::progress_display *progress = NULL;
if (verbosity >= VerbosityNormal) {
progress = new boost::progress_display(2 * old_count);
}
for (m = 0; m < old_count; m++) {
typename Cluster<T>::ptr oldCluster = previous->clusters[m];
if (verbosity >= VerbosityNormal) {
progress->operator++();
}
for (n = 0; n < new_count; n++) {
typename Cluster<T>::ptr newCluster = current->clusters[n];
// Calculate overlap
T overlap = index_of_previous.occupation_ratio(newCluster, oldCluster);
if (overlap > 0 && verbosity >= VerbosityDetails) {
printf("old #%4lu with new #%4lu overlap = %3.2f\n", oldCluster->id, newCluster->id, overlap);
}
coverNewByOld[n][m] = overlap;
}
}
// for each new blob check coverage of old blobs
typedef set<typename Cluster<T>::ptr> cset_t;
cset_t erased, merged;
for (m = 0; m < previous->clusters.size(); m++) {
if (verbosity >= VerbosityNormal) {
progress->operator++();
}
typename Cluster<T>::ptr old_cluster = previous->clusters[m];
vector<size_t> candidates;
// figure out the largest candidate
// TODO: do we still need this here?
for (n = 0; n < current->clusters.size(); n++) {
T overlap = coverNewByOld[n][m];
if (overlap >= 0.33) {
candidates.push_back(n);
}
}
if (candidates.size() > 1) {
if (verbosity >= VerbosityDetails) {
printf("Old cluster ID#%4lu seems to have split into new clusters IDs ", old_cluster->id);
for (int i = 0; i < candidates.size(); i++) {
typename Cluster<T>::ptr c = current->clusters[candidates[i]];
printf("#%lu ", c->id);
}
cout << endl;
}
typename Cluster<T>::ptr merged_cluster
= new Cluster<T>(old_cluster->mode, old_cluster->spatial_rank());
merged_cluster->id = ++current_id;
vector<T> mode(previous->rank(), 0.0);
// merge with those candidates, that are direct neighbours
// neglect those, that have no direct boundary with any of
// the other candidates
size_t num_picked_candidates = 0;
for (int i = 0; i < candidates.size(); i++) {
bool have_boundary = true;
if (have_boundary) {
typename Cluster<T>::ptr c = current->clusters[candidates[i]];
merged_cluster->add_points(c->get_points());
mode += c->mode;
erased.insert(c);
num_picked_candidates++;
}
}
if (num_picked_candidates > 1) {
merged_cluster->mode = mode / ((T) num_picked_candidates);
merged.insert(merged_cluster);
} else {
delete merged_cluster;
}
}
}
// remove the erased ones and add the merged ones
typename cset_t::iterator ci;
for (ci = erased.begin(); ci != erased.end(); ++ci) {
typename Cluster<T>::ptr c = *ci;
typename Cluster<T>::list::iterator di = find(current->clusters.begin(), current->clusters.end(), c);
current->clusters.erase(di);
delete c;
}
for (ci = merged.begin(); ci != merged.end(); ci++) {
typename Cluster<T>::ptr c = *ci;
current->clusters.push_back(c);
}
if (verbosity >= VerbosityNormal) {
cout << " done. (Found " << current->clusters.size() << " clusters in " << stop_timer() << " seconds)" <<
endl;
delete progress;
}
}
template<typename T>
void
ClusterUtils<T>::replace_points_from_datastore(typename ClusterList<T>::ptr list,
typename DataStore<T>::ptr dataStore) {
for (size_t ci = 0; ci < list->size(); ci++) {
typename Cluster<T>::ptr c = list->clusters.at(ci);
typename Point<T>::list::iterator pi;
for (pi = c->get_points().begin(); pi != c->get_points().end(); ++pi) {
typename Point<T>::ptr p = *pi;
for (int vi = 0; vi < dataStore->rank(); vi++) {
bool isInRange = false;
bool isValid = false;
T value = dataStore->get(vi, p->gridpoint, isInRange, isValid);
p->values[c->spatial_rank() + vi] = value;
}
}
}
}
template<typename T>
void
ClusterUtils<T>::obtain_margin_flag(typename ClusterList<T>::ptr list,
typename FeatureSpace<T>::ptr fs) {
vector<size_t> dims = fs->coordinate_system->get_dimension_sizes();
ArrayIndex<T> index(dims, fs->points, false);
typename Cluster<T>::list::iterator ci;
for (ci = list->clusters.begin(); ci != list->clusters.end(); ++ci) {
typename Cluster<T>::ptr c = *ci;
typename Point<T>::list::iterator pi;
for (pi = c->get_points().begin(); pi != c->get_points().end() && !c->has_margin_points(); ++pi) {
typename Point<T>::ptr p = *pi;
if (!p->isOriginalPoint) continue;
typename Point<T>::list neighbors;
neighbors = index.find_neighbours(p->gridpoint, 1);
typename Point<T>::list::iterator ni;
for (ni = neighbors.begin(); ni != neighbors.end(); ++ni) {
typename Point<T>::ptr n = *ni;
if (fs->off_limits()->get(n->gridpoint)) {
c->set_has_margin_points(true);
break;
}
}
}
}
}
template<typename T>
void
ClusterUtils<T>::provideUuids(typename ClusterList<T>::ptr list, uuid_t &uuid) {
typename Cluster<T>::list::iterator ci;
for (ci = list->clusters.begin(); ci != list->clusters.end(); ++ci) {
typename Cluster<T>::ptr c = *ci;
uuid = m3D::nextUuid(uuid);
c->uuid = uuid;
}
}
template<typename T>
void
ClusterUtils<T>::provideIds(typename ClusterList<T>::ptr list, id_t &id) {
typename Cluster<T>::list::iterator ci;
for (ci = list->clusters.begin(); ci != list->clusters.end(); ++ci) {
typename Cluster<T>::ptr c = *ci;
id = m3D::nextId(id);
c->id = id;
}
}
}
#endif
| 38.003745 | 117 | 0.53336 | [
"vector"
] |
7c0f2d72841b378ae54b8436cef651606db79d55 | 6,157 | h | C | headers/view_graph.h | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | 6 | 2018-01-29T10:20:20.000Z | 2021-06-13T05:35:32.000Z | headers/view_graph.h | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | null | null | null | headers/view_graph.h | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | 2 | 2019-04-03T12:10:54.000Z | 2019-05-13T09:44:01.000Z | #ifndef VIEW_GRAPH_H_
#define VIEW_GRAPH_H_
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/impl/point_types.hpp>
#include <pcl/common/transforms.h>
#include <pcl/io/pcd_io.h>
#include <vector>
#include <queue>
class View_Graph
{
private:
typedef pcl::PointXYZ PointT;
typedef pcl::PointCloud<PointT> PointCloudT;
/**
A structure for the node data
*/
struct node
{
PointT viewpoint_;
Eigen::Matrix3d rotation_;
std::vector<int> neighbors_;
float utility_;
int view_index;
float cost;
int previous;
bool operator < (const node &n) const
{
return (cost < n.cost);
}
};
std::vector<node> graph;
std::string model_name_;
std::vector<float> utilities_;
std::vector<bool> valid_nodes_;
std::vector<bool> visited_nodes_; // Array for keeping track of visited nodes
/**
Returns the path to Data in /masters_thesis
*/
boost::filesystem::path
path_to_model_in_model_data (std::string model);
public:
/**
Empty constructor.
*/
View_Graph () : graph () {}
/**
Returns the camera viewpoint for a given view
@param index The view-index
*/
PointT
get_viewpoint (int index);
/**
Returns the rotation matrix for a given view
@param index The view-index
*/
Eigen::Matrix3d
get_rotation (int index);
/**
Returns the neighbors for a given view
@param index The view-index
*/
std::vector<int>
get_neighbors (int index);
/**
Returns the neighbors for a given view
@param index The view-index
*/
int
get_size (void);
/**
Returns the name of the model
*/
std::string
get_model_name (void);
/**
Sets the name of the model
@param model_name The name of the model
*/
void
set_model_name (std::string model_name);
/**
Computes and stores all the valid nodes in the graph. Valid nodes are nodes that are above the plane in the scene and doesn't share similar z-axis as current and previous camera positions.
@param plane The plane in the scene
@param previous_positions The previous camera positions
@param angle_thr The angle threshold to determine if a node is invalid due to having similar z-axis as previous camera locations
*/
void
find_valid_nodes (pcl::ModelCoefficients plane, std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > previous_positions, PointT model_center, float angle_thr);
/**
Determines if two views are neighbors
@param view_index1 The first view
@param view_index2 The second view
@return True if the views are neighbors and false otherwise
*/
bool
is_neighbor (int view_index1, int view_index2);
/**
Set manualy if a view-node is valid or not
@param index The view index
@param value True if the node is valid and false otherwise
*/
void
set_valid_node (int index, bool value);
/**
Returns a vector containing all the valid nodes
@return The vector containing all the valid nodes
*/
std::vector<bool>
get_valid_nodes (void);
/**
Returns the visited nodes during the graph search
@return Vector containing a true value if the node was visited during the graph search.
*/
std::vector<bool>
get_visited_nodes (void);
/**
Stores all viewpoints as a pointcloud
@param viewpoints[out] The pointcloud containing all viewpoints in the graph
*/
void
get_all_viewpoints (PointCloudT::Ptr viewpoints);
/**
Plots the view-graph
@param visu The visualize-object
@param radiu The radius of the spheres (nodes)
@param viewport Id of the viewport
@param show_rotations Set if the nodes should show rotations
*/
void
add_graph_to_viewer ( pcl::visualization::PCLVisualizer &visu,
double radius,
int viewport,
bool show_rotations );
/**
Plots the view-graph
@param visu The visualize-object
@param radiu The radius of the spheres (nodes)
@param r_vec Vector containing color information for the spheres (red)
@param g_vec Vector containing color information for the spheres (green)
@param b_vec Vector containing color information for the spheres (blue)
@param viewport Id of the viewport
@param show_rotations Set if the nodes should show rotations
*/
void
add_graph_to_viewer ( pcl::visualization::PCLVisualizer &visu,
double radius,
std::vector<float> r_vec,
std::vector<float> g_vec,
std::vector<float> b_vec,
int viewport,
bool show_rotations );
/**
Adds a node to the view-graph
@param viewpoint The viewpoint of the virtual camera
@param rotation The rotation of the virtual camera
@param neighbors The nearest neighbors of the node
*/
void
add_node (PointT viewpoint, Eigen::Matrix3d rotation, std::vector<int> neighbors);
/**
Saves the view-graph to CSV-file.
*/
void
save_graph ();
/**
Loads the view-graph of a model (see structure node for details)
@param model The name of the model
*/
void
load_graph (std::string model);
/**
Adds utility to all nodes
@param utilities Vector containing the utilities
*/
void
add_utilities (std::vector<float> utilities);
/**
Searches for an optimal view given the valid nodes in the view-graph. Returns the optimal view and an optimal trajectory leading to the optimal view
@param initial_view_node The current view in the graph
@return Vector containing the optimal view and a trajectory of views to visit in order to get to the optimal view
*/
std::vector<int>
search_for_better_view (int initial_view_node);
/**
Adds a transformation to the view-graph
@param transform The transformation
*/
void
add_transformation (Eigen::Matrix4f transform);
/**
Finds the view that best aligns with the input camera axis
@param cam_axis The camera axis
@return The node with best alignment
*/
int
find_aligned_view (Eigen::Vector3f cam_axis);
};
#endif
| 26.65368 | 192 | 0.67809 | [
"object",
"vector",
"model",
"transform"
] |
7c1ed16c885c139793a9ffe3c86ffe7731719f07 | 2,234 | h | C | Exercise13/1/gradient_descent_with_steps.h | jtrillos/LabBasicGraphicsSol | 5487e568a332d8ee37ad064da0dd5ceddf35f5eb | [
"Apache-2.0"
] | 2 | 2018-01-15T13:39:56.000Z | 2018-04-25T14:27:31.000Z | Exercise13/1/gradient_descent_with_steps.h | jtrillos/LabBasicGraphicsSol | 5487e568a332d8ee37ad064da0dd5ceddf35f5eb | [
"Apache-2.0"
] | null | null | null | Exercise13/1/gradient_descent_with_steps.h | jtrillos/LabBasicGraphicsSol | 5487e568a332d8ee37ad064da0dd5ceddf35f5eb | [
"Apache-2.0"
] | null | null | null | #ifndef GRADIENT_DESCENT_WITH_STEPS_H
#define GRADIENT_DESCENT_WITH_STEPS_H
#include <iostream>
#include "tools.h"
using namespace std;
vector<double> gradient_descent_nd_with_steps( const vector<double>& x0s, double (*energy_nd)( const vector<double>& x, vector<double>& grad ), double maxStepSize = -1, int steps = -1, void (*progress)( const vector<double>& x, const vector<double>& grad ) = NULL ) {
double stepsize = 1000;
vector<double> xs( x0s );
double stepRest = maxStepSize;
int iter = 0;
vector<double> grad(xs.size());
double e = energy_nd( xs, grad );
if( progress ) {
progress( xs, grad );
}
while( true ) {
if( stepsize < 1e-10 ) {
cout << "break: stepsize too small (" << stepsize << ")" << endl;
break; // lambda too small
}
if( vector_norm(grad) < 1e-10 ) {
cout << "break: gradient too small (" << vector_norm(grad) << ")" << endl;
break; // gradient too small
}
if( steps == 0 ) {
cout << "break: sufficient steps" << endl;
break;
}
// do not walk past the rest of maxStepSize
double curStepSize = (stepRest <= 0 || stepsize < stepRest) ? (stepsize) : (stepRest);
// normalize gradient
// vector<double> gradNormalized = mulVector( 1.0/vectorNorm(grad), grad );
// do the step
double gradNorm = vector_norm( grad );
vector<double> xs_next = add_vector( xs, mul_vector( -curStepSize/gradNorm, grad ) );
vector<double> grad_next(xs.size());
double e_next = energy_nd( xs_next, grad_next );
double c1 = 0.9; // 1e-3;
if( e_next <= e - gradNorm * curStepSize * c1 ) { // wolfe condition
// if( e_next <= e - sqr(gradNorm) * curStepSize * c1 ) { // wolfe condition
cout << "iter: " << ++ iter << " energy: " << e << " -> " << e_next << "; stepsize: " << stepsize << endl;
xs = xs_next;
e = e_next;
grad = grad_next;
stepsize = stepsize * 1.1;
if( maxStepSize > 0 ) {
stepsize = std::min( stepsize, maxStepSize );
}
stepRest -= curStepSize;
if( stepRest <= 0 ) {
if( progress && steps % 10 == 0 ) {
progress( xs, grad );
}
if( steps > 0 ) {
-- steps;
}
stepRest = maxStepSize;
}
} else {
stepsize = stepsize / 2.0;
}
}
return xs;
}
#endif
| 25.678161 | 267 | 0.604745 | [
"vector"
] |
7c251576b911821df707be54eace233fecb9c82b | 441 | h | C | src/common.h | Andze/GamesProgramming | 3aefd81862630fb2ce55ef4f91b8645ccc649d05 | [
"MIT"
] | null | null | null | src/common.h | Andze/GamesProgramming | 3aefd81862630fb2ce55ef4f91b8645ccc649d05 | [
"MIT"
] | null | null | null | src/common.h | Andze/GamesProgramming | 3aefd81862630fb2ce55ef4f91b8645ccc649d05 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <string>
#include <memory>
#include <SDL.h>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;
#include <SDL_mixer.h>
#include <SDL_net.h>
#include <stdio.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include "Sprite.h"
#include "Text.h"
#include "Sound.h"
#include "Score.h"
#include "Button.h"
#include "Collision.h"
| 17.64 | 49 | 0.725624 | [
"vector"
] |
7c259a943f72ab1c9229aa40650f4c7ac362423b | 20,346 | c | C | src/transaction/replication.c | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 253 | 2016-03-12T01:03:42.000Z | 2022-03-14T08:24:39.000Z | src/transaction/replication.c | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1,124 | 2016-03-31T03:48:58.000Z | 2022-03-31T23:44:04.000Z | src/transaction/replication.c | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 268 | 2016-03-02T06:48:44.000Z | 2022-03-04T05:17:24.000Z | /*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID Corporation
*
* 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.
*
*/
/*
* replication.c -
*/
#ident "$Id$"
#include "replication.h"
#include "dbtype.h"
#include "heap_file.h"
#include "log_lsa.hpp"
#include "object_primitive.h"
#include "object_representation.h"
#include "transform.h"
#include <assert.h>
#include <stdio.h>
/*
* EXTERN TO ALL SERVER RECOVERY FUNCTION CODED SOMEWHERE ELSE
*/
#define REPL_LOG_IS_NOT_EXISTS(tran_index) \
(log_Gl.trantable.all_tdes[(tran_index)]->num_repl_records == 0)
#define REPL_LOG_IS_FULL(tran_index) \
(log_Gl.trantable.all_tdes[(tran_index)]->num_repl_records \
== log_Gl.trantable.all_tdes[(tran_index)]->cur_repl_record+1)
static const int REPL_LOG_INFO_ALLOC_SIZE = 100;
#if defined(SERVER_MODE) || defined(SA_MODE)
static int repl_log_info_alloc (LOG_TDES * tdes, int arr_size, bool need_realloc);
#endif /* SERVER_MODE || SA_MODE */
#if defined(SERVER_MODE) || defined(SA_MODE)
/*
* repl_data_insert_log_dump - dump the "DATA INSERT" replication log
*
* return:
*
* length(in): length of the data
* data(in): log data
*
* NOTE:
*/
void
repl_data_insert_log_dump (FILE * fp, int length, void *data)
{
char *class_name;
DB_VALUE key;
char *ptr;
ptr = or_unpack_string_nocopy ((char *) data, &class_name);
ptr = or_unpack_mem_value (ptr, &key);
fprintf (fp, " class_name: %s\n", class_name);
fprintf (fp, " pk_value: ");
db_value_print (&key);
pr_clear_value (&key);
fprintf (fp, "\n");
fflush (fp);
}
#if defined (ENABLE_UNUSED_FUNCTION)
/*
* repl_data_udpate_log_dump - dump the "DATA UPDATE" replication log
*
* return:
*
* length(in): length of the data
* data(in): log data
*
* NOTE:
*/
void
repl_data_udpate_log_dump (FILE * fp, int length, void *data)
{
/* currently same logic as insert case, but I can't gaurantee it's true after this... */
repl_data_insert_log_dump (fp, length, data);
}
/*
* repl_data_delete_log_dump - dump the "DATA DELETE" replication log
*
* return:
*
* length(in): length of the data
* data(in): log data
*
* NOTE:
*/
void
repl_data_delete_log_dump (FILE * fp, int length, void *data)
{
/* currently same logic as insert case, but I can't gaurantee it's true after this... */
repl_data_insert_log_dump (fp, length, data);
}
#endif
/*
* repl_schema_log_dump -
*
* return:
*
* length(in):
* data(in):
*
* NOTE:
*/
void
repl_schema_log_dump (FILE * fp, int length, void *data)
{
int type;
char *class_name, *ddl;
char *ptr;
ptr = or_unpack_int ((char *) data, &type);
ptr = or_unpack_string_nocopy (ptr, &class_name);
ptr = or_unpack_string_nocopy (ptr, &ddl);
fprintf (fp, " type: %d\n", type);
fprintf (fp, " class_name: %s\n", class_name);
fprintf (fp, " DDL: %s\n", ddl);
fflush (fp);
}
/*
* repl_log_info_alloc - log info area allocation
*
* return: Error Code
*
* tdes(in): transaction descriptor
* arr_size(in): array size to be allocated
* need_realloc(in): 0-> initial allocation (malloc), otherwise "realloc"
*
* NOTE:This function allocates the memory for the log info area of the
* target transaction. It is called when the transaction tries to to
* insert/update/delete operation. If the transaction do read operation
* only, no memory is allocated.
*
* The allocation size is defined by a constant - REPL_LOG_INFO_ALLOC_SIZE
* We need to set the size for the user request ?
*/
static int
repl_log_info_alloc (LOG_TDES * tdes, int arr_size, bool need_realloc)
{
int i = 0, k;
int error = NO_ERROR;
if (need_realloc == false)
{
i = arr_size * DB_SIZEOF (LOG_REPL_RECORD);
tdes->repl_records = (LOG_REPL_RECORD *) malloc (i);
if (tdes->repl_records == NULL)
{
error = ER_REPL_ERROR;
er_set (ER_WARNING_SEVERITY, ARG_FILE_LINE, ER_REPL_ERROR, 1, "can't allocate memory");
return error;
}
tdes->num_repl_records = arr_size;
k = 0;
}
else
{
i = tdes->num_repl_records + arr_size;
tdes->repl_records = (LOG_REPL_RECORD *) realloc (tdes->repl_records, i * DB_SIZEOF (LOG_REPL_RECORD));
if (tdes->repl_records == NULL)
{
error = ER_REPL_ERROR;
er_set (ER_WARNING_SEVERITY, ARG_FILE_LINE, ER_REPL_ERROR, 1, "can't allocate memory");
return error;
}
k = tdes->num_repl_records;
tdes->num_repl_records = i;
}
for (i = k; i < tdes->num_repl_records; i++)
{
tdes->repl_records[i].repl_data = NULL;
}
return error;
}
/*
* repl_add_update_lsa - update the LSA of the target transaction lo
*
* return: NO_ERROR or error code
*
* inst_oid(in): OID of the instance
*
* NOTE:For update operation, the server does "Heap stuff" after "Index Stuff".
* In order to reduce the cost of replication log, we generates a
* replication log at the point of indexing processing step.
* (During index processing, the primary key value is fetched ..)
* After Heap operation, we have to set the target LSA into the
* replication log.
*
* For update case, this function is called by locator_update_force().
* In the case of insert/delete cases, when the replication log info. is
* generated, the server already has the target transaction log(HEAP_INSERT
* or HEAP_DELETE).
* But, for the udpate case, the server doesn't has the target log when
* it generates the replication log. So, the server has to find out the
* location of replication record and match with the target transaction
* log after heap_update(). This is done by locator_update_force().
*/
int
repl_add_update_lsa (THREAD_ENTRY * thread_p, const OID * inst_oid)
{
int tran_index;
LOG_TDES *tdes;
LOG_REPL_RECORD *repl_rec;
int i;
bool find = false;
int error = NO_ERROR;
tran_index = LOG_FIND_THREAD_TRAN_INDEX (thread_p);
tdes = LOG_FIND_TDES (tran_index);
if (tdes == NULL)
{
return ER_FAILED;
}
/* If suppress_replication flag is set, do not write replication log. */
if (tdes->suppress_replication != 0)
{
return NO_ERROR;
}
for (i = tdes->cur_repl_record - 1; i >= 0; i--)
{
repl_rec = (LOG_REPL_RECORD *) (&tdes->repl_records[i]);
if (OID_EQ (&repl_rec->inst_oid, inst_oid) && !LSA_ISNULL (&tdes->repl_update_lsa))
{
assert (repl_rec->rcvindex == RVREPL_DATA_UPDATE || repl_rec->rcvindex == RVREPL_DATA_UPDATE_START
|| repl_rec->rcvindex == RVREPL_DATA_UPDATE_END);
if (repl_rec->rcvindex == RVREPL_DATA_UPDATE || repl_rec->rcvindex == RVREPL_DATA_UPDATE_START
|| repl_rec->rcvindex == RVREPL_DATA_UPDATE_END)
{
LSA_COPY (&repl_rec->lsa, &tdes->repl_update_lsa);
LSA_SET_NULL (&tdes->repl_update_lsa);
LSA_SET_NULL (&tdes->repl_insert_lsa);
find = true;
break;
}
}
}
if (find == false && prm_get_bool_value (PRM_ID_DEBUG_REPLICATION_DATA))
{
_er_log_debug (ARG_FILE_LINE, "can't find out the UPDATE LSA");
}
return error;
}
/*
* repl_log_insert - insert a replication info to the transaction descriptor
*
* return: NO_ERROR or error code
*
* class_oid(in): OID of the class
* inst_oid(in): OID of the instance
* log_type(in): log type (DATA or SCHEMA)
* rcvindex(in): recovery index (INSERT or DELETE or UPDATE)
* key_dbvalue(in): Primary Key value
*
* NOTE:insert a replication log info to the transaction descriptor (tdes)
*/
int
repl_log_insert (THREAD_ENTRY * thread_p, const OID * class_oid, const OID * inst_oid, LOG_RECTYPE log_type,
LOG_RCVINDEX rcvindex, DB_VALUE * key_dbvalue, REPL_INFO_TYPE repl_info)
{
int tran_index;
LOG_TDES *tdes;
LOG_REPL_RECORD *repl_rec;
TDE_ALGORITHM tde_algo = TDE_ALGORITHM_NONE;
char *class_name = NULL;
char *ptr;
int error = NO_ERROR, strlen;
tran_index = LOG_FIND_THREAD_TRAN_INDEX (thread_p);
tdes = LOG_FIND_TDES (tran_index);
if (tdes == NULL)
{
return ER_FAILED;
}
/* If suppress_replication flag is set, do not write replication log. */
if (tdes->suppress_replication != 0)
{
/* clear repl lsa in tdes since no replication log will be written */
LSA_SET_NULL (&tdes->repl_insert_lsa);
LSA_SET_NULL (&tdes->repl_update_lsa);
return NO_ERROR;
}
if (thread_p->no_logging && tdes->fl_mark_repl_recidx == -1)
{
return NO_ERROR;
}
/* check the replication log array status, if we need to alloc? */
if (REPL_LOG_IS_NOT_EXISTS (tran_index)
&& ((error = repl_log_info_alloc (tdes, REPL_LOG_INFO_ALLOC_SIZE, false)) != NO_ERROR))
{
return error;
}
/* the replication log array is full? re-alloc? */
else if (REPL_LOG_IS_FULL (tran_index)
&& (error = repl_log_info_alloc (tdes, REPL_LOG_INFO_ALLOC_SIZE, true)) != NO_ERROR)
{
return error;
}
repl_rec = (LOG_REPL_RECORD *) (&tdes->repl_records[tdes->cur_repl_record]);
repl_rec->repl_type = log_type;
repl_rec->tde_encrypted = false;
repl_rec->rcvindex = rcvindex;
if (rcvindex == RVREPL_DATA_UPDATE)
{
switch (repl_info)
{
case REPL_INFO_TYPE_RBR_START:
repl_rec->rcvindex = RVREPL_DATA_UPDATE_START;
break;
case REPL_INFO_TYPE_RBR_END:
repl_rec->rcvindex = RVREPL_DATA_UPDATE_END;
break;
case REPL_INFO_TYPE_RBR_NORMAL:
default:
break;
}
}
COPY_OID (&repl_rec->inst_oid, inst_oid);
/* make the common info for the data replication */
if (log_type == LOG_REPLICATION_DATA)
{
char *ptr_to_packed_key_value_size = NULL;
int packed_key_len = 0;
if (heap_get_class_name (thread_p, class_oid, &class_name) != NO_ERROR || class_name == NULL)
{
ASSERT_ERROR_AND_SET (error);
if (error == NO_ERROR)
{
error = ER_REPL_ERROR;
er_set (ER_WARNING_SEVERITY, ARG_FILE_LINE, ER_REPL_ERROR, 1, "can't get class_name");
}
return error;
}
if (heap_get_class_tde_algorithm (thread_p, class_oid, &tde_algo) != NO_ERROR)
{
ASSERT_ERROR_AND_SET (error);
if (error == NO_ERROR)
{
error = ER_REPL_ERROR;
}
return error;
}
repl_rec->tde_encrypted = tde_algo != TDE_ALGORITHM_NONE;
repl_rec->length = OR_INT_SIZE; /* packed_key_value_size */
repl_rec->length += or_packed_string_length (class_name, &strlen);
repl_rec->length += OR_VALUE_ALIGNED_SIZE (key_dbvalue);
ptr = (char *) malloc (repl_rec->length);
if (ptr == NULL)
{
error = ER_REPL_ERROR;
er_set (ER_WARNING_SEVERITY, ARG_FILE_LINE, ER_REPL_ERROR, 1, "can't allocate memory");
free_and_init (class_name);
return error;
}
#if !defined (NDEBUG)
/* Suppress valgrind complaint. */
memset (ptr, 0, repl_rec->length);
#endif // DEBUG
repl_rec->repl_data = ptr;
/* first 4 bytes are for packed_key_len which will be filled after packing the value. */
ptr_to_packed_key_value_size = ptr;
ptr += OR_INT_SIZE;
ptr = or_pack_string_with_length (ptr, class_name, strlen);
ptr = or_pack_mem_value (ptr, key_dbvalue, &packed_key_len);
/* fill the length of disk image of pk */
or_pack_int (ptr_to_packed_key_value_size, packed_key_len);
}
else
{
repl_rec->repl_data = NULL;
repl_rec->length = 0;
}
repl_rec->must_flush = LOG_REPL_COMMIT_NEED_FLUSH;
switch (rcvindex)
{
case RVREPL_DATA_INSERT:
if (!LSA_ISNULL (&tdes->repl_insert_lsa))
{
LSA_COPY (&repl_rec->lsa, &tdes->repl_insert_lsa);
LSA_SET_NULL (&tdes->repl_insert_lsa);
LSA_SET_NULL (&tdes->repl_update_lsa);
}
break;
case RVREPL_DATA_UPDATE:
/*
* for the update case, this function is called before the heap
* file update, so we don't need to LSA for update log here.
*/
LSA_SET_NULL (&repl_rec->lsa);
break;
case RVREPL_DATA_DELETE:
/*
* for the delete case, we don't need to find out the target
* LSA. Delete is operation is possible without "After Image"
*/
if (LSA_ISNULL (&tdes->tail_lsa))
{
LSA_COPY (&repl_rec->lsa, &log_Gl.prior_info.prior_lsa);
}
else
{
LSA_COPY (&repl_rec->lsa, &tdes->tail_lsa);
}
break;
default:
break;
}
tdes->cur_repl_record++;
/* if flush marking is started, mark "must_flush" at current log except the log conflicts with previous logs due to
* same instance update */
if (tdes->fl_mark_repl_recidx != -1)
{
LOG_REPL_RECORD *recsp = tdes->repl_records;
int i;
if (strcmp (class_name, CT_SERIAL_NAME) != 0)
{
for (i = 0; i < tdes->fl_mark_repl_recidx; i++)
{
if (recsp[i].must_flush == LOG_REPL_COMMIT_NEED_FLUSH && OID_EQ (&recsp[i].inst_oid, &repl_rec->inst_oid))
{
break;
}
}
if (i >= tdes->fl_mark_repl_recidx)
{
repl_rec->must_flush = LOG_REPL_NEED_FLUSH;
}
}
else
{
repl_rec->must_flush = LOG_REPL_NEED_FLUSH;
}
}
if (class_name != NULL)
{
free_and_init (class_name);
}
return error;
}
/*
* repl_log_insert_schema - insert a replication info(schema) to the
* transaction descriptor
*
* return: NO_ERROR or error code
*
* repl_schema(in):
*
* NOTE:insert a replication log info(schema) to the transaction
* descriptor (tdes)
*/
int
repl_log_insert_statement (THREAD_ENTRY * thread_p, REPL_INFO_SBR * repl_info)
{
int tran_index;
LOG_TDES *tdes;
LOG_REPL_RECORD *repl_rec;
char *ptr;
int error = NO_ERROR, strlen1, strlen2, strlen3, strlen4;
tran_index = LOG_FIND_THREAD_TRAN_INDEX (thread_p);
tdes = LOG_FIND_TDES (tran_index);
if (tdes == NULL)
{
return ER_FAILED;
}
/* If suppress_replication flag is set, do not write replication log. */
if (tdes->suppress_replication != 0)
{
return NO_ERROR;
}
/* check the replication log array status, if we need to alloc? */
if (REPL_LOG_IS_NOT_EXISTS (tran_index)
&& ((error = repl_log_info_alloc (tdes, REPL_LOG_INFO_ALLOC_SIZE, false)) != NO_ERROR))
{
return error;
}
/* the replication log array is full? re-alloc? */
else if (REPL_LOG_IS_FULL (tran_index)
&& (error = repl_log_info_alloc (tdes, REPL_LOG_INFO_ALLOC_SIZE, true)) != NO_ERROR)
{
return error;
}
repl_rec = (LOG_REPL_RECORD *) (&tdes->repl_records[tdes->cur_repl_record]);
repl_rec->repl_type = LOG_REPLICATION_STATEMENT;
repl_rec->tde_encrypted = false;
repl_rec->rcvindex = RVREPL_STATEMENT;
repl_rec->must_flush = LOG_REPL_COMMIT_NEED_FLUSH;
OID_SET_NULL (&repl_rec->inst_oid);
/* make the common info for the schema replication */
repl_rec->length = (OR_INT_SIZE /* REPL_INFO_SCHEMA.statement_type */
+ or_packed_string_length (repl_info->name, &strlen1)
+ or_packed_string_length (repl_info->stmt_text, &strlen2)
+ or_packed_string_length (repl_info->db_user, &strlen3)
+ or_packed_string_length (repl_info->sys_prm_context, &strlen4));
repl_rec->repl_data = (char *) malloc (repl_rec->length);
if (repl_rec->repl_data == NULL)
{
error = ER_REPL_ERROR;
er_set (ER_WARNING_SEVERITY, ARG_FILE_LINE, ER_REPL_ERROR, 1, "can't allocate memory");
return error;
}
ptr = repl_rec->repl_data;
ptr = or_pack_int (ptr, repl_info->statement_type);
ptr = or_pack_string_with_length (ptr, repl_info->name, strlen1);
ptr = or_pack_string_with_length (ptr, repl_info->stmt_text, strlen2);
ptr = or_pack_string_with_length (ptr, repl_info->db_user, strlen3);
ptr = or_pack_string_with_length (ptr, repl_info->sys_prm_context, strlen4);
if (prm_get_bool_value (PRM_ID_DEBUG_REPLICATION_DATA))
{
_er_log_debug (ARG_FILE_LINE,
"repl_log_insert_statement: repl_info_sbr { type %d, name %s, stmt_txt %s, user %s, "
"sys_prm_context %s }\n", repl_info->statement_type, repl_info->name, repl_info->stmt_text,
repl_info->db_user, repl_info->sys_prm_context);
}
LSA_COPY (&repl_rec->lsa, &tdes->tail_lsa);
if (tdes->fl_mark_repl_recidx != -1 && tdes->cur_repl_record >= tdes->fl_mark_repl_recidx)
{
/*
* statement replication does not check log conflicts, so
* use repl_start_flush_mark with caution.
*/
repl_rec->must_flush = LOG_REPL_NEED_FLUSH;
}
tdes->cur_repl_record++;
return error;
}
/*
* repl_start_flush_mark -
*
* return:
*
* NOTE:start to mark "must_flush" for repl records to be appended after this
*/
void
repl_start_flush_mark (THREAD_ENTRY * thread_p)
{
LOG_TDES *tdes;
tdes = LOG_FIND_CURRENT_TDES (thread_p);
if (tdes == NULL)
{
er_set (ER_FATAL_ERROR_SEVERITY, ARG_FILE_LINE, ER_LOG_UNKNOWN_TRANINDEX, 1,
LOG_FIND_THREAD_TRAN_INDEX (thread_p));
return;
}
if (tdes->fl_mark_repl_recidx == -1)
{
tdes->fl_mark_repl_recidx = tdes->cur_repl_record;
} /* else already started, return */
return;
}
/*
* repl_end_flush_mark -
*
* return:
*
* need_undo(in):
*
* NOTE:end to mark "must_flush" for repl records
*/
void
repl_end_flush_mark (THREAD_ENTRY * thread_p, bool need_undo)
{
LOG_TDES *tdes;
int i;
tdes = LOG_FIND_CURRENT_TDES (thread_p);
if (tdes == NULL)
{
er_set (ER_FATAL_ERROR_SEVERITY, ARG_FILE_LINE, ER_LOG_UNKNOWN_TRANINDEX, 1,
LOG_FIND_THREAD_TRAN_INDEX (thread_p));
return;
}
if (need_undo)
{
LOG_REPL_RECORD *recsp = tdes->repl_records;
for (i = tdes->fl_mark_repl_recidx; i < tdes->cur_repl_record; i++)
{
/* initialize repl records to be marked as flush */
free_and_init (recsp[i].repl_data);
}
tdes->cur_repl_record = tdes->fl_mark_repl_recidx;
}
tdes->fl_mark_repl_recidx = -1;
return;
}
/*
* repl_log_abort_after_lsa -
*
* return:
*
* tdes (in) :
* start_lsa (in) :
*
*/
int
repl_log_abort_after_lsa (LOG_TDES * tdes, LOG_LSA * start_lsa)
{
LOG_REPL_RECORD *repl_rec_arr;
int i;
repl_rec_arr = tdes->repl_records;
for (i = 0; i < tdes->cur_repl_record; i++)
{
if (LSA_GT (&repl_rec_arr[i].lsa, start_lsa))
{
repl_rec_arr[i].must_flush = LOG_REPL_DONT_NEED_FLUSH;
}
}
return NO_ERROR;
}
#if defined(CUBRID_DEBUG)
/*
* repl_debug_info - DEBUGGING Function, print out the replication log info.
*
* return:
*
* NOTE:Dump the replication log info to the stdout.
*/
void
repl_debug_info ()
{
LOG_TDES *tdes;
LOG_REPL_RECORD *repl_rec;
int tnum, rnum;
char *class_name;
DB_VALUE key;
char *ptr;
fprintf (stdout, "REPLICATION LOG DUMP -- Memory\n");
for (tnum = 0; tnum < log_Gl.trantable.num_assigned_indices; tnum++)
{
fprintf (stdout, "*************************************************\n");
tdes = log_Gl.trantable.all_tdes[tnum];
fprintf (stdout, "For the Trid : %d\n", (int) tdes->trid);
for (rnum = 0; rnum < tdes->cur_repl_record; rnum++)
{
fprintf (stdout, " RECORD # %d\n", rnum);
repl_rec = (LOG_REPL_RECORD *) (&tdes->repl_records[rnum]);
fprintf (stdout, " type: %s\n", log_to_string (repl_rec->repl_type));
fprintf (stdout, " OID: %d - %d - %d\n", repl_rec->inst_oid.volid, repl_rec->inst_oid.pageid,
repl_rec->inst_oid.slotid);
ptr = or_unpack_string_nocopy (repl_rec->repl_data, &class_name);
ptr = or_unpack_mem_value (ptr, &key);
fprintf (stdout, " class_name: %s\n", class_name);
fprintf (stdout, " LSA: %lld | %d\n", repl_rec->lsa.pageid, repl_rec->lsa.offset);
db_value_print (&key);
fprintf (stdout, "\n----------------------------------------------\n");
pr_clear_value (&key);
}
}
fflush (stdout);
}
#endif /* CUBRID_DEBUG */
#endif /* SERVER_MODE || SA_MODE */
| 27.757162 | 117 | 0.664848 | [
"transform"
] |
7c2893d732f46a79aeb76b5d8e5ea41a1cfd8eef | 3,126 | h | C | IPStreamingCPP/RecordingListener/Recording.h | srw2ho/IPStreaming | 2a3345351f99c11fb69b2caedb3fd18ca7e5da73 | [
"Apache-2.0"
] | 2 | 2020-01-20T11:08:13.000Z | 2020-09-01T17:35:56.000Z | IPStreamingCPP/RecordingListener/Recording.h | srw2ho/IPStreaming | 2a3345351f99c11fb69b2caedb3fd18ca7e5da73 | [
"Apache-2.0"
] | 1 | 2020-08-20T01:24:57.000Z | 2020-08-20T01:24:57.000Z | IPStreamingCPP/RecordingListener/Recording.h | srw2ho/IPStreaming | 2a3345351f99c11fb69b2caedb3fd18ca7e5da73 | [
"Apache-2.0"
] | 1 | 2022-01-25T08:30:15.000Z | 2022-01-25T08:30:15.000Z | #pragma once
#include <queue>
#include <map>
#include "SocketListener.h"
#include "GPIOInOut.h"
typedef std::map<int, GPIODriver::GPIOInputPin* > MapInputClientsPins;
namespace RecordingListener
{
public ref class Recording sealed
{
StreamSocketComm::SocketListener^ m_pSocketListener;
concurrency::cancellation_token_source* m_pPackageCancelTaskToken;
GPIODriver::GPIOInOut^ m_GPIOClientInOut;
MapInputClientsPins m_MapInputClientsPins;
GPIODriver::GPIOEventPackageQueue* m_pGPIOEventPackageQueue;
bool m_bProcessingPackagesStarted;
concurrency::task<void> m_ProcessingPackagesTsk;
Windows::Foundation::EventRegistrationToken m_startStreamingEventRegister;
Windows::Foundation::EventRegistrationToken m_stopStreamingEventRegister;
Windows::Foundation::EventRegistrationToken m_FailedEventRegister;
Windows::Foundation::EventRegistrationToken m_OnClientConnected;
Platform::String ^ m_HostName;
int m_port;
unsigned int m_FailedConnectionCount;
Windows::Foundation::Collections::PropertySet^ m_outputconfigoptions;
bool m_Movement;
public:
Recording();
virtual ~Recording();
event Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^ >^ ChangeMovement;
event Windows::Foundation::TypedEventHandler<Platform::Object^, Windows::Foundation::Collections::PropertySet^ >^ startStreaming;
event Windows::Foundation::TypedEventHandler<Platform::Object^, Platform::String ^>^ stopStreaming;
event Windows::Foundation::TypedEventHandler<Platform::Object^, Platform::String ^> ^ Failed;
Windows::Foundation::IAsyncAction ^ startProcessingPackagesAsync(Windows::Foundation::Collections::PropertySet^ inputconfigoptions, Windows::Foundation::Collections::PropertySet^ outputconfigoptions);
Windows::Foundation::IAsyncAction ^ stopProcessingPackagesAsync();
property Platform::String ^ HostName {
Platform::String ^ get() { return m_HostName; };
void set(Platform::String ^ value);
}
property int Port {
int get() { return m_port; };
void set(int value);
}
property bool IsMoment {
bool get() { return m_Movement; };
void set(bool value);
}
property unsigned int FailedConnectionCount {
unsigned int get() { return m_FailedConnectionCount; };
void set(unsigned int value);
}
private:
Concurrency::task<void> doProcessPackages();
void cancelPackageAsync();
void OnFailed(Platform::Object ^sender, Platform::Exception ^args);
void OnOnClientConnected(Windows::Networking::Sockets::StreamSocket ^sender, int args);
void OnstartStreaming(Platform::Object ^sender, Windows::Networking::Sockets::StreamSocket ^args);
void OnstopStreaming(Platform::Object ^sender, Platform::Exception ^exception);
bool InitGPIOOutput(Windows::Foundation::Collections::PropertySet^ inputconfigoptions);
void clearGPIOs();
void startProcessingPackages(Windows::Foundation::Collections::PropertySet^ inputconfigoptions, Windows::Foundation::Collections::PropertySet^ outputconfigoptions);
void stopProcessingPackages();
void DisableMovementActivated();
};
}
| 37.662651 | 202 | 0.779271 | [
"object"
] |
8e35dd68ce1a29d4f669fb5832ed079c9ead4676 | 1,778 | h | C | src/Manager/AssetMgr.h | ounols/CSEngine | beebdede6eb223c1ec3ec533ed0eb03b80f68a3b | [
"BSD-2-Clause"
] | 37 | 2021-05-19T12:23:57.000Z | 2022-03-21T23:51:30.000Z | src/Manager/AssetMgr.h | ounols/CSEngine | beebdede6eb223c1ec3ec533ed0eb03b80f68a3b | [
"BSD-2-Clause"
] | 3 | 2021-10-12T11:12:52.000Z | 2021-11-28T16:11:19.000Z | src/Manager/AssetMgr.h | ounols/CSEngine | beebdede6eb223c1ec3ec533ed0eb03b80f68a3b | [
"BSD-2-Clause"
] | 4 | 2021-09-16T15:17:42.000Z | 2021-10-02T21:29:38.000Z | //
// Created by ounols on 19. 6. 6.
//
//참조 : https://codingcoding.tistory.com/900
#pragma once
#include <string>
#include <vector>
#include "../Util/Loader/ZIP/zip.h"
#ifdef __ANDROID__
#include <android/asset_manager.h>
#include <jni.h>
#endif
namespace CSE {
class AssetMgr {
public:
enum TYPE {
NONE, TEX_2D, TEX_CUBEMAP, TEX_FRAMEBUFFER, MATERIAL, DAE, PREFAB, SCENE, SCRIPT, TXT, SHADER, SHADER_HANDLE, INI
};
struct AssetReference {
std::string path;
std::string name;
std::string id;
std::string name_full;
std::string extension;
TYPE type = NONE;
};
public:
AssetMgr();
~AssetMgr();
void Exterminate();
void LoadAssets(bool isPacked);
AssetReference* GetAsset(std::string name) const;
std::vector<AssetReference*> GetAssets(TYPE type) const;
static std::string LoadAssetFile(const std::string& path);
#ifdef __ANDROID__
void SetAssetManager(AAssetManager* obj);
AAssetManager* GetAssetManager();
void SetEnv(JNIEnv* obj);
JNIEnv* GetEnv();
#endif
private:
void ReadDirectory(const std::string& path);
void ReadPackage(const std::string& path);
AssetReference* CreateAsset(const std::string& path, const std::string& name_full, std::string name = "");
void SetType();
static AssetReference* AppendSubName(AssetReference* asset, const std::string& sub_name);
private:
std::vector<AssetReference*> m_assets;
zip_t* m_zip = nullptr;
#ifdef __ANDROID__
AAssetManager* m_assetManager;
JNIEnv* m_env = nullptr;
std::string m_package_raw;
#endif
};
} | 24.027027 | 125 | 0.616985 | [
"vector"
] |
8e3712f2e852780076f0116ca920f5b4ab368d37 | 44,552 | h | C | release-0.96/src/ddpt.h | doug-gilbert/ddpt | 78d6724db6508807fc9d9ecc1fe047d8da8df975 | [
"BSD-3-Clause"
] | 2 | 2019-03-30T18:51:50.000Z | 2019-07-24T13:56:38.000Z | release-0.96/src/ddpt.h | doug-gilbert/ddpt | 78d6724db6508807fc9d9ecc1fe047d8da8df975 | [
"BSD-3-Clause"
] | 1 | 2018-09-03T22:26:04.000Z | 2020-04-16T02:33:57.000Z | release-0.96/src/ddpt.h | doug-gilbert/ddpt | 78d6724db6508807fc9d9ecc1fe047d8da8df975 | [
"BSD-3-Clause"
] | 2 | 2017-11-28T09:13:39.000Z | 2019-09-04T03:25:46.000Z | /*
* Copyright (c) 2008-2019, Douglas Gilbert
* 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 OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DDPT_H
#define DDPT_H
/* This is a C header file for the ddpt utility. See ddpt.c and ddpt.8
* for more information.
*/
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/time.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef SG_LIB_WIN32
#include <windows.h>
#endif
#ifdef SG_LIB_FREEBSD
#ifndef SIGINFO
/* hack to undo hiding by _XOPEN_SOURCE and _GNU_SOURCE */
#define SIGINFO 29
#endif
#endif
#ifdef SG_LIB_WIN32
#ifdef SG_LIB_MINGW
#define SIGPIPE 13
#define SIGQUIT 3
#define SIGUSR1 25
#endif
#endif
/* Borrow signal handling from dd (src/dd.c in coreutils-8.13) */
/* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
present. */
#ifndef SA_NOCLDSTOP
# define SA_NOCLDSTOP 0
# define sigprocmask(How, Set, Oset) /* empty */
# define sigset_t int
# if ! HAVE_SIGINTERRUPT
# define siginterrupt(sig, flag) /* empty */
# endif
#endif
/* NonStop circa 2011 lacks SA_RESETHAND; see Bug#9076. */
#ifndef SA_RESETHAND
# define SA_RESETHAND 0
#endif
#ifndef SIGINFO
# define SIGINFO SIGUSR1
#endif
/* end of borrow from dd signal handling defines */
#define STR_SZ 1024
#define INOUTF_SZ 512
#define EBUFF_SZ 512
#define DEF_BLOCK_SIZE 512
#define DEF_BPT_LT4 16384 /* BPT when IBS < 4 */
#define DEF_BPT_LT8 8192 /* BPT when IBS < 8 */
#define DEF_BPT_LT64 1024 /* BPT when IBS < 64 */
#define DEF_BPT_LT1024 128 /* BPT when IBS < 1024 */
#define DEF_BPT_LT8192 16 /* BPT when IBS < 8192 */
#define DEF_BPT_LT32768 4 /* BPT when IBS < 32768 */
#define DEF_BPT_GE32768 1 /* BPT when IBS >= 32768 */
#define MAX_XC_BPT 65535 /* BPT maximum for xcopy(LID1) */
#define MAX_XC_BPT_POW2 32768 /* BPT maximum that is power of 2 */
#define DEF_SCSI_CDBSZ 10
#define MAX_SCSI_CDBSZ 32
#define DDPT_MAX_JF_DEPTH 4
#define DDPT_MAX_JF_LINES 1000
#define DDPT_MAX_JF_ARGS_PER_LINE 16
#define DDPT_COUNT_INDEFINITE (-1)
#define DDPT_LBA_INVALID DDPT_COUNT_INDEFINITE
#define VPD_DEVICE_ID 0x83
#define VPD_3PARTY_COPY 0x8f
#define SENSE_BUFF_LEN 64 /* Arbitrary, could be larger */
#define READ_CAP_REPLY_LEN 8
#define RCAP16_REPLY_LEN 32
#define DEF_RW_TIMEOUT 60 /* 60 seconds for READ and WRITE */
#define WRITE_SAME16_TIMEOUT 180 /* 3 minutes */
#define DEF_GROUP_NUM 0
#define DEF_LID4_LID 257 /* just above the LID1 highest of 255 */
#define DEF_LID4_WR_LID 258
/* status=progress or status=progress,progress */
#define PROGRESS_TRIGGER_MS 120000 /* milliseconds: 2 minutes */
#define PROGRESS2_TRIGGER_MS 60000 /* milliseconds: 1 minute */
#define PROGRESS3_TRIGGER_MS 30000 /* milliseconds: 30 seconds */
#ifdef SG_LIB_LINUX
#define DEV_NULL_MINOR_NUM 3
#define DEV_ZERO_MINOR_NUM 5
#endif
#define SG_LIB_FLOCK_ERR 47
/* File/device type groups, (N.B. powers of 2), so file can be multiple */
#define FT_OTHER 1 /* unknown (unable to identify), default */
#define FT_PT 2 /* SCSI commands can be sent via a
pass-through */
#define FT_REG 4 /* a normal (regular) file */
#define FT_DEV_NULL 8 /* either "/dev/null" or "." as filename */
/* as input equivalent to /dev/zero */
#define FT_TAPE 16 /* tape style device */
#define FT_BLOCK 32 /* block device */
#define FT_FIFO 64 /* fifo (named or unnamed pipe (stdout)) */
#define FT_CHAR 128 /* char dev, doesn't fit another category */
#define FT_ALL_FF 256 /* iflag=ff so input will be 0xff bytes */
#define FT_ERROR 0x800000 /* couldn't "stat" file */
/* ODX type requested */
#define ODX_REQ_NONE 0 /* some other type of copy */
#define ODX_READ_INTO_RODS 1 /* POPULATE TOKENs (PTs): disk->rods */
#define ODX_WRITE_FROM_RODS 2 /* WRITE USING TOKENs (WUTs): rods->disk */
#define ODX_COPY 3 /* odx disk->disk or zero->disk */
/* ROD Types used by ODX */
#define RODT_CM_INTERNAL 0x0
#define RODT_ACCESS_ON_REF 0x10000
#define RODT_PIT_DEF 0x800000
#define RODT_PIT_VULN 0x800001
#define RODT_PIT_PERS 0x800002
#define RODT_PIT_COW 0x800003 /* added spc5r20 */
#define RODT_PIT_ANY 0x80ffff
#define RODT_BLK_ZERO 0xffff0001
/* If O_DIRECT or O_SYNC not supported then define harmlessly */
#ifndef O_DIRECT
#define O_DIRECT 0
#endif
#ifndef O_SYNC
#define O_SYNC 0
#endif
#ifndef O_NONBLOCK
#define O_NONBLOCK 0
#endif
#define DDPT_ARG_IN 0
#define DDPT_ARG_OUT 1
#define DDPT_ARG_OUT2 2
#define MIN_RESERVED_SIZE 8192
#define MAX_UNIT_ATTENTIONS 10
#define MAX_ABORTED_CMDS 16
/* So ddpt does not hog all the CPU and IO resources, allow delays defined
* by delay=MS[,W_MS] . Used in signals_process_delay(). */
#define DELAY_COPY_SEGMENT 0 /* after each copy segment (prior to next) */
#define DELAY_WRITE 1 /* prior to each write, may be muliple per segment */
/* cp_state_t::leave_reason indication */
#define DDPT_REASON_UNKNOWN -1
#define DDPT_REASON_EOF_ON_READ 0
#define DDPT_REASON_TAPE_SHORT_READ 1024
#define DDPT_CAT_PARAM_LST_LEN_ERR 100
#define DDPT_CAT_INVALID_FLD_IN_PARAM 101
#define DDPT_CAT_TOO_MANY_SEGS_IN_PARAM 102
#define DDPT_CAT_TARGET_UNDERRUN 103
#define DDPT_CAT_TARGET_OVERRUN 104
#define DDPT_CAT_OP_IN_PROGRESS 105
#define DDPT_CAT_INSUFF_RES_CREATE_ROD 106
#define DDPT_CAT_INSUFF_RES_CREATE_RODTOK 107
#define DDPT_CAT_CMDS_CLEARED_BY_DEV_SVR 108
#define DDPT_CAT_SEE_LEAVE_REASON 109 /* see cp_state_t::leave_reason */
#define DDPT_CAT_TOKOP_BASE 110 /* + ascq; Invalid token operation (0x23) */
#define XCOPY_TO_SRC "XCOPY_TO_SRC"
#define XCOPY_TO_DST "XCOPY_TO_DST"
#define DEF_XCOPY_SRC0_DST1 1
#define ODX_RTF_LEN "ODX_RTF_LEN" /* append 8 byte ROD size to token */
#define DDPT_DEF_BS "DDPT_DEF_BS" /* default logical block size: 512 bytes */
#define DDPT_BIGGEST_CONTINUAL (1024LL * 1024 * 1024 * 64)
/* ODX: length field inside ROD Token constant, implies 512 byte ROD Token */
#define ODX_ROD_TOK_LEN_FLD 504 /* 0x1f8 */
#define DEF_ODX_POLL_DELAY_MS 500
/* In SPC-4 the cdb opcodes have more generic names */
#define THIRD_PARTY_COPY_OUT_CMD 0x83
#define THIRD_PARTY_COPY_IN_CMD 0x84
/* Third party copy IN (opcode 0x84) and OUT (opcode 0x83) command service
* actions */
#define SA_XCOPY_LID1 0x0 /* OUT, originate */
#define SA_XCOPY_LID4 0x1 /* OUT, originate */
#define SA_POP_TOK 0x10 /* OUT, originate [PT] */
#define SA_WR_USING_TOK 0x11 /* OUT, originate [WUT] */
#define SA_COPY_ABORT 0x1C /* OUT, abort */
#define SA_COPY_STATUS_LID1 0x0 /* IN, retrieve */
#define SA_COPY_DATA_LID1 0x1 /* IN, retrieve */
#define SA_COPY_OP_PARAMS 0x3 /* IN, retrieve */
#define SA_COPY_FAIL_DETAILS 0x4 /* IN, retrieve */
#define SA_COPY_STATUS_LID4 0x5 /* IN, retrieve [RCS] */
#define SA_COPY_DATA_LID4 0x6 /* IN, retrieve */
#define SA_ROD_TOK_INFO 0x7 /* IN, retrieve [RRTI] */
#define SA_ALL_ROD_TOKS 0x8 /* IN, retrieve */
#define MAX_FIXED_SGL_ELEMS 128 /* same for gl and sl; MS max is 64 */
struct sg_pt_base;
struct val_str_t {
int num;
const char * name;
};
/* Sizing matches largest SCSI READ and WRITE commands plus those of Unix
* read(2)s and write(2)s. User can give larger than 31 bit 'num's but they
* are split into several consecutive elements. */
struct scat_gath_elem {
uint64_t lba; /* of start block */
uint32_t num; /* number of blocks from and including start block */
};
/* Old cylinder/head/sector addressing than can be manipulated by ddpt_sgl.
* Assume 28 bit format as used by early ATA standards (EIDE + ATA-2) */
struct chs_t {
uint16_t cyls; /* 0 based; 16 bits, all bits used */
uint8_t heads; /* 0 based; 4 bits used, to 4 bits zero */
uint8_t sects; /* 1 based; all 8 bits used except 0 */
};
/* Used by ddpt_sgl */
struct sgl_stats {
bool last_degen;
bool not_mono_asc; /* negated so zeroed default is mono_asc */
bool not_mono_desc; /* LBAn+1 < (LBAn + NUMn - 1) while (NUMn > 0) */
bool fragmented; /* false if monotonic and all LBAs between highest
* and lowest are transferred once (i.e no holes) */
int num_degen;
int elems; /* because of degen_mask may have < sge_p array elements */
int64_t sum; /* sum of number_of_blocks (NUM) fields in sgl */
uint64_t lowest_lba;
uint64_t highest_lba;
};
/* Used by ddpt_sgl */
struct cl_sgl_stats {
struct sgl_stats a_stats;
struct sgl_stats b_stats;
};
/* Iterator on a scatter gather list (which are arrays). IFILE and OFILE have
* iterators, not OFILE2. The iterator is a "post increment" type starting
* [0,0]. If the sgl is accessed in a linear fashion, after the last IO the
* iterator will be at [<elems>, 0]. */
struct sgl_iter_t {
bool extend_last; /* hack for extending (sglp + elems - 1)->num */
int elems; /* elements in sglp array */
int it_e_ind; /* iterator element index into sglp array */
int it_bk_off; /* iterator: 0 <= it_blk_off < (sglp + i_e_ind)->num */
/* underlying (what iterator points to) and filepos, if needed */
struct scat_gath_elem * sglp; /* start of scatter gather list array */
int64_t filepos; /* file 'pos' is a byte offset in reg/block file,
* origin 0, next byte to read */
};
/* Holds one scatter gather list and its associated metadata */
struct sgl_info_t {
bool fragmented; /* only valid if 'monotonic' is true. Thence true
* if gaps between first and last LBA, else false */
bool monotonic; /* LBAs grow larger in [0..elems). Allow LBAn ==
* LBAn+1 only if NUMn is zero */
bool overlapping; /* only valid if 'monotonic' is true. Means at least
* one LBA is in two sgl elements. Makes sgl
* sensitive to order its elements are processed */
bool sum_hard; /* 'num' in last element of 'sgl' is > 0 */
int elems; /* number of elements; when 0 'sgl' must be NULL */
int64_t high_lba_p1; /* highest LBA plus 1, next write from and above */
int64_t lowest_lba; /* initialized to 0 */
int64_t sum; /* of all 'num' elements in 'sgl' */
struct scat_gath_elem * sglp; /* an array on heap [0..elems), owner */
};
/* Info from SCSI Third Party Copy VPD page (0x8f), descriptor 0 (Block
* device ROD Limits). */
struct block_rodtok_vpd {
uint16_t max_range_desc;
uint32_t max_inactivity_to;
uint32_t def_inactivity_to;
uint32_t max_tok_xfer_size;
uint32_t optimal_xfer_count;
};
/* one instance per file/device: if, of and of2 */
struct dev_info_t {
bool limits_xfer; /* size of this object is xfer limit */
int d_type; /* one of FT_* values */
int d_type_hold;
int fd; /* Unix file descriptor corresponding to fn[] */
#ifdef SG_LIB_WIN32
HANDLE fh;
#endif
int pdt;
int prot_type; /* from RCAP(16) or 0 */
int p_i_exp; /* protection intervals (PIs) exponent */
int bs_pi; /* logical block size plus PI, if any */
int ddpt_arg; /* 1 of DDPT_ARG_IN, DDPT_ARG_OUT or DDPT_ARG_OUT2 */
uint32_t xc_min_bytes;
uint32_t xc_max_bytes;
int64_t reg_sz; /* regular file size in bytes, -1 --> no info */
char fn[INOUTF_SZ]; /* file/device name */
struct block_rodtok_vpd * odxp;
uint8_t * free_odxp;
struct sg_pt_base * ptvp;
const char * dir_n; /* points to "in", "out" or "out2" */
};
struct cp_statistics_t {
bool copied_from_working;
bool prev_valid; /* if delta throughput available */
int64_t in_full; /* full blocks read from IFILE so far */
int64_t out_full; /* full blocks written to OFILE so far */
int64_t prev_count; /* full blocks written to OFILE so far */
int64_t dd_count_start; /* dd_count prior to start of copy/read */
int64_t out_sparse; /* counter for sparse, sparing + trim */
int in_partial;
int out_partial;
int out_sparse_partial;
int recovered_errs; /* on reads */
int unrecovered_errs; /* on reads */
int wr_recovered_errs;
int wr_unrecovered_errs;
int trim_errs;
int num_retries;
int sum_of_resids;
int interrupted_retries;
int io_eagains;
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
struct timespec prev_tm;
#elif defined(HAVE_GETTIMEOFDAY)
struct timeval prev_tm;
#endif
};
/* state of working variables within do_copy(). Note that logical block size
* from the copy buffer's perspective is dip->bs_pi bytes. */
struct cp_state_t {
bool leave_after_write; /* partial read then EOF or error */
bool in_soft; /* keep going at end of in sgl */
bool out_soft; /* keep going at end of out sgl */
bool reading;
bool last_segment;
int icbpt; /* input, current blocks_per_transfer */
int ocbpt; /* output, current blocks_per_transfer */
int bytes_read; /* previous IO: into the working buffer */
int bytes_of; /* previous IO: bytes written to of */
int bytes_of2; /* previous IO: bytes written to of2 */
int blks_xfer; /* prev IO: blocks transferred (e.g. bytes_read/ibs) */
int bytes_xfer; /* prev IO: bytes transferred, -1 -> block device */
int leave_reason; /* def: -1 (unknown); 0: EOF on read; else error */
int rem_seg_bytes; /* remaining valid bytes in buffer (after short) */
int partial_write_bytes;
int last_seg_wbytes; /* when ofile sz is limit; 0: no reduction */
uint32_t cur_in_num; /* current in number of blocks */
uint32_t cur_out_num; /* current out number of blocks */
uint64_t cur_in_lba; /* current in starts at this logical block */
uint64_t prev_in_lba; /* previous in leaves file "pointer" here */
uint64_t cur_out_lba; /* current out starts at this logical block */
uint64_t prev_out_lba; /* previous out leaves file "pointer" here */
struct cp_statistics_t stats; /* running totals kept here */
struct sgl_iter_t in_iter;
struct sgl_iter_t out_iter;
uint8_t * low_bp; /* byte pointer to start of work segment */
uint8_t * subseg_bp; /* byte pointer to start of sub-segment */
uint8_t * cur_bp; /* pointer in sub-segment for start of current IO */
int64_t * cur_countp; /* points to in_full, out_full, or is NULL for
* don't count */
const char * buf_name; /* optional buffer name for debugging */
};
/* This data is extracted from the response of the Receive ROD Token
* Information (RRTI) command and the Receive Copy Status (RCS) command. */
struct rrti_resp_t {
uint8_t for_sa; /* response to service action */
uint8_t cstat; /* copy operation status */
uint8_t xc_cstatus; /* extended copy completion status */
uint8_t sense_len; /* (parameter data, actual) sense data length */
uint32_t esu_del; /* estimated status update delay (ms) */
uint64_t tc; /* transfer count (blocks) */
/* Prior to this point response * is in common with the RCS command */
uint32_t rt_len; /* might differ from 512, 0 if no ROD token */
uint8_t rod_tok[512]; /* (perhaps truncate to) ODX ROD Token */
};
/* One instance for arguments to iflag= , another instance for oflag=
* conv= arguments are mapped to flag arguments.
* flags for classic dd on disks or files unless otherwise noted. */
struct flags_t {
bool append; /* open non-pt OF with O_APPEND flag */
bool atomic; /* for pt OF use WRITE ATOMIC instead of WRITE */
bool block; /* only for pt, non blocking open is default */
bool cat; /* xcopy(lid1) tape: strategy for inexact fit */
bool coe; /* continue on (read) error, supply zeros */
bool dc; /* xcopy(lid1): destination count */
bool del_tkn; /* xcopy(odx): delete token after operation */
bool direct; /* set O_DIRECT on non-pt open() */
bool dpo; /* 'disable page out' bits on READ and WRITE cdbs */
bool errblk; /* write unreadable LB addresses to errblk.txt */
bool excl; /* opens IF and OF with O_EXCL flag */
bool fdatasync; /* use fdatasync() system call on OF after xfer */
bool ff; /* iflag=ff makes input all 0xff bytes */
bool flock; /* linux: use flock(LOCK_EX | LOCK_NB) before xfer */
bool fsync; /* use fsync() system call on OF after xfer */
bool fua; /* force unit access on pt calls */
bool fua_nv; /* obsolete (sbc3r35l): fua_non_volatile on pt */
bool ignoreew; /* tape: ignore early warning */
bool immed; /* xcopy(odx): returns immediately from POPULATE
* TOKEN and WRITE USING TOKEN then poll */
bool no_del_tkn; /* xcopy(odx): don't delete token after xfer */
bool nofm; /* tape: no filemark on close */
bool nopad; /* tape: no pad on partial writes */
bool norcap; /* no READ CAPACITY calls on pt */
bool nowrite; /* don't write to OF */
bool odx; /* xcopy(LID4), sbc-3's POPULATE TOKEN++ */
bool pad; /* pad with zeros partial (trailing) pt writes; also
* xcopy(lid1) tape: strategy for inexact fit */
bool prealloc; /* use (posix_)fallocate() on output file before
* transfer */
bool prefer_rcs; /* prefer Receive Copy Status command over RRTI */
bool pt; /* use pass-through to inject SCSI commands */
bool rarc; /* Set Rebuild Assist Recovery Control bit on READs */
bool resume; /* try to restart previously interrupted copy */
bool rtf_len; /* odx: append number of bytes ROD represents to end
* of RTF */
bool self; /* trim (zero segments) out of a file in place (i.e.
* with no copy) */
bool sparing; /* saves on writes by reading OF (and/or OF2) and if
* same as segment read from IF, move on (i.e. don't
* overwrite OF (and/or OF2) with same data */
bool ssync; /* for pt OF (or OF2) do a SCSI SYNCHRONIZE CACHE
* at end of transfer before close */
bool strunc; /* perform sparse copy on non-pt OF using the
* ftruncate() call to extend/truncate OF */
bool sync; /* open non-pt file with O_SYNC flag */
bool trunc; /* truncate non-pt OF to SEEK (typically 0 length)
* before start of copy */
bool v_verify; /* oflag with pt, hidden flag, set by --verify */
bool wsame16; /* given trim or unmap then wsame16 is set. Trim/unmap
* done on pt using SCSI WRITE SAME(16) command */
bool wstream; /* oflag with pt, send WRITE STREAM(16) with list_id
* as Stream ID (valid range: 0x1 to 0xffff) */
bool wverify; /* oflag with pt, turns WRITE into WRITE AND VERIFY */
bool xcopy; /* xcopy(LID1) requested */
bool zero; /* iflag=00 makes input all 0x0 bytes */
int bytchk; /* set field (2 bit) in WRITE AND VERIFY */
int cdbsz; /* 6, 10, 12, 16 or 32 */
int force; /* overrides errors, 2: force harder */
int nocache; /* (1 & nocache): IF and/or OF; (2 & nocache): OF .
* OF, OF2: use posix_fadvise(POSIX_FADV_DONTNEED)
* IF: use posix_fadvise(POSIX_FADV_SEQUENTIAL) */
int retries; /* retry each failed READ or WRITE this number of
* times (def: 0 (for no retries)) */
int sparse; /* when > 0 skips writes on segments that are all
* zeros. When 1 writes last segment even if all
* zeros, if > 1 then will skip last segment as well
* if all zeros */
};
/* Command line options plus some other state variables.
* The _given fields indicate whether option was given or if true, the
* corresponding value takes its default value when false. */
struct opts_t {
bool bpt_given; /* true when bpt= given, BPT --> bpt_i */
bool bs_given; /* bs=BS given, check if ibs= or obs= also given */
bool bs_same; /* true when ibs[_lb|_pi] and obs[_lb|_pi] the same */
bool cdbsz_given;
bool count_given; /* count=COUNT value placed in dd_count variable */
bool do_time; /* default true, set false by --status=none */
bool flexible; /* if 'HEX' in sgl file, parse as hex without
* 'H' prior to @ in skip= or seek= argument */
bool has_odx; /* --odx: equivalent to iflag=odx or oflag=odx */
bool has_xcopy; /* --xcopy (LID1): iflag=xcopy or oflag=xcopy */
bool ibs_given;
bool interrupt_io; /* [intio=0|1] if false, mask SIGINFO++ during IO */
bool jf_given; /* at least 1 level of job file given */
bool list_id_given;
bool obs_given;
bool o_readonly;
bool out_sparing_active;
bool out_sparse_active;
bool out_trim_active;
bool outf_given;
bool prefetch_given;/* only active with --verify */
bool primary_ddpt; /* true if ddpt, false if helper utility */
bool quiet; /* set true when verbose=-1 (or any negative int) */
bool reading_fifo; /* true when if=- (read stdin) or if=PIPE */
bool read1_or_transfer; /* true when of=/dev/null or similar */
bool rod_type_given;
bool rtf_append; /* if rtf is regular file: open(O_APPEND) */
bool rtf_len_add; /* append 64 bit ROD byte size to token */
bool show_sgl_v2; /* show built sgls if -vv or higher also given */
bool status_none; /* status=none given */
bool subsequent_wdelay; /* so no delay before first write */
bool verbose_given;
bool verify_given;
bool version_given;
bool xc_cat;
bool xc_dc;
/* command line related variables */
int ddpt_strs; /* number of times 'ddpt' appears in job_file(s) */
int delay; /* intra copy segment delay in milliseconds */
int wdelay; /* delay prior to each write in copy segment */
int dry_run; /* do preparation, bypass copy; >1 go deeper */
int ibs_lb; /* ibs= value, stress its logical block size */
int ibs_pi; /* if (PI) ibs_pi = ibs_lb+pi_len else ibs_pi=ibs_lb */
int ibs_hold; /* not sure why we need this hold */
int obs_lb; /* obs= value, stress its logical block size */
int obs_pi; /* if (PI) obs_pi = obs_lb+pi_len else obs_pi=obs_lb */
int bpt_i; /* Blocks Per Transfer, input sized blocks */
int obpch; /* output blocks per check, granularity of sparse,
* sparing and trim checks for zeros (def: 0) */
int id_usage; /* xcopy(LID1) List identifier usage, init to -1 */
int prio; /* xcopy(LID1) related */
int rdprotect;
int wrprotect;
int coe_limit;
int coe_count;
int progress; /* status=progress, report every 2 minutes or less */
int verbose;
int do_help;
int odx_request; /* ODX_REQ_NONE==0 for no ODX */
int timeout_xcopy; /* xcopy(LID1) and ODX */
int rtf_fd; /* ODX: rtf's file descriptor (init: -1) */
uint32_t inactivity_to; /* ODX: timeout in seconds */
uint32_t list_id; /* xcopy(LID1), odx + wstream related */
uint32_t rod_type; /* ODX: ROD type */
int64_t offset_in_rod; /* ODX: units are obs bytes */
/* working variables and statistics */
int64_t dd_count; /* -1 for not specified, 0 for no blocks to copy */
/* after copy/read starts, decrements to 0 */
/* unit is ibs (input logical block size) */
int64_t lowest_unrecovered; /* on reads */
int64_t highest_unrecovered; /* on reads */
int64_t resume_iblks; /* nz when this indicates restart point */
int64_t num_xcopy; /* xcopy(LID1) */
int max_aborted;
int max_uas;
int err_to_report;
int read_tape_numbytes;
int last_tape_read_len; /* Length of previous tape read */
unsigned int consec_same_len_reads;
FILE * errblk_fp;
struct flags_t * iflagp;
struct dev_info_t * idip;
struct flags_t * oflagp;
struct dev_info_t * odip;
struct dev_info_t * o2dip; /* of2=OFILE2 reg or pipe file, no sgl */
uint8_t * wrkPos;
uint8_t * free_wrkPos;
uint8_t * wrkPos2;
uint8_t * free_wrkPos2;
uint8_t * zeros_buff;
uint8_t * free_zeros_buff;
struct cp_statistics_t * stp; /* NULL or points to cp_state_t's copy */
struct cp_statistics_t stats; /* copied here after internal copy done */
struct sgl_info_t i_sgli; /* in scatter gather list info including list */
struct sgl_info_t o_sgli; /* out scatter gather list info */
char rtf[INOUTF_SZ]; /* ODX: ROD token filename */
#ifdef SG_LIB_WIN32
int wscan; /* only used on Windows, for scanning devices */
#endif
#ifdef HAVE_POSIX_FADVISE
off_t lowest_skip;
off_t lowest_seek;
#endif
#if SA_NOCLDSTOP
sigset_t caught_signals;
sigset_t orig_mask;
#endif
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
bool start_tm_valid;
struct timespec start_tm;
#elif defined(HAVE_GETTIMEOFDAY)
bool start_tm_valid;
struct timeval start_tm;
#endif
};
struct sg_simple_inquiry_resp;
typedef int (*ddpt_rw_f)(struct dev_info_t * dip, struct cp_state_t * csp,
struct opts_t * op);
typedef int (*process_sge_f)(FILE * fp, const struct scat_gath_elem * sge_r,
int hex, int verbose);
extern const char * ddpt_arg_strs[];
/* Some inline functions */
/* Make sure multiplication doesn't overflow int */
static inline int x_mult_div(int x, int mult, int div)
{
return ((int64_t)x * mult) / div;
}
/* Make sure multiplication doesn't overflow int */
static inline int x_mult_rem(int x, int mult, int rem)
{
return ((int64_t)x * mult) % rem;
}
/* Functions declared below are shared by different compilation units */
/* defined in ddpt.c */
/* No global function defined in ddpt.c apart from main() */
/* defined in ddpt_com.c */
const char * get_ddpt_arg_str(int ddpt_arg);
void sleep_ms(int millisecs);
void state_init(struct opts_t * op, struct flags_t * ifp,
struct flags_t * ofp, struct dev_info_t * idip,
struct dev_info_t * odip, struct dev_info_t * o2dip);
void print_stats(const char * str, struct opts_t * op, int who,
bool estimate);
int dd_filetype(const char * filename, int verbose);
char * dd_filetype_str(int ft, char * buff, int max_bufflen,
const char * fname);
void calc_duration_init(struct opts_t * op);
void calc_duration_throughput(const char * leadin, bool contin,
struct opts_t * op);
void print_blk_sizes(const char * fname, const char * access_typ,
int64_t num_blks, int blk_sz, bool to_stderr);
void zero_coe_limit_count(struct opts_t * op);
int get_blkdev_capacity(struct opts_t * op, int which_arg,
int64_t * num_blks, int * blk_sz);
void errblk_open(struct opts_t * op);
void errblk_put(uint64_t lba, struct opts_t * op);
void errblk_put_range(uint64_t lba, int num, struct opts_t * op);
void errblk_close(struct opts_t * op);
#ifdef SG_LIB_LINUX
void print_tape_summary(struct opts_t * op, int res, const char * str);
void print_tape_pos(const char * prefix, const char * postfix,
struct opts_t * op);
#endif
void install_signal_handlers(struct opts_t * op);
void signals_process_delay(struct opts_t * op, int delay_type);
void decode_designation_descriptor(const uint8_t * ucp, int len_less_4,
bool to_stderr, int verb);
int coe_process_eio(struct opts_t * op, int64_t skip);
char * rod_type_str(uint32_t rt, char * b, int b_mlen);
char * rt_cm_id_str(const uint8_t * rtp, int rt_len, char * b,
int b_mlen);
void print_exit_status_msg(const char * prefix, int exit_stat,
bool to_stderr);
struct scat_gath_elem * cl2sgl(const char * inp, int * arr_elems, bool b_vb);
struct scat_gath_elem * file2sgl(const char * file_name, bool def_hex,
bool flexible, int * arr_elems, int * errp,
bool b_vb);
/* Assumes sgli_p->elems and sgli_p->slp are setup and the other fields
* in struct sgl_info_t are zeroed. This function will populate the other
* fields in that structure. Does one pass through the scatter gather list
* (array). Sets these fields in struct sgl_info_t: fragmented, lowest_lba,
* high_lba_p1, monotonic, overlapping, sum and sum_hard. Degenerate
* elements (i.e. those with 0 blocks) are ignored apart from when one is
* last which makes sum_hard false and its LBA becomes high_lba_p1 if it
* is the highest in the list. An empty sgl is equivalent to a 1 element
* list with [0, 0], so sum_hard==false, monit==true, fragmented==false
* overlapping ==false . id_str may be NULL, present to enhance verbose
* output. */
void sgl_sum_scan(struct sgl_info_t * sgli_p, const char * id_str,
bool show_sgl, bool b_verbose);
/* Prints sgl to stderr or stdout. */
void sgl_print(struct sgl_info_t * sgli_p, bool skip_meta,
const char * id_str, bool to_stdout, bool show_sg);
/* Prints a single sge (scatter gather list element) to stderr or stdout. */
void sge_print(const struct scat_gath_elem * sgep, const char * id_str,
bool to_stdout);
/* Return minimum(num_blks, <blocks_from_sgl-post-blk_off>). First it
* starts skipping blk_off blocks and if elems is exceeded then it
* returns 0. Then it sums up the number of blocks from each subsequent
* sg element checking that elems and max_descriptors are not exceeded. It
* also stops counting if that sum exceeds num_blks. If max_descriptors is
* 0 then it is not constraining. Note that elems and blk_off are relative
* to the start of the sgl; while num_blks and max_descriptors are relative
* to the sgl+blk_off . */
uint64_t count_sgl_blocks_from(const struct scat_gath_elem * sglp, int elems,
uint64_t blk_off, uint32_t num_blks,
uint32_t max_descriptors /* from blk_off */);
/* Points to start of sgl after init, sets extend_last bit */
void sgl_iter_init(struct sgl_iter_t * iter_p, struct scat_gath_elem * sglp,
int elems);
/* Given a blk_count, the iterator (*iter_p) is moved toward the EOL. If
* relative is true the move is from the current position of the iterator.
* If relative is false then the move is from the start of the sgl. The
* sgl_iter_add(itp, 0, false) call sets the iterator to the start of the
* sgl. Returns true unless blk_count takes iterator two or more past the
* last element. So if blk_count takes the iterator to the EOL, this
* function returns true. */
bool sgl_iter_add(struct sgl_iter_t * iter_p, uint64_t blk_count,
bool relative);
/* Move the iterator from its current position (which may be to EOL) towards
* the start of the sgl (i.e. backwards) for blk_count blocks. Returns true
* if iterator is valid after the move, else returns false. N.B. if false is
* returned, then the iterator is invalid and may need to set it to a valid
* value. */
bool sgl_iter_sub(struct sgl_iter_t * iter_p, uint64_t blk_count);
/* Calculates difference between iterators, logically: res <-- lhs - rhs
* Checks that lhsp and rhsp have same underlying sgl, if not returns
* INT_MIN. Assumes iterators close enough for result to lie in range
* from (-INT_MAX) to INT_MAX (inclusive). */
int sgl_iter_diff(const struct sgl_iter_t * lhsp,
const struct sgl_iter_t * rhsp);
/* For each segment from and including iter_p, for length blk_count call
* *a_fp with fp and my_op as arguments. Move iter_p forward by blk_count
* (if valid). Returns 0 for good, else error value. */
int iter_add_process(struct sgl_iter_t * iter_p, uint64_t blk_count,
process_sge_f a_fp, FILE * fp, int hex, int rblks,
int verbose);
/* Returns the number of times 'ch' is found in string 's' given the
* string's length. */
int num_chs_in_str(const char * s, int slen, int ch);
/* Returns the number of times either 'ch1' or 'ch2' is found in
* string 's' given the string's length. */
int num_either_ch_in_str(const char * s, int slen, int ch1, int ch2);
/* Copies abs(add_blks) blocks for current position of file/device (referred
* to by dip) to or from a segment of the computer's ram. The copy is into
* ram when ddpt_arg is 0 (i.e. a "read"), otherwise it is from ram (i.e. a
* "write"). IO is performed by the fp (callback function) and the iterator
* (or file pointer) is moved forward (i.e. toward the end) when add_blks > 0.
* When add_blks < 0, the iterator is moved backward (i.e. toward the
* beginning). Returns 0 for okay else an error number. -9999 is returned
* for an unexpected error with the iterator. */
int cp_via_sgl_iter(struct dev_info_t * dip, struct cp_state_t * csp,
int add_blks, ddpt_rw_f fp, struct opts_t * op);
/* Returns number elements in scatter gather list (array) whose pointer
* is written to *sge_pp. On error returns negated error number and
* NULL is written to *sge_pp . The caller is responsible for freeing
* memory associated with *sge_pp . */
int build_sgl(struct scat_gath_elem ** sge_pp, int64_t count, int64_t offs);
/* Builds single element sgl with (*sge_pp)->num==0 . */
int build_degen_sgl(struct scat_gath_elem ** sge_pp, int64_t start_lba);
/* Similar to build_sgl but appends to existing sgl whose length is cur_elems.
* Note that *sge_pp will probably change (in which case the previous *sge_pp
* is freed). */
int append2sgl(struct scat_gath_elem ** sge_pp, int cur_elems,
int64_t extra_blks, int64_t start_lba);
/* Returns true if associated iterator is monotonic (increasing) and not
* fragmented. Empty sgl and single element degenerate considered linear.
* Assumes sgl_sum_scan() has been called on sgl. */
bool is_iter_linear(const struct sgl_info_t * sglip);
/* Returns LBA referred to by iterator if valid or returns DDPT_LBA_INVALID
* (-1) if at end or invalid. */
int64_t sgl_iter_lba(const struct sgl_iter_t * itp);
/* Returns true of no sgl or sgl is at the end [<elems>, 0], otherwise it
* returns false. */
bool sgl_iter_at_end(const struct sgl_iter_t * itp);
/* Print data held in struct sgl_iter_t to fp. If fp is NULL then to stderr */
void sgl_iter_print(const struct sgl_iter_t * itp, const char * leadin,
bool index_only, bool in_hex, FILE * fp);
/* Returns true if either argument is NULL/0 or a 1 element list with both
* lba and num 0; otherwise returns false. */
bool sgl_empty(struct scat_gath_elem * sglp, int elems);
/* Returns >= 0 if sgl can be simplified to a single LBA. So an empty sgl
* will return 0; a one element sgl will return its LBA. A multiple element
* sgl only returns the first element's LBA (that is not degenerate) if the
* sgl is monotonic and not fragmented. In the extreme case takes last
* element's LBA if all prior elements are degenerate. Else returns -1 .
* Assumes sgl_sum_scan() has been called. */
int64_t get_low_lba_from_linear(const struct sgl_info_t * sglip);
/* If bad arguments returns -1, otherwise returns the lowest LBA in *sglp .
* If no elements considered returns 0. If ignore_degen is true than
* ignores all elements with num_blks zero unless always_last is also
* true in which case the last element is always considered. */
int64_t get_lowest_lba(const struct scat_gath_elem * sglp, int num_elems,
bool ignore_degen, bool always_last);
void cp_state_init(struct cp_state_t * csp, struct opts_t * op);
/* Writes the LBA and number_of_blocks in sge_r to a line at the current
* file position (typically the end) of fp, with a trailing \n character.
* Returns 0 on success, else SG_LIB_FILE_ERROR . */
int output_sge_f(FILE * fp, const struct scat_gath_elem * sgep, int hex,
int verbose);
/* Compares from lsgep, offset by l_bk_off against rsgep, offset by r_bk_off.
* While lbas compare equal lsgep is advanced by up to lelems, while rsgep
* is advanced by up to relems. Returns false on the first inequality;
* otherwise if both list are exhausted at the same point, then returns true.
* If no inequality and one list is exhausted before the other, then returns
* allow_partial. */
bool sgl_eq_f(const struct scat_gath_elem * lsgep, int lelems, int l_bk_off,
const struct scat_gath_elem * rsgep, int relems, int r_bk_off,
bool allow_partial);
/* Compares from the current iterator positions of lhsp and rhsp until
* the shorter list is exhausted. Returns false on the first inequality.
* If no inequality and both remaining lists are same length then returns
* true. If no inequality but remaining lists differ in length then returns
* allow_partial. */
bool sgl_iter_eq(const struct sgl_iter_t * lhsp,
const struct sgl_iter_t * rhsp, bool allow_partial);
/* defined in ddpt_pt.c */
void * pt_construct_obj(void);
void pt_destruct_obj(void * vp);
int pt_open_if(struct opts_t * op, struct sg_simple_inquiry_resp * sirp);
int pt_open_of(struct opts_t * op, struct sg_simple_inquiry_resp * sirp);
void pt_close(int fd);
int pt_read_capacity(struct opts_t * op, bool in0_out1, int64_t * num_blks,
int * blk_sz);
int pt_read(struct opts_t * op, bool in0_out1, uint8_t * buff,
int blocks, int64_t from_block, int * blks_readp);
int pt_write(struct opts_t * op, const uint8_t * buff, int blocks,
int64_t to_block);
/* Sets UNMAP bit and no other flags, sends 1 block (which should be
* ignored by device). */
int pt_write_same16(struct opts_t * op, const uint8_t * buff, int bs,
int blocks, int64_t start_block);
void pt_sync_cache(int fd);
int pt_3party_copy_out(int sg_fd, int sa, uint32_t list_id, int group_num,
int timeout_secs, void * paramp, int param_len,
bool noisy, int verbose, int err_vb);
int pt_3party_copy_in(int sg_fd, int sa, uint32_t list_id, int timeout_secs,
void * resp, int mx_resp_len, bool noisy, int verbose,
int err_vb);
int pt_pre_fetch(struct opts_t * op, int blocks, int64_t start_block);
/* defined in ddpt_xcopy.c */
int open_rtf(struct opts_t * op);
const char * cpy_op_status_str(int cos, char * b, int blen);
int print_3pc_vpd(struct opts_t * op, bool to_stderr);
int do_xcopy_lid1(struct opts_t * op);
int do_pop_tok(struct opts_t * op, uint64_t blk_off, uint32_t num_blks,
bool walk_list_id, int vb_a);
int do_rrti(struct opts_t * op, bool in0_out1, struct rrti_resp_t * rrp,
int verb);
int do_rcs(struct opts_t * op, bool in0_out1, struct rrti_resp_t * rrp,
int verb);
void get_local_rod_tok(uint8_t * tokp, int max_tok_len);
int process_after_poptok(struct opts_t * op, uint64_t * tcp, int vb_a);
int do_wut(struct opts_t * op, uint8_t * tokp, uint64_t blk_off,
uint32_t num_blks, uint64_t oir, bool more_left, bool walk_list_id,
int vb_a);
int process_after_wut(struct opts_t * op, uint64_t * tcp, int vb_a);
int do_odx(struct opts_t * op);
/* defined in ddpt_cl.c */
int cl_parse(struct opts_t * op, int argc, char * argv[],
const char * version_str, int jf_depth);
void ddpt_usage(int help);
#ifdef SG_LIB_WIN32
/* defined in ddpt_win32.c */
int win32_dd_filetype(const char * fn, int verbose);
int win32_get_blkdev_capacity(struct opts_t * optsp, int which_arg,
int64_t * num_blks, int * blk_sz);
void win32_adjust_fns_pt(struct opts_t * optsp);
int win32_open_if(struct opts_t * optsp, int flags, int verbose);
int win32_open_of(struct opts_t * optsp, int flags, int verbose);
int win32_set_file_pos(struct dev_info_t * dip, int64_t pos, int verbose);
int win32_block_read(struct opts_t * optsp, uint8_t * bp, int num_bytes,
int verbose);
int win32_block_read_from_of(struct opts_t * optsp, uint8_t * bp,
int num_bytes, int verbose);
int win32_block_write(struct opts_t * optsp, const uint8_t * bp,
int num_bytes, int verbose);
int win32_cp_read_block(struct opts_t * optsp, struct cp_state_t * csp,
uint8_t * wrkPos, int * ifull_extrap, int verbose);
void win32_sleep_ms(int millisecs);
int sg_do_wscan(char letter, int do_scan, int verb);
#ifndef HAVE_SYSCONF
size_t win32_pagesize(void);
#endif
#endif /* SG_LIB_WIN32 */
#ifdef __cplusplus
} /* trailing brace for 'extern "C" { ' at top of this file */
/* Following only compiled to C++, bypassed for C */
struct split_fn_fp {
// constructor
split_fn_fp(const char * fn, FILE * a_fp) : out_fn(fn), fp(a_fp) {}
public:
std::string out_fn;
FILE * fp;
};
struct sgl_opts_t {
bool append2iaf;
bool append2out_f;
bool chs_given;
bool div_lba_only;
bool div_num_only;
bool elem_given;
bool flexible;
bool iaf2stdout;
bool index_given;
bool out2stdout;
bool non_overlap_chk;
bool pr_stats;
bool quiet;
int act_val;
int degen_mask;
int div_scale_n;
int document; /* Add comment(s) to O_SGL(s), >1 add cmdline */
int do_hex;
int help;
int interleave; /* when splitting a sgl, max number of blocks before
* moving to next sgl; def=0 --> no interleave */
int last_elem; /* init to -1 which makes start_elem a singleton */
int round_blks;
int sort_cmp_val;
int split_n;
int start_elem; /* init to -1 which means write out whole O_SGL */
int verbose;
const char * b_sgl_arg;
const char * iaf; /* index array filename */
const char * out_fn;
const char * fne;
struct chs_t chs;
struct cl_sgl_stats ab_sgl_stats;
std::string cmd_line;
std::vector<int> index_arr; /* input from --index=IA */
std::vector<struct split_fn_fp> split_out_fns;
std::vector<struct split_fn_fp> b_split_out_fns; /* 'b' side for tsplit */
};
#endif /* end of __cplusplus block */
#endif /* DDPT_H guard against multiple includes */
| 44.686058 | 79 | 0.669263 | [
"object",
"vector"
] |
8e3f602a329d7de3e059b334311f64606fe31a7c | 7,223 | c | C | quicktour/07-mcore/src/main.c | bluccino/tutorial | 15f606c0f1b5f000b78deaa6972fd1b656a0f2ce | [
"Apache-2.0"
] | 1 | 2021-12-23T16:19:15.000Z | 2021-12-23T16:19:15.000Z | quicktour/07-mcore/src/main.c | bluccino/tutorial | 15f606c0f1b5f000b78deaa6972fd1b656a0f2ce | [
"Apache-2.0"
] | 3 | 2021-12-11T21:49:22.000Z | 2022-03-21T22:25:16.000Z | quicktour/07-mcore/src/main.c | bluccino/tutorial | 15f606c0f1b5f000b78deaa6972fd1b656a0f2ce | [
"Apache-2.0"
] | null | null | null | //==============================================================================
// main.c
// main program for mcore test
//
// Created by Hugo Pristauz on 2022-Jan-04
// Copyright © 2022 Bluenetics. All rights reserved.
//==============================================================================
//
// Event Flow in unprovisioned state ("device" state)
// - any button press toggles (local) LED @2 (red LED on 52840 dongle)
//
// +-----------+
// | BUTTON @1 |---+
// +-----------+ |
// |
// +-----------+ |
// | BUTTON @2 |---+
// +-----------+ | +--------+
// +--------------------------------------->| LED @2 |
// +-----------+ | +--------+
// | BUTTON @3 |---+
// +-----------+ |
// |
// +-----------+ |
// | BUTTON @4 |---+
// +-----------+
//
// Event Flow in provisioned state ("node" state)
// - any button switch state is posted via GOOCLI to mesh network
//
// +-----------+
// | BUTTON @1 |---+
// +-----------+ |
// |
// +-----------+ |
// | BUTTON @2 |---+
// +-----------+ | +-----------+ +-----------+ +--------+
// +--->| GOOCLI @1 | ))))) | GOOSRV @1 |-->| LED @2 |
// +-----------+ | +-----------+ +-----------| +--------+
// | BUTTON @3 |---+
// +-----------+ |
// |
// +-----------+ |
// | BUTTON @4 |---+
// +-----------+
//
// APP has to implement the following event message flow:
// - [SWITCH:STS @id,val] events are forwarded to [GOOCLI:SET @1,val] posts
// - mesh network has to be configured as follows:
// -- GOOCLI @1 has to post to group G1
// -- GOOSRV @1 has to subscribe group G1
// - [GOOSRV:STS @1,val] events are forwarded to [LED:SET @2,val] calls
// - bl_led(id,val) is a helper routine for posting [LED:SET @id,val] events
//
//==============================================================================
#include "bluccino.h"
#include "bl_basis.h"
//==============================================================================
// MAIN level logging shorthands
//==============================================================================
#define LOG LOG_MAIN
#define LOGO(lvl,col,o,val) LOGO_MAIN(lvl,col"main:",o,val)
#define LOG0(lvl,col,o,val) LOGO_MAIN(lvl,col,o,val)
//==============================================================================
// defines & locals
//==============================================================================
#define VERSION CFG_APP_VERSION
#define VERBOSE CFG_APP_VERBOSE // verbose level for application
#define T_BLINK 1000 // 1000 ms RGB blink period
static volatile int id = 0; // THE LED id
//==============================================================================
// helper: attention blinker (let green status LED @0 attention blinking)
// - @id=0: dark, @id=1: status, @id=2: red, @id=3: green, @id=4: blue
//==============================================================================
static int blink(BL_ob *o, int ticks) // attention blinker to be ticked
{
static BL_ms due = 0; // need for periodic action
if (id <= 1 || !bl_due(&due,T_BLINK)) // no blinking if @id:off or not due
return 0; // bye if LED off or not due
if ( bl_get(bl_basis,ATT_) || // no blinking in attention mode
bl_get(bl_basis,BUSY_)) // no blinking during startup
return 0; // bye if attention state
static bool toggle;
toggle = !toggle;
if (toggle)
return (bl_led(id,1), bl_led(2+id%3,0)); // flip LED pair
else
return (bl_led(id,0), bl_led(2+id%3,1)); // flip back LED pair
}
//==============================================================================
// public app module interface
//==============================================================================
//
// APP Interfaces:
// SYS Interface: [] = SYS(INIT,TICK,TOCK)
//
// +--------------------+
// | APP |
// +--------------------+
// INIT ->| SYS: |
// TICK ->| |
// TOCK ->| |
// +--------------------+
// STS ->| SWITCH: |
// +--------------------+
// STS ->| GOOSRV: |
// +--------------------+
// | GOOCLI: |-o SET
// +--------------------+
// Input Messages:
// [SYS:INIT <cb>] init app, ignore output callback
// [SYS:TICK @id,cnt] ticking the app
// [SYS:TOCK @id,cnt] tocking the app
// [SWITCH:STS @id,sts] receive status update from switch @id
// [GOOSRV:STS @id,sts] receive status update from generic onoffserver @id
//
// Output Messages:
// [GOOCLI:SET @id,val] publish SET message via generic onoff client
//
//==============================================================================
int app(BL_ob *o, int val) // public APP module interface
{
switch (bl_id(o))
{
case BL_ID(_SYS,INIT_): // [SYS:INIT <cb>]
return bl_init(bl_basis,bl_down); // init BL_BASIS, output goes down
case BL_ID(_SYS,TICK_): // [SYS:TICK @id,cnt]
blink(o,val); // tick blinker
bl_basis(o,val); // tick BL_BASIS module
return 0; // OK
case BL_ID(_SYS,TOCK_): // [SYS:TOCK @id,cnt]
if (val % 5 == 0) // log every 5th tock
LOGO(1,"I'm alive! ",o,val); // log to see we are alife
return 0; // OK
case BL_ID(_SWITCH,STS_): // button press to cause LED on off
LOGO(1,"@",o,val);
if ( bl_get(bl_basis,PRV_)) // only if provisioned
{
BL_ob oo = {_GOOCLI,SET_,1,NULL};
bl_down(&oo,val); // post via generic on/off client
}
else
bl_led(2,val); // switch LED @2 on/off
return 0; // OK
case BL_ID(_GOOSRV,STS_): // [GOOSRV:STS] status update
LOGO(1,BL_R,o,val);
if (o->id == 1)
bl_led(2,val); // switch LED @2
return 0; // OK
default:
return bl_basis(o,val); // else forward event to BL_BASE module
}
}
//==============================================================================
// main function
//==============================================================================
void main(void)
{
bl_hello(VERBOSE,VERSION); // set verbose level, print hello message
bl_run(app,10,1000,app); // run app with 10/1000 ms tick/tock
}
| 39.255435 | 80 | 0.359823 | [
"mesh"
] |
8e3fbf4ef23fbd170bb4f68decce6e50a819499b | 11,942 | h | C | source/common/config/xds_mux/grpc_mux_impl.h | giantcroc/envoy | c535d5abf8d106925070fe6fd018a716e6bf2bf1 | [
"Apache-2.0"
] | 17,703 | 2017-09-14T18:23:43.000Z | 2022-03-31T22:04:17.000Z | source/common/config/xds_mux/grpc_mux_impl.h | giantcroc/envoy | c535d5abf8d106925070fe6fd018a716e6bf2bf1 | [
"Apache-2.0"
] | 15,957 | 2017-09-14T16:38:22.000Z | 2022-03-31T23:56:30.000Z | source/common/config/xds_mux/grpc_mux_impl.h | giantcroc/envoy | c535d5abf8d106925070fe6fd018a716e6bf2bf1 | [
"Apache-2.0"
] | 3,780 | 2017-09-14T18:58:47.000Z | 2022-03-31T17:10:47.000Z | #pragma once
#include <cstdint>
#include <memory>
#include <queue>
#include "envoy/common/random_generator.h"
#include "envoy/common/time.h"
#include "envoy/common/token_bucket.h"
#include "envoy/config/grpc_mux.h"
#include "envoy/config/subscription.h"
#include "envoy/event/dispatcher.h"
#include "envoy/grpc/status.h"
#include "envoy/service/discovery/v3/discovery.pb.h"
#include "envoy/upstream/cluster_manager.h"
#include "source/common/common/logger.h"
#include "source/common/common/utility.h"
#include "source/common/config/api_version.h"
#include "source/common/config/grpc_stream.h"
#include "source/common/config/pausable_ack_queue.h"
#include "source/common/config/watch_map.h"
#include "source/common/config/xds_mux/delta_subscription_state.h"
#include "source/common/config/xds_mux/sotw_subscription_state.h"
#include "source/common/grpc/common.h"
#include "absl/container/node_hash_map.h"
namespace Envoy {
namespace Config {
namespace XdsMux {
class ShutdownableMux {
public:
virtual ~ShutdownableMux() = default;
virtual void shutdown() PURE;
};
// Manages subscriptions to one or more type of resource. The logical protocol
// state of those subscription(s) is handled by SubscriptionState.
// This class owns the GrpcStream used to talk to the server, maintains queuing
// logic to properly order the subscription(s)' various messages, and allows
// starting/stopping/pausing of the subscriptions.
//
// @tparam S SubscriptionState state type, either SotwSubscriptionState or DeltaSubscriptionState
// @tparam F SubscriptionStateFactory type, either SotwSubscriptionStateFactory or
// DeltaSubscriptionStateFactory
// @tparam RQ Xds request type, either envoy::service::discovery::v3::DiscoveryRequest or
// envoy::service::discovery::v3::DeltaDiscoveryRequest
// @tparam RS Xds response type, either envoy::service::discovery::v3::DiscoveryResponse or
// envoy::service::discovery::v3::DeltaDiscoveryResponse
//
template <class S, class F, class RQ, class RS>
class GrpcMuxImpl : public GrpcStreamCallbacks<RS>,
public GrpcMux,
public ShutdownableMux,
Logger::Loggable<Logger::Id::config> {
public:
GrpcMuxImpl(std::unique_ptr<F> subscription_state_factory, bool skip_subsequent_node,
const LocalInfo::LocalInfo& local_info, Grpc::RawAsyncClientPtr&& async_client,
Event::Dispatcher& dispatcher, const Protobuf::MethodDescriptor& service_method,
Random::RandomGenerator& random, Stats::Scope& scope,
const RateLimitSettings& rate_limit_settings);
~GrpcMuxImpl() override;
// Causes all GrpcMuxImpl objects to stop sending any messages on `grpc_stream_` to fix a crash
// on Envoy shutdown due to dangling pointers. This may not be the ideal fix; it is probably
// preferable for the `ServerImpl` to cause all configuration subscriptions to be shutdown, which
// would then cause all `GrpcMuxImpl` to be destructed.
// TODO: figure out the correct fix: https://github.com/envoyproxy/envoy/issues/15072.
static void shutdownAll();
void shutdown() override { shutdown_ = true; }
bool isShutdown() { return shutdown_; }
// TODO (dmitri-d) return a naked pointer instead of the wrapper once the legacy mux has been
// removed and the mux interface can be changed
Config::GrpcMuxWatchPtr addWatch(const std::string& type_url,
const absl::flat_hash_set<std::string>& resources,
SubscriptionCallbacks& callbacks,
OpaqueResourceDecoder& resource_decoder,
const SubscriptionOptions& options) override;
void updateWatch(const std::string& type_url, Watch* watch,
const absl::flat_hash_set<std::string>& resources,
const SubscriptionOptions& options);
void removeWatch(const std::string& type_url, Watch* watch);
ScopedResume pause(const std::string& type_url) override;
ScopedResume pause(const std::vector<std::string> type_urls) override;
void start() override;
const absl::flat_hash_map<std::string, std::unique_ptr<S>>& subscriptions() const {
return subscriptions_;
}
// GrpcStreamCallbacks
void onStreamEstablished() override { handleEstablishedStream(); }
void onEstablishmentFailure() override { handleStreamEstablishmentFailure(); }
void onWriteable() override { trySendDiscoveryRequests(); }
void onDiscoveryResponse(std::unique_ptr<RS>&& message,
ControlPlaneStats& control_plane_stats) override {
genericHandleResponse(message->type_url(), *message, control_plane_stats);
}
GrpcStream<RQ, RS>& grpcStreamForTest() { return grpc_stream_; }
protected:
class WatchImpl : public Envoy::Config::GrpcMuxWatch {
public:
WatchImpl(const std::string& type_url, Watch* watch, GrpcMuxImpl& parent,
const SubscriptionOptions& options)
: type_url_(type_url), watch_(watch), parent_(parent), options_(options) {}
~WatchImpl() override { remove(); }
void remove() {
if (watch_) {
parent_.removeWatch(type_url_, watch_);
watch_ = nullptr;
}
}
void update(const absl::flat_hash_set<std::string>& resources) override {
parent_.updateWatch(type_url_, watch_, resources, options_);
}
private:
const std::string type_url_;
Watch* watch_;
GrpcMuxImpl& parent_;
const SubscriptionOptions options_;
};
void sendGrpcMessage(RQ& msg_proto, S& sub_state);
void maybeUpdateQueueSizeStat(uint64_t size) { grpc_stream_.maybeUpdateQueueSizeStat(size); }
bool grpcStreamAvailable() { return grpc_stream_.grpcStreamAvailable(); }
bool rateLimitAllowsDrain() { return grpc_stream_.checkRateLimitAllowsDrain(); }
void sendMessage(RQ& msg_proto) { grpc_stream_.sendMessage(msg_proto); }
S& subscriptionStateFor(const std::string& type_url);
WatchMap& watchMapFor(const std::string& type_url);
void handleEstablishedStream();
void handleStreamEstablishmentFailure();
void genericHandleResponse(const std::string& type_url, const RS& response_proto,
ControlPlaneStats& control_plane_stats);
void trySendDiscoveryRequests();
bool skipSubsequentNode() const { return skip_subsequent_node_; }
bool anyRequestSentYetInCurrentStream() const { return any_request_sent_yet_in_current_stream_; }
void setAnyRequestSentYetInCurrentStream(bool value) {
any_request_sent_yet_in_current_stream_ = value;
}
const LocalInfo::LocalInfo& localInfo() const { return local_info_; }
private:
// Checks whether external conditions allow sending a DeltaDiscoveryRequest. (Does not check
// whether we *want* to send a (Delta)DiscoveryRequest).
bool canSendDiscoveryRequest(const std::string& type_url);
// Checks whether we have something to say in a (Delta)DiscoveryRequest, which can be an ACK
// and/or a subscription update. (Does not check whether we *can* send that
// (Delta)DiscoveryRequest). Returns the type_url we should send the DeltaDiscoveryRequest for (if
// any). First, prioritizes ACKs over non-ACK subscription interest updates. Then, prioritizes
// non-ACK updates in the order the various types of subscriptions were activated (as tracked by
// subscription_ordering_).
absl::optional<std::string> whoWantsToSendDiscoveryRequest();
// Invoked when dynamic context parameters change for a resource type.
void onDynamicContextUpdate(absl::string_view resource_type_url);
GrpcStream<RQ, RS> grpc_stream_;
// Resource (N)ACKs we're waiting to send, stored in the order that they should be sent in. All
// of our different resource types' ACKs are mixed together in this queue. See class for
// description of how it interacts with pause() and resume().
PausableAckQueue pausable_ack_queue_;
// Makes SubscriptionStates, to be held in the subscriptions_ map. Whether this GrpcMux is doing
// delta or state of the world xDS is determined by which concrete subclass this variable gets.
std::unique_ptr<F> subscription_state_factory_;
// Map key is type_url.
// Only addWatch() should insert into these maps.
absl::flat_hash_map<std::string, std::unique_ptr<S>> subscriptions_;
absl::flat_hash_map<std::string, std::unique_ptr<WatchMap>> watch_maps_;
// Determines the order of initial discovery requests. (Assumes that subscriptions are added
// to this GrpcMux in the order of Envoy's dependency ordering).
std::list<std::string> subscription_ordering_;
// Whether to enable the optimization of only including the node field in the very first
// discovery request in an xDS gRPC stream (really just one: *not* per-type_url).
const bool skip_subsequent_node_;
// State to help with skip_subsequent_node's logic.
bool any_request_sent_yet_in_current_stream_{};
// Used to populate the (Delta)DiscoveryRequest's node field. That field is the same across
// all type_urls, and moreover, the 'skip_subsequent_node' logic needs to operate across all
// the type_urls. So, while the SubscriptionStates populate every other field of these messages,
// this one is up to GrpcMux.
const LocalInfo::LocalInfo& local_info_;
Common::CallbackHandlePtr dynamic_update_callback_handle_;
// True iff Envoy is shutting down; no messages should be sent on the `grpc_stream_` when this is
// true because it may contain dangling pointers.
std::atomic<bool> shutdown_{false};
};
class GrpcMuxDelta : public GrpcMuxImpl<DeltaSubscriptionState, DeltaSubscriptionStateFactory,
envoy::service::discovery::v3::DeltaDiscoveryRequest,
envoy::service::discovery::v3::DeltaDiscoveryResponse> {
public:
GrpcMuxDelta(Grpc::RawAsyncClientPtr&& async_client, Event::Dispatcher& dispatcher,
const Protobuf::MethodDescriptor& service_method, Random::RandomGenerator& random,
Stats::Scope& scope, const RateLimitSettings& rate_limit_settings,
const LocalInfo::LocalInfo& local_info, bool skip_subsequent_node);
// GrpcStreamCallbacks
void requestOnDemandUpdate(const std::string& type_url,
const absl::flat_hash_set<std::string>& for_update) override;
};
class GrpcMuxSotw : public GrpcMuxImpl<SotwSubscriptionState, SotwSubscriptionStateFactory,
envoy::service::discovery::v3::DiscoveryRequest,
envoy::service::discovery::v3::DiscoveryResponse> {
public:
GrpcMuxSotw(Grpc::RawAsyncClientPtr&& async_client, Event::Dispatcher& dispatcher,
const Protobuf::MethodDescriptor& service_method, Random::RandomGenerator& random,
Stats::Scope& scope, const RateLimitSettings& rate_limit_settings,
const LocalInfo::LocalInfo& local_info, bool skip_subsequent_node);
// GrpcStreamCallbacks
void requestOnDemandUpdate(const std::string&, const absl::flat_hash_set<std::string>&) override {
ENVOY_BUG(false, "unexpected request for on demand update");
}
};
class NullGrpcMuxImpl : public GrpcMux {
public:
void start() override {}
ScopedResume pause(const std::string&) override {
return std::make_unique<Cleanup>([]() {});
}
ScopedResume pause(const std::vector<std::string>) override {
return std::make_unique<Cleanup>([]() {});
}
Config::GrpcMuxWatchPtr addWatch(const std::string&, const absl::flat_hash_set<std::string>&,
SubscriptionCallbacks&, OpaqueResourceDecoder&,
const SubscriptionOptions&) override;
void requestOnDemandUpdate(const std::string&, const absl::flat_hash_set<std::string>&) override {
ENVOY_BUG(false, "unexpected request for on demand update");
}
};
} // namespace XdsMux
} // namespace Config
} // namespace Envoy
| 45.754789 | 100 | 0.725507 | [
"vector"
] |
8e452034829e726f8933661b24edbfb305c07097 | 555 | h | C | Google Tech Dev Guide/Foundations Path/Former Coding Interview Question: Minesweeper/Board.h | RitamDey/My-Simple-Programs | 147b455a6a40c371ec894ce979e8a61d242e03bd | [
"Unlicense"
] | 2 | 2016-10-14T16:58:05.000Z | 2017-05-04T04:59:18.000Z | Google Tech Dev Guide/Foundations Path/Former Coding Interview Question: Minesweeper/Board.h | GreenJoey/My-Simple-Programs | 147b455a6a40c371ec894ce979e8a61d242e03bd | [
"Unlicense"
] | null | null | null | Google Tech Dev Guide/Foundations Path/Former Coding Interview Question: Minesweeper/Board.h | GreenJoey/My-Simple-Programs | 147b455a6a40c371ec894ce979e8a61d242e03bd | [
"Unlicense"
] | null | null | null | #ifndef MATRIX_CLASS_H
#define MATRIX_CLASS_H
#include <vector>
#include <iostream>
#include "Cell.h"
using namespace std;
class Board {
using matrix = vector<vector<Cell>>;
private:
int n_rows;
int n_cols;
matrix board;
void populate_mines();
void populate_neighbour(int r, int c);
vector<pair<int, int>> neighbours(pair<int, int> cell);
public:
Board(int rows, int cols);
int at(int row, int col);
int rows();
int columns();
friend ostream& operator<<(ostream& stream, Board& obj);
};
#endif
| 19.137931 | 60 | 0.655856 | [
"vector"
] |
8e58c37a025e4f0aa170cb092c08f04edc79b414 | 1,025 | h | C | src/ReadParse.h | shah-rohan/MultiMap | 5db9103bb2275b58edb68d822f5cfd5b7aeb2d59 | [
"MIT-0"
] | 3 | 2021-04-22T07:13:06.000Z | 2021-05-01T05:37:43.000Z | src/ReadParse.h | shah-rohan/MultiMap | 5db9103bb2275b58edb68d822f5cfd5b7aeb2d59 | [
"MIT-0"
] | 3 | 2021-04-22T07:21:54.000Z | 2021-12-09T16:10:55.000Z | src/ReadParse.h | shah-rohan/SmartMap | 5db9103bb2275b58edb68d822f5cfd5b7aeb2d59 | [
"MIT-0"
] | null | null | null | /*
* ReadParse.h
*
* Created on: Jun 24, 2020
* Author: rohan
*/
#ifndef READPARSE_H_
#define READPARSE_H_
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <iomanip>
#include <chrono>
#include "gzstream.h"
#include "SMCommon.h"
using namespace std;
using namespace std::chrono;
void parseReadsFile(igzstream& reads_file, string& read_ids, int& id_counter, int& raw_counter, int crossval, int cval, int maxaligns, float score_min, bool onsa);
void parseReadsFile(ifstream& reads_file, string& read_ids, int& id_counter, int& raw_counter, int crossval, int cval, int maxaligns, float score_min, bool onsa);
void parseReadsFileStranded(igzstream& reads_file, string& read_ids, int& id_counter, int& raw_counter, int crossval, int cval, int maxaligns, float score_min, bool onsa);
void parseReadsFileStranded(ifstream& reads_file, string& read_ids, int& id_counter, int& raw_counter, int crossval, int cval, int maxaligns, float score_min, bool onsa);
#endif /* READPARSE_H_ */
| 32.03125 | 171 | 0.758049 | [
"vector"
] |
8e5cba2b0fa72bf3f166827e4a28e6753c87887e | 9,314 | h | C | extensions/DRM/dream/util/Buffer.h | mfkiwl/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | 9 | 2020-09-22T17:26:17.000Z | 2022-03-10T17:58:03.000Z | extensions/DRM/dream/util/Buffer.h | hikijun/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | null | null | null | extensions/DRM/dream/util/Buffer.h | hikijun/FlyDog_SDR_GPS | d4870af35e960282a3c1b7e6b41444be4cb53fab | [
"MIT"
] | 4 | 2021-02-10T16:13:19.000Z | 2021-09-21T08:04:25.000Z | /******************************************************************************\
* Technische Universitaet Darmstadt, Institut fuer Nachrichtentechnik
* Copyright (c) 2001
*
* Author(s):
* Volker Fischer
*
* Description:
* Transfer buffer between different modules
*
*
******************************************************************************
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
\******************************************************************************/
#if !defined(PUFFER_H__3B0BA660_CA63_4344_BB2B_23E7A0D31912__INCLUDED_)
#define PUFFER_H__3B0BA660_CA63_4344_BB2B_23E7A0D31912__INCLUDED_
#include "../GlobalDefinitions.h"
#include "Vector.h"
/* Classes ********************************************************************/
/* Buffer base class */
template<class TData> class CBuffer
{
public:
CBuffer() : iBufferSize(0), bRequestFlag(false) {}
virtual ~CBuffer() {}
void SetRequestFlag(const bool bNewRequestFlag)
{bRequestFlag = bNewRequestFlag;}
bool GetRequestFlag() const {return bRequestFlag;}
/* Virtual function to be declared by the derived object */
virtual void Init(const int iNewBufferSize);
virtual CVectorEx<TData>* Get(const int iRequestedSize) = 0;
virtual CVectorEx<TData>* QueryWriteBuffer() = 0;
virtual void Put(const int iOfferedSize) = 0;
virtual void Clear() = 0;
virtual int GetFillLevel() const = 0;
protected:
CVectorEx<TData> vecBuffer;
int iBufferSize;
bool bRequestFlag;
};
/* Single block buffer */
template<class TData> class CSingleBuffer : public CBuffer<TData>
{
public:
CSingleBuffer() : iFillLevel(0) {}
CSingleBuffer(const int iNBufSize) {Init(iNBufSize);}
virtual ~CSingleBuffer() {}
virtual void Init(const int iNewBufferSize);
virtual CVectorEx<TData>* Get(const int iRequestedSize);
virtual CVectorEx<TData>* QueryWriteBuffer() {return &(this->vecBuffer);}
virtual void Put(const int iOfferedSize);
virtual void Clear() {iFillLevel = 0;}
virtual int GetFillLevel() const {return iFillLevel;}
protected:
int iFillLevel;
};
/* Cyclic buffer */
template<class TData> class CCyclicBuffer : public CBuffer<TData>
{
public:
enum EBufferState {BS_FULL, BS_EMPTY}; // BS: Buffer Status
CCyclicBuffer() {Clear();}
CCyclicBuffer(const int iNBufSize) {Init(iNBufSize);}
virtual ~CCyclicBuffer() {}
virtual void Init(const int iNewBufferSize);
virtual CVectorEx<TData>* Get(const int iRequestedSize);
virtual CVectorEx<TData>* QueryWriteBuffer() {return &vecInOutBuffer;}
virtual void Put(const int iOfferedSize);
virtual void Clear();
virtual int GetFillLevel() const;
protected:
CVectorEx<TData> vecInOutBuffer;
int iPut;
int iGet;
EBufferState iBufferState;
};
/* Implementation *************************************************************/
template<class TData> void CBuffer<TData>::Init(const int iNewBufferSize)
{
/* Assign buffer size */
iBufferSize = iNewBufferSize;
/* Allocate memory for data field */
vecBuffer.Init(iBufferSize);
}
/******************************************************************************\
* Single block buffer *
\******************************************************************************/
template<class TData> void CSingleBuffer<TData>::Init(const int iNewBufferSize)
{
/* Only initialize buffer when size has changed, otherwise preserve data */
if (iNewBufferSize != this->iBufferSize)
{
CBuffer<TData>::Init(iNewBufferSize);
/* Reset buffer parameters (empty buffer) */
iFillLevel = 0;
}
}
template<class TData> CVectorEx<TData>* CSingleBuffer<TData>::Get(const int iRequestedSize)
{
/* Get data */
#ifdef _DEBUG_DREAM
if (iRequestedSize > iFillLevel)
{
DebugError("SingleBuffer Get()", "FillLevel",
iFillLevel, "Requested size", iRequestedSize);
}
#endif
/* Block is read, buffer is now empty again */
iFillLevel -= iRequestedSize;
return &(this->vecBuffer);
}
template<class TData> void CSingleBuffer<TData>::Put(const int iOfferedSize)
{
/* New Block was added, set new fill level */
iFillLevel += iOfferedSize;
#ifdef _DEBUG_DREAM
if (iFillLevel > this->iBufferSize)
{
DebugError("SingleBuffer Put()", "FillLevel",
iFillLevel, "Buffer size", this->iBufferSize);
}
#endif
}
/******************************************************************************\
* Cyclic buffer *
\******************************************************************************/
template<class TData> void CCyclicBuffer<TData>::Init(const int iNewBufferSize)
{
/* Only initialize buffer when size has changed, otherwise preserve data */
if (iNewBufferSize != this->iBufferSize)
{
CBuffer<TData>::Init(iNewBufferSize);
/* Make in- and output buffer the same size as the main buffer to
make sure that the worst-case is no problem */
vecInOutBuffer.Init(iNewBufferSize);
/* Reset buffer parameters (empty buffer) */
iPut = 0;
iGet = 0;
iBufferState = BS_EMPTY;
}
}
template<class TData> void CCyclicBuffer<TData>::Clear()
{
/* Clear buffer by resetting the pointer */
iPut = 0;
iGet = 0;
iBufferState = BS_EMPTY;
this->bRequestFlag = false;
}
template<class TData> CVectorEx<TData>* CCyclicBuffer<TData>::Get(const int iRequestedSize)
{
int i;
int iAvailSpace;
int iElementCount;
/* Test if enough data is available for reading */
iAvailSpace = iPut - iGet;
/* Test if wrap is needed */
if ((iAvailSpace < 0) || ((iAvailSpace == 0) && (iBufferState == BS_FULL)))
iAvailSpace += this->iBufferSize;
#ifdef _DEBUG_DREAM
if (iAvailSpace < iRequestedSize)
{
DebugError("CyclicBuffer Get()", "Available space",
iAvailSpace, "Requested size", iAvailSpace);
}
#endif
/* Get data ------------------------------------------------------------- */
iElementCount = 0;
/* Test if data can be read in one block */
if (this->iBufferSize - iGet < iRequestedSize)
{
/* Data must be read in two portions */
for (i = iGet; i < this->iBufferSize; i++)
{
vecInOutBuffer[iElementCount] = this->vecBuffer[i];
iElementCount++;
}
for (i = 0; i < iRequestedSize - this->iBufferSize + iGet; i++)
{
vecInOutBuffer[iElementCount] = this->vecBuffer[i];
iElementCount++;
}
}
else
{
/* Data can be read in one block */
for (i = iGet; i < iGet + iRequestedSize; i++)
{
vecInOutBuffer[iElementCount] = this->vecBuffer[i];
iElementCount++;
}
}
/* Adjust iGet pointer */
iGet += iRequestedSize;
if (iGet >= this->iBufferSize)
iGet -= this->iBufferSize;
/* Test if buffer is empty. If yes, set empty-flag */
if ((iGet == iPut) && (iRequestedSize > 0))
iBufferState = BS_EMPTY;
return &vecInOutBuffer;
}
template<class TData> void CCyclicBuffer<TData>::Put(const int iOfferedSize)
{
int iAvailSpace;
int i;
int iElementCount;
/* Test if enough data is available for writing */
iAvailSpace = iGet - iPut;
/* Test if wrap is needed */
if ((iAvailSpace < 0) || ((iAvailSpace == 0) && (iBufferState == BS_EMPTY)))
iAvailSpace += this->iBufferSize;
#ifdef _DEBUG_DREAM
if (iAvailSpace < iOfferedSize)
{
DebugError("CyclicBuffer Put()", "Available space",
iAvailSpace, "Offered size", iOfferedSize);
}
#endif
/* Put data ------------------------------------------------------------- */
iElementCount = 0;
/* Test if data can be written in one block */
if (this->iBufferSize - iPut < iOfferedSize)
{
/* Data must be written in two steps */
for (i = iPut; i < this->iBufferSize; i++)
{
this->vecBuffer[i] = vecInOutBuffer[iElementCount];
iElementCount++;
}
for (i = 0; i < iOfferedSize - this->iBufferSize + iPut; i++)
{
this->vecBuffer[i] = vecInOutBuffer[iElementCount];
iElementCount++;
}
}
else
{
/* Data can be written in one block */
for (i = iPut; i < iPut + iOfferedSize; i++)
{
this->vecBuffer[i] = vecInOutBuffer[iElementCount];
iElementCount++;
}
}
/* Adjust iPut pointer */
iPut += iOfferedSize;
if (iPut >= this->iBufferSize)
iPut -= this->iBufferSize;
/* Test if buffer is full. If yes, set full-flag */
if ((iGet == iPut) && (iOfferedSize > 0))
iBufferState = BS_FULL;
}
template<class TData> int CCyclicBuffer<TData>::GetFillLevel() const
{
int iFillLevel;
/* Calculate the available data in the buffer. Test if wrap is needed!
Take into account the flag-information (full or empty buffer) */
iFillLevel = iPut - iGet;
if ((iFillLevel == 0) && (iBufferState == BS_FULL))
iFillLevel = this->iBufferSize;
if (iFillLevel < 0)
iFillLevel += this->iBufferSize; /* Wrap around */
return iFillLevel;
}
#endif // !defined(PUFFER_H__3B0BA660_CA63_4344_BB2B_23E7A0D31912__INCLUDED_)
| 27.886228 | 91 | 0.639253 | [
"object",
"vector"
] |
8e61c393f3623a55a20364c4f309b9987e1a9918 | 835 | h | C | game.h | manhtoanbkhn/snakegame | a8b688bba3f9a66f2b3d05db6ab019dd68e0137c | [
"MIT"
] | null | null | null | game.h | manhtoanbkhn/snakegame | a8b688bba3f9a66f2b3d05db6ab019dd68e0137c | [
"MIT"
] | null | null | null | game.h | manhtoanbkhn/snakegame | a8b688bba3f9a66f2b3d05db6ab019dd68e0137c | [
"MIT"
] | null | null | null | #pragma once
#include "common.h"
#include "box.h"
#include "snake.h"
#include "score.h"
class Game
{
public:
struct player
{
string name;
}player;
enum Speed
{
SLOW = 5,
NORMAL = 8,
FAST = 13
};
public:
Game();
~Game();
void initialize();
void start();
void end();
void wait();
void menu();
void showHighScore();
void showMainMenu();
void clearMainMenu();
void showLevelMenu();
void clearLevelMenu();
void showHowToPlay();
void clearHowToPlay();
private:
Cursor* cursor;
SnakeBox* snakebox;
MenuBox* menubox;
Snake* snake;
Score* score;
unique_ptr<thread> move_thread;
unique_ptr<thread> input_control_thread;
bool gameover;
int level;
vector<string> mainMenu = { "Play Game", "Level", "High Score" , "How To Play" , "Quit" };
vector<string> levelMenu = { "SLOW", "NORMAL", "FAST" };
};
| 14.910714 | 91 | 0.662275 | [
"vector"
] |
8e61ca3311f045b28f47904908429f31fa73080c | 2,485 | h | C | PWGUD/UPC/AliAnalysisTaskUpcFilter.h | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | 1 | 2020-07-18T17:36:58.000Z | 2020-07-18T17:36:58.000Z | PWGUD/UPC/AliAnalysisTaskUpcFilter.h | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | 1 | 2017-03-14T15:11:43.000Z | 2017-03-14T15:53:09.000Z | PWGUD/UPC/AliAnalysisTaskUpcFilter.h | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | 1 | 2018-09-22T01:09:25.000Z | 2018-09-22T01:09:25.000Z | #ifndef ALIANALYSISTASKUPCFILTER_H
#define ALIANALYSISTASKUPCFILTER_H
// task for upc semiforward filter
// creates upc event from esd or aod
//
// jaroslav.adam@cern.ch
#include "AliAnalysisTaskSE.h"
class AliUPCEvent;
class AliAODMCHeader;
class AliMuonTrackCuts;
class AliESDtrackCuts;
class AliPIDResponse;
class AliTriggerAnalysis;
class AliAnalysisTaskUpcFilter : public AliAnalysisTaskSE {
public:
AliAnalysisTaskUpcFilter(const char *name="AliAnalysisTaskUpcFilter");
virtual ~AliAnalysisTaskUpcFilter();
void SetIsESD(Bool_t isESD) {fIsESD = isESD;}
void SetIsMC(Bool_t isMC) {fIsMC = isMC;}
void SetFillSPD(Bool_t fill=kTRUE) {fFillSPD = fill;}
void SetAllTrg(Bool_t set);
void SetTrgClass(Int_t idx, Bool_t set);
void SetMuonTrackCutsPassName(const char *passname) {fMuonCutsPassName->Clear(); fMuonCutsPassName->SetString(passname);}
virtual void UserCreateOutputObjects();
virtual void NotifyRun();
virtual void UserExec(Option_t *option);
Bool_t RunAOD();
void RunAODMC(TClonesArray *arrayMC, AliAODMCHeader *headerMC);
Bool_t RunESD();
void RunESDMC();
virtual void Terminate(Option_t *);
private:
AliAnalysisTaskUpcFilter(const AliAnalysisTaskUpcFilter &o); // not implemented
AliAnalysisTaskUpcFilter &operator=(const AliAnalysisTaskUpcFilter &o); // not implemented
Bool_t fIsESD; // analysis type, ESD / AOD
Bool_t fIsMC; // mc or data selection
Bool_t fFillSPD; // fill SPD fired FO chips
static const Int_t fgkNtrg = 51; // number of trigger classes
Bool_t fTrgMask[fgkNtrg]; // allows to mask or un-mask the selected trigger classes
AliMuonTrackCuts *fMuonCuts; // class for muon track cuts, used for pDCA
AliTriggerAnalysis *fTriggerAna; // class for trigger analysis, used for fired SPD FO
AliESDtrackCuts **fCutsList; // array of pointers to filtering task for ESD tracks
AliPIDResponse *fPIDResponse; // PID response object
TObjString *fMuonCutsPassName; //-> name of pass used by AliMuonTrackCuts
TList *fHistList; // list of output histograms
TH1I *fCounter; // analysis counter
TH2I *fTriggerCounter; // counter of triggers per run
TH1I *fMuonCounter;
AliUPCEvent *fUPCEvent; // output UPC event
TTree *fUPCTree; // output tree
enum EvtCount{ kAna=1, kTrg, kSpecific, kPass1, kPass2, kPassX, kWritten, kAOD, kMunTrack, kCenTrack, kESD, kPidErr };
enum MuonCount{kMunAll=1, kMunRabs, kMunEta, kMunPDCA};
ClassDef(AliAnalysisTaskUpcFilter, 1);
};
#endif
| 31.455696 | 123 | 0.760966 | [
"object"
] |
8e69b55ae9284eee14da1ce1fc66b6ec05007e06 | 10,853 | h | C | src/gpu_runtime/patch_hostside.h | hughperkins/toy_proc | 501caddd100e5245658008bb42f17ef8e97d4192 | [
"MIT"
] | 4 | 2022-03-22T06:58:06.000Z | 2022-03-25T12:35:06.000Z | src/gpu_runtime/patch_hostside.h | hughperkins/toy_proc | 501caddd100e5245658008bb42f17ef8e97d4192 | [
"MIT"
] | null | null | null | src/gpu_runtime/patch_hostside.h | hughperkins/toy_proc | 501caddd100e5245658008bb42f17ef8e97d4192 | [
"MIT"
] | 1 | 2022-03-25T01:06:32.000Z | 2022-03-25T01:06:32.000Z | /*
based on patch_hostside.h from https://github.com/hughperkins/coriander
I'm probalby going to comment a bunch of stufff out first, and then gradually figure out what we want to keep,
and what we wnat to throw
What this does / how this works
===============================
The input to this module is hostside llvm ir code, probably from a *-hostraw.ll file. This file contains
calls to NVIDIA® CUDA™ kernel launch commands, such as cudaSetupArgument. What we are going to do is
to re-route these into our own runtime, performing any appropriate transformations first.
- int32, int8, float, any primitives basically:
- a call to one of the methods such as setKernelArgInt64 or setKernelArgFloat will be added to the bytecode
- the actual value of the primitive will be directly passed, as a parameter in this method
- we do need a slight hack to get this value, since the original cudaSetupArgument method will pass a pointer, whereas
we are going to pass the underlying value
- we get the underlying value by hunting for the upstream alloca
Note: I've moved this to a class, to force me to declare all the methods here :-) It's a stateless class though, everything
is static :-)
Ok, so the doc is mostly below, inside the class declaration, at the bottom of this file. So go there now :-)
*/
#pragma once
// #include "cocl/struct_clone.h"
#include <string>
#include <vector>
#include <memory>
// #include "cocl/llvm_dump.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Analysis/LoopAccessAnalysis.h"
namespace veriGPU
{
class ParamInfo
{
public:
llvm::Type *typeDevicesideFn = 0; // how this param is defined in device bytecode function declaration
bool devicesideByVal = false; // in deviceside arg, is it byvalue?
llvm::Value *value = 0; // from the first arg to the bitcast feeding into cudaSetupArgument
llvm::Value *pointer = 0; // from cudaSetupArgument
llvm::Argument *devicesideArg = 0;
int size = 0; // from CudaLaunch function call declaration
int paramIndex = 0; // in the original function, nto in our hacked around kernel function
};
class LaunchCallInfo
{
public:
LaunchCallInfo()
{
grid_xy_value = 0;
grid_z_value = 0;
block_xy_value = 0;
block_z_value = 0;
}
LaunchCallInfo(const LaunchCallInfo &) = delete;
LaunchCallInfo &operator=(const LaunchCallInfo &) = delete;
std::string stubKernelName = "";
std::string kernelName = "";
// this only contains non-readnone args. readnone (devicesdie) are ignored, not stored in this (since hostside wont call them,
// eg see the random_op_gpu.cc kernel, from tensorflow, which has NormalDistribution as readnone, on its 4th arg,
// but the hostside only passes 3 args, skips the NOrmalDistribution arg)
std::vector<std::unique_ptr<ParamInfo>> params;
llvm::Value *stream;
llvm::Value *grid_xy_value;
llvm::Value *grid_z_value;
llvm::Value *block_xy_value;
llvm::Value *block_z_value;
};
class GenericCallInst
{
// its children can hold a CallInst or an InvokeInst
// These instructions do almost the same thing, but their methods are not on a common
// base/interface class. So, we wrap them here, provide such a common base/interface class
public:
// GenericCallInst() {}
virtual ~GenericCallInst() {}
// The following methods create specialized GenericCallInst methods, encapsulating an InvokeInst
// or a CallInst
static std::unique_ptr<GenericCallInst> create(llvm::InvokeInst *inst);
static std::unique_ptr<GenericCallInst> create(llvm::CallInst *inst);
virtual llvm::Value *getArgOperand(int idx) = 0;
virtual llvm::Value *getOperand(int idx) = 0;
virtual llvm::Module *getModule() = 0;
virtual llvm::Instruction *getInst() = 0;
// virtual void dump() = 0;
};
std::ostream &operator<<(std::ostream &os, const LaunchCallInfo &info);
std::ostream &operator<<(std::ostream &os, const llvm::RuntimePointerChecking::PointerInfo &pointerInfo);
class GenericCallInst_Call : public GenericCallInst
{
public:
GenericCallInst_Call(llvm::CallInst *inst) : inst(inst) {}
llvm::CallInst *inst;
virtual llvm::Value *getArgOperand(int idx) override { return inst->getArgOperand(idx); }
virtual llvm::Value *getOperand(int idx) override { return inst->getArgOperand(idx); }
virtual llvm::Module *getModule() override { return inst->getModule(); }
virtual llvm::Instruction *getInst() override { return inst; }
// virtual void dump() override { COCL_LLVM_DUMP(inst); }
};
class GenericCallInst_Invoke : public GenericCallInst
{
public:
GenericCallInst_Invoke(llvm::InvokeInst *inst) : inst(inst) {}
llvm::InvokeInst *inst;
virtual llvm::Value *getArgOperand(int idx) override { return inst->getArgOperand(idx); }
virtual llvm::Value *getOperand(int idx) override { return inst->getArgOperand(idx); }
virtual llvm::Module *getModule() override { return inst->getModule(); }
virtual llvm::Instruction *getInst() override { return inst; }
// virtual void dump() override { COCL_LLVM_DUMP(inst); }
};
class PatchHostside
{
public:
// returns path without the directory name (I think). this should go into some utiity class really...
static std::string getBasename(std::string path);
// handle primitive ints and floats (not arrays):
static llvm::Instruction *addSetKernelArgInst_int(llvm::Instruction *lastInst, llvm::Value *value, llvm::IntegerType *intType);
static llvm::Instruction *addSetKernelArgInst_float(llvm::Instruction *lastInst, llvm::Value *value);
// handle generic pointers. This will arrive in hostside_opencl_funcs at runtime, as a pointer to char,
// containing a virtual memory pointer (possibly with an offset added)
// the corresponding hostside_opencl_funcs method will:
// - look up the virtual mem, to get cl_mem object, and offset
// - check if it's already received a cl_mem, and if not add it to the list of cl_mems to send to the kernel
// - record the index number of this cl_mem, into the list of distinct/unique cl_mems
//
// The corresponding kernel parameters for this will be:
// - there will be a cl_mem pointer added, if this cl_mem hasnt already been received at least once
// - an offset integer parameter will be added
//
// the corresponding hostside_opencl_funcs method is:
// setKernelArgGpuBuffer(char *memory_as_charstar, int32_t elementSize)
//
// The hostside_opencl_funcs method needs no information other than the (virtual) pointer really
// currently we are providing the elementsize too, to mitigate against a crash on beignet, but I might
// remove that, whilst I get Mac radeon working :-P (since structs might not have useful element sizes)
static llvm::Instruction *addSetKernelArgInst_pointer(llvm::Instruction *lastInst, llvm::Value *value);
// this will add bytecode to pass a pointer to the cpu-side struct object to hostside_opencl_funcs, at runtime
// the entry point into hostside_opencl_funcs will be:
// setKernelArgHostsideBuffer(char *pCpuStruct, int structAllocateSize)
//
// The hostside_opencl_funcs method setKernelArgHostsideBuffer expects to receive a host-side allocated struct/buffer
// setKernelArgHostsideBuffer will:
// - allocate a gpu buffer
// - queue an opencl command, to copy the host-side struct into the gpu buffer
// - add the clmem, and a zero-offset, to the list of kernel parameters
//
// Note that the setKernelArgHostsideBuffer method needs no information on the structure of the struct
//
// this patch_hostside addSetKernelArgInst_byvaluestruct function is going to handle walking the struct, and sending
// the other pointers through using additional method calls, likely to setKernelArgGpuBuffer
// static llvm::Instruction *addSetKernelArgInst_byvaluestruct(
// llvm::Instruction *lastInst, veriGPU::ParamInfo *paramInfo, llvm::Value *valueAsPointerInstr);
// this needs to do the same as addSetKernelArgInst_byvaluestruct , but it passes the struct pointer into the
// setKernelArgGpuBuffer function, rather than the setKernelArgHostsideBuffer
// but it still needs to walk the struct, at patching time, compile time, and add calls to pass any pointers
// in the struct through too
// hmmmm. actually. I think we'll forbid pointers in gpuside structs for now. unless we have to
// why? because, how are we going to get those pointers, if they're stored on the gpu :-P
// like, how are we going to clone it, first issue. Possible to to do, but a bunch of work, unless we have to
// static llvm::Instruction *addSetKernelArgInst_pointerstruct(llvm::Instruction *lastInst, llvm::Value *structPointer);
static llvm::Instruction *addSetKernelArgInst_byvaluevector(llvm::Instruction *lastInst, llvm::Value *structPointer);
// all setKernelArgs pass through addSetKernelArgInst, which dispatches to other functions
static llvm::Instruction *addSetKernelArgInst(
llvm::Instruction *lastInst, ParamInfo *paramInfo);
static void getLaunchTypes(llvm::Module *M, const llvm::Module *MDevice, GenericCallInst *inst, LaunchCallInfo *info);
// given a bytecode that calls the cudaSetupArgument method, obtains information
// about this, such as the type of the argument being set, and an instruction that represents
// its value, stores that, in info, along with the arguments there already
static void getLaunchArgValue(GenericCallInst *inst, LaunchCallInfo *info, ParamInfo *paramInfo);
static void patchCudaLaunch(
llvm::Module *M, const llvm::Module *MDevice,
llvm::Function *F, GenericCallInst *inst, std::vector<llvm::Instruction *> &to_replace_with_zero);
static void patchFunction(llvm::Module *M, const llvm::Module *MDevice, llvm::Function *F); // patch all kernel launch commands in function F
static void patchModule(llvm::Module *M, const llvm::Module *MDevice); // main entry point. Scan through module M, and rewrite kernel launch commands
};
} // namespace veriGPU
| 50.953052 | 178 | 0.690961 | [
"object",
"vector"
] |
8e6a1463bdd40e51b8176eba0de63ef551cf5c2d | 1,347 | h | C | include/apt-pkg/debmetaindex.h | iMokhles/MyTheosHeaders | 2c263362a8a6f947b1a868e03983ed188ead6539 | [
"MIT"
] | 7 | 2016-07-22T14:29:58.000Z | 2021-03-19T05:31:48.000Z | include/apt-pkg/debmetaindex.h | iMokhles/MyTheosHeaders | 2c263362a8a6f947b1a868e03983ed188ead6539 | [
"MIT"
] | null | null | null | include/apt-pkg/debmetaindex.h | iMokhles/MyTheosHeaders | 2c263362a8a6f947b1a868e03983ed188ead6539 | [
"MIT"
] | 3 | 2017-02-06T23:58:01.000Z | 2017-10-31T03:47:52.000Z | // ijones, walters
#ifndef PKGLIB_DEBMETAINDEX_H
#define PKGLIB_DEBMETAINDEX_H
#include <apt-pkg/metaindex.h>
#include <apt-pkg/sourcelist.h>
class debReleaseIndex : public metaIndex {
public:
class debSectionEntry
{
public:
debSectionEntry (string Section, bool IsSrc);
bool IsSrc;
string Section;
};
private:
vector <const debSectionEntry *> SectionEntries;
public:
debReleaseIndex(string URI, string Dist);
~debReleaseIndex();
virtual string ArchiveURI(string File) const {return URI + File;};
virtual bool GetIndexes(pkgAcquire *Owner, bool GetAll=false) const;
vector <struct IndexTarget *>* ComputeIndexTargets() const;
string Info(const char *Type, const string Section) const;
string MetaIndexInfo(const char *Type) const;
string MetaIndexFile(const char *Types) const;
string MetaIndexURI(const char *Type) const;
string IndexURI(const char *Type, const string Section) const;
string IndexURISuffix(const char *Type, const string Section) const;
string SourceIndexURI(const char *Type, const string Section) const;
string SourceIndexURISuffix(const char *Type, const string Section) const;
virtual vector <pkgIndexFile *> *GetIndexFiles();
virtual bool IsTrusted() const;
void PushSectionEntry(const debSectionEntry *Entry);
};
#endif
| 29.282609 | 77 | 0.734967 | [
"vector"
] |
8e721d85cc95aa7382bd08319829c96831d303a3 | 1,580 | c | C | lib/wizards/siki/troll/f19.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/siki/troll/f19.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/siki/troll/f19.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "room/room";
object monster;
reset(arg) {
if(!monster) {
monster = clone_object("/wizards/siki/troll/monsters/wolf");
move_object(monster, this_object());
}
if(arg) return;
add_exit("west","wizards/siki/troll/f18");
short_desc = "Great forest";
long_desc = "A deep and sinister forest. There are different types of trees\n"+
"in very dense, old and new, living and dead ones. Visibility is\n"+
"extremely low cause of the trees. The ground is covered with a\n"+
"layer of bushes. A small path leads deeper into the forest.\n";
items = allocate(6);
items[0] = "trees";
items[1] = "Old and new, dead and living trees";
items[2] = "bushes";
items[3] = "Thick layers of bushes covering the whole ground making it hard to move";
items[4] = "path";
items[5] = "A very small path leading deeper into the forest. It is extremely hard to\n"+
"to notice it and it looks like it has been tried to cover with leaves";
}
init() {
add_action("enter", "enter");
add_action("enter", "walk");
::init();
}
enter(str) {
if(str == "path" || str == "forest") {
write("You walk the path deeper into the forest and find a small clearing.\n");
say(this_player()->query_name()+" walks the path deeper into the forest.\n");
move_object(this_player(), "/guilds/fighter/berserker");
say(this_player()->query_name()+" arrives from the forest.\n");
return 1;
} else {
write("What ?\n");
return 1;
}
}
| 31.6 | 92 | 0.611392 | [
"object"
] |
8e74f4eb4ff97d691bbbae2de72389b12eba715e | 6,224 | h | C | GEMS_modules/opal/fetch/igshare.h | ma3mool/Approxilyzer | e05a38d0222cd31a59c8fb49ac7078eacfce7494 | [
"Ruby"
] | 4 | 2017-02-25T13:17:35.000Z | 2021-04-27T06:30:24.000Z | GEMS_modules/opal/fetch/igshare.h | ma3mool/Approxilyzer | e05a38d0222cd31a59c8fb49ac7078eacfce7494 | [
"Ruby"
] | null | null | null | GEMS_modules/opal/fetch/igshare.h | ma3mool/Approxilyzer | e05a38d0222cd31a59c8fb49ac7078eacfce7494 | [
"Ruby"
] | 4 | 2017-03-19T02:13:45.000Z | 2019-12-20T05:37:49.000Z |
/*
Copyright (C) 1999-2005 by Mark D. Hill and David A. Wood for the
Wisconsin Multifacet Project. Contact: gems@cs.wisc.edu
http://www.cs.wisc.edu/gems/
--------------------------------------------------------------------
This file is part of the Opal Timing-First Microarchitectural
Simulator, a component of the Multifacet GEMS (General
Execution-driven Multiprocessor Simulator) software toolset
originally developed at the University of Wisconsin-Madison.
Opal was originally developed by Carl Mauer based upon code by
Craig Zilles.
Substantial further development of Multifacet GEMS at the
University of Wisconsin was performed by Alaa Alameldeen, Brad
Beckmann, Jayaram Bobba, Ross Dickson, Dan Gibson, Pacia Harper,
Milo Martin, Michael Marty, Carl Mauer, Michelle Moravan,
Kevin Moore, Manoj Plakal, Daniel Sorin, Min Xu, and Luke Yen.
--------------------------------------------------------------------
If your use of this software contributes to a published paper, we
request that you (1) cite our summary paper that appears on our
website (http://www.cs.wisc.edu/gems/) and (2) e-mail a citation
for your published paper to gems@cs.wisc.edu.
If you redistribute derivatives of this software, we request that
you notify us and either (1) ask people to register with us at our
website (http://www.cs.wisc.edu/gems/) or (2) collect registration
information and periodically send it to us.
--------------------------------------------------------------------
Multifacet GEMS is free software; you can redistribute it and/or
modify it under the terms of version 2 of the GNU General Public
License as published by the Free Software Foundation.
Multifacet GEMS 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 the Multifacet GEMS; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307, USA
The GNU General Public License is contained in the file LICENSE.
### END HEADER ###
*/
#ifndef _IGSHARE_H_
#define _IGSHARE_H_
/*------------------------------------------------------------------------*/
/* Includes */
/*------------------------------------------------------------------------*/
#include "bitfield.h"
#include "directbp.h"
/*------------------------------------------------------------------------*/
/* Macro declarations */
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/* Class declaration(s) */
/*------------------------------------------------------------------------*/
/** Per PC history and predictor table */
class predictor_entry_t {
public:
/**
* Constructor: creates object
* @param pht_entries The log-base-2 number of entries in the history
*/
predictor_entry_t( uint32 history_size );
/** Destructor: frees object. */
~predictor_entry_t( void );
/// local history for this PC
uint32 m_history;
/// Predictor table for this PC
bitfield_t m_bitfield;
};
/** Per PC predictor table */
typedef map<la_t, predictor_entry_t *> PerPCTable;
/**
* Implements an infinite (idealized?) gshare predictor.
*
* @author cmauer
* @version $Id: igshare.h 1.6 06/02/13 18:49:12-06:00 mikem@maya.cs.wisc.edu $
*/
class igshare_t : public direct_predictor_t {
public:
/**
* @name Constructor(s) / destructor
*/
//@{
/**
* Constructor: creates object
* @param history_length The log-base-2 number of entries in history table
* @param globalHistory True == use global history, false == per addr hist
*/
igshare_t( uint32 history_length, bool globalHistory );
/**
* Destructor: frees object.
*/
virtual ~igshare_t( void );
//@}
/**
* @name Methods
*/
//@{
/** Branch predict on the branch_PC
* @param branch_PC The virtual address of the PC.
* @param history The branch history register associated w/ this pred
* @return bool true or false branch prediction
*/
bool Predict(my_addr_t branch_PC, word_t history, bool staticPred);
/** Update the branch prediction table, based on the actual branch pattern.
* @param taken True if the last branch was taken.
*/
void Update(my_addr_t branch_PC, cond_state_t history,
bool staticPred, bool taken);
/** Prints out identifing information about this branch predictor */
void printInformation( FILE *fp );
//@}
/** @name Checkpointing */
//@{
/// set_ function for checkpointing
set_error_t set_data( attr_value_t *value );
/// get_ function for checkpointing
attr_value_t get_data( void );
/** register state saving function for the branch predictor */
int registerCheckpoint( confio_t *conf );
//@}
private:
/// True if we should use the global history
bool m_use_global;
/// The length of each history (associated with each PC)
uint32 m_history_length;
/// The size of the history tables (2^history_length)
uint32 m_history_size;
/// A mask for removing all bits, except those used to index the history table
uint32 m_history_mask;
/// A hash table for per pc histories
PerPCTable m_perPCtable;
};
/*------------------------------------------------------------------------*/
/* Global variables */
/*------------------------------------------------------------------------*/
/*------------------------------------------------------------------------*/
/* Global functions */
/*------------------------------------------------------------------------*/
#endif /* _IGSHARE_H_ */
| 33.643243 | 80 | 0.557359 | [
"object"
] |
8e7aa658a6ed9976983025843a768969b0e02f46 | 14,565 | h | C | knl/mrg8.h | kenmiura/mrg8 | a3d660f0b20d6263d14f518e12b2035323f5b9d7 | [
"BSD-3-Clause-LBNL"
] | 8 | 2015-04-01T22:33:08.000Z | 2021-04-22T18:33:19.000Z | knl/mrg8.h | kenmiura/mrg8 | a3d660f0b20d6263d14f518e12b2035323f5b9d7 | [
"BSD-3-Clause-LBNL"
] | null | null | null | knl/mrg8.h | kenmiura/mrg8 | a3d660f0b20d6263d14f518e12b2035323f5b9d7 | [
"BSD-3-Clause-LBNL"
] | 2 | 2015-04-17T20:10:06.000Z | 2017-02-26T05:01:25.000Z | /*
* mrg8.h
*
* Created on: Apr 6, 2015
* Author: aghasemi
* Updated on: Jul 15, 2017
* Author: Yusuke
* Updated on: April 9, 2018
* Author: Yusuke
*/
#ifndef MRG8_H
#define MRG8_H
#include <vector>
#include <stdint.h> // for uint32_t and uint64_t
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <cmath>
#include <omp.h>
// S[n] = (A0* S[n-1] + A1 * S[n-2] + ...+ A7 * S[n-8]) mod (2^31-1)
// y[n] = S[n]
// Coefficients Ak are carefully chosen 31-bit integers
// S[k]'s are 31-bit integers
// Period of this random sequence is (2 ^ 31 - 1)^ 8 - 1 =~ 4.5 * 10^74
class mrg8 {
public:
const uint32_t MAX_RND;
mrg8();
mrg8(const uint32_t seed_val);
void seed_init(const uint32_t seed_val);
void get_state(uint32_t st[8]) const;
void set_state(const uint32_t st[8]);
void print_state() const;
void print_matrix(const uint32_t jm[8][8]) const;
/* Sequential Random Generator for int32 ver.1 */
void randint(uint32_t * iran, int n);
uint32_t randint();
/* Sequential Random Generator for double ver.1 */
void rand(double * fran, int n);
double rand();
double rand(uint32_t *new_state);
double operator() ()
{
return rand();
}
/* Sequential Random Generator for double ver.2 */
void mrg8dnz2(double * ran, int n);
/* Thread parallel Random Generator */
void jump_ahead(const short jump_val_bin[200], uint32_t *new_state);
void jump_ahead(const uint64_t jump_val, uint32_t *new_state);
void rand_tp(double *ran, int n);
void mrg8dnz2_tp(double *ran, int n);
protected:
const uint64_t MASK; //2^31 - 1
const uint32_t COEFF0, COEFF1, COEFF2, COEFF3, COEFF4, COEFF5, COEFF6, COEFF7;
bool isJumpMatrix;
uint32_t iseed;
std::vector<uint32_t> JUMP_MATRIX;
uint32_t state[8];// state[0] = S[n-1], state[1] = S[n-2], ..., state[7] = S[n-8]
void mcg64ni();
void jump_calc(const short jump_val_bin[200], uint32_t jump_mat[8][8]);
void read_jump_matrix();
uint32_t bigDotProd(const uint32_t x[8], const uint32_t y[8]) const;
void dec2bin(const uint64_t jval, short jump_val_bin[200]) const;
private:
void randint(uint32_t * iran, int n, uint32_t *new_state);
void rand(double * fran, int n, uint32_t *new_state);
void mrg8dnz2(double * ran, int n, uint32_t *new_state);
};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
mrg8::mrg8(): MAX_RND(2147483646), MASK(2147483647), COEFF0(1089656042), COEFF1(1906537547), COEFF2(1764115693), COEFF3(1304127872), COEFF4(189748160), COEFF5(1984088114), COEFF6(626062218), COEFF7(1927846343), iseed(0), JUMP_MATRIX(8 * 8 * 247), isJumpMatrix(false)
{
mcg64ni();
read_jump_matrix();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
mrg8::mrg8(const uint32_t seed_val): MAX_RND(2147483646), MASK(2147483647), COEFF0(1089656042), COEFF1(1906537547), COEFF2(1764115693), COEFF3(1304127872), COEFF4(189748160), COEFF5(1984088114), COEFF6(626062218), COEFF7(1927846343), iseed(seed_val), JUMP_MATRIX(8 * 8 * 247), isJumpMatrix(false)
{
mcg64ni();
read_jump_matrix();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// initializing the state with a 32-bit seed
void mrg8::seed_init(const uint32_t seed_val)
{
iseed = seed_val;
mcg64ni();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void mrg8::get_state(uint32_t st[8]) const
{
for (int k = 0; k < 8; ++k)
st[k] = state[k];
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void mrg8::print_state() const
{
std::cout << "(S[n-1], S[n-2], ..., S[n-8])= (";
for (int i = 0; i < 7; ++i) {
std::cout<<std::setw(10)<<state[i]<<", ";
}
std::cout << state[7]<<")"<<std::endl;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void mrg8::print_matrix(const uint32_t jm[8][8]) const
{
for (int i = 0; i < 8;++i) {
for(int j = 0; j < 8; ++j) {
std::cout<<std::setw(10)<<jm[i][j]<<" ";
}
std::cout << std::endl;
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void mrg8::set_state(const uint32_t st[8])
{
for (int i = 0; i < 8; ++i)
state[i] = st[i];
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//calculate (x[0]*y[0] + x[1]*y[1]+...+x[7]*y[7]) mod (2^31-1)
// where x[i] < 2^31 and y[i] < 2^31, i = 0, ..., 7
// Let:
// s1 = x[0] * y[0] + ... + x[3] * y[3]
// s2 = x[4] * y[4] + ... + x[7] * y[7]
// mask = 2^31 -1
// Note that s1 < 2^64 and s2 < 2^64
// (s1 + s2) mod (2^31 -1) = (s1 mod (2^31-1) + s2 mod (2^31-1)) mod (2^31-1)
// s1 = (s1 & mask) + 2^31 * (s1 >> 31) --> s1 mod (2^31-1) = (s1 & mask) + (s1 >> 31)
// s2 = (s2 & mask) + 2^31 * (s2 >> 31) --> s2 mod (2^31-1) = (s2 & mask) + (s2 >> 31)
inline uint32_t mrg8::bigDotProd(const uint32_t x[8], const uint32_t y[8]) const
{
uint64_t s, s1, s2;
s1 = 0;s2 = 0;s = 0;
for (int q = 0; q < 4; ++q) {
s1 += uint64_t(x[q]) * y[q];
s2 += uint64_t(x[4 + q]) * y[4 + q];
}
s = (s1 & MASK) + (s1 >> 31) + (s2 & MASK) + ( s2 >> 31);
s = (s & MASK) + (s >> 31);
return ((s & MASK) + (s >> 31));
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// reading pre-calculated jump matrix from file
// A^(2^j) mod (2^31 - 1) for j = 0, 1, ..., 246 where A is the 8x8 one-step jump matrix
// Each matrix is in column order, that is (A^(2^j))(r,c) = JUMP_MATRIX[j * 64 + r + 8*c]
void mrg8::read_jump_matrix()
{
if (isJumpMatrix) return;
std::ifstream infile;
infile.open("jump_matrix.txt");
if(infile.fail()){
std::cerr << "jump_matrix.txt could not be opened! Terminating!"<<std::endl;
exit(EXIT_FAILURE);
}
uint32_t t;
for (int k = 0; k < 8 * 8 * 247; ++k) {
infile >> t;
JUMP_MATRIX[k] = t;
}
infile.close();
isJumpMatrix = true;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Jumping the state ahead by a 200-bit value with the zero index as the LSB
inline void mrg8::jump_ahead(const short jump_val_bin[200], uint32_t *new_state)
{
uint32_t jump_mat[8][8], rowVec[8];
// Calculating the jump matrix
jump_calc(jump_val_bin, jump_mat);
// Multiply the current state by jump_mat
for (int r = 0; r < 8; ++r) {
for (int c = 0; c < 8; ++c) {
rowVec[c] = jump_mat[r][c];
}
new_state[r] = bigDotProd(rowVec, state);
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Jumping the state ahead by a jum_val
inline void mrg8::jump_ahead(const uint64_t jump_val, uint32_t *new_state)
{
short jump_val_bin[200];
uint32_t next_state[8];
dec2bin(jump_val, jump_val_bin);
for (int i = 0; i < 8; ++i) {
new_state[i] = state[i];
}
for (int nb = 0; nb < 200; ++nb) {
if (jump_val_bin[nb]) {
for (int i = 0; i < 8; ++i) {
uint64_t s, s1, s2;
s1 = s2 = 0;
for (int q = 0; q < 4; ++q) {
s1 += uint64_t(JUMP_MATRIX[8 * 8 * nb + i + q * 8]) * new_state[q];
s2 += uint64_t(JUMP_MATRIX[8 * 8 * nb + i + (q + 4) * 8]) * new_state[q + 4];
}
s = (s1 & MASK) + (s1 >> 31) + (s2 & MASK) + ( s2 >> 31);
s = (s & MASK) + (s >> 31);
next_state[i] = (s & MASK) + (s >> 31);
}
for (int i = 0; i < 8; ++i) {
new_state[i] = next_state[i];
}
}
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
inline void mrg8::dec2bin(const uint64_t jval, short jump_val_bin[200]) const
{
for (int nb = 0;nb < 200;++nb) {
jump_val_bin[nb] = 0;
}
for (int nb = 0; nb < 64; ++nb) {
if (jval & (1ul << nb)) {
jump_val_bin[nb] = 1;
}
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Calculating the jump matrix for a given 200-bit jump value
// jump_val_bin is the jump value with jump_val_bin[0] as the LSB
inline void mrg8::jump_calc(const short jump_val_bin[200], uint32_t jump_mat[8][8])
{
uint32_t tmp_mat[8][8], vec1[8], vec2[8];
for (int r = 0; r < 8; ++r) {
for (int c = 0; c < 8; ++c) {
if (r == c) {
jump_mat[r][c] = 1;
}
else {
jump_mat[r][c] = 0;
}
}
}
for (int nb = 0; nb < 200; ++nb) {
if (jump_val_bin[nb]) {
for (int r = 0; r < 8; ++r){
for (int c = 0; c < 8; ++c){
for (int q = 0; q < 8; ++q) {
vec1[q] = jump_mat[r][q];
vec2[q] = JUMP_MATRIX[64*nb + q + 8*c];
}
tmp_mat[r][c] = bigDotProd(vec1, vec2);
}
}
for (int r = 0;r < 8;++r)
for (int c = 0;c < 8;++c)
jump_mat[r][c] = tmp_mat[r][c];
}
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// A multiplicative congruential model to initialize the state using a 32-bit integer
inline void mrg8::mcg64ni()
{
uint64_t x, tmp;
uint64_t ia = 6364136223846793005ull;
if(iseed == 0)
iseed = 97531;
x = iseed;
for(int k=0;k<8;++k){
x = ia * x;
tmp = (x >> 32);
state[k] = (tmp>>1);
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Generate integer uniform RVs in [0, 2^31 -1)
inline void mrg8::randint(uint32_t * iran, int n, uint32_t *new_state)
{
uint32_t a[8], z;
a[0] = COEFF0;
a[1] = COEFF1;
a[2] = COEFF2;
a[3] = COEFF3;
a[4] = COEFF4;
a[5] = COEFF5;
a[6] = COEFF6;
a[7] = COEFF7;
for (int k=0;k<n;++k){
z = bigDotProd(a, new_state);
new_state[7] = new_state[6];// S[n-8] = S[n-7]
new_state[6] = new_state[5];// S[n-7] = S[n-6]
new_state[5] = new_state[4];// S[n-6] = S[n-5]
new_state[4] = new_state[3];// S[n-5] = S[n-4]
new_state[3] = new_state[2];// S[n-4] = S[n-3]
new_state[2] = new_state[1];// S[n-3] = S[n-2]
new_state[1] = new_state[0];// S[n-2] = S[n-1]
new_state[0] = z;
iran[k] = new_state[0];// y[n] = S[n]
}
}
inline void mrg8::randint(uint32_t * iran, int n)
{
randint(iran, n, state);
}
inline uint32_t mrg8::randint()
{
uint32_t r[1];
randint(r, 1, state);
return r[0];
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Generate uniform RVs in [0, 1)
inline void mrg8::rand(double * fran, int n, uint32_t *new_state)
{
uint32_t * iran1 = new uint32_t[n];
double rnorm = 1.0/static_cast<double>(MASK);
randint(iran1, n, new_state);
for (int i = 0; i < n; ++i) {
fran[i] = static_cast<double>(iran1[i] - 1) * rnorm;
}
delete [] iran1;
}
inline void mrg8::rand(double * ran, int n)
{
rand(ran, n, state);
}
inline double mrg8::rand()
{
const double rnorm = 1.0/static_cast<double>(MASK);
uint32_t ir;
randint(&ir, 1, state);
return static_cast<double>(ir) * rnorm;
}
inline double mrg8::rand(uint32_t *new_state)
{
const double rnorm = 1.0/static_cast<double>(MASK);
uint32_t ir;
randint(&ir, 1, new_state);
return static_cast<double>(ir) * rnorm;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Generate uniform RVs in [0, 1)
inline void mrg8::mrg8dnz2(double * ran, int n, uint32_t *new_state)
{
int i, j, k;
double rnorm = 1.0 / static_cast<double>(MASK);
int kmax = 1024;
int nn;
uint64_t s, s1, s2;
uint32_t a[8], z;
uint32_t x[kmax + 8];
a[0] = COEFF0;
a[1] = COEFF1;
a[2] = COEFF2;
a[3] = COEFF3;
a[4] = COEFF4;
a[5] = COEFF5;
a[6] = COEFF6;
a[7] = COEFF7;
for (k = 0; k < 8; ++k) {
x[kmax + k] = new_state[k];
}
nn = n % kmax;
for (j = 0; j < n - nn; j += kmax) {
for (k = kmax - 1; k >= 0; --k) {
s1 = 0;
s2 = 0;
for (i = 0; i < 4; ++i) {
s1 += uint64_t(a[i]) * x[k + 1 + i];
s2 += uint64_t(a[i + 4]) * x[k + 5 + i];
}
s = (s1 & MASK) + (s1 >> 31) + (s2 & MASK) + (s2 >> 31);
s = (s & MASK) + (s >> 31);
x[k] = (s & MASK) + (s >> 31);
ran[j + kmax - 1 - k] = static_cast<double>(x[k] - 1) * rnorm;
}
for (k = 0; k < 8; ++k) {
x[kmax + k] = x[k];
}
}
for (k = 0; k < 8; ++k) {
new_state[k] = x[kmax + k];
}
if (nn > 0) {
rand(ran + (n - nn), nn, new_state);
}
}
inline void mrg8::mrg8dnz2(double * ran, int n)
{
mrg8dnz2(ran, n, state);
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Thread Parallel Random Number Generation with uniform RVs in [0, 1)
inline void mrg8::rand_tp(double * ran, int n)
{
int tnum = omp_get_max_threads();
uint32_t next_state[8];
#pragma omp parallel
{
int each_n = n / tnum;
int tid = omp_get_thread_num();
int start = each_n * tid;
uint32_t *each_state = new uint32_t[8];
if (tid == (tnum - 1)) {
each_n = n - each_n * tid;
}
jump_ahead(start, each_state);
rand(ran + start, each_n, each_state);
if (tid == tnum - 1) {
for (int j = 0; j < 8; ++j) {
next_state[j] = each_state[j];
}
}
delete[] each_state;
}
for (int i = 0; i < 8; ++i) {
state[i] = next_state[i];
}
}
inline void mrg8::mrg8dnz2_tp(double * ran, int n)
{
int tnum = omp_get_max_threads();
uint32_t next_state[8];
#pragma omp parallel
{
int each_n = n / tnum;
int tid = omp_get_thread_num();
int start = each_n * tid;
uint32_t *each_state = new uint32_t[8];
if (tid == (tnum - 1)) {
each_n = n - each_n * tid;
}
jump_ahead(start, each_state);
mrg8dnz2(ran + start, each_n, each_state);
if (tid == tnum - 1) {
for (int j = 0; j < 8; ++j) {
next_state[j] = each_state[j];
}
}
delete[] each_state;
}
for (int i = 0; i < 8; ++i) {
state[i] = next_state[i];
}
}
#endif
| 29.13 | 296 | 0.477515 | [
"vector",
"model"
] |
8e7c1df85dfd604ab535806515bd0e46d3b37b3c | 8,836 | c | C | bbltenc.c | leiradel/bitblt | c565537d4a5981f0590b8694644268f56cda2d9d | [
"MIT"
] | 1 | 2016-10-27T10:54:15.000Z | 2016-10-27T10:54:15.000Z | bbltenc.c | leiradel/bitblt | c565537d4a5981f0590b8694644268f56cda2d9d | [
"MIT"
] | null | null | null | bbltenc.c | leiradel/bitblt | c565537d4a5981f0590b8694644268f56cda2d9d | [
"MIT"
] | null | null | null | /******************************************************************************
The MIT License (MIT)
Copyright (c) 2014 Andre Leiradella
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.
******************************************************************************/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <malloc.h>
#include <png.h>
typedef struct
{
int width;
int height;
uint32_t pixels[ 0 ];
}
image_t;
static uint32_t get_pixel( const image_t* image, int x, int y )
{
if ( x >= 0 && x < image->width && y >= 0 && y < image->height )
{
return image->pixels[ y * image->width + x ];
}
/* return transparent pixel */
return 0;
}
static image_t* load_png( const char* path )
{
png_byte header[ 8 ]; // 8 is the maximum size that can be checked
/* open file and test for it being a png */
FILE *fp = fopen( path, "rb" );
if ( fp == NULL )
{
fprintf( stderr, "File \"%s\" could not be opened for reading\n", path );
return NULL;
}
fread( header, 1, 8, fp );
if ( png_sig_cmp( header, 0, 8 ) )
{
fclose( fp );
fprintf( stderr, "File \"%s\" is not recognized as a PNG file\n", path );
return NULL;
}
/* initialize stuff */
png_structp png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL );
if ( png_ptr == NULL )
{
fclose( fp );
fprintf( stderr, "png_create_read_struct failed\n" );
return NULL;
}
png_infop info_ptr = png_create_info_struct( png_ptr );
if ( info_ptr == NULL )
{
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
fclose( fp );
fprintf( stderr, "png_create_info_struct failed\n" );
return NULL;
}
if ( setjmp( png_jmpbuf( png_ptr ) ) )
{
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
fclose( fp );
fprintf( stderr, "Error during init_io\n" );
return NULL;
}
png_init_io( png_ptr, fp );
png_set_sig_bytes( png_ptr, 8 );
png_read_info( png_ptr, info_ptr );
png_set_expand( png_ptr );
png_set_scale_16( png_ptr );
int width = png_get_image_width( png_ptr, info_ptr );
int height = png_get_image_height( png_ptr, info_ptr );
int color_type = png_get_color_type( png_ptr, info_ptr );
int bit_depth = png_get_bit_depth( png_ptr, info_ptr );
int number_of_passes = png_set_interlace_handling( png_ptr );
png_read_update_info( png_ptr, info_ptr );
/* read file */
if ( setjmp( png_jmpbuf( png_ptr ) ) )
{
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
fclose( fp );
fprintf( stderr, "Error during read_image\n" );
return NULL;
}
image_t* image = (image_t*)malloc( sizeof( image_t ) + width * height * sizeof( uint32_t ) );
if ( image == NULL )
{
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
fclose( fp );
fprintf( stderr, "Out of memory\n" );
return NULL;
}
png_byte** row_pointers = (png_byte**)malloc( height * sizeof( png_byte* ) );
if ( row_pointers == NULL )
{
free( image );
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
fclose( fp );
fprintf( stderr, "Out of memory\n" );
return NULL;
}
for ( int y = 0; y < height; y++ )
{
row_pointers[ y ] = (png_byte*)( image->pixels + y * width );
}
png_read_image( png_ptr, row_pointers );
png_destroy_read_struct( &png_ptr, &info_ptr, NULL );
fclose( fp );
image->width = width;
image->height = height;
return image;
}
static int generate_code( const char* path, const char* name, FILE* out )
{
image_t* image = load_png( path );
if ( image == NULL )
{
return 0;
}
int height_aligned = 8 * ( ( image->height + 7 ) / 8 );
uint8_t* layer1 = (uint8_t*)malloc( image->width * height_aligned );
uint8_t* layer2 = (uint8_t*)malloc( image->width * height_aligned );
if ( layer1 == NULL || layer2 == NULL )
{
free( layer1 );
free( layer2 );
fprintf( stderr, "Out of memory\n" );
return 0;
}
for ( int x = 0; x < image->width; ++x )
{
for ( int y = 0; y < height_aligned; ++y )
{
uint32_t color = get_pixel( image, x, y );
uint8_t a = color >> 24;
uint8_t b = ( color >> 16 ) & 255;
uint8_t g = ( color >> 8 ) & 255;
uint8_t r = color & 255;
uint8_t grey = ( r * 76 + g * 150 + b * 30 ) / 256;
if ( a < 128 )
{
// transparent
layer1[ x * height_aligned + y ] = 0;
layer2[ x * height_aligned + y ] = 0;
}
else if ( grey > 192 )
{
// white
layer1[ x * height_aligned + y ] = 0;
layer2[ x * height_aligned + y ] = 128;
}
else if ( grey < 64 )
{
// black
layer1[ x * height_aligned + y ] = 128;
layer2[ x * height_aligned + y ] = 0;
}
else
{
// grey
layer1[ x * height_aligned + y ] = 128;
layer2[ x * height_aligned + y ] = 128;
}
}
printf( "\n" );
}
fprintf( out, "static const uint8_t %s[] PROGMEM =\n", name );
fprintf( out, "{\n" );
fprintf( out, " /* width in pixels */ %4d,\n", image->width );
fprintf( out, " /* height in pixels */ %4d,\n", image->height );
for ( int x = 0; x < image->width; ++x )
{
fprintf( out, " /* column %3d l1/l2 */ ", x );
for ( int y = 0; y < height_aligned - 1; y += 8 )
{
uint8_t byte = 0;
for ( int k = 0; k < 8; ++k )
{
byte = byte >> 1 | layer1[ x * height_aligned + y + k ];
}
fprintf( out, "0x%02x, ", byte );
byte = 0;
for ( int k = 0; k < 8; ++k )
{
byte = byte >> 1 | layer2[ x * height_aligned + y + k ];
}
fprintf( out, "0x%02x, ", byte );
}
fprintf( out, "\n" );
}
fprintf( out, "};\n\n" );
return 1;
}
static void show_usage( FILE* out )
{
fprintf( out, "USAGE: bbltenc [ -n array_name ] [ -o output_path ] input_path\n\n" );
fprintf( out, "-n array_name set the generated array name (default = sprite)\n" );
fprintf( out, "-o output_path set the name of the generated file (default = stdout)\n" );
fprintf( out, "input_path set the name of the PNG image\n\n" );
}
int main( int argc, const char* argv[] )
{
if ( argc < 2 )
{
show_usage( stderr );
return 1;
}
const char* default_array_name = "sprite";
const char* input_path = NULL;
const char* output_path = NULL;
const char* array_name = default_array_name;
for ( int i = 1; i < argc; ++i )
{
if ( !strcmp( argv[ i ], "-o" ) )
{
if ( output_path != NULL )
{
fprintf( stderr, "Duplicated output path\n" );
return 1;
}
if ( ++i == argc )
{
fprintf( stderr, "Missing argument to -o\n" );
return 1;
}
output_path = argv[ i ];
}
else if ( !strcmp( argv[ i ], "-n" ) )
{
if ( array_name != default_array_name )
{
fprintf( stderr, "Duplicated array name\n" );
return 1;
}
if ( ++i == argc )
{
fprintf( stderr, "Missing argument to -n\n" );
return 1;
}
array_name = argv[ i ];
}
else if ( !strcmp( argv[ i ], "-h" ) )
{
show_usage( stdout );
return 0;
}
else
{
if ( input_path != NULL )
{
fprintf( stderr, "Duplicated input file\n" );
return 1;
}
input_path = argv[ i ];
}
}
FILE* out = stdout;
if ( output_path != NULL )
{
out = fopen( output_path, "w" );
if ( out == NULL )
{
fprintf( stderr, "Error opening \"%s\"\n", output_path );
return 1;
}
}
int retcode = generate_code( input_path, array_name, out );
if ( out != stdout )
{
fclose( out );
}
return retcode;
}
| 25.031161 | 95 | 0.564282 | [
"3d"
] |
8e80414d374540fe288ac6fad6c2de28956a1a08 | 3,689 | h | C | src/utils/vector.h | gtsc/HPC-divers-license | fa1493e217ff76a407feea9b80623eca4691e044 | [
"BSD-3-Clause"
] | null | null | null | src/utils/vector.h | gtsc/HPC-divers-license | fa1493e217ff76a407feea9b80623eca4691e044 | [
"BSD-3-Clause"
] | null | null | null | src/utils/vector.h | gtsc/HPC-divers-license | fa1493e217ff76a407feea9b80623eca4691e044 | [
"BSD-3-Clause"
] | 1 | 2021-06-29T08:56:59.000Z | 2021-06-29T08:56:59.000Z |
#ifndef VECTOR_H_
#define VECTOR_H_
#include <array>
#include <cmath>
#include <iostream>
namespace dive {
template <typename T, size_t N>
struct VectorT {
std::array<T, N> components;
VectorT<T, N>() {
components[0] = 0;
components[1] = 0;
if constexpr (N == 3) components[2] = 0;
}
VectorT<T, N>(T a) {
components[0] = a;
components[1] = a;
if constexpr (N == 3) components[2] = a;
}
VectorT<T, N>(T a, T b) {
components[0] = a;
components[1] = b;
if constexpr (N == 3) components[2] = 0;
}
VectorT<T, N>(T a, T b, T c) {
components[0] = a;
components[1] = b;
if constexpr (N == 3) components[2] = c;
}
VectorT<T, N> operator+(const VectorT<T, N>& b) const {
if constexpr (N == 2)
return VectorT<T, N>(components[0] + b.components[0], components[1] + b.components[1]);
else
return VectorT<T, N>(components[0] + b.components[0], components[1] + b.components[1], components[2] + b.components[2]);
}
VectorT<T, N> operator-(const VectorT<T, N>& b) const {
if constexpr (N == 2)
return VectorT<T, N>(components[0] - b.components[0], components[1] - b.components[1]);
else
return VectorT<T, N>(components[0] - b.components[0], components[1] - b.components[1], components[2] - b.components[2]);
}
T operator*(const VectorT<T, N>& b) const {
if constexpr (N == 2)
return components[0] * b.components[0] + components[1] * b.components[1];
else
return components[0] * b.components[0] + components[1] * b.components[1] + components[2] * b.components[2];
}
VectorT<T, N>& operator+=(const VectorT<T, N>& b) {
if constexpr (N == 2) {
components[0] += b.components[0];
components[1] += b.components[1];
return *this;
} else {
components[0] += b.components[0];
components[1] += b.components[1];
components[2] += b.components[2];
return *this;
}
}
VectorT<T, N>& operator-=(const VectorT<T, N>& b) {
if constexpr (N == 2) {
components[0] -= b.components[0];
components[1] -= b.components[1];
return *this;
} else {
components[0] -= b.components[0];
components[1] -= b.components[1];
components[2] -= b.components[2];
return *this;
}
}
VectorT<T, N> operator*(const T& b) const {
if constexpr (N == 2)
return VectorT<T, N>(components[0] * b, components[1] * b);
else
return VectorT<T, N>(components[0] * b, components[1] * b, components[2] * b);
}
VectorT<T, N> operator/(const T& b) const {
if constexpr (N == 2)
return VectorT<T, N>(components[0] / b, components[1] / b);
else
return VectorT<T, N>(components[0] / b, components[1] / b, components[2] / b);
}
VectorT<T, N>& operator*=(const T& b) {
components[0] *= b;
components[1] *= b;
if constexpr (N == 3) components[2] *= b;
}
VectorT<T, N>& operator/=(const T& b) {
components[0] /= b;
components[1] /= b;
if constexpr (N == 3) components[2] /= b;
}
template <typename K>
T& operator[](K idx) {
return components[idx];
}
template <typename K>
T operator[](K idx) const {
return components[idx];
}
T Length() const { return std::sqrt((*this) * (*this)); }
VectorT<T, N> Normal() const { return (*this) / this->Length(); };
};
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& out, const VectorT<T, N>& a) {
out << "Vector( ";
out << a.components[0];
for (size_t i = 1; i < N; i++) {
out << ", " << a.components[i];
}
out << " )";
return out;
}
template <size_t N>
using Vector = VectorT<double, N>;
} // namespace dive
#endif // VECTOR_H_
| 28.596899 | 126 | 0.574139 | [
"vector"
] |
8e80b9ff6d74444523d1cc33e5e9a6659e355ae6 | 10,986 | h | C | include/tastylib/NPuzzle.h | chuyangliu/tastylib | 0f353938b18e39efdfce27be36ad511b3112af6b | [
"MIT"
] | 11 | 2019-06-12T03:11:05.000Z | 2021-08-13T16:04:31.000Z | include/tastylib/NPuzzle.h | chuyangliu/tastylib | 0f353938b18e39efdfce27be36ad511b3112af6b | [
"MIT"
] | null | null | null | include/tastylib/NPuzzle.h | chuyangliu/tastylib | 0f353938b18e39efdfce27be36ad511b3112af6b | [
"MIT"
] | 3 | 2019-12-05T20:56:48.000Z | 2021-07-25T20:44:57.000Z | #ifndef TASTYLIB_NPUZZLE_H_
#define TASTYLIB_NPUZZLE_H_
#include "tastylib/internal/base.h"
#include "tastylib/util/random.h"
#include "tastylib/HashTable.h"
#include "tastylib/BinaryHeap.h"
#include <vector>
#include <sstream>
#include <string>
#include <list>
#include <utility>
TASTYLIB_NS_BEGIN
enum Direc {
NONE,
LEFT,
UP,
RIGHT,
DOWN
};
class NPuzzle;
class PuzzleNode {
friend class NPuzzle;
public:
using Container = std::vector<int>;
using SizeType = Container::size_type;
/*
Initialize the node. The node value is stored in an one-dimension array.
For a 3*3 puzzle, the contents of the array must be like this:
{1, 2, 3, 4, 5, 6, 7, 8, 0}, where number '0' indicates the the empty grid
and number '1-8' denote other eight grids. The configuration is similar when
the puzzle's size is 4*4, 5*5, etc.
@param val_ The node value
@param row_ The row amount
@param col_ The column amount
*/
PuzzleNode(const Container& val_, const SizeType row_, const SizeType col_)
: val(val_), row(row_), col(col_) {
for (SizeType i = 0; i < val.size(); ++i) {
if (val[i] == 0) {
emptyPos = i;
}
}
}
// Return the amount of rows
SizeType getRowCount() const noexcept {
return row;
}
// Return the amount of columns
SizeType getColCount() const noexcept {
return col;
}
// Return true if the empty grid can move one step along a given direction
bool canMove(const Direc d) const noexcept {
switch (d) {
case LEFT:
return getCol(emptyPos) != 0;
case UP:
return getRow(emptyPos) != 0;
case RIGHT:
return getCol(emptyPos) != col - 1;
case DOWN:
return getRow(emptyPos) != row - 1;
case NONE:
return true;
default:
return false;
}
}
// Move the empty grid along a given direction
void move(const Direc d) {
SizeType goalPos = emptyPos;
switch (d) {
case LEFT:
goalPos -= 1;
break;
case UP:
goalPos -= col;
break;
case RIGHT:
goalPos += 1;
break;
case DOWN:
goalPos += col;
break;
default:
break;
}
if (emptyPos != goalPos) {
std::swap(val[emptyPos], val[goalPos]);
emptyPos = goalPos;
}
}
// Randomly rearrange the node value (ensuring a solution exists)
void shuffle() {
Random *random = Random::getInstance();
for (SizeType i = 0; i < SHUFFLE_TIMES; ++i) {
Direc d = Direc(random->nextInt(1, 4));
if (canMove(d)) {
move(d);
}
}
}
/*
Return a string description of the node value.
*/
std::string toString() const {
std::ostringstream oss;
oss << "{";
for (SizeType i = 0; i < val.size(); ++i) {
if (i) oss << ", ";
oss << val[i];
}
oss << "}";
return oss.str();
}
/*
Return the direction of this node relelative to a given adjacent node.
@param n The given adjacent node
*/
Direc getDirectionTo(const PuzzleNode *const n) const noexcept {
if (n) {
int offset = (int)emptyPos - (int)n->emptyPos;
if (offset == -1) {
return LEFT;
} else if (offset == 1) {
return RIGHT;
} else if (offset == (int)col) {
return DOWN;
} else if (offset == -(int)col) {
return UP;
}
}
return NONE;
}
bool operator==(const PuzzleNode& n) const noexcept {
return getVal() == n.getVal();
}
bool operator<(const PuzzleNode& n) const noexcept {
return getF() < n.getF();
}
private:
// Return the node value
const Container& getVal() const noexcept {
return val;
}
// Return the hash value of the node
SizeType hash() const {
return std::hash<std::string>()(toString());
}
/*
Compute the row number according to a given index of one-dimension array.
@param i The given index
@return The row number in interval [0, row - 1]
*/
SizeType getRow(const SizeType i) const noexcept {
return i / col;
}
/*
Compute the column number according to a given index of one-dimension array.
@param i The given index
@return The row number in interval [0, col - 1]
*/
SizeType getCol(const SizeType i) const noexcept {
return i % col;
}
/*
Return the adjacent node at a given direction.
Precondition: the current node can move along the given direction
@param d The given direction
*/
PuzzleNode* getNeighbor(const Direc d) const {
PuzzleNode* n = new PuzzleNode(*this);
n->move(d);
return n;
}
/*
Return the heuristic value to the destination node.
@param des The destination node
@param index The index of each number in the destination node value array
*/
SizeType heuristic(const PuzzleNode *const des, const std::vector<SizeType>& index) const {
SizeType size = val.size();
// Number of nodes which are in a wrong position
SizeType wrong = 0;
for (SizeType i = 0; i < size; ++i) {
if (val[i] != des->val[i]) {
++wrong;
}
}
// Distance to the destination
SizeType manhatten = 0, geometric = 0;
for (SizeType i = 0; i < size; ++i) {
if (val[i]) { // Escape value 0
SizeType curR = getRow(i);
SizeType curC = getCol(i);
SizeType desR = getRow(index[val[i]]);
SizeType desC = getCol(index[val[i]]);
SizeType dR = curR > desR ? curR - desR : desR - curR;
SizeType dC = curC > desC ? curC - desC : desC - curC;
manhatten += dR + dC;
geometric += (SizeType)(sqrt(dR * dR + dC * dC));
}
}
return 5 * (1 * wrong + 2 * manhatten + 1 * geometric);
}
void setG(const SizeType g_) noexcept {
g = g_;
}
void setH(const SizeType h_) noexcept {
h = h_;
}
void setParent(PuzzleNode* p) noexcept {
parent = p;
}
SizeType getG() const noexcept {
return g;
}
SizeType getH() const noexcept {
return h;
}
SizeType getF() const noexcept {
return getG() + getH();
}
const PuzzleNode* getParent() const {
return parent;
}
private:
static const SizeType SHUFFLE_TIMES = 1000;
Container val;
SizeType emptyPos = 0;
SizeType row = 0;
SizeType col = 0;
SizeType g = 0;
SizeType h = 0;
PuzzleNode *parent = nullptr;
};
class NPuzzle {
public:
using Node = PuzzleNode;
using SizeType = Node::SizeType;
NPuzzle(const Node& beg_, const Node& end_)
: beg(beg_), end(end_), closeList(1000000) {}
void solve() {
std::vector<SizeType> index = buildIndex();
searchCnt = 0;
openList.push(&beg);
while (!openList.isEmpty()) {
Node *cur = nullptr;
do {
// Loop until the open list is empty or a node
// that is not in the close list is found.
cur = openList.top();
openList.pop();
} while (!openList.isEmpty() && closeList.has(cur));
if (openList.isEmpty() && closeList.has(cur)) {
// If all the nodes in the open list is in the
// close list, then there is no available path
// between the two nodes.
return;
}
++searchCnt;
closeList.insert(cur);
if (*cur == end) {
buildPath(cur);
freeResources();
return;
}
for (int i = 1; i < 5; ++i) {
Direc d = Direc(i);
if (cur->canMove(d)) {
Node *adj = cur->getNeighbor(d);
alloc.push_back(adj);
if (!closeList.has(adj)) {
adj->setParent(cur);
adj->setG(cur->getG() + 1);
adj->setH(adj->heuristic(&end, index));
openList.push(adj);
}
}
}
}
}
const std::list<Direc>& getPath() const {
return path;
}
SizeType getSearchCount() const {
return searchCnt;
}
const Node& shuffleBeg() {
beg.shuffle();
return beg;
}
const Node& shuffleEnd() {
end.shuffle();
return end;
}
void setBeg(const Node& beg_) {
beg = beg_;
}
void setEnd(const Node& end_) {
end = end_;
}
const Node& getBeg() const {
return beg;
}
const Node& getEnd() const {
return end;
}
private:
// Return the index of the grid numbers in the ending node value.
std::vector<SizeType> buildIndex() const {
const auto &endVal = end.getVal();
std::vector<SizeType> index(endVal.size());
for (SizeType i = 0; i < endVal.size(); ++i) {
index[endVal[i]] = i;
}
return index;
}
// Build a path from the beginning node to the destination node
void buildPath(const Node* des) {
path.clear();
while (des) {
auto parent = des->getParent();
Direc d = des->getDirectionTo(parent);
if (d != Direc::NONE) {
path.push_front(d);
}
des = parent;
}
}
void freeResources() {
for (const auto &n : alloc) {
delete n;
}
alloc.clear();
openList.clear();
closeList.clear();
}
private:
struct Equal {
bool operator()(const Node *const &n1,
const Node *const &n2) const noexcept {
return *n1 == *n2;
}
};
struct Less {
bool operator()(const Node *const &n1,
const Node *const &n2) const noexcept {
return *n1 < *n2;
}
};
struct Hash {
SizeType operator()(const Node *const &n) const noexcept {
return n->hash();
}
};
Node beg;
Node end;
BinaryHeap<Node*, Less> openList;
HashTable<Node*, Equal, Hash> closeList;
std::list<Direc> path;
std::list<Node*> alloc;
SizeType searchCnt = 0;
};
TASTYLIB_NS_END
#endif
| 25.371824 | 95 | 0.509376 | [
"vector"
] |
8e8150fcbcb259deb3e8964b33a893c1e129dbad | 955 | h | C | resources/usr/lib/root/etc/dictpch/math/genvector/inc/Math/LinkDef_GenVector2.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/usr/lib/root/etc/dictpch/math/genvector/inc/Math/LinkDef_GenVector2.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/usr/lib/root/etc/dictpch/math/genvector/inc/Math/LinkDef_GenVector2.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | 1 | 2020-05-28T23:01:44.000Z | 2020-05-28T23:01:44.000Z | // dictionary for std::vector of genvector objects
// problem on Windows: CINT cannot deal with too long class name
// generated by an std::vector<ROOT::Math::Vector>
#ifndef _WIN32
#pragma extra_include "vector";
#include <vector>
// conflict on solaris between template class T from std::vector and T().
#ifndef __sun
#pragma link C++ class std::vector<ROOT::Math::XYZTVector >+;
#pragma link C++ class std::vector<ROOT::Math::PtEtaPhiEVector >+;
#endif
#pragma link C++ class std::vector<ROOT::Math::XYZVector >+;
#pragma link C++ class std::vector<ROOT::Math::XYZPoint >+;
#pragma link C++ class std::vector<ROOT::Math::RhoEtaPhiVector >+;
#pragma link C++ class std::vector<ROOT::Math::RhoEtaPhiPoint >+;
// for floating types
#pragma link C++ class std::vector<ROOT::Math::XYZVectorF >+;
#pragma link C++ class std::vector<ROOT::Math::XYZPointF >+;
#pragma link C++ class std::vector<ROOT::Math::XYZTVectorF >+;
#endif // endif Win32
| 34.107143 | 73 | 0.707853 | [
"vector"
] |
8e8748f3b112002ac26d33a9f170d6930d0595a7 | 21,740 | h | C | Prototype/src/libsbml-5.10.0/src/sbml/packages/render/sbml/GlobalRenderInformation.h | Cosmo-Tech/biopredyn | 0f5bcd4cb1f723bfdea07d4973e46e676f4175e8 | [
"BSD-3-Clause"
] | null | null | null | Prototype/src/libsbml-5.10.0/src/sbml/packages/render/sbml/GlobalRenderInformation.h | Cosmo-Tech/biopredyn | 0f5bcd4cb1f723bfdea07d4973e46e676f4175e8 | [
"BSD-3-Clause"
] | 95 | 2015-03-06T12:14:06.000Z | 2015-03-20T11:15:54.000Z | Prototype/src/libsbml-5.10.0/src/sbml/packages/render/sbml/GlobalRenderInformation.h | Cosmo-Tech/biopredyn | 0f5bcd4cb1f723bfdea07d4973e46e676f4175e8 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file GlobalRenderInformation.h
* @brief class for representing global render information
* @author Ralph Gauges
*
*/
/* Copyright 2010 Ralph Gauges
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is
* provided in the file named "LICENSE.txt" included with this software
* distribution. It is also available online at
* http://sbml.org/software/libsbml/license.html
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* The original code contained here was initially developed by:
*
* Ralph Gauges
* Group for the modeling of biological processes
* University of Heidelberg
* Im Neuenheimer Feld 267
* 69120 Heidelberg
* Germany
*
* mailto:ralph.gauges@bioquant.uni-heidelberg.de
*
* Contributor(s):
*
* @class GlobalRenderInformation
* @brief GlobalRenderInformation is the render information stored in the ListOfLayouts. GlobalRenderInformation can be
* applied to all layouts.
*
* GlobalRenderInformation is one of the subclasses of RenderInformationBase. A global render information object
* contains color definitions, gradient definitions and line endings as defined in RenderInformationBase.
* Additionally it has a list of global styles which specifies type and role based render information.
* Global render information can not specify id based render information because it does not belong to a certain layout
* but it belongs to all layouts.
*
* @class ListOfGlobalRenderInformation
* @brief container class that stores GlobalRenderInformation objects.
*
* The ListOfLayouts in the SBML model contains a ListOfGlobalRenderInformation which holds all GlobalRenderInformation
* objects.
*/
#ifndef GlobalRenderInformation_H__
#define GlobalRenderInformation_H__
#include <sbml/common/sbmlfwd.h>
#include <sbml/packages/render/sbml/RenderInformationBase.h>
#include <sbml/packages/render/sbml/GlobalStyle.h>
#include <sbml/xml/XMLNode.h>
#ifdef __cplusplus
#include <string>
#include <sbml/packages/render/extension/RenderExtension.h>
LIBSBML_CPP_NAMESPACE_BEGIN
class LIBSBML_EXTERN GlobalRenderInformation : public RenderInformationBase
{
protected:
/** @cond doxygenLibsbmlInternal */
ListOfGlobalStyles mListOfStyles;
static const std::string ELEMENT_NAME;
/** @endcond */
public:
/**
* Creates a new GlobalRenderInformation object with the given SBML level
* and SBML version.
*
* @param level SBML level of the new object
* @param level SBML version of the new object
*/
GlobalRenderInformation (unsigned int level = RenderExtension::getDefaultLevel(),
unsigned int version = RenderExtension::getDefaultVersion(),
unsigned int pkgVersion = RenderExtension::getDefaultPackageVersion());
/**
* Creates a new GlobalRenderInformation object with the given SBMLNamespaces.
*
* @param sbmlns The SBML namespace for the object.
*/
GlobalRenderInformation (RenderPkgNamespaces* renderns);
/**
* Destroy this GlobalRenderInformation object.
*/
virtual ~GlobalRenderInformation ();
/**
* Parses the xml information in the given node and sets the attributes.
* This method should never be called by the user. It is only used to read render
* information from annotations.
*
* @param node the XMLNode object reference that describes the GlobalRenderInformation
* object to be instantiated.
*/
void parseXML(const XMLNode& node);
#ifndef OMIT_DEPRECATED
/**
* Constructor which creates a GlobalRenderInformation with the given @p id
* and all lists empty.
*
* @param id the new id for the GlobalRenderInformation.
*
* This constructor is deprecated. The new libsbml API only has
* constructors which take the SBML level and version or one that takes
* an SBMLNamespaces object.
*/
GlobalRenderInformation(RenderPkgNamespaces* renderns, const std::string& id);
#endif // OMIT_DEPRECATED
/**
* Returns the number of styles.
*
* @return the number of global styles in the global render information object
*/
unsigned int getNumStyles() const;
/**
* Returns a pointer to the ListOfGlobalStyles object.
*
* @return pointer to the list of global styles.
*/
ListOfGlobalStyles* getListOfStyles();
/**
* Returns a const pointer to the ListOfGlobalStyles object.
*
* @return const pointer to the list of global styles.
*/
const ListOfGlobalStyles* getListOfStyles() const;
/**
* Returns a pointer to the style with the given index.
* If the index is invalid, @c NULL is returned.
*
* @param i index of the GlobalStyle to be returned.
*
* @return pointer to the style with the given index or NULL
*/
GlobalStyle* getStyle(unsigned int i);
/**
* Returns a const pointer to the style with the given index.
* If the index is invalid, @c NULL is returned.
*
* @param i index of the GlobalStyle to be returned.
*
* @return const pointer to the style with the given index or NULL
*/
const GlobalStyle* getStyle(unsigned int i) const;
/**
* Returns a pointer to the style with the given @p id.
* If the id is invalid, @c NULL is returned.
*
* @param id id of the GlobalStyle to be returned.
*
* @return pointer to the style with the given @p id or @c NULL
*/
GlobalStyle* getStyle(const std::string& id);
/**
* Returns a pointer to the style with the given @p id.
* If the id is invalid, @c NULL is returned.
*
* @param id id of the GlobalStyle to be returned.
*
* @return const pointer to the style with the given @p id or @c NULL
*/
const GlobalStyle* getStyle(const std::string& id) const;
/**
* Creates a new GlobalStyle object. The object is added to and owned
* by the GlobalRenderInformation object.
*
* @param id for the new style.
*
* @ return a pointer to the newly created GlobalStyle object.
*/
GlobalStyle* createStyle(const std::string& id);
/**
* Adds a copy of a GlobalStyle to the GlobalRenderInformation object.
* The style is only added if it is valid, i.e. it has to have an id and
* a valid group.
*
* @param pointer to the global style object to be added.
*
* @return integer value indicating success/failure of the
* function. @if clike The value is drawn from the
* enumeration #OperationReturnValues_t. @endif The possible values
* returned by this function are:
* @li LIBSBML_OPERATION_SUCCESS
* @li LIBSBML_LEVEL_MISMATCH
* @li LIBSBML_VERSION_MISMATCH
* @li LIBSBML_OPERATION_FAILED
*
* @note This method should be used with some caution. The fact that
* this method @em copies the object passed to it means that the caller
* will be left holding a physically different object instance than the
* one contained in this GlobalRenderInformation. Changes made to the original object
* instance (such as resetting attribute values) will <em>not affect the
* instance in the GlobalRenderInformation</em>. In addition, the caller should make
* sure to free the original object if it is no longer being used, or
* else a memory leak will result. Please see GlobalRenderInformation::createStyle()
* for a method that does not lead to these issues.
*
* @see createStyle()
*/
int addStyle(const GlobalStyle* pStyle);
/**
* Returns a List of all child SBase objects, including those nested to an
* arbitrary depth
*
* @return a List* of pointers to all children objects.
*/
virtual List* getAllElements(ElementFilter* filter=NULL);
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to write out their contained
* SBML objects as XML elements. Be sure to call your parents
* implementation of this method as well. For example:
*
* SBase::writeElements(stream);
* mReactants.write(stream);
* mProducts.write(stream);
* ...
*/
virtual void writeElements (XMLOutputStream& stream) const;
/** @endcond */
/**
* Returns the XML element name of this object, which for
* GlobalRenderInformation, is always @c "renderInformation".
*
* @return the name of this element, i.e., @c "renderInformation".
*/
virtual const std::string& getElementName () const ;
/**
* Creates and returns a deep copy of this GlobalRenderInformation object.
*
* @return a (deep) copy of this GlobalRenderInformation.
*/
virtual GlobalRenderInformation* clone () const;
/**
* Returns the libSBML type code for this %SBML object.
*
* @if clike LibSBML attaches an identifying code to every
* kind of SBML object. These are known as <em>SBML type codes</em>.
* The set of possible type codes is defined in the enumeration
* #SBMLTypeCode_t. The names of the type codes all begin with the
* characters @c SBML_. @endif@if java LibSBML attaches an
* identifying code to every kind of SBML object. These are known as
* <em>SBML type codes</em>. In other languages, the set of type codes
* is stored in an enumeration; in the Java language interface for
* libSBML, the type codes are defined as static integer constants in
* interface class {@link libsbmlConstants}. The names of the type codes
* all begin with the characters @c SBML_. @endif
*
* @return the SBML type code for this object, or @c SBML_UNKNOWN (default).
*
* @see getElementName()
*/
int getTypeCode () const;
/**
* Accepts the given SBMLVisitor.
*
* @return the result of calling <code>v.visit()</code>, which indicates
* whether or not the Visitor would like to visit the SBML object's next
* sibling object (if available).
*/
virtual bool accept (SBMLVisitor& v) const;
/**
* Creates an XMLNode object from this GlobalRenderInformation object.
*
* @return the XMLNode with the XML representation for the
* GlobalRenderInformation object.
*
*/
XMLNode toXML() const;
/** @cond doxygenLibsbmlInternal */
/**
* Sets the parent SBMLDocument of this SBML object.
*
* @param d the SBMLDocument object to use
*/
virtual void setSBMLDocument (SBMLDocument* d);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Sets this SBML object to child SBML objects (if any).
* (Creates a child-parent relationship by the parent)
*
* Subclasses must override this function if they define
* one ore more child elements.
* Basically, this function needs to be called in
* constructor, copy constructor, assignment operator.
*
* @see setSBMLDocument
* @see enablePackageInternal
*/
virtual void connectToChild ();
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Enables/Disables the given package with this element and child
* elements (if any).
* (This is an internal implementation for enablePakcage function)
*
* @note Subclasses in which one or more child elements are defined
* must override this function.
*/
virtual void enablePackageInternal(const std::string& pkgURI,
const std::string& pkgPrefix, bool flag);
/** @endcond */
protected:
/** @cond doxygenLibsbmlInternal */
/**
* @return the SBML object corresponding to next XMLToken in the
* XMLInputStream or NULL if the token was not recognized.
*/
virtual SBase* createObject (XMLInputStream& stream);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to read values from the given
* XMLAttributes set into their specific fields. Be sure to call your
* parents implementation of this method as well.
*/
virtual void readAttributes (const XMLAttributes& attributes, const ExpectedAttributes& expectedAttributes);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to get the list of
* expected attributes.
* This function is invoked from corresponding readAttributes()
* function.
*/
virtual void addExpectedAttributes(ExpectedAttributes& attributes);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
* Subclasses should override this method to write their XML attributes
* to the XMLOutputStream. Be sure to call your parents implementation
* of this method as well. For example:
*
* SBase::writeAttributes(stream);
* stream.writeAttribute( "id" , mId );
* stream.writeAttribute( "name", mName );
* ...
*/
virtual void writeAttributes (XMLOutputStream& stream) const;
/** @endcond */
};
class LIBSBML_EXTERN ListOfGlobalRenderInformation : public ListOf
{
public:
/**
* Creates and returns a deep copy of the ListOfGlobalRenderInformation object.
*
* @return a (deep) copy of this ListOfGlobalRenderInformation
*/
virtual ListOfGlobalRenderInformation* clone () const;
/**
* Parses the xml information in the given node and sets the attributes.
* This method should never be called by the user. It is only used to read render
* information from annotations.
*
* @param node the XMLNode object reference that describes the ListOfGlobalRenderInformation
* object to be instantiated.
*/
void parseXML(const XMLNode& node);
/**
* Constructor which instantiates an empty ListOfGlobalRenderInformation object.
*/
ListOfGlobalRenderInformation(unsigned int level = RenderExtension::getDefaultLevel(),
unsigned int version = RenderExtension::getDefaultVersion(),
unsigned int pkgVersion = RenderExtension::getDefaultPackageVersion());
/**
* Ctor.
*/
ListOfGlobalRenderInformation(RenderPkgNamespaces* renderns);
/**
* Copy constructor for ListOfGlobalRenderInformation objects.
*/
ListOfGlobalRenderInformation(const ListOfGlobalRenderInformation& source);
/**
* Assignment operator for ListOfGlobalRenderInformationObjects.
*/
ListOfGlobalRenderInformation& operator=(const ListOfGlobalRenderInformation& source);
/**
* Get the type code of the objects contained in this ListOf.
*
* @if clike LibSBML attaches an identifying code to every kind of SBML
* object. These are known as <em>SBML type codes</em>. The set of
* possible type codes is defined in the enumeration #SBMLTypeCode_t.
* The names of the type codes all begin with the characters @c
* SBML_. @endif@if java LibSBML attaches an identifying code to every
* kind of SBML object. These are known as <em>SBML type codes</em>. In
* other languages, the set of type codes is stored in an enumeration; in
* the Java language interface for libSBML, the type codes are defined as
* static integer constants in the interface class {@link
* libsbmlConstants}. The names of the type codes all begin with the
* characters @c SBML_. @endif@if python LibSBML attaches an identifying
* code to every kind of SBML object. These are known as <em>SBML type
* codes</em>. In the Python language interface for libSBML, the type
* codes are defined as static integer constants in the interface class
* @link libsbml@endlink. The names of the type codes all begin with the
* characters @c SBML_. @endif@if csharp LibSBML attaches an identifying
* code to every kind of SBML object. These are known as <em>SBML type
* codes</em>. In the C# language interface for libSBML, the type codes
* are defined as static integer constants in the interface class @link
* libsbmlcs.libsbml@endlink. The names of the type codes all begin with
* the characters @c SBML_. @endif
*
* @return the SBML type code for the objects contained in this ListOf
* instance, or @link SBMLTypeCode_t#SBML_UNKNOWN SBML_UNKNOWN@endlink (default).
*/
virtual int getItemTypeCode () const;
virtual bool isValidTypeForList(SBase * item);
/**
* Returns the XML element name of this object, which for
* ListOfGlobalRenderInformation, is always @c "listOfGlobalRenderInformation".
*
* @return the name of this element, i.e., @c "listOfGlobalRenderInformation".
*/
virtual const std::string& getElementName () const;
/**
* Creates an XMLNode object from this ListOfGlobalRenderInformation object.
*
* @return the XMLNode with the XML representation for the
* ListOfGlobalRenderInformation object.
*/
XMLNode toXML() const;
/**
* Sets the version of the render information list.
* The version consists of a major and a minor version number.
*
* @param major major version number
* @param minor minor version number
*/
void setVersion(unsigned int major,unsigned int minor);
/**
* Returns the major version of the render information list.
*
* @return the major version number of the global render information list
*/
unsigned int getMajorVersion() const;
/**
* Returns the minor version of the render information list.
*
* @return the minor version number of the global render information list
*/
unsigned int getMinorVersion() const;
/**
* Returns the version as a string.
*
* @return the version of the GlobalRenderInformation object
* as a string
*/
std::string getVersionString() const;
/**
* Returns a pointer to the GlobalRenderInformation with the given index or NULL if
* the index is invalid.
*
* @param i index of the GlobalRenderInformation object to be returned
*
* @return pointer to the GlobalRenderInformation at the given index or NULL.
*/
GlobalRenderInformation* get(unsigned int i);
/**
* Returns a const pointer to the GlobalRenderInformation with the given index or NULL if
* the index is invalid.
*
* @param i index of the GlobalRenderInformation object to be returned
*
* @return const pointer to the GlobalRenderInformation at the given index or NULL.
*/
const GlobalRenderInformation* get(unsigned int i) const;
/**
* Returns a pointer to the GlobalRenderInformation with the given @p id or @c NULL if
* the id is invalid.
*
* @param id id of the GlobalRenderInformation object to be returned
*
* @return pointer to the GlobalRenderInformation at the given @p id or @c NULL.
*/
GlobalRenderInformation* get(const std::string& id);
/**
* Returns a const pointer to the GlobalRenderInformation with the given @p id or @c NULL if
* the id is invalid.
*
* @param id id of the GlobalRenderInformation object to be returned
*
* @return const pointer to the GlobalRenderInformation at the given @p id or @c NULL.
*/
const GlobalRenderInformation* get(const std::string& id) const;
/**
* Removes the nth item from this ListOfGlobalRenderInformation items and returns a pointer to
* it.
*
* The caller owns the returned item and is responsible for deleting it.
*
* @param n the index of the item to remove
*
* @see size()
*/
virtual GlobalRenderInformation* remove (unsigned int n);
/**
* Removes item in this ListOfGlobalRenderInformation items with the given identifier.
*
* The caller owns the returned item and is responsible for deleting it.
* If none of the items in this list have the identifier @p sid, then @c
* NULL is returned.
*
* @param sid the identifier of the item to remove
*
* @return the item removed. As mentioned above, the caller owns the
* returned item.
*/
virtual GlobalRenderInformation* remove (const std::string& sid);
protected:
/** @cond doxygenLibsbmlInternal */
/**
* @return the SBML object corresponding to next XMLToken in the
* XMLInputStream or NULL if the token was not recognized.
*/
virtual SBase* createObject (XMLInputStream& stream);
/** @endcond */
/** @cond doxygenLibsbmlInternal */
virtual void addExpectedAttributes(ExpectedAttributes& attributes);
/**
* Subclasses should override this method to write their XML attributes
* to the XMLOutputStream. Be sure to call your parents implementation
* of this method as well. For example:
*
* SBase::writeAttributes(stream);
* stream.writeAttribute( "id" , mId );
* stream.writeAttribute( "name", mName );
* ...
*/
virtual void writeAttributes (XMLOutputStream& stream) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/**
*
* Subclasses should override this method to write their xmlns attriubutes
* (if any) to the XMLOutputStream.
*
*/
virtual void writeXMLNS (XMLOutputStream& stream) const;
/** @endcond */
/** @cond doxygenLibsbmlInternal */
static const std::string ELEMENT_NAME;
unsigned int mVersionMajor;
unsigned int mVersionMinor;
/** @endcond */
};
LIBSBML_CPP_NAMESPACE_END
#endif /* __cplusplus */
#endif /* GlobalRenderInformation_H__ */
| 34.075235 | 120 | 0.688546 | [
"render",
"object",
"model"
] |
8e8e46614c63e25d6bc466336db673ae2dab3668 | 3,507 | h | C | iOSOpenDev/frameworks/iLifeSlideshow.framework/Headers/MCContainerEffect.h | bzxy/cydia | f8c838cdbd86e49dddf15792e7aa56e2af80548d | [
"MIT"
] | 678 | 2017-11-17T08:33:19.000Z | 2022-03-26T10:40:20.000Z | iOSOpenDev/frameworks/iLifeSlideshow.framework/Headers/MCContainerEffect.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 22 | 2019-04-16T05:51:53.000Z | 2021-11-08T06:18:45.000Z | iOSOpenDev/frameworks/iLifeSlideshow.framework/Headers/MCContainerEffect.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 170 | 2018-06-10T07:59:20.000Z | 2022-03-22T16:19:33.000Z | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iLifeSlideshow.framework/iLifeSlideshow
*/
#import <iLifeSlideshow/MCContainer.h>
@class NSSet, NSMutableDictionary, NSArray, NSDictionary, NSString, NSMutableSet, NSRecursiveLock;
@interface MCContainerEffect : MCContainer {
NSMutableSet *mSlides; // 28 = 0x1c
NSRecursiveLock *mSlidesLock; // 32 = 0x20
NSArray *mCachedOrderedSlides; // 36 = 0x24
NSMutableSet *mTexts; // 40 = 0x28
NSRecursiveLock *mTextsLock; // 44 = 0x2c
NSArray *mCachedOrderedTexts; // 48 = 0x30
NSString *mEffectID; // 52 = 0x34
NSMutableDictionary *mEffectAttributes; // 56 = 0x38
}
@property(copy) NSString *effectID; // G=0x8a25; S=0x89fd; @synthesize=mEffectID
@property(copy) NSDictionary *effectAttributes; // G=0x8b55; S=0x8a3d;
@property(readonly, assign) NSArray *orderedTexts; // G=0x9f39;
@property(readonly, assign) NSArray *orderedSlides; // G=0xb0dd;
@property(readonly, assign) NSSet *texts; // G=0xa07d;
@property(readonly, assign) NSSet *slides; // G=0xb221;
+ (id)keyPathsForValuesAffectingValueForKey:(id)key; // 0x8941
- (id)init; // 0x8815
- (id)initFromScratchWithMontage:(id)montage; // 0xbd49
- (id)initWithImprint:(id)imprint andMontage:(id)montage; // 0xb951
- (void)demolish; // 0xb5f1
- (id)imprint; // 0xb349
- (void)observeValueForKeyPath:(id)keyPath ofObject:(id)object change:(id)change context:(void *)context; // 0xb2d1
// declared property getter: - (id)slides; // 0xb221
// declared property getter: - (id)orderedSlides; // 0xb0dd
- (unsigned)countOfSlides; // 0xb081
- (id)slideAtIndex:(unsigned)index; // 0xaf2d
- (id)addSlide; // 0xaf01
- (id)addSlides:(int)slides; // 0xad0d
- (id)insertSlideAtIndex:(int)index; // 0xaab5
- (id)addSlideForAsset:(id)asset; // 0xaa51
- (id)addSlidesForAssets:(id)assets; // 0xaa1d
- (id)insertSlideForAsset:(id)asset atIndex:(unsigned)index; // 0xa9cd
- (id)insertSlidesForAssets:(id)assets atIndex:(unsigned)index; // 0xa639
- (void)removeSlidesAtIndices:(id)indices; // 0xa3fd
- (void)removeAllSlides; // 0xa39d
- (void)moveSlidesAtIndices:(id)indices toIndex:(unsigned)index; // 0xa12d
// declared property getter: - (id)texts; // 0xa07d
// declared property getter: - (id)orderedTexts; // 0x9f39
- (unsigned)countOfTexts; // 0x9edd
- (id)textAtIndex:(unsigned)index; // 0x9d89
- (id)addTextForAttributedString:(id)attributedString; // 0x9d25
- (id)addTextsForAttributedStrings:(id)attributedStrings; // 0x9cf1
- (id)addTextForAsset:(id)asset andKey:(id)key; // 0x9c7d
- (id)addTextsForAssets:(id)assets andKey:(id)key; // 0x9c39
- (id)insertTextForAttributedString:(id)attributedString atIndex:(unsigned)index; // 0x9be5
- (id)insertTextsForAttributedStrings:(id)attributedStrings atIndex:(unsigned)index; // 0x9829
- (id)insertTextForAsset:(id)asset andKey:(id)key atIndex:(unsigned)index; // 0x97cd
- (id)insertTextsForAssets:(id)assets andKey:(id)key atIndex:(unsigned)index; // 0x93bd
- (void)removeTextsAtIndices:(id)indices; // 0x911d
- (void)removeAllTexts; // 0x90bd
- (void)moveTextsAtIndices:(id)indices toIndex:(unsigned)index; // 0x8e4d
- (id)effectAttributeForKey:(id)key; // 0x8d61
- (void)setEffectAttribute:(id)attribute forKey:(id)key; // 0x8c21
// declared property getter: - (id)effectAttributes; // 0x8b55
// declared property setter: - (void)setEffectAttributes:(id)attributes; // 0x8a3d
// declared property getter: - (id)effectID; // 0x8a25
// declared property setter: - (void)setEffectID:(id)anId; // 0x89fd
@end
| 50.1 | 115 | 0.741374 | [
"object"
] |
8e945924a2e12210e99ea6c411a9341edd42e576 | 3,461 | h | C | t2s/src/SliceExprTree.h | vmiheer/t2sp | c9401668f85589e3d7263a4c7e024dca698adb8d | [
"BSD-2-Clause-Patent"
] | 24 | 2021-09-02T22:54:51.000Z | 2022-01-27T19:28:04.000Z | t2s/src/SliceExprTree.h | vmiheer/t2sp | c9401668f85589e3d7263a4c7e024dca698adb8d | [
"BSD-2-Clause-Patent"
] | 5 | 2021-11-08T20:10:11.000Z | 2022-03-08T01:12:57.000Z | t2s/src/SliceExprTree.h | vmiheer/t2sp | c9401668f85589e3d7263a4c7e024dca698adb8d | [
"BSD-2-Clause-Patent"
] | 8 | 2021-09-06T21:07:02.000Z | 2022-03-10T01:54:48.000Z | /*******************************************************************************
* Copyright 2021 Intel Corporation
*
* Licensed under the BSD-2-Clause Plus Patent License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSDplusPatent
*
* 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.
*
*
* SPDX-License-Identifier: BSD-2-Clause-Patent
*******************************************************************************/
#ifndef T2S_SLICE_EXPR_TREE_H
#define T2S_SLICE_EXPR_TREE_H
#include "../../Halide/src/IRVisitor.h"
#include "../../Halide/src/Util.h"
#include <set>
#include <map>
#include <string>
#include <sstream>
/** \file
* Slice an express tree for a path leading to an operand.
* The operand can be a Func Call or an Expr.
* There can be only a single match.
* The operand cannot be an immediate number, string, variable,
* or in the condition of a Select.
*/
namespace Halide {
namespace Internal {
// In an expression tree, match an operand (based on either a Func name,
// or an Expr). Record the condition of the path leading to the operand,
// and the Let Exprs on the path.
class SliceExprTree : public IRVisitor {
private:
// The Func or Expr to match.
std::string func_to_match;
Expr expr_to_match;
// The message header when an error is encountered.
std::string error_msg_header;
public:
// Results
Expr matched_operand;
Expr condition;
std::vector<const Let*> lets;
using IRVisitor::visit;
SliceExprTree(std::string func_to_match, Expr expr_to_match,
std::string error_msg_header = "") :
func_to_match(func_to_match), expr_to_match(expr_to_match),
error_msg_header(error_msg_header) {
// Must match a Func name, or an Expr, but not both
internal_assert(func_to_match != "" || expr_to_match.defined());
internal_assert(!(func_to_match != "" && expr_to_match.defined()));
matched_operand = Expr();
}
template<typename T>
void match_expr(const T* op);
void visit(const Add *op) override;
void visit(const Sub *op) override;
void visit(const Mul *op) override;
void visit(const Div *op) override;
void visit(const Mod *op) override;
void visit(const Min *op) override;
void visit(const Max *op) override;
void visit(const EQ *op) override;
void visit(const NE *op) override;
void visit(const LT *op) override;
void visit(const LE *op) override;
void visit(const GT *op) override;
void visit(const GE *op) override;
void visit(const And *op) override;
void visit(const Or *op) override;
void visit(const Not *op) override;
void visit(const Select *op) override;
void visit(const Call *op) override;
void visit(const Let *op) override;
void visit(const Load *op) override;
// Print out the slice found.
std::string to_string() const;
};
}
}
#endif
| 33.278846 | 80 | 0.627275 | [
"vector"
] |
8e9577fd7a594a71e59a47bbe1e632912d7da06d | 4,812 | h | C | sc_tool/lib/sc_tool/cthread/ScThreadBuilder.h | rseac/systemc-compiler | ad1c68054467ed8db1c4e9b8f63eda092945d56d | [
"Apache-2.0"
] | 1 | 2021-05-19T02:24:58.000Z | 2021-05-19T02:24:58.000Z | sc_tool/lib/sc_tool/cthread/ScThreadBuilder.h | chmodJack/systemc-compiler | ef59ab45b90485ce38084e084834d5fd205934f6 | [
"Apache-2.0"
] | null | null | null | sc_tool/lib/sc_tool/cthread/ScThreadBuilder.h | chmodJack/systemc-compiler | ef59ab45b90485ce38084e084834d5fd205934f6 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
/**
* Author: Roman Popov
* Modified by: Mikhail Moiseev
*/
#ifndef SCTOOL_SCTHREADBUILDER_H
#define SCTOOL_SCTHREADBUILDER_H
#include <sc_tool/utils/ScTypeTraits.h>
#include <sc_tool/cthread/ScFindWaitCallVisitor.h>
#include <sc_tool/elab/ScObjectView.h>
#include <sc_tool/utils/RawIndentOstream.h>
#include <sc_tool/utils/InsertionOrderSet.h>
#include <sc_tool/cthread/ScThreadVerilogGen.h>
#include <sc_tool/cthread/ScCThreadStates.h>
#include <sc_tool/elab/ScElabDatabase.h>
#include <sc_tool/elab/ScVerilogModule.h>
#include <sc_tool/cfg/ScTraverseConst.h>
#include <sc_tool/cfg/ScState.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/Decl.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/Analysis/CFG.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <unordered_map>
#include <queue>
#include <unordered_set>
namespace sc {
/**
* Thread Builder coordinates SC_THREAD/SC_CTHREAD analysis and code generation
*
* Currently it does following things:
* - Runs const propagation for all wait states
* - Creates extra variables to model register by pair of X and X_next variables
* - Runs Verilog code generation for all wait states
*/
class ThreadBuilder {
public:
ThreadBuilder(const clang::ASTContext &astCtx,
sc_elab::ElabDatabase &elabDB,
const sc_elab::ProcessView procView,
std::shared_ptr<ScState> globalState,
const SValue &modval,
const SValue &dynmodval
);
/**
* @param constPropOnly - run constant propagation only,
* without Verilog generation
*
* @return generated code
*/
sc_elab::VerilogProcCode run(bool constPropOnly);
const clang::CFG * getCurrentCFG(const CfgCursorStack &callStack,
const SValue & dynModVal);
const clang::FunctionDecl* getCurrentFuncDecl(
const CfgCursorStack &callStack,
const SValue & dynModVal);
/// If callCursor is function call, returns CallExpr, otherwise nullptr
const clang::CallExpr * getCursorCallExpr(const CfgCursor &callCursor);
private:
/// Run constant propagation for all states
void runConstProp();
/// Run constant propagation for a single state (starting from wait() call)
void runConstPropForState(WaitID stateID);
/// Analyze UseDef analysis results to create registers
void analyzeUseDefResults(const ScState *finalState);
/// Generate Verilog for thread body
void runVerilogGeneration();
/// Generate Verilog for a single state
/// Fill @traverseContextMap and return reachable wait IDs
std::set<WaitID> generateVerilogForState(WaitID stateID);
/// Generate Verilog module variables for registers discovered in thread
void generateThreadLocalVariables();
const clang::SourceManager &sm;
const clang::ASTContext &astCtx;
CfgFabric &cfgFab;
const clang::FunctionDecl * entryFuncDecl;
FindWaitCallVisitor findWaitVisitor;
sc_elab::ElabDatabase &elabDB;
std::shared_ptr<sc::ScState> globalState;
const SValue &modSval;
const SValue &dynModSval;
// Filled by local CPA, contains call stack for wait`s
ScCThreadStates threadStates;
/// Registers assigned by thread
InsertionOrderSet<SValue> threadRegVars;
/// Thread-local combinational variables
InsertionOrderSet<SValue> threadCombVars;
/// Read-only constant or channel variables
InsertionOrderSet<SValue> threadReadOnlyVars;
/// Read but not defined non-constant non-channel variable,
/// used to report error
InsertionOrderSet<SValue> threadReadNotDefVars;
/// Read non-channel variable, used to register the variable as used
std::unordered_set<SValue> threadReadVars;
bool isSingleState;
std::unordered_map<WaitID, ScProcContext> traverseContextMap;
const sc_elab::ProcessView procView;
// States to be analyzed, reachable state from previous state
std::set<WaitID> scheduledStates;
// Previously visited state, CPA start each wait() only once
std::set<WaitID> visitedStates;
std::unique_ptr<ScThreadVerilogGen> vGen;
std::unique_ptr<ScTraverseConst> globalConstProp;
// Name and next name
std::pair<std::string, std::string> waitNRegNames;
std::pair<std::string, std::string> stateRegNames;
};
} // namespace sc
#endif //SCTOOL_SCTHREADBUILDER_H
| 31.86755 | 81 | 0.682253 | [
"model"
] |
8e96611dae18dce8b985c212c7d03961b78f9118 | 1,557 | h | C | src/common/config_file.h | maxest/MaxestFramework | aa396c2e15543ba4d62bb5cf908c3919e4e84fb7 | [
"MIT"
] | 9 | 2018-09-16T14:12:35.000Z | 2021-06-20T19:03:11.000Z | src/common/config_file.h | maxest/MaxestFramework | aa396c2e15543ba4d62bb5cf908c3919e4e84fb7 | [
"MIT"
] | null | null | null | src/common/config_file.h | maxest/MaxestFramework | aa396c2e15543ba4d62bb5cf908c3919e4e84fb7 | [
"MIT"
] | 3 | 2018-06-08T13:57:03.000Z | 2018-11-21T12:54:18.000Z | #include "../essentials/string.h"
#include "../essentials/file.h"
namespace NMaxestFramework { namespace NCommon
{
class CConfigFile
{
public:
CConfigFile()
{
fileOpened = false;
}
void Open(const string& path)
{
this->path = path;
if (file.Open(path, NEssentials::CFile::EOpenMode::ReadText))
{
fileOpened = true;
while (!file.EndOfFile())
{
string word1, word2;
file.ReadText(word1);
file.ReadText(word2);
if (word1 != "" && word2 != "")
{
pair<string, string> keyValue;
keyValue.first = word1;
keyValue.second = word2;
options.push_back(keyValue);
}
}
}
}
void Close()
{
if (fileOpened)
file.Close();
fileOpened = false;
if (file.Open(path, NEssentials::CFile::EOpenMode::WriteText))
{
for (uint i = 0; i < options.size(); i++)
file.WriteText(options[i].first + " " + options[i].second + "\n");
file.Close();
}
}
template<typename TYPE> void Process(const string& key, TYPE& value)
{
for (uint i = 0; i < options.size(); i++)
{
if (options[i].first == key)
{
value = FromString(options[i].second, value);
return;
}
}
// not found, add
pair<string, string> keyValue;
keyValue.first = key;
keyValue.second = ToString(value);
options.push_back(keyValue);
}
private:
string path;
NEssentials::CFile file;
bool fileOpened;
vector< pair<string, string> > options;
};
} }
| 19.708861 | 72 | 0.563263 | [
"vector"
] |
8e982765a9d11bead8b7a5190b86316d6fe4d813 | 36,059 | h | C | NEST-14.0-FPGA/nestkernel/nest_names.h | OpenHEC/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 45 | 2019-12-09T06:45:53.000Z | 2022-01-29T12:16:41.000Z | NEST-14.0-FPGA/nestkernel/nest_names.h | zlchai/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 2 | 2020-05-23T05:34:21.000Z | 2021-09-08T02:33:46.000Z | NEST-14.0-FPGA/nestkernel/nest_names.h | OpenHEC/SNN-simulator-on-PYNQcluster | 14f86a76edf4e8763b58f84960876e95d4efc43a | [
"MIT"
] | 10 | 2019-12-09T06:45:59.000Z | 2021-03-25T09:32:56.000Z | /*
* nest_names.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST 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.
*
* NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef NEST_NAMES_H
#define NEST_NAMES_H
// Includes from sli:
#include "name.h"
namespace nest
{
/**
* This namespace contains global Name objects. These can be used in
* Node::get_status and Node::set_status to make data exchange
* more efficient and consistent. Creating a Name from a std::string
* is in O(log n), for n the number of Names already created. Using
* predefined names should make data exchange much more efficient.
*/
namespace names
{
extern const Name a; //!< Specific to Brette & Gerstner 2005 (aeif_cond-*)
extern const Name a_acausal; //!< Used by stdp_connection_facetshw_hom
extern const Name a_causal; //!< Used by stdp_connection_facetshw_hom
extern const Name A_lower;
extern const Name A_mean;
extern const Name A_minus; //!< Used by stdp_dopa_connection
extern const Name A_plus; //!< Used by stdp_dopa_connection
extern const Name A_std;
extern const Name a_thresh_th; //!< Used by stdp_connection_facetshw_hom
extern const Name a_thresh_tl; //!< Used by stdp_connection_facetshw_hom
extern const Name A_upper;
extern const Name acceptable_latency; //!< Used in music_message_in_proxy
extern const Name accumulator; //!< Recorder parameter
extern const Name Act_h; //!< Specific to Hodgkin Huxley models
extern const Name Act_m; //!< Specific to Hodgkin Huxley models
extern const Name activity; //!< Used in pulsepacket_generator
extern const Name address; //!< Node parameter
extern const Name ahp_bug; //!< Used in iaf_chxk_2008
extern const Name allow_offgrid_spikes; //!< Used in spike_generator
extern const Name allow_offgrid_times; //!< Used in step_current_generator
extern const Name alpha; //!< stdp_synapse parameter
extern const Name alpha_1; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name alpha_2; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name Aminus; //!< Used by stdp_connection_facetshw_hom
extern const Name Aminus_triplet; //!< Used by stdp_connection_facetshw_hom
extern const Name AMPA;
extern const Name amplitude; //!< Signal modulation amplitude
extern const Name amplitude_times; //!< Used by sted_current_generator
extern const Name amplitude_values; //!< Used by sted_current_generator
extern const Name Aplus; //!< Used by stdp_connection_facetshw_hom
extern const Name Aplus_triplet; //!< Used by stdp_connection_facetshw_hom
extern const Name archiver_length; //!< used for ArchivingNode
extern const Name available; //!< model paramater
extern const Name autapses; //!< Connectivity-related
extern const Name b; //!< Specific to Brette & Gerstner 2005 (aeif_cond-*)
extern const Name beta; //!< Specific to amat2_*
extern const Name
beta_Ca; //!< Increment in calcium concentration with each spike
extern const Name binary; //!< Recorder parameter
extern const Name c; //!< Specific to Izhikevich 2003
extern const Name c_1; //!< Specific to stochastic neuron pp_psc_delta
extern const Name c_2; //!< Specific to stochastic neuron pp_psc_delta
extern const Name c_3; //!< Specific to stochastic neuron pp_psc_delta
extern const Name C_m; //!< Membrane capacitance
extern const Name Ca; //!< Calcium concentration
extern const Name calibrate; //!< Command to calibrate the neuron (sli_neuron)
extern const Name
calibrate_node; //!< Command to calibrate the neuron (sli_neuron)
extern const Name capacity; //!< model paramater
extern const Name clear; //!< used for ArchivingNode
extern const Name close_after_simulate; //!< Recorder parameter
extern const Name close_on_reset; //!< Recorder parameter
extern const Name
coeff_ex; //!< tau_lcm=coeff_ex*tau_ex (precise timing neurons (Brette 2007))
extern const Name
coeff_in; //!< tau_lcm=coeff_in*tau_in (precise timing neurons (Brette 2007))
extern const Name
coeff_m; //!< tau_lcm=coeff_m*tau_m (precise timing neurons (Brette 2007))
extern const Name configbit_0; //!< Used in stdp_connection_facetshw_hom
extern const Name configbit_1; //!< Used in stdp_connection_facetshw_hom
extern const Name connection_count; //!< Parameters for MUSIC devices
extern const Name consistent_integration; //!< Specific to Izhikevich 2003
extern const Name continuous; //!< Parameter for MSP dynamics
extern const Name count_covariance; //!< Specific to correlomatrix_detector
extern const Name count_histogram; //!< Specific to correlation_detector
extern const Name covariance; //!< Specific to correlomatrix_detector
extern const Name currents; //!< Recorder parameter
extern const Name customdict; //!< Used by Subnet
extern const Name d; //!< Specific to Izhikevich 2003
extern const Name D_lower;
extern const Name D_mean;
extern const Name D_std;
extern const Name D_upper;
extern const Name data; //!< Used in music_message_in_proxy
extern const Name data_path; //!< Data path, used by io_manager
extern const Name data_prefix; //!< Data prefix, used by io_manager
extern const Name
dead_time; //!< Specific to ppd_sup_generator and gamma_sup_generator
extern const Name dead_time_random; //!< Random dead time or fixed dead time
//!< (stochastic neuron pp_psc_delta)
extern const Name dead_time_shape; //!< Shape parameter of the dead time
//!< distribution (stochastic neuron pp_psc_delta)
extern const Name delay; //!< Connection parameters
extern const Name delays; //!< Connection parameters
extern const Name deliver_interval; //!< Used by volume_transmitter
extern const Name delta_P; //!< specific to Hill & Tononi 2005
extern const Name Delta_T; //!< Specific to Brette & Gerstner 2005 (aeif_cond-*)
extern const Name delta_tau; //!< Specific to correlation_and correlomatrix
//!< detector
extern const Name Delta_V; //!< Specific to gif models
extern const Name delta_u; //!< Specific to population point process model
//!< (pp_pop_psc_delta)
extern const Name dg; //!< Derivative of the conductance
extern const Name dg_ex; //!< Derivative of the excitatory conductance
extern const Name dg_in; //!< Derivative of the inhibitory conductance
extern const Name dI_syn_ex; //!< Derivative of the excitatory synaptic current
extern const Name dI_syn_in; //!< Derivative of the inhibitory synaptic current
extern const Name dict_miss_is_error; //!< Used by logging_manager
extern const Name diffusion_factor; //!< Specific to diffusion connection
extern const Name distal_curr; //!< Used by iaf_cond_alpha_mc
extern const Name distal_exc; //!< Used by iaf_cond_alpha_mc
extern const Name distal_inh; //!< Used by iaf_cond_alpha_mc
extern const Name distribution; //!< Connectivity-related
extern const Name drift_factor; //!< Specific to diffusion connection
extern const Name driver_readout_time; //!< Used by stdp_connection_facetshw_hom
extern const Name dt; //!< Miscellaneous parameters
extern const Name
dU; //!< Unit increment of the utilization for a facilitating synapse [0...1]
//!< (Tsodyks2_connection)
extern const Name E_ahp; //!< Specific to iaf_chxk_2008 neuron
extern const Name E_ex; //!< Excitatory reversal potential
extern const Name E_in; //!< Inhibitory reversal potential
extern const Name E_K; //!< Potassium reversal potential
extern const Name E_L; //!< Resting potential
extern const Name E_Na; //!< Sodium reversal potential
extern const Name E_rev; //!< Reversal potential (array)
extern const Name E_rev_AMPA; //!< specific to Hill & Tononi 2005
extern const Name E_rev_GABA_A; //!< specific to Hill & Tononi 2005
extern const Name E_rev_GABA_B; //!< specific to Hill & Tononi 2005
extern const Name E_rev_h; //!< specific to Hill & Tononi 2005
extern const Name E_rev_KNa; //!< specific to Hill & Tononi 2005
extern const Name E_rev_NaP; //!< specific to Hill & Tononi 2005
extern const Name E_rev_NMDA; //!< specific to Hill & Tononi 2005
extern const Name E_rev_T; //!< specific to Hill & Tononi 2005
extern const Name E_rr; //!< Other adaptation
extern const Name E_sfa; //!< Other adaptation
extern const Name element_type; //!< Node type
extern const Name elementsize; //!< Used in genericmodel
extern const Name epoch;
extern const Name eps; //!< MSP growth curve parameter
extern const Name equilibrate; //!< specific to ht_neuron
extern const Name error; //!< Indicates an error (sli_neuron)
extern const Name eta; //!< MSP growth curve parameter
extern const Name events; //!< Recorder parameter
extern const Name
ex_spikes; //!< Number of arriving excitatory spikes (sli_neuron)
extern const Name F_lower;
extern const Name F_mean;
extern const Name F_std;
extern const Name F_upper;
extern const Name fbuffer_size; //!< Recorder parameter
extern const Name file; //!< Recorder parameter
extern const Name file_extension; //!< Recorder parameter
extern const Name filename; //!< Recorder parameter
extern const Name
filenames; //!< Recorder parameter---keep, will disappear with NESTIO
extern const Name flush_after_simulate; //!< Recorder parameter
extern const Name flush_records; //!< Recorder parameter
extern const Name frequency; //!< Signal modulation frequency
extern const Name frozen; //!< Node parameter
extern const Name g; //!< Conductance or gain scaling in rate models
extern const Name g_AMPA; //!< specific to Hill & Tononi 2005
extern const Name g_ahp; //!< Specific to iaf_chxk_2008 neuron
extern const Name g_ex; //!< Excitatory conductance
extern const Name g_GABA_A; //!< specific to Hill & Tononi 2005
extern const Name g_GABA_B; //!< specific to Hill & Tononi 2005
extern const Name g_in; //!< inhibitory conductance
extern const Name g_K; //!< Potassium conductance
extern const Name g_KL; //!< specific to Hill & Tononi 2005
extern const Name g_Kv1; //!< Kv1 Potassium conductance
extern const Name g_Kv3; //!< Kv3 Potassium conductance
extern const Name g_L; //!< Leak conductance
extern const Name g_Na; //!< Sodium conductance
extern const Name g_NaL; //!< specific to Hill & Tononi 2005
extern const Name g_NMDA; //!< specific to Hill & Tononi 2005
extern const Name g_peak_AMPA; //!< specific to Hill & Tononi 2005
extern const Name g_peak_GABA_A; //!< specific to Hill & Tononi 2005
extern const Name g_peak_GABA_B; //!< specific to Hill & Tononi 2005
extern const Name g_peak_h; //!< specific to Hill & Tononi 2005
extern const Name g_peak_KNa; //!< specific to Hill & Tononi 2005
extern const Name g_peak_NaP; //!< specific to Hill & Tononi 2005
extern const Name g_peak_NMDA; //!< specific to Hill & Tononi 2005
extern const Name g_peak_T; //!< specific to Hill & Tononi 2005
extern const Name g_pd; //!< Used by iaf_cond_alpha_mc
extern const Name g_rr; //!< Other adaptation
extern const Name g_sfa; //!< Other adaptation
extern const Name g_sp; //!< Used by iaf_cond_alpha_mc
extern const Name GABA_A;
extern const Name GABA_B;
extern const Name gamma; //!< Specific to mirollo_strogatz_ps
extern const Name gamma_shape; //!< Specific to ppd_sup_generator and
//!< gamma_sup_generator
extern const Name gaussian; //!< Parameter for MSP growth curves
extern const Name global_id; //!< Node parameter
extern const Name grng; //!< Used in rng_manager
extern const Name grng_seed; //!< Seed
extern const Name growth_curve; //!< Growth curve for MSP dynamics
extern const Name growth_rate; //!< Parameter of the growth curve for MSP
//!< dynamics
extern const Name gsl_error_tol; //!< GSL integrator tolerance
extern const Name h; //!< Summed input to a neuron (Ginzburg neuron)
extern const Name has_connections; //!< Specific to iaf_psc_exp_multisynapse and
//!< iaf_psc_alpha_multisynapse
extern const Name has_delay; //!< Used in connector_model_impl
extern const Name histogram; //!< Specific to correlation_detector
extern const Name histogram_correction; //!< Specific to correlation_detector
extern const Name HMIN; //!< Smallest integration step for adaptive stepsize
//!< (Brette & Gerstner 2005)
extern const Name I; //!< mirollo_strogatz_ps, StimulatingDevice
extern const Name I_adapt; //!< Goal of current homeostasis
//!< (current homeostasis)
extern const Name I_ahp; //!< Used in iaf_chxk_2008
extern const Name I_e; //!< Input current
extern const Name I_ex; //!< Excitatory synaptic input current
extern const Name I_h; //!< specific to Hill & Tononi 2005
extern const Name I_in; //!< Inhibitory synaptic input current
extern const Name I_KNa; //!< specific to Hill & Tononi 2005
extern const Name I_L; //!< Leak current
extern const Name I_NaP; //!< specific to Hill & Tononi 2005
extern const Name I_stc; //!< relevant for gif models
extern const Name I_std; //!< Standard deviation of current distribution
//!< (current homeostasis)
extern const Name I_syn; //!< used for iaflossless_count_exp
extern const Name I_syn_ex; //!< Total excitatory synaptic current
//!< (iaf_tum_2000)
extern const Name I_syn_in; //!< Total inhibitory synaptic current
//!< (iaf_tum_2000)
extern const Name I_T; //!< specific to Hill & Tononi 2005
extern const Name I_total; //!< Total current (current homeostasis)
extern const Name
in_spikes; //!< Number of arriving inhibitory spikes (sli_neuron)
extern const Name Inact_n; //!< Specific to Hodgkin Huxley models
extern const Name
Inact_p; //!< Specific to Hodgkin Huxley models with gap junctions
extern const Name indegree; //!< In FixedInDegreeBuilder
extern const Name index_map; //!< Parameters for MUSIC devices
extern const Name individual_spike_trains; //!< Generator parameters
extern const Name inh_conductance; //!< Recorder parameter
extern const Name init_flag; //!< Used by stdp_connection_facetshw_hom
extern const Name instant_unblock_NMDA; //!< specific to Hill-Tononi
extern const Name instantiations; //!< model paramater
extern const Name
Interpol_Order; //!< Interpolation order (precise timing neurons)
extern const Name interval; //!< Recorder parameter
extern const Name is_refractory; //!< Neuron is in refractory period (debugging)
extern const Name Kplus; //!< Used by stdp_connection_facetshw_hom
extern const Name Kplus_triplet; //!< Used by stdp_connection_facetshw_hom
extern const Name label; //!< Miscellaneous parameters
extern const Name lambda; //!< stdp_synapse parameter
extern const Name lambda_0; //!< Specific to gif models
extern const Name len_kernel; //!< Specific to population point process model
//!< (pp_pop_psc_delta)
extern const Name linear; //!< Parameter for MSP growth curves
extern const Name linear_summation; //!< Specific to rate models
extern const Name local; //!< Node parameter
extern const Name local_id; //!< Node
extern const Name local_num_threads; //!< Local number of threads
extern const Name local_spike_counter; //!< Used by event_delivery_manager
extern const Name lookuptable_0; //!< Used in stdp_connection_facetshw_hom
extern const Name lookuptable_1; //!< Used in stdp_connection_facetshw_hom
extern const Name lookuptable_2; //!< Used in stdp_connection_facetshw_hom
extern const Name make_symmetric; //!< Connectivity-related
extern const Name max_delay; //!< In ConnBuilder
extern const Name MAXERR; //!< Largest permissible error for adaptive stepsize
//!< (Brette & Gerstner 2005)
extern const Name mean; //!< Miscellaneous parameters
extern const Name memory; //!< Recorder parameter
extern const Name message_times; //!< Used in music_message_in_proxy
extern const Name messages; //!< Used in music_message_in_proxy
extern const Name min_delay; //!< In ConnBuilder
extern const Name model; //!< Node parameter
extern const Name mother_rng; //!< Specific to mip_generator
extern const Name mother_seed; //!< Specific to mip_generator
extern const Name ms_per_tic; //!< Simulation-related
extern const Name mu; //!< Used by stdp_dopa_connection
extern const Name mu_minus; //!< stdp_synapse parameter
extern const Name mu_plus; //!< stdp_synapse parameter
extern const Name multapses; //!< Connectivity-related
extern const Name music_channel; //!< Parameters for MUSIC devices
extern const Name n; //!< Number of synaptic release sites (int >=0)
//!< (Tsodyks2_connection)
extern const Name N; //!< Specific to population point process model
//!< (pp_pop_psc_delta)
extern const Name N_channels; //!< Specific to correlomatrix_detector
extern const Name n_events; //!< Recorder parameter
extern const Name n_messages; //!< Used in music_message_in_proxy
extern const Name
n_proc; //!< Number of component processes of ppd_sup_/gamma_sup_generator
extern const Name n_receptors; //!< number of receptor ports
extern const Name n_synapses;
extern const Name neuron; //!< Node type
extern const Name network_size; //!< Network size
extern const Name next_readout_time; //!< Used by stdp_connection_facetshw_hom
extern const Name NMDA;
extern const Name node_uses_wfr; //!< Node parameter
extern const Name noise; //!< Specific to iaf_chs_2008 neuron
//!< and rate models
extern const Name noisy_rate; //!< Specific to rate models
extern const Name no_synapses; //!< Used by stdp_connection_facetshw_hom
extern const Name num_connections; //!< In ConnBuilder
extern const Name num_processes; //!< Number of processes
extern const Name number_of_children; //!< Used by Subnet
extern const Name off_grid_spiking; //!< Used by event_delivery_manager
extern const Name offset; //!< Miscellaneous parameters
extern const Name offsets; //!< Recorder parameter
extern const Name omega; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name order; //!< Specific to sinusoidally modulated generators
extern const Name origin; //!< Device parameters
extern const Name other; //!< Node type
extern const Name outdegree; //!< In FixedOutDegreeBuilder
extern const Name overwrite_files; //!< Used in io_manager
extern const Name P; //!< specific to Hill & Tononi 2005
extern const Name p; //!< current release probability (Tsodyks2_connection)
extern const Name p_copy; //!< Specific to mip_generator
extern const Name p_transmit; //!< Specific to bernoulli_synapse
extern const Name parent; //!< Node parameter
extern const Name phase; //!< Signal phase in degrees
extern const Name phi; //!< Specific to mirollo_strogatz_ps
extern const Name phi_th; //!< Specific to mirollo_strogatz_ps
extern const Name port; //!< Connection parameters
extern const Name ports; //!< Recorder parameter
extern const Name port_name; //!< Parameters for MUSIC devices
extern const Name port_width; //!< Parameters for MUSIC devices
extern const Name post_synaptic_element; //!< Post synaptic elements
extern const Name potentials; //!< Recorder parameter
extern const Name pre_synaptic_element; //!< Pre synaptic elements
extern const Name precise_times; //!< Recorder parameter
extern const Name precision; //!< Recorder parameter
extern const Name print_time; //!< Simulation-related
extern const Name proximal_curr; //!< Used by iaf_cond_alpha_mc
extern const Name proximal_exc; //!< Used by iaf_cond_alpha_mc
extern const Name proximal_inh; //!< Used by iaf_cond_alpha_mc
extern const Name PSC_adapt_step; //!< PSC increment (current homeostasis)
extern const Name PSC_Unit_amplitude; //!< Scaling of PSC (current homeostasis)
extern const Name psi; //!< Width parameter for sigmoid growth curve
extern const Name published; //!< Parameters for MUSIC devices
extern const Name pulse_times; //!< used in pulsepacket:generator
extern const Name q_rr; //!< Other adaptation
extern const Name q_sfa; //!< Other adaptation
extern const Name q_stc; //!< Specific to gif models
extern const Name rate; //!< Specific to ppd_sup_generator,
//!< gamma_sup_generator and rate models
extern const Name readout_cycle_duration; //!< Used by
//!< stdp_connection_facetshw_hom
extern const Name receive_buffer_size; //!< mpi-related
extern const Name receptor_type; //!< Connection parameter
extern const Name receptor_types; //!< Publishing available types
extern const Name receptors; //!< Used in mpi_manager
extern const Name record_from; //!< Recorder parameter
extern const Name record_to; //!< Recorder parameter
extern const Name
recordables; //!< List of recordable state data (Device parameters)
extern const Name recorder; //!< Node type
extern const Name
refractory_input; //!< Spikes arriving during refractory period are counted
//!< (precise timing neurons)
extern const Name registered; //!< Parameters for MUSIC devices
extern const Name
relative_amplitude; //!< Signal modulation amplitude relative to mean
extern const Name reset_pattern; //!< Used in stdp_connection_facetshw_hom
extern const Name resolution; //!< Time resolution
extern const Name requires_symmetric; //!< Used in connector_model_impl
extern const Name rho_0; //!< Specific to population point process model
//!< (pp_pop_psc_delta)
extern const Name rms; //!< Root mean square
extern const Name rng_seeds; //!< Used in rng_manager
extern const Name root_finding_epsilon; //!< Accuracy of the root of the
//!< polynomial (precise timing neurons (Brette 2007))
extern const Name rport; //!< Connection parameters
extern const Name rports; //!< Recorder parameter
extern const Name rule; //!< Connectivity-related
extern const Name S; //!< Binary state (output) of neuron (Ginzburg neuron)
extern const Name S_act_NMDA; //!< specific to Hill & Tononi 2005
extern const Name scientific; //!< Recorder parameter
extern const Name screen; //!< Recorder parameter
extern const Name sdev; //!< Used in pulsepacket_generator
extern const Name send_buffer_size; //!< mpi-related
extern const Name senders; //!< Recorder parameter
extern const Name shift_now_spikes; //!< Used by spike_generator
extern const Name sigmoid; //!< Sigmoid MSP growth curve
extern const Name size_of; //!< Connection parameters
extern const Name soma_curr; //!< Used by iaf_cond_alpha_mc
extern const Name soma_exc; //!< Used by iaf_cond_alpha_mc
extern const Name soma_inh; //!< Used by iaf_cond_alpha_mc
extern const Name source; //!< Connection parameters
extern const Name spike; //!< true if the neuron spikes and false if not.
//!< (sli_neuron)
extern const Name spike_multiplicities; //!x Used by spike_generator
extern const Name spike_times; //!< Recorder parameter
extern const Name spike_weights; //!< Used by spike_generator
extern const Name start; //!< Device parameters
extern const Name state; //!< Node parameter
extern const Name std; //!< Miscellaneous parameters
extern const Name std_mod; //!< Miscellaneous parameters
extern const Name stimulator; //!< Node type
extern const Name stop; //!< Device parameters
extern const Name structural_plasticity_synapses; //!< Synapses defined for
// structural plasticity
extern const Name structural_plasticity_update_interval; //!< Update interval
// for structural
// plasticity
extern const Name structure; //!< Node type
extern const Name success;
extern const Name supports_precise_spikes; //!< true if model supports precise
//!< spikes
extern const Name synapse; //!< Node type
extern const Name synapse_id; //!< Used by stdp_connection_facetshw_hom
extern const Name synapse_label; //!< Label id of synapses with labels
extern const Name synapse_model; //!< Connection parameters
extern const Name synapse_modelid; //!< Connection parameters
extern const Name synapses_per_driver; //!< Used by stdp_connection_facetshw_hom
extern const Name synaptic_elements; //!< Synaptic elements used in structural
//!< plasticity
extern const Name synaptic_elements_param; //!< Used to update parameters
//!< of synaptic elements
extern const Name t_lag; //!< Lag within a time slice
extern const Name T_min; //!< Minimum time
extern const Name T_max; //!< Maximum time
extern const Name t_origin; //!< Origin of a time-slice
extern const Name t_ref; //!< Refractory period
extern const Name t_ref_abs; //!< Absolute refractory period, iaf_tum_2000
extern const Name
t_ref_remaining; //!< Time remaining till end of refractory state
extern const Name t_ref_tot; //!< Total refractory period, iaf_tum_2000
extern const Name t_spike; //!< Time of last spike
extern const Name target; //!< Connection parameters
extern const Name target_thread; //!< Connection parameters
extern const Name targets; //!< Connection parameters
extern const Name tau; //!< Used by stdp_connection_facetshw_hom
//!< and rate models
extern const Name tau_1; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name tau_2; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name tau_ahp; //!< Specific to iaf_chxk_2008 neuron
extern const Name tau_Ca; //!< Rate of loss of calcium concentration
extern const Name tau_c; //!< Used by stdp_dopa_connection
extern const Name tau_D_KNa; //!< specific to Hill & Tononi 2005
extern const Name tau_decay; //!< Synapse decay constant (beta fct decay)
extern const Name tau_decay_AMPA; //!< specific to Hill & Tononi 2005
extern const Name tau_decay_GABA_A; //!< specific to Hill & Tononi 2005
extern const Name tau_decay_GABA_B; //!< specific to Hill & Tononi 2005
extern const Name tau_decay_NMDA; //!< specific to Hill & Tononi 2005
extern const Name tau_epsp; //!< Specific to iaf_chs_2008 neuron
extern const Name tau_eta; //!< Specific to population point process model
//!< (pp_pop_psc_delta)
extern const Name
tau_fac; //!< facilitation time constant (ms) (Tsodyks2_connection)
extern const Name
tau_lcm; //!< Least common multiple of tau_m, tau_ex and tau_in
//!< (precise timing neurons (Brette 2007))
extern const Name tau_m; //!< Membrane time constant
extern const Name
tau_max; //!< Specific to correlation_and correlomatrix detector
extern const Name tau_Mg_fast_NMDA; //!< specific to Hill & Tononi 2005
extern const Name tau_Mg_slow_NMDA; //!< specific to Hill & Tononi 2005
extern const Name tau_minus; //!< used for ArchivingNode
extern const Name tau_minus_stdp; //!< Used by stdp_connection_facetshw_hom
extern const Name tau_minus_triplet; //!< used for ArchivingNode
extern const Name tau_n; //!< Used by stdp_dopa_connection
extern const Name tau_P; //!< specific to Hill & Tononi 2005
extern const Name tau_plus; //!< stdp_synapse parameter
extern const Name tau_plus_triplet; //!< Used by stdp_connection_facetshw_hom
extern const Name tau_psc; //!< Used by stdp_connection_facetshw_hom
extern const Name
tau_rec; //!< time constant for recovery (ms) (Tsodyks2_connection)
extern const Name tau_reset; //!< Specific to iaf_chs_2008 neuron
extern const Name tau_rise; //!< Synapse rise constant (beta fct rise)
extern const Name tau_rise_AMPA; //!< specific to Hill & Tononi 2005
extern const Name tau_rise_GABA_A; //!< specific to Hill & Tononi 2005
extern const Name tau_rise_GABA_B; //!< specific to Hill & Tononi 2005
extern const Name tau_rise_NMDA; //!< specific to Hill & Tononi 2005
extern const Name tau_rr; //!< Other adaptation
extern const Name tau_sfa; //!< Other adaptation
extern const Name tau_spike; //!< Specific to Hill-Tononi (2005)
extern const Name tau_stc; //!< Specific to gif models
extern const Name tau_syn; //!< Synapse time constant
extern const Name tau_syn_ex; //!< Excitatory synaptic time constant
extern const Name tau_syn_in; //!< Inhibitory synaptic time constant
extern const Name tau_theta; //!< Specific to Hill-Tononi (2005)
extern const Name tau_v; //!< Specific to amat2_*
extern const Name tau_vacant; //!< Parameter for MSP dynamics
extern const Name tau_w; //!< Specific to Brette & Gerstner 2005 (aeif_cond-*)
extern const Name theta; //!< Did not compile without (theta neuron problem)
extern const Name theta_eq; //!< specific to Hill & Tononi 2005
extern const Name thread; //!< Node parameter
extern const Name thread_local_id; //!< Thead-local ID of node,
//!< see Kunkel et al 2014, Sec 3.3.2
extern const Name tics_per_ms; //!< Simulation-related
extern const Name tics_per_step; //!< Simulation-related
extern const Name time_in_steps; //!< Recorder parameter
extern const Name time; //!< Simulation-related
extern const Name time_collocate; //!< Used by event_delivery_manager
extern const Name time_communicate; //!< Used by event_delivery_manager
extern const Name times; //!< Recorder parameter
extern const Name to_accumulator; //!< Recorder parameter
extern const Name to_do; //!< Simulation-related
extern const Name to_file; //!< Recorder parameter
extern const Name to_memory; //!< Recorder parameter
extern const Name to_screen; //!< Recorder parameter
extern const Name total_num_virtual_procs; //!< Total number virtual processes
extern const Name Tstart; //!< Specific to correlation and
//!< correlomatrix detector
extern const Name Tstop; //!< Specific to correlation and correlomatrix detector
extern const Name type_id; //!< model paramater
extern const Name u; //!< probability of release [0...1] (Tsodyks2_connection)
extern const Name U; //!< Used by stdp_connection_facetshw_hom
extern const Name U_lower;
extern const Name U_m; //!< Specific to Izhikevich 2003
extern const Name U_mean;
extern const Name U_std;
extern const Name U_upper;
extern const Name update; //!< Command to execute the neuron (sli_neuron)
extern const Name update_node; //!< Command to execute the neuron (sli_neuron)
extern const Name use_wfr; //!< Simulation-related
extern const Name use_gid_in_filename; //!< use gid in the filename
extern const Name V_act_NMDA; //!< specific to Hill & Tononi 2005
extern const Name V_epsp; //!< Specific to iaf_chs_2008 neuron
extern const Name V_m; //!< Membrane potential
extern const Name V_min; //!< Absolute lower value for the membrane potential
extern const Name V_noise; //!< Specific to iaf_chs_2008 neuron
extern const Name
V_peak; //!< Spike detection threshold (Brette & Gerstner 2005)
extern const Name V_reset; //!< Reset potential
extern const Name V_T; //!< Voltage offset
extern const Name V_T_star; //!< Specific to gif models
extern const Name V_th; //!< Threshold
extern const Name
V_th_alpha_1; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name
V_th_alpha_2; //!< Specific to Kobayashi, Tsubo, Shinomoto 2009
extern const Name V_th_v; //!< Specific to amat2_*
extern const Name
val_eta; //!< Specific to population point process model (pp_pop_psc_delta)
extern const Name voltage_clamp; //!< Enforce voltage clamp
extern const Name vt; //!< Used by stdp_dopa_connection
extern const Name vp; //!< Node parameter
extern const Name w; //!< Specific to Brette & Gerstner 2005 (aeif_cond-*)
extern const Name weight; //!< Connection parameters
extern const Name weight_per_lut_entry; //!< Used by
//!< stdp_connection_facetshw_hom
extern const Name weight_std; //!< Standard deviation/mean of noisy synapse.
extern const Name weighted_spikes_ex; //!< Weighted incoming excitatory spikes
extern const Name weighted_spikes_in; //!< Weighted incoming inhibitory spikes
extern const Name weights; //!< Connection parameters --- topology
extern const Name weight_recorder; //!< Device name
extern const Name wfr_comm_interval; //!< Simulation-related
extern const Name wfr_interpolation_order; //!< Simulation-related
extern const Name wfr_max_iterations; //!< Simulation-related
extern const Name wfr_tol; //!< Simulation-related
extern const Name with_noise; //!< Simulation-related
extern const Name with_reset; //!< Shall the pp_neuron reset after each spike?
//!< (stochastic neuron pp_psc_delta)
extern const Name withgid; //!< Recorder parameter
extern const Name withpath; //!< Recorder parameter
extern const Name withport; //!< Recorder parameter
extern const Name withrport; //!< Recorder parameter
extern const Name withtargetgid; //!< Recorder parameter
extern const Name withtime; //!< Recorder parameter
extern const Name withweight; //!< Recorder parameter
extern const Name Wmax; //!< stdp_synapse parameter
extern const Name Wmin; //!< Used by stdp_dopa_connection
extern const Name x; //!< current scaling factor of the synaptic weight [0...1]
//!< (Tsodyks2_connection)
extern const Name y; //!< Used by stdp_connection_facetshw_hom
extern const Name y_0; //!< Used by ac_generator
extern const Name y_1; //!< Used by ac_generator
extern const Name y1; //!< Used in iaf_psc_alpha_canon
extern const Name y2; //!< Used in iaf_psc_alpha_canon
extern const Name z; //!< Number of available synaptic elements per node
extern const Name
z_connected; //!< Number of connected synaptic elements per node
}
}
#endif
| 57.327504 | 80 | 0.697829 | [
"shape",
"model"
] |
8e9868f55e45fd4e8d30bb7ba40ac81b9b84c167 | 12,498 | h | C | include/mstdlib/formats/m_csv.h | Monetra/mstdlib | aecbaa0c14a3a618923331250427e175db7ebef9 | [
"BSD-2-Clause"
] | 22 | 2017-09-28T16:12:10.000Z | 2022-03-11T03:21:11.000Z | include/mstdlib/formats/m_csv.h | Monetra/mstdlib | aecbaa0c14a3a618923331250427e175db7ebef9 | [
"BSD-2-Clause"
] | 13 | 2018-03-06T16:24:12.000Z | 2020-03-02T13:25:19.000Z | include/mstdlib/formats/m_csv.h | Monetra/mstdlib | aecbaa0c14a3a618923331250427e175db7ebef9 | [
"BSD-2-Clause"
] | 5 | 2018-03-06T15:54:42.000Z | 2020-03-10T16:02:06.000Z | /* The MIT License (MIT)
*
* Copyright (c) 2015 Monetra Technologies, LLC.
*
* 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.
*/
#ifndef __M_CSV_H__
#define __M_CSV_H__
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#include <mstdlib/base/m_defs.h>
#include <mstdlib/base/m_types.h>
#include <mstdlib/base/m_buf.h>
#include <mstdlib/base/m_list_str.h>
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
__BEGIN_DECLS
/*! \addtogroup m_csv CSV
* \ingroup m_formats
* CSV Parser.
*
* RFC 4180 compliant CSV parser.
*
* The first row in the CSV is assumed to be the header. If there is no
* header the *raw* functions should be used to reterive data. If there
* is a header the non-raw functions should be used. These functions
* take into account the header when indexing rows automatically. The
* first row after the header is index 0.
*
* Example:
*
* \code{.c}
* const char *data = "header1,header1\ncell1,cell2"
* M_csv_t *csv;
* const char *const_temp;
*
* csv = M_csv_parse(data, M_str_len(data), ',', '"', M_CSV_FLAG_NONE);
* const_temp = M_csv_get_header(csv, 0);
* M_printf("header='%s'\n", const_temp);
*
* const_temp = M_csv_get_cellbynum(csv, 0, 1);
* M_printf("cell='%s'\n", const_temp);
*
* M_csv_destroy(csv);
* \endcode
*
* Example output:
*
* \code
* header='header1'
* cell='cell2'
* \endcode
*
* @{
*/
struct M_csv;
typedef struct M_csv M_csv_t;
/*! Flags controlling parse behavior */
enum M_CSV_FLAGS {
M_CSV_FLAG_NONE = 0, /*!< No Flags */
M_CSV_FLAG_TRIM_WHITESPACE = 1 << 0 /*!< If a cell is not quoted, trim leading and trailing whitespace */
};
/*! Callback that can be used to filter rows from data returned by M_csv_output_rows_buf().
*
* \param[in] csv the csv being output.
* \param[in] row the idx of the current row being considered (NOT raw - 0 is the first row after the header).
* \param[in] thunk pointer to thunk object passed into M_csv_output_rows_buf() by caller.
* \return M_TRUE, if the row should be included in output. M_FALSE otherwise.
*/
typedef M_bool (*M_csv_row_filter_cb)(const M_csv_t *csv, size_t row, void *thunk);
/*! Callback that can be used to edit data from certain columns as it's written out.
*
* \param[in] buf buffer to write new version of cell data to.
* \param[in] cell original cell data (may be empty/NULL, if cell was empty)
* \param[in] header header of column this cell came from
* \param[in] thunk pointer to thunk object passed into M_csv_output_rows_buf() by caller.
* \return M_TRUE if we added a modified value to buf. M_FALSE if value was OK as-is.
*/
typedef M_bool (*M_csv_cell_writer_cb)(M_buf_t *buf, const char *cell, const char *header, void *thunk);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/*! Parse a string into a CSV object.
*
* \param[in] data The data to parse.
* \param[in] len The length of the data to parse.
* \param[in] delim CSV delimiter character. Typically comma (",").
* \param[in] quote CSV quote character. Typically double quote (""").
* \param[in] flags Flags controlling parse behavior.
*
* \return CSV object.
*
* \see M_csv_destroy
*/
M_API M_csv_t *M_csv_parse(const char *data, size_t len, char delim, char quote, M_uint32 flags) M_MALLOC;
/*! Parse a string into a CSV object, using given column headers.
*
* Same as M_csv_parse, but add the given headers as the first row before parsing the data into the table.
*
* \param[in] data The data to parse.
* \param[in] len The length of data to parse.
* \param[in] delim CSV delimiter character. Typically comma (',').
* \param[in] quote CSV quote character. Typically double quote ('"').
* \param[in] flags Flags controlling parse behavior.
* \param[in] headers List of headers to add as first row of table.
*
* \return CSV object
*/
M_API M_csv_t *M_csv_parse_add_headers(const char *data, size_t len, char delim, char quote, M_uint32 flags,
M_list_str_t *headers);
/*! Parse a string into a CSV object.
*
* This will take ownership of the data passed in. The data must be valid for the life of the
* returned CSV object and will be destroyed by the CSV object when the CSV object is destroyed.
*
* \param[in] data The string to parse.
* \param[in] len The length of the data to parse.
* \param[in] delim CSV delimiter character. Typically comma (",").
* \param[in] quote CSV quote character. Typically double quote (""").
* \param[in] flags Flags controlling parse behavior.
*
* \return CSV object.
*
* \see M_csv_destroy
*/
M_API M_csv_t *M_csv_parse_inplace(char *data, size_t len, char delim, char quote, M_uint32 flags) M_MALLOC_ALIASED;
/*! Destory a CSV object.
*
* \param[in] csv The csv.
*/
M_API void M_csv_destroy(M_csv_t *csv) M_FREE(1);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Raw getters if no headers used */
/*! Get the raw number of csv rows.
*
* This should be used when the CSV data does not contain a header.
* This count will include the header as a row in the count.
*
* \param[in] csv The csv.
*
* \return The number of rows including the header as a row.
*
* \see M_csv_get_numrows
*/
M_API size_t M_csv_raw_num_rows(const M_csv_t *csv);
/*! Get the raw number of csv columns.
*
* This should be used when the CSV data does not contain a header.
*
* \param[in] csv The csv.
*
* \return The number of columns.
*
* \see M_csv_get_numcols
*/
M_API size_t M_csv_raw_num_cols(const M_csv_t *csv);
/*! Get the cell at the given position.
*
* This should be used when the CSV data does not contain a header.
* This assumes that the first row is data (not the header).
*
* \param[in] csv The csv.
* \param[in] row The row. Indexed from 0 where 0 is the header (if there is a header).
* \param[in] col The column. Indexed from 0.
*
* \return The csv data at the position or NULL if the position if invalid.
*
* \see M_csv_get_cellbynum
*/
M_API const char *M_csv_raw_cell(const M_csv_t *csv, size_t row, size_t col);
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
* Getters if headers used (default) */
/*! Get the number of csv rows.
*
* This should be used when the CSV data contains a header.
* This count will not include the header as a row in the count.
*
* \param[in] csv The csv.
*
* \return The number of rows excluding the header as a row.
*
* \see M_csv_raw_num_rows
*/
M_API size_t M_csv_get_numrows(const M_csv_t *csv);
/*! Get the raw number of csv columns.
*
* This should be used when the CSV data contains a header.
*
* \param[in] csv The csv.
*
* \return The number of columns.
*
* \see M_csv_raw_num_cols
*/
M_API size_t M_csv_get_numcols(const M_csv_t *csv);
/*! Get the cell at the given position.
*
* This should be used when the CSV data contains a header.
* This assumes that the first row is a header (not data).
*
* \param[in] csv The csv.
* \param[in] row The row. Indexed from 0 where 0 is the first row after the header.
* \param[in] col The column. Indexed from 0.
*
* \return The csv data at the position or NULL if the position if invalid.
*
* \see M_csv_raw_cell
*/
M_API const char *M_csv_get_cellbynum(const M_csv_t *csv, size_t row, size_t col);
/*! Get the header for a given column
*
* This should be used when the CSV data contains a header.
* This assumes that the first row is a header (not data).
*
* \param[in] csv The csv.
* \param[in] col The column. Indexed from 0.
*
* \return The header for the given column.
*/
M_API const char *M_csv_get_header(const M_csv_t *csv, size_t col);
/*! Get the cell at the for the given header.
*
* This should be used when the CSV data contains a header.
* This assumes that the first row is a header (not data).
*
* \param[in] csv The csv.
* \param[in] row The row. Indexed from 0 where 0 is the first row after the header.
* \param[in] colname The column name to get the data from.
*
* \return The csv data at the position or NULL if the position if invalid.
*/
M_API const char *M_csv_get_cell(const M_csv_t *csv, size_t row, const char *colname);
/*! Get the column number for a given column (header) name.
*
* This should be used when the CSV data contains a header.
* This assumes that the first row is a header (not data).
*
* \param[in] csv The csv.
* \param[in] colname The column name to get the data from.
*
* \return Column number for the given name on success. Otherwise -1.
*/
M_API ssize_t M_csv_get_cell_num(const M_csv_t *csv, const char *colname);
/*! Use different delim and quote characters for output than for parsing.
*
* By default, M_csv_output_headers_buf() and M_csv_output_rows_buf() will use the same
* delimiter and quote characters that were used when parsing the data.
*
* However, if you need to use a different delimiter and/or quote character in your
* output, call this function first to change them.
*
* \param csv The csv.
* \param delim delimiter char to use in subsequent write operations
* \param quote quote char to use in subsequent write operations
*/
void M_csv_output_set_control_chars(M_csv_t *csv, char delim, char quote);
/*! Write the header row, in CSV format.
*
* When outputting CSV data, this should be called first, with the exact same list of headers
* that you'll be using later with M_csv_output_rows_buf().
*
* If \a headers is NULL, all headers defined in the CSV data will be output, in the same order
* they were originally stored in.
*
* \see M_csv_output_rows_buf()
*
* \param[out] buf buffer to place output in.
* \param[in] csv the CSV data to output.
* \param[in] headers names of columns to include in header row (will be written in this exact order).
*/
M_API void M_csv_output_headers_buf(M_buf_t *buf, const M_csv_t *csv, M_list_str_t *headers);
/*! Write the parsed data to the given buffer, in CSV format.
*
* If \a headers is not NULL, only the columns whose names match will be output, in the same order
* that the column headers are listed in \a headers. If there are names in \a headers which aren't
* present in the parsed CSV file, an empty value will be added for that column in every row.
*
* A filter callback may be used to omit certain rows from the output. If no filter callback is
* provided, all rows will be output.
*
* \see M_csv_output_headers_buf()
*
* \param[out] buf buffer to place output in
* \param[in] csv the CSV data to output.
* \param[in] headers names of columns to include in output (also controls column order).
* \param[in] filter_cb callback to control which rows are output (may be NULL).
* \param[in] filter_thunk pointer to pass to \a filter_cb (may be NULL).
* \param[in] writer_cb callback to allow editing cell values (may be NULL).
* \param[in] writer_thunk pointer to pass to \a writer_cb (may be NULL).
*/
M_API void M_csv_output_rows_buf(M_buf_t *buf, const M_csv_t *csv, M_list_str_t *headers,
M_csv_row_filter_cb filter_cb, void *filter_thunk, M_csv_cell_writer_cb writer_cb, void *writer_thunk);
/*! @} */
__END_DECLS
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#endif /* __M_CSV_H__ */
| 34.81337 | 116 | 0.676908 | [
"object"
] |
8e993b93940bb23ab2108e47ae3ba2179548bcf1 | 531 | h | C | chrome/renderer/external_extension.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | chrome/renderer/external_extension.h | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | chrome/renderer/external_extension.h | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Implements the window.external object.
#ifndef CHROME_RENDERER_EXTERNAL_EXTENSION_H_
#define CHROME_RENDERER_EXTERNAL_EXTENSION_H_
#pragma once
namespace v8 {
class Extension;
}
namespace extensions_v8 {
class ExternalExtension {
public:
static v8::Extension* Get();
};
} // namespace extensions_v8
#endif // CHROME_RENDERER_EXTERNAL_EXTENSION_H_
| 21.24 | 73 | 0.779661 | [
"object"
] |
8e9b97f246071aa0a9caf8220348282623bb8c26 | 1,438 | h | C | src/grpc_obj_det/DetectorFactory.h | vishnu-muthiah/grpc-video-analyser | d6fd15eee0750e345469562e809d33c50b399a0a | [
"MIT"
] | 1 | 2021-05-11T12:58:38.000Z | 2021-05-11T12:58:38.000Z | src/grpc_obj_det/DetectorFactory.h | vishnu-muthiah/grpc-video-analyser | d6fd15eee0750e345469562e809d33c50b399a0a | [
"MIT"
] | 7 | 2021-05-10T07:54:03.000Z | 2021-11-11T12:21:53.000Z | src/grpc_obj_det/DetectorFactory.h | vishnu3649m/grpc-video-analyzer | d6fd15eee0750e345469562e809d33c50b399a0a | [
"MIT"
] | null | null | null | /**
* A factory for instantiating object detection modules on request.
*/
#ifndef GRPC_OBJ_DET_DETECTORFACTORY_H_
#define GRPC_OBJ_DET_DETECTORFACTORY_H_
#include <string>
#include "FaceEyesDetector.h"
#include "OnnxYoloV4Detector.h"
#include "RandomPokemonDetector.h"
namespace ObjDet {
class DetectorFactory {
public:
static std::unique_ptr<ObjDet::DetectorInterface> get_detector(const std::string& name) {
if (name == "cascade_face_detector") {
return std::unique_ptr<ObjDet::DetectorInterface>(
new ObjDet::FaceEyesDetector(name,
"config/cascade_face_detector/haarcascade_frontalface_alt.xml",
"config/cascade_face_detector/haarcascade_eye_tree_eyeglasses.xml"));
} else if (name == "onnx_yolov4_coco") {
return std::unique_ptr<ObjDet::DetectorInterface>(
new ObjDet::OnnxYoloV4Detector(name,
"config/onnx_yolov4/yolov4.onnx",
"config/onnx_yolov4/yolov4_anchors.txt",
"config/onnx_yolov4/coco_labels.txt"));
} else if (name == "random_pokemon") {
return std::unique_ptr<ObjDet::DetectorInterface>(new ObjDet::RandomPokemonDetector());
} else {
return std::unique_ptr<ObjDet::DetectorInterface>(nullptr);
}
}
};
}
#endif //GRPC_OBJ_DET_DETECTORFACTORY_H_
| 35.073171 | 108 | 0.64395 | [
"object"
] |
8eb8b07acb20fd0fcb4aef5f705b9e52b9663f5f | 2,410 | c | C | d/avatars/helm/waveguards.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/avatars/helm/waveguards.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | null | null | null | d/avatars/helm/waveguards.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
inherit ARMOUR;
void create(){
::create();
set_name("bracers");
set_id(({ "wave guards", "bracers", "guards" }));
set_short("%^RESET%^%^CYAN%^%^BOLD%^Wa%^RESET%^%^CYAN%^ve Gua%^BOLD%^rds%^RESET%^");
set_obvious_short("a pair of gently glowing bracers");
set_long(
@AVATAR
%^BOLD%^%^CYAN%^These bracers are made of an odd metal with a slightly bluish tint. The hue changes with the light seemingly like shadows over the ocean floor when the sun shines through the water. Small %^BOLD%^%^BLUE%^w%^RESET%^%^CYAN%^a%^BOLD%^t%^RESET%^e%^BOLD%^r o%^RESET%^p%^CYAN%^%^BOLD%^a%^RESET%^%^CYAN%^l%^BLUE%^%^BOLD%^s %^CYAN%^and %^BLUE%^a%^RESET%^%^CYAN%^q%^BOLD%^u%^RESET%^a%^BOLD%^m%^RESET%^a%^BOLD%^r%^RESET%^i%^CYAN%^%^BOLD%^n%^RESET%^%^CYAN%^e%^BOLD%^%^BLUE%^s %^CYAN%^line the front ends of the bracers and they sparkle softly with a faint blue glow. On top of each bracer there is an ornate circle with an intricate cresting wave motif.
AVATAR
);
set_weight(2);
set_value(0);
set_type("bracer");
set_limbs(({ "torso" }));
set_size(2);
set_property("enchantment",3);
set_ac(3);
set_wear((:TO,"wear_func":));
set_remove((:TO,"remove_func":));
set_struck((:TO,"strike_func":));
}
int wear_func(){
tell_room(ETP,"%^CYAN%^%^BOLD%^"+ETO->query_cap_name()+"%^CYAN%^%^BOLD%^ wears the glowing bracers. %^RESET%^",TP);
tell_object(TP,"%^CYAN%^%^BOLD%^You slip the bracers over your hands and feel their gentle clasp.%^RESET%^");
ETO->add_damage_bonus(3);
ETO->set_property("magic resistance",20);
return 1;
}
int remove_func(){
tell_room(ETP,"%^CYAN%^%^BOLD%^"+ETO->query_cap_name()+"%^CYAN%^%^BOLD%^ reluctantly removes the bracers.%^RESET%^",TP);
tell_object(TP,"%^CYAN%^%^BOLD%^You reluctantly remove the bracers and feel a bond lessen.%^RESET%^");
ETO->add_damage_bonus(-3);
ETO->set_property("magic resistance",-20);
return 1;
}
int strike_func(int damage, object what, object who){
if(random(1000) < 300){
tell_room(environment(query_worn()),"%^CYAN%^%^BOLD%^"+ETO->query_cap_name()+"%^CYAN%^%^BOLD%^ parries "+who->query_cap_name()+"%^CYAN%^%^BOLD%^'s wild thrust with the bracers.%^RESET%^",({ETO,who}));
tell_object(ETO,"%^CYAN%^%^BOLD%^You parry "+who->query_cap_name()+"%^CYAN%^%^BOLD%^'s wild thrust with your bracers.%^RESET%^");
tell_object(who,"%^CYAN%^%^BOLD%^Your wild thrust is parried by "+ETO->query_cap_name()+"%^RESET%^");
return (damage*50)/100;
}
} | 50.208333 | 658 | 0.670539 | [
"object"
] |
8ebc3326e1c46a58ca704b9ca41373ca0fa6024f | 652 | h | C | indigo_libs/externals/novas/nutation.h | RusDavies/indigo | f46003ffd0d9f5fd5d3cf1daf8292ca216ad982f | [
"RSA-MD"
] | 138 | 2019-05-31T01:46:16.000Z | 2022-03-30T12:31:49.000Z | indigo_libs/externals/novas/nutation.h | RusDavies/indigo | f46003ffd0d9f5fd5d3cf1daf8292ca216ad982f | [
"RSA-MD"
] | 202 | 2016-11-05T10:58:09.000Z | 2022-03-30T23:51:45.000Z | indigo_libs/externals/novas/nutation.h | RusDavies/indigo | f46003ffd0d9f5fd5d3cf1daf8292ca216ad982f | [
"RSA-MD"
] | 57 | 2016-12-15T06:43:29.000Z | 2022-03-10T17:53:16.000Z | /*
Naval Observatory Vector Astrometry Software (NOVAS)
C Edition, Version 3.1
nutation.h: Header file for nutation models
U. S. Naval Observatory
Astronomical Applications Dept.
Washington, DC
http://www.usno.navy.mil/USNO/astronomical-applications
*/
#ifndef _NUTATION_
#define _NUTATION_
/*
Function prototypes
*/
void iau2000a (double jd_high, double jd_low,
double *dpsi, double *deps);
void iau2000b (double jd_high, double jd_low,
double *dpsi, double *deps);
void nu2000k (double jd_high, double jd_low,
double *dpsi, double *deps);
#endif
| 19.757576 | 58 | 0.654908 | [
"vector"
] |
8ec1b1056843ac7122df617f692b4798387d99b9 | 9,009 | c | C | bp/library/ext/bsp/ciphersuites/bib_hmac_sha256.c | amontilla24/AndroidFixMe | 0e4c7599beaf87e62be441fd30ba6b57500ca1b0 | [
"Unlicense"
] | 2 | 2018-10-20T12:41:45.000Z | 2018-10-20T14:48:21.000Z | bp/library/ext/bsp/ciphersuites/bib_hmac_sha256.c | amontilla24/AndroidFixMe | 0e4c7599beaf87e62be441fd30ba6b57500ca1b0 | [
"Unlicense"
] | null | null | null | bp/library/ext/bsp/ciphersuites/bib_hmac_sha256.c | amontilla24/AndroidFixMe | 0e4c7599beaf87e62be441fd30ba6b57500ca1b0 | [
"Unlicense"
] | 2 | 2018-10-20T14:16:39.000Z | 2020-10-21T16:27:52.000Z | /*
* bib_hmac_sha256.c: implementation of the BIB_HMAC_SHA256
* ciphersuite.
*
* Copyright (c) 2014, California Institute of Technology.
* ALL RIGHTS RESERVED. U.S. Government Sponsorship
* acknowledged.
*
* Author: Scott Burleigh, JPL
*/
#include "bib_hmac_sha256.h"
#include "crypto.h"
#if (BIB_DEBUGGING == 1)
extern char gMsg[]; /* Debug message buffer. */
#endif
#define BSP_BIB_BLOCKING_SIZE 4096
#define BIB_HMAC_SHA256_RESULT_LEN 32
int bib_hmac_sha256_construct(ExtensionBlock *blk, BspOutboundBlock *asb)
{
asb->ciphersuiteType = BSP_CSTYPE_BIB_HMAC_SHA256;
asb->ciphersuiteFlags = BSP_ASB_RES;
/* Result length 34 is the length of a type/length/value
* triplet: length of result information item type (1)
* plus length of the length of the security result (the
* length of an SDNV large enough to contain the length
* of the result, i.e., 1) plus the length of the result
* itself (BIB_HMAC_SHA256_RESULT_LEN = 32). */
asb->resultsLen = 34;
asb->parmsLen = 0;
asb->parmsData = 0;
asb->resultsData = 0;
return 0;
}
/******************************************************************************
*
* \par Function Name: computePayloadDigest
*
* \par Purpose: Calculates HMAC SHA256 digest for a payload block given a
* key value.
*
* \retval unsigned char * - The security result.
*
* \param[in] dataObj - The payload object to hash.
* \param[in] keyValue - Value of the key to use.
* \param[in] keyLen - Length of the key to use.
* \param[out] hashLen - Length of the computed digest.
*
* \par Notes:
*****************************************************************************/
static unsigned char *computePayloadDigest(Object dataObj,
unsigned char *keyValue, unsigned int keyLen,
unsigned int *hashLen)
{
Sdr bpSdr = getIonsdr();
unsigned char *hashData = NULL;
char *dataBuffer;
ZcoReader dataReader;
char *authContext;
int authCtxLen = 0;
unsigned int bytesRemaining = 0;
unsigned int chunkSize = BSP_BIB_BLOCKING_SIZE;
unsigned int bytesRetrieved = 0;
*hashLen = 0; /* Default, indicating failure. */
/* Allocate a data buffer. */
dataBuffer = MTAKE(BSP_BIB_BLOCKING_SIZE);
CHKNULL(dataBuffer);
/* Grab a context for the hmac. A local context allows
* re-entrant calls to the HMAC libraries. */
if ((authCtxLen = hmac_sha256_context_length()) <= 0)
{
BIB_DEBUG_ERR("x computePayloadDigest: Bad context length (%d)",
authCtxLen);
MRELEASE(dataBuffer);
BIB_DEBUG_PROC("- computePayloadDigest--> NULL", NULL);
return NULL;
}
BIB_DEBUG_INFO("i computePayloadDigest: context length is %d",
authCtxLen);
if ((authContext = MTAKE(authCtxLen)) == NULL)
{
BIB_DEBUG_ERR("x computePayloadDigest: Can't allocate %d bytes",
authCtxLen);
MRELEASE(dataBuffer);
BIB_DEBUG_PROC("- computePayloadDigest--> NULL", NULL);
return NULL;
}
/* Initialize the digest computation. */
hmac_sha256_init(authContext,(unsigned char *) keyValue, keyLen);
bytesRemaining = zco_length(bpSdr, dataObj);
CHKNULL(sdr_begin_xn(bpSdr));
zco_start_transmitting(dataObj, &dataReader);
BIB_DEBUG_INFO("i computePayloadDigest: size is %d", bytesRemaining);
BIB_DEBUG_INFO("i computePayloadDigest: key value = %s, key len = %d",
keyValue, keyLen);
while (bytesRemaining > 0)
{
if (bytesRemaining < chunkSize)
{
chunkSize = bytesRemaining;
}
bytesRetrieved = zco_transmit(bpSdr, &dataReader, chunkSize,
dataBuffer);
if (bytesRetrieved != chunkSize)
{
BIB_DEBUG_ERR("x computePayloadDigest: Read %d bytes, \
but expected %d.", bytesRetrieved, chunkSize);
MRELEASE(authContext);
sdr_exit_xn(bpSdr);
MRELEASE(dataBuffer);
BIB_DEBUG_PROC("- computePayloadDigest--> NULL", NULL);
return NULL;
}
/* Add the data to the hmac_sha1 context. */
hmac_sha256_update(authContext, (unsigned char *)dataBuffer,
chunkSize);
bytesRemaining -= bytesRetrieved;
}
sdr_exit_xn(bpSdr);
MRELEASE(dataBuffer);
/* Allocate a buffer for the hash result. */
if ((hashData = MTAKE(BIB_HMAC_SHA256_RESULT_LEN)) == NULL)
{
putErrmsg("Failed allocating buffer for hash result.", NULL);
MRELEASE(authContext);
BIB_DEBUG_PROC("- computePayloadDigest--> NULL", NULL);
return NULL;
}
/* Initialize the buffer to all zeros in case the
* hmac_sha1_final function doesn't fill up the buffer. */
memset(hashData, 0, BIB_HMAC_SHA256_RESULT_LEN);
BIB_DEBUG_INFO("i computePayloadDigest: allocated hash data.",NULL);
/* Calculate the hash result. */
hmac_sha256_final(authContext, hashData, BIB_HMAC_SHA256_RESULT_LEN);
hmac_sha256_reset(authContext);
MRELEASE(authContext);
*hashLen = BIB_HMAC_SHA256_RESULT_LEN;
BIB_DEBUG_PROC("- computePayloadDigest(%x)", (unsigned long) hashData);
return (unsigned char *) hashData;
}
int bib_hmac_sha256_sign(Bundle *bundle, ExtensionBlock *blk,
BspOutboundBlock *asb)
{
Sdr bpSdr = getIonsdr();
unsigned char *keyValue;
int keyLen;
unsigned char *digest;
unsigned int digestLen;
Sdnv digestSdnv;
int resultsLen;
unsigned char *temp;
keyValue = bsp_retrieveKey(&keyLen, asb->keyName);
switch (asb->targetBlockType)
{
case BLOCK_TYPE_PRIMARY:
BIB_DEBUG_ERR("x bib_hmac_sha256_sign: Can't compute digest \
for primary block: canonicalization not implemented.", NULL);
BIB_DEBUG_PROC("- bib_hmac_sha256_sign--> NULL", NULL);
MRELEASE(keyValue);
return 0;
case BLOCK_TYPE_PAYLOAD:
digest = computePayloadDigest(bundle->payload.content,
keyValue, keyLen, &digestLen);
break;
default:
BIB_DEBUG_ERR("x bib_hmac_sha256_sign: Can't compute digest \
for block type %d: canonicalization not implemented.", asb->targetBlockType);
BIB_DEBUG_PROC("- bib_hmac_sha256_sign--> NULL", NULL);
MRELEASE(keyValue);
return 0;
}
MRELEASE(keyValue);
if (digestLen != BIB_HMAC_SHA256_RESULT_LEN)
{
if (digest != NULL)
{
MRELEASE(digest);
}
BIB_DEBUG_ERR("x bib_hmac_sha256_sign: Bad hash. hashData \
is 0x%x and length is %d.", digest, digestLen);
BIB_DEBUG_PROC("- bib_hmac_sha256_sign--> 0", NULL);
return 0;
}
encodeSdnv(&digestSdnv, digestLen);
resultsLen = 1 + digestSdnv.length + digestLen;
temp = (unsigned char *) MTAKE(resultsLen);
if (temp == NULL)
{
BIB_DEBUG_ERR("x bib_hmac_sha256_sign: Can't allocate \
memory for ASB result, len %ld.", resultsLen);
MRELEASE(digest);
BIB_DEBUG_PROC("- bib_hmac_sha256_sign --> %d", -1);
return -1;
}
*temp = BSP_CSPARM_INT_SIG;
memcpy(temp + 1, digestSdnv.text, digestSdnv.length);
memcpy(temp + 1 + digestSdnv.length, digest, digestLen);
MRELEASE(digest);
asb->resultsLen = resultsLen;
asb->resultsData = sdr_malloc(bpSdr, resultsLen);
if (asb->resultsData == 0)
{
BIB_DEBUG_ERR("x bib_hmac_sha256_sign: Can't allocate heap \
space for ASB result, len %ld.", resultsLen);
MRELEASE(temp);
BIB_DEBUG_PROC("- bib_hmac_sha256_sign --> %d", -1);
return -1;
}
sdr_write(bpSdr, asb->resultsData, (char *) temp, resultsLen);
MRELEASE(temp);
return 0;
}
int bib_hmac_sha256_verify(AcqWorkArea *wk, AcqExtBlock *blk)
{
BspInboundBlock *asb;
unsigned char *keyValue;
int keyLen;
unsigned char *digest;
unsigned int digestLen;
unsigned char *assertedDigest;
unsigned int assertedDigestLen;
int outcome;
asb = (BspInboundBlock *) (blk->object);
keyValue = bsp_retrieveKey(&keyLen, asb->keyName);
switch (asb->targetBlockType)
{
case BLOCK_TYPE_PRIMARY:
BIB_DEBUG_ERR("x bib_hmac_sha256_verify: Can't compute digest \
for primary block: canonicalization not implemented.", NULL);
BIB_DEBUG_PROC("- bib_hmac_sha256_verify--> NULL", NULL);
MRELEASE(keyValue);
return 0;
case BLOCK_TYPE_PAYLOAD:
digest = computePayloadDigest(wk->bundle.payload.content,
keyValue, keyLen, &digestLen);
break;
default:
BIB_DEBUG_ERR("x bib_hmac_sha256_verify: Can't compute digest \
for block type %d: canonicalization not implemented.", asb->targetBlockType);
BIB_DEBUG_PROC("- bib_hmac_sha256_verify--> NULL", NULL);
MRELEASE(keyValue);
return 0;
}
MRELEASE(keyValue);
if (digestLen != BIB_HMAC_SHA256_RESULT_LEN)
{
if (digest != NULL)
{
MRELEASE(digest);
}
BIB_DEBUG_ERR("x bib_hmac_sha256_verify: Bad hash. hashData is \
0x%x and length is %d.", digest, digestLen);
BIB_DEBUG_PROC("- bib_hmac_sha256_verify--> 0", NULL);
return -1;
}
bsp_getInboundBspItem(BSP_CSPARM_INT_SIG, asb->resultsData,
asb->resultsLen, &assertedDigest, &assertedDigestLen);
if (assertedDigestLen != BIB_HMAC_SHA256_RESULT_LEN)
{
BIB_DEBUG_ERR("x bib_hmac_sha256_verify: Wrong length digest \
in BIB: %d.", assertedDigestLen);
MRELEASE(digest);
return 0;
}
/* Compare the digests to verify bundle authenticity. */
if (memcmp(digest, assertedDigest, BIB_HMAC_SHA256_RESULT_LEN) == 0)
{
outcome = 1; /* Target block not altered. */
}
else
{
BIB_DEBUG_WARN("x bsp_hmac_sha256_verify: digests don't match.",
NULL);
outcome = 4; /* Target block was altered. */
}
MRELEASE(digest);
return outcome;
}
| 27.382979 | 79 | 0.708736 | [
"object"
] |
8ece1fcd1470f674f3d7cfeb2bf81fbea7e5e41f | 2,190 | c | C | kubernetes/unit-test/test_apps_v1beta1_deployment_list.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 69 | 2020-03-17T13:47:05.000Z | 2022-03-30T08:25:05.000Z | kubernetes/unit-test/test_apps_v1beta1_deployment_list.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 115 | 2020-03-17T14:53:19.000Z | 2022-03-31T11:31:30.000Z | kubernetes/unit-test/test_apps_v1beta1_deployment_list.c | minerba/c | 8eb6593e55d0e5d57a2dd3153c15c9645de677bc | [
"Apache-2.0"
] | 28 | 2020-03-17T13:42:21.000Z | 2022-03-19T23:37:16.000Z | #ifndef apps_v1beta1_deployment_list_TEST
#define apps_v1beta1_deployment_list_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define apps_v1beta1_deployment_list_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/apps_v1beta1_deployment_list.h"
apps_v1beta1_deployment_list_t* instantiate_apps_v1beta1_deployment_list(int include_optional);
#include "test_v1_list_meta.c"
apps_v1beta1_deployment_list_t* instantiate_apps_v1beta1_deployment_list(int include_optional) {
apps_v1beta1_deployment_list_t* apps_v1beta1_deployment_list = NULL;
if (include_optional) {
apps_v1beta1_deployment_list = apps_v1beta1_deployment_list_create(
"0",
list_create(),
"0",
// false, not to have infinite recursion
instantiate_v1_list_meta(0)
);
} else {
apps_v1beta1_deployment_list = apps_v1beta1_deployment_list_create(
"0",
list_create(),
"0",
NULL
);
}
return apps_v1beta1_deployment_list;
}
#ifdef apps_v1beta1_deployment_list_MAIN
void test_apps_v1beta1_deployment_list(int include_optional) {
apps_v1beta1_deployment_list_t* apps_v1beta1_deployment_list_1 = instantiate_apps_v1beta1_deployment_list(include_optional);
cJSON* jsonapps_v1beta1_deployment_list_1 = apps_v1beta1_deployment_list_convertToJSON(apps_v1beta1_deployment_list_1);
printf("apps_v1beta1_deployment_list :\n%s\n", cJSON_Print(jsonapps_v1beta1_deployment_list_1));
apps_v1beta1_deployment_list_t* apps_v1beta1_deployment_list_2 = apps_v1beta1_deployment_list_parseFromJSON(jsonapps_v1beta1_deployment_list_1);
cJSON* jsonapps_v1beta1_deployment_list_2 = apps_v1beta1_deployment_list_convertToJSON(apps_v1beta1_deployment_list_2);
printf("repeating apps_v1beta1_deployment_list:\n%s\n", cJSON_Print(jsonapps_v1beta1_deployment_list_2));
}
int main() {
test_apps_v1beta1_deployment_list(1);
test_apps_v1beta1_deployment_list(0);
printf("Hello world \n");
return 0;
}
#endif // apps_v1beta1_deployment_list_MAIN
#endif // apps_v1beta1_deployment_list_TEST
| 32.686567 | 145 | 0.812329 | [
"model"
] |
c23264a4dcd494750986bbc467c3e4b9edd325a2 | 2,345 | h | C | include/slang/mir/Procedure.h | masc-ucsc/slang | 344f4b415d03ef4dc5b9cfcd3a9fcffdf44d5e8a | [
"MIT"
] | 240 | 2017-02-03T22:29:12.000Z | 2022-03-31T08:22:04.000Z | include/slang/mir/Procedure.h | masc-ucsc/slang | 344f4b415d03ef4dc5b9cfcd3a9fcffdf44d5e8a | [
"MIT"
] | 412 | 2017-02-04T04:57:18.000Z | 2022-03-29T23:30:30.000Z | include/slang/mir/Procedure.h | masc-ucsc/slang | 344f4b415d03ef4dc5b9cfcd3a9fcffdf44d5e8a | [
"MIT"
] | 51 | 2017-02-19T23:57:30.000Z | 2022-03-02T13:55:00.000Z | //------------------------------------------------------------------------------
//! @file Procedure.h
//! @brief MIR procedures (always, initial, etc)
//
// File is under the MIT license; see LICENSE for details
//------------------------------------------------------------------------------
#pragma once
#include "slang/mir/MIRBuilder.h"
namespace slang {
class Expression;
class ProceduralBlockSymbol;
namespace mir {
class Procedure {
public:
Procedure(MIRBuilder& builder, const ProceduralBlockSymbol& block);
MIRValue emitExpr(const Expression& expr);
MIRValue emitCall(SysCallKind sysCall, const Type& returnType, span<const MIRValue> args);
void emitCall(SysCallKind sysCall, span<const MIRValue> args);
void emitCall(SysCallKind sysCall, MIRValue arg0);
MIRValue emitInstr(InstrKind kind, const Type& type, MIRValue op0);
MIRValue emitInstr(InstrKind kind, const Type& type, MIRValue op0, MIRValue op1);
MIRValue emitConst(const Type& type, const ConstantValue& val) {
return builder.emitConst(type, val);
}
MIRValue emitConst(const Type& type, ConstantValue&& val) {
return builder.emitConst(type, std::move(val));
}
MIRValue emitInt(bitwidth_t width, uint64_t value, bool isSigned);
MIRValue emitBool(bool b) { return emitInt(1, uint64_t(b), /* isSigned */ false); }
MIRValue emitString(std::string&& str);
template<int N>
MIRValue emitString(const char (&str)[N]) {
return emitString(std::string(str));
}
void emitLocal(const VariableSymbol& symbol);
MIRValue emitGlobal(const VariableSymbol& symbol) { return builder.emitGlobal(symbol); }
span<const Instr> getInstructions() const { return instructions; }
span<const VariableSymbol* const> getLocals() const { return locals; }
const VariableSymbol& getLocalSymbol(MIRValue val) const;
MIRValue findLocalSlot(const VariableSymbol& symbol) const;
Compilation& getCompilation() const;
std::string toString() const;
private:
span<const MIRValue> copyValues(span<const MIRValue> values);
MIRBuilder& builder;
std::vector<Instr> instructions;
std::vector<BasicBlock> blocks;
std::vector<const VariableSymbol*> locals;
flat_hash_map<const VariableSymbol*, MIRValue> localMap;
};
} // namespace mir
} // namespace slang | 31.689189 | 94 | 0.669083 | [
"vector"
] |
c23700a83ddecf1a3cafb1add8d083537272bd0f | 4,948 | h | C | src/rseclp/solvers/Solver.h | CTU-IIG/RSECLP | 1703da43368b6715f72b356e2801770695de779e | [
"MIT"
] | 2 | 2017-10-13T10:34:43.000Z | 2017-10-16T13:22:00.000Z | src/rseclp/solvers/Solver.h | CTU-IIG/RSECLP | 1703da43368b6715f72b356e2801770695de779e | [
"MIT"
] | null | null | null | src/rseclp/solvers/Solver.h | CTU-IIG/RSECLP | 1703da43368b6715f72b356e2801770695de779e | [
"MIT"
] | 1 | 2022-02-04T11:02:07.000Z | 2022-02-04T11:02:07.000Z | /*
Copyright (C) 2017 Czech Technical University in Prague
The MIT License (MIT)
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.
*/
#ifndef ROBUSTENERGYAWARESCHEDULING_SOLVER_H
#define ROBUSTENERGYAWARESCHEDULING_SOLVER_H
#include <vector>
#include <map>
#include <memory>
#include <chrono>
#include "../utils/StartTimes.h"
#include "../objectives/Objective.h"
namespace rseclp {
using namespace std;
enum FeasibilityResult {
FEASIBLE = 0,
INFEASIBLE = 1
};
class Solver {
public:
class Config;
class Status;
class SpecialisedConfig {
private:
map<string, map<string, string>> mSolverToParams;
public:
void addValue(const string &keySolver, const string &key, const string &value);
void addValue(const string &keySolver, const string &key, const bool value);
void addValue(const string &keySolver, const string &key, const int value);
bool testAndGetValue(const string &keySolver, const string &key, string &valueOut) const;
bool testAndGetValue(const string &keySolver, const string &key, bool &valueOut) const;
int testAndGetValue(const string &keySolver, const string &key, int &valueOut) const;
template<typename T>
T getValue(const string &keySolver, const string &key, T defaultValue) const {
T value;
return testAndGetValue(keySolver, key, value) ? value : defaultValue;
}
};
class Config {
private:
const chrono::milliseconds mTimeLimit;
const Objective *mObjective;
const bool mUseInitStartTimes;
const StartTimes mInitStartTimes;
const SpecialisedConfig mSpecialisedConfig;
public:
Config(chrono::milliseconds timeLimit,
const Objective *objective,
bool useInitStartTimes,
StartTimes initStartTimes,
SpecialisedConfig specialisedConfig);
const chrono::milliseconds &getTimeLimit() const;
const Objective *getObjective() const;
bool getUseInitStartTimes() const;
const StartTimes &getInitStartTimes() const;
const SpecialisedConfig &getSpecialisedConfig() const;
};
class Result {
public:
enum Status {
NO_SOLUTION = 0,
OPTIMAL = 1,
INFEASIBLE = 2,
FEASIBLE = 3,
// TODO: put here OPTIMAL_NO_DEVIATIONS
};
Result(const int numOperations, const double objectiveValue);
Result(Status status,
StartTimes startTimes,
double objectiveValue,
chrono::milliseconds solverRuntime,
map<string, string> optional);
void setStatus(const Status status);
void setSolution(const Status status, const StartTimes &startTimes, const double objectiveValue);
void setSolverRuntime(const chrono::milliseconds &solverRuntime);
void setOptional(const string &key, const string &value);
Status getStatus() const;
const StartTimes &getStartTimes() const;
double getObjectiveValue() const;
const chrono::milliseconds &getSolverRuntime() const;
const map<string, string> &getOptional() const;
private:
Status mStatus;
StartTimes mStartTimes;
double mObjectiveValue;
chrono::milliseconds mSolverRuntime;
map<string, string> mOptional;
};
public:
virtual ~Solver();
virtual Result solve(const Config &cfg) = 0;
};
}
#endif //ROBUSTENERGYAWARESCHEDULING_SOLVER_H
| 32.339869 | 109 | 0.632983 | [
"vector"
] |
c237bb71a24d2a198538db249cac1b0c977a4636 | 6,251 | h | C | TameParse/Util/syntax_ptr.h | Logicalshift/TameParse | 59512fc5c098046922099a59328ca82f174d8f68 | [
"MIT"
] | 6 | 2018-01-10T22:37:32.000Z | 2019-06-19T04:44:32.000Z | TameParse/Util/syntax_ptr.h | Logicalshift/TameParse | 59512fc5c098046922099a59328ca82f174d8f68 | [
"MIT"
] | null | null | null | TameParse/Util/syntax_ptr.h | Logicalshift/TameParse | 59512fc5c098046922099a59328ca82f174d8f68 | [
"MIT"
] | null | null | null | //
// syntax_ptr.h
// TameParse
//
// Created by Andrew Hunter on 17/09/2011.
//
// Copyright (c) 2011-2012 Andrew Hunter
//
// 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.
//
#ifndef _UTIL_SYNTAX_PTR_H
#define _UTIL_SYNTAX_PTR_H
#include <cstdlib>
namespace util {
/// \brief Definition of a reference to a pointer of the given type
///
/// This is an internal structure used by the syntax_ptr class
struct syntax_ptr_reference {
/// \brief Creates a reference to NULL
syntax_ptr_reference()
: usageCount(1)
, value(NULL) {
}
/// \brief Creates a reference to a value
syntax_ptr_reference(const void* newValue)
: usageCount(1)
, value(newValue) {
}
/// \brief Number of syntax_ptr objects that refer to this reference
int usageCount;
/// \brief The value in this reference
const void* value;
private:
syntax_ptr_reference(const syntax_ptr_reference& noCopying);
syntax_ptr_reference& operator=(const syntax_ptr_reference& noAssign);
};
/// \brief Shared pointer class similar to container, except without the requirements for cloning and comparisons
///
/// This will initialise to NULL if called with the default constructor. Once a given pointer is set to be managed by
/// one of these objects, it cannot be deleted any way other than by destroying all of the referencing objects.
template<typename ptr_type> class syntax_ptr {
private:
/// \brief The value that is being pointed at
syntax_ptr_reference* m_Reference;
public:
/// \brief Constructs a syntax_ptr from a reference
///
/// Generally, you should not use this constructor, it's mainly here to support pointer casting (the cast_to() function)
inline explicit syntax_ptr(syntax_ptr_reference* ref)
: m_Reference(ref) {
++m_Reference->usageCount;
}
public:
/// \brief Default constructor, assigns the pointer to NULL
inline syntax_ptr()
: m_Reference(new syntax_ptr_reference()) {
}
/// \brief Set to a specific pointer value
///
/// The pointer will be freed when this class is freed: it is invalid to assign a given pointer to more than
/// one of these objects simultaneously.
explicit inline syntax_ptr(const ptr_type* value)
: m_Reference(new syntax_ptr_reference(value)) {
}
/// \brief Copy constructor
inline syntax_ptr(const syntax_ptr<ptr_type>& copyFrom)
: m_Reference(copyFrom.m_Reference) {
// Increase the reference count for this object
++m_Reference->usageCount;
}
/// \brief Assignment
syntax_ptr<ptr_type>& operator=(const syntax_ptr<ptr_type>& assignFrom) {
// Nothing to do if the reference is the same
if (m_Reference == assignFrom.m_Reference) return *this;
// Deallocate the reference
m_Reference->usageCount--;
if (m_Reference->usageCount <= 0) {
delete (ptr_type*) m_Reference->value;
m_Reference->value = NULL;
delete m_Reference;
}
m_Reference = NULL;
// Switch to the reference in the other object
m_Reference = assignFrom.m_Reference;
++m_Reference->usageCount;
return *this;
}
/// \brief Destructs a syntax_ptr
~syntax_ptr() {
m_Reference->usageCount--;
if (m_Reference->usageCount <= 0) {
delete (ptr_type*) m_Reference->value;
m_Reference->value = NULL;
delete m_Reference;
m_Reference = NULL;
}
}
public:
/// \brief Converts this object back to its underlying type
inline operator const ptr_type*() const { return (ptr_type*) m_Reference->value; }
/// \brief Evaluating this as a boolean returns whether or not the item is present
inline operator bool() const { return m_Reference->value != NULL; }
/// \brief Casts this pointer to a pointer of a different type (but maintains reference counting)
///
/// Note that the destructor will be called on an object of the type of the last syntax_ptr to be destroyed.
/// That is, this call should only be made on objects with virtual destructors and between classes which are
/// part of the same hierarchy.
template<typename cast_type> inline syntax_ptr<cast_type> cast_to() const {
return syntax_ptr<cast_type>(m_Reference);
}
// Other operators
inline const ptr_type* operator->() const { return (ptr_type*) m_Reference->value; }
inline const ptr_type& operator*() { return *(ptr_type*) m_Reference->value; }
inline const ptr_type* item() const { return (ptr_type*) m_Reference->value; }
};
}
#endif
| 39.563291 | 128 | 0.629659 | [
"object"
] |
c23bf65b8d57b6d9e03918ca05604f1a2766f604 | 24,166 | c | C | release/src-rt-6.x.4708/router/samba3/lib/util/asn1.c | zaion520/ATtomato | 4d48bb79f8d147f89a568cf18da9e0edc41f93fb | [
"FSFAP"
] | 2 | 2019-01-13T09:19:10.000Z | 2019-02-15T01:21:02.000Z | release/src-rt-6.x.4708/router/samba3/lib/util/asn1.c | zaion520/ATtomato | 4d48bb79f8d147f89a568cf18da9e0edc41f93fb | [
"FSFAP"
] | null | null | null | release/src-rt-6.x.4708/router/samba3/lib/util/asn1.c | zaion520/ATtomato | 4d48bb79f8d147f89a568cf18da9e0edc41f93fb | [
"FSFAP"
] | 2 | 2020-03-08T01:58:25.000Z | 2020-12-20T10:34:54.000Z | /*
Unix SMB/CIFS implementation.
simple ASN1 routines
Copyright (C) Andrew Tridgell 2001
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "../lib/util/asn1.h"
/* allocate an asn1 structure */
struct asn1_data *asn1_init(TALLOC_CTX *mem_ctx)
{
struct asn1_data *ret = talloc_zero(mem_ctx, struct asn1_data);
if (ret == NULL) {
DEBUG(0,("asn1_init failed! out of memory\n"));
}
return ret;
}
/* free an asn1 structure */
void asn1_free(struct asn1_data *data)
{
talloc_free(data);
}
/* write to the ASN1 buffer, advancing the buffer pointer */
bool asn1_write(struct asn1_data *data, const void *p, int len)
{
if (data->has_error) return false;
if (data->length < data->ofs+len) {
uint8_t *newp;
newp = talloc_realloc(data, data->data, uint8_t, data->ofs+len);
if (!newp) {
asn1_free(data);
data->has_error = true;
return false;
}
data->data = newp;
data->length = data->ofs+len;
}
memcpy(data->data + data->ofs, p, len);
data->ofs += len;
return true;
}
/* useful fn for writing a uint8_t */
bool asn1_write_uint8(struct asn1_data *data, uint8_t v)
{
return asn1_write(data, &v, 1);
}
/* push a tag onto the asn1 data buffer. Used for nested structures */
bool asn1_push_tag(struct asn1_data *data, uint8_t tag)
{
struct nesting *nesting;
asn1_write_uint8(data, tag);
nesting = talloc(data, struct nesting);
if (!nesting) {
data->has_error = true;
return false;
}
nesting->start = data->ofs;
nesting->next = data->nesting;
data->nesting = nesting;
return asn1_write_uint8(data, 0xff);
}
/* pop a tag */
bool asn1_pop_tag(struct asn1_data *data)
{
struct nesting *nesting;
size_t len;
nesting = data->nesting;
if (!nesting) {
data->has_error = true;
return false;
}
len = data->ofs - (nesting->start+1);
/* yes, this is ugly. We don't know in advance how many bytes the length
of a tag will take, so we assumed 1 byte. If we were wrong then we
need to correct our mistake */
if (len > 0xFFFFFF) {
data->data[nesting->start] = 0x84;
if (!asn1_write_uint8(data, 0)) return false;
if (!asn1_write_uint8(data, 0)) return false;
if (!asn1_write_uint8(data, 0)) return false;
if (!asn1_write_uint8(data, 0)) return false;
memmove(data->data+nesting->start+5, data->data+nesting->start+1, len);
data->data[nesting->start+1] = (len>>24) & 0xFF;
data->data[nesting->start+2] = (len>>16) & 0xFF;
data->data[nesting->start+3] = (len>>8) & 0xFF;
data->data[nesting->start+4] = len&0xff;
} else if (len > 0xFFFF) {
data->data[nesting->start] = 0x83;
if (!asn1_write_uint8(data, 0)) return false;
if (!asn1_write_uint8(data, 0)) return false;
if (!asn1_write_uint8(data, 0)) return false;
memmove(data->data+nesting->start+4, data->data+nesting->start+1, len);
data->data[nesting->start+1] = (len>>16) & 0xFF;
data->data[nesting->start+2] = (len>>8) & 0xFF;
data->data[nesting->start+3] = len&0xff;
} else if (len > 255) {
data->data[nesting->start] = 0x82;
if (!asn1_write_uint8(data, 0)) return false;
if (!asn1_write_uint8(data, 0)) return false;
memmove(data->data+nesting->start+3, data->data+nesting->start+1, len);
data->data[nesting->start+1] = len>>8;
data->data[nesting->start+2] = len&0xff;
} else if (len > 127) {
data->data[nesting->start] = 0x81;
if (!asn1_write_uint8(data, 0)) return false;
memmove(data->data+nesting->start+2, data->data+nesting->start+1, len);
data->data[nesting->start+1] = len;
} else {
data->data[nesting->start] = len;
}
data->nesting = nesting->next;
talloc_free(nesting);
return true;
}
/* "i" is the one's complement representation, as is the normal result of an
* implicit signed->unsigned conversion */
static bool push_int_bigendian(struct asn1_data *data, unsigned int i, bool negative)
{
uint8_t lowest = i & 0xFF;
i = i >> 8;
if (i != 0)
if (!push_int_bigendian(data, i, negative))
return false;
if (data->nesting->start+1 == data->ofs) {
/* We did not write anything yet, looking at the highest
* valued byte */
if (negative) {
/* Don't write leading 0xff's */
if (lowest == 0xFF)
return true;
if ((lowest & 0x80) == 0) {
/* The only exception for a leading 0xff is if
* the highest bit is 0, which would indicate
* a positive value */
if (!asn1_write_uint8(data, 0xff))
return false;
}
} else {
if (lowest & 0x80) {
/* The highest bit of a positive integer is 1,
* this would indicate a negative number. Push
* a 0 to indicate a positive one */
if (!asn1_write_uint8(data, 0))
return false;
}
}
}
return asn1_write_uint8(data, lowest);
}
/* write an Integer without the tag framing. Needed for example for the LDAP
* Abandon Operation */
bool asn1_write_implicit_Integer(struct asn1_data *data, int i)
{
if (i == -1) {
/* -1 is special as it consists of all-0xff bytes. In
push_int_bigendian this is the only case that is not
properly handled, as all 0xff bytes would be handled as
leading ones to be ignored. */
return asn1_write_uint8(data, 0xff);
} else {
return push_int_bigendian(data, i, i<0);
}
}
/* write an integer */
bool asn1_write_Integer(struct asn1_data *data, int i)
{
if (!asn1_push_tag(data, ASN1_INTEGER)) return false;
if (!asn1_write_implicit_Integer(data, i)) return false;
return asn1_pop_tag(data);
}
/* write a BIT STRING */
bool asn1_write_BitString(struct asn1_data *data, const void *p, size_t length, uint8_t padding)
{
if (!asn1_push_tag(data, ASN1_BIT_STRING)) return false;
if (!asn1_write_uint8(data, padding)) return false;
if (!asn1_write(data, p, length)) return false;
return asn1_pop_tag(data);
}
bool ber_write_OID_String(TALLOC_CTX *mem_ctx, DATA_BLOB *blob, const char *OID)
{
unsigned int v, v2;
const char *p = (const char *)OID;
char *newp;
int i;
if (!isdigit(*p)) return false;
v = strtoul(p, &newp, 10);
if (newp[0] != '.') return false;
p = newp + 1;
if (!isdigit(*p)) return false;
v2 = strtoul(p, &newp, 10);
if (newp[0] != '.') return false;
p = newp + 1;
/*the ber representation can't use more space then the string one */
*blob = data_blob_talloc(mem_ctx, NULL, strlen(OID));
if (!blob->data) return false;
blob->data[0] = 40*v + v2;
i = 1;
while (*p) {
if (!isdigit(*p)) return false;
v = strtoul(p, &newp, 10);
if (newp[0] == '.') {
p = newp + 1;
/* check for empty last component */
if (!*p) return false;
} else if (newp[0] == '\0') {
p = newp;
} else {
data_blob_free(blob);
return false;
}
if (v >= (1<<28)) blob->data[i++] = (0x80 | ((v>>28)&0x7f));
if (v >= (1<<21)) blob->data[i++] = (0x80 | ((v>>21)&0x7f));
if (v >= (1<<14)) blob->data[i++] = (0x80 | ((v>>14)&0x7f));
if (v >= (1<<7)) blob->data[i++] = (0x80 | ((v>>7)&0x7f));
blob->data[i++] = (v&0x7f);
}
blob->length = i;
return true;
}
/**
* Serialize partial OID string.
* Partial OIDs are in the form:
* 1:2.5.6:0x81
* 1:2.5.6:0x8182
*/
bool ber_write_partial_OID_String(TALLOC_CTX *mem_ctx, DATA_BLOB *blob, const char *partial_oid)
{
TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
char *oid = talloc_strdup(tmp_ctx, partial_oid);
char *p;
/* truncate partial part so ber_write_OID_String() works */
p = strchr(oid, ':');
if (p) {
*p = '\0';
p++;
}
if (!ber_write_OID_String(mem_ctx, blob, oid)) {
talloc_free(tmp_ctx);
return false;
}
/* Add partially encoded sub-identifier */
if (p) {
DATA_BLOB tmp_blob = strhex_to_data_blob(tmp_ctx, p);
if (!data_blob_append(mem_ctx, blob, tmp_blob.data,
tmp_blob.length)) {
talloc_free(tmp_ctx);
return false;
}
}
talloc_free(tmp_ctx);
return true;
}
/* write an object ID to a ASN1 buffer */
bool asn1_write_OID(struct asn1_data *data, const char *OID)
{
DATA_BLOB blob;
if (!asn1_push_tag(data, ASN1_OID)) return false;
if (!ber_write_OID_String(NULL, &blob, OID)) {
data->has_error = true;
return false;
}
if (!asn1_write(data, blob.data, blob.length)) {
data_blob_free(&blob);
data->has_error = true;
return false;
}
data_blob_free(&blob);
return asn1_pop_tag(data);
}
/* write an octet string */
bool asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length)
{
asn1_push_tag(data, ASN1_OCTET_STRING);
asn1_write(data, p, length);
asn1_pop_tag(data);
return !data->has_error;
}
/* write a LDAP string */
bool asn1_write_LDAPString(struct asn1_data *data, const char *s)
{
asn1_write(data, s, strlen(s));
return !data->has_error;
}
/* write a LDAP string from a DATA_BLOB */
bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s)
{
asn1_write(data, s->data, s->length);
return !data->has_error;
}
/* write a general string */
bool asn1_write_GeneralString(struct asn1_data *data, const char *s)
{
asn1_push_tag(data, ASN1_GENERAL_STRING);
asn1_write_LDAPString(data, s);
asn1_pop_tag(data);
return !data->has_error;
}
bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob)
{
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num));
asn1_write(data, blob->data, blob->length);
asn1_pop_tag(data);
return !data->has_error;
}
/* write a BOOLEAN */
bool asn1_write_BOOLEAN(struct asn1_data *data, bool v)
{
asn1_push_tag(data, ASN1_BOOLEAN);
asn1_write_uint8(data, v ? 0xFF : 0);
asn1_pop_tag(data);
return !data->has_error;
}
bool asn1_read_BOOLEAN(struct asn1_data *data, bool *v)
{
uint8_t tmp = 0;
asn1_start_tag(data, ASN1_BOOLEAN);
asn1_read_uint8(data, &tmp);
if (tmp == 0xFF) {
*v = true;
} else {
*v = false;
}
asn1_end_tag(data);
return !data->has_error;
}
/* write a BOOLEAN in a simple context */
bool asn1_write_BOOLEAN_context(struct asn1_data *data, bool v, int context)
{
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context));
asn1_write_uint8(data, v ? 0xFF : 0);
asn1_pop_tag(data);
return !data->has_error;
}
bool asn1_read_BOOLEAN_context(struct asn1_data *data, bool *v, int context)
{
uint8_t tmp = 0;
asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(context));
asn1_read_uint8(data, &tmp);
if (tmp == 0xFF) {
*v = true;
} else {
*v = false;
}
asn1_end_tag(data);
return !data->has_error;
}
/* check a BOOLEAN */
bool asn1_check_BOOLEAN(struct asn1_data *data, bool v)
{
uint8_t b = 0;
asn1_read_uint8(data, &b);
if (b != ASN1_BOOLEAN) {
data->has_error = true;
return false;
}
asn1_read_uint8(data, &b);
if (b != v) {
data->has_error = true;
return false;
}
return !data->has_error;
}
/* load a struct asn1_data structure with a lump of data, ready to be parsed */
bool asn1_load(struct asn1_data *data, DATA_BLOB blob)
{
ZERO_STRUCTP(data);
data->data = (uint8_t *)talloc_memdup(data, blob.data, blob.length);
if (!data->data) {
data->has_error = true;
return false;
}
data->length = blob.length;
return true;
}
/* Peek into an ASN1 buffer, not advancing the pointer */
bool asn1_peek(struct asn1_data *data, void *p, int len)
{
if (data->has_error)
return false;
if (len < 0 || data->ofs + len < data->ofs || data->ofs + len < len)
return false;
if (data->ofs + len > data->length) {
/* we need to mark the buffer as consumed, so the caller knows
this was an out of data error, and not a decode error */
data->ofs = data->length;
return false;
}
memcpy(p, data->data + data->ofs, len);
return true;
}
/* read from a ASN1 buffer, advancing the buffer pointer */
bool asn1_read(struct asn1_data *data, void *p, int len)
{
if (!asn1_peek(data, p, len)) {
data->has_error = true;
return false;
}
data->ofs += len;
return true;
}
/* read a uint8_t from a ASN1 buffer */
bool asn1_read_uint8(struct asn1_data *data, uint8_t *v)
{
return asn1_read(data, v, 1);
}
bool asn1_peek_uint8(struct asn1_data *data, uint8_t *v)
{
return asn1_peek(data, v, 1);
}
bool asn1_peek_tag(struct asn1_data *data, uint8_t tag)
{
uint8_t b;
if (asn1_tag_remaining(data) <= 0) {
return false;
}
if (!asn1_peek_uint8(data, &b))
return false;
return (b == tag);
}
/*
* just get the needed size the tag would consume
*/
bool asn1_peek_tag_needed_size(struct asn1_data *data, uint8_t tag, size_t *size)
{
off_t start_ofs = data->ofs;
uint8_t b;
size_t taglen = 0;
if (data->has_error) {
return false;
}
if (!asn1_read_uint8(data, &b)) {
data->ofs = start_ofs;
data->has_error = false;
return false;
}
if (b != tag) {
data->ofs = start_ofs;
data->has_error = false;
return false;
}
if (!asn1_read_uint8(data, &b)) {
data->ofs = start_ofs;
data->has_error = false;
return false;
}
if (b & 0x80) {
int n = b & 0x7f;
if (!asn1_read_uint8(data, &b)) {
data->ofs = start_ofs;
data->has_error = false;
return false;
}
if (n > 4) {
/*
* We should not allow more than 4 bytes
* for the encoding of the tag length.
*
* Otherwise we'd overflow the taglen
* variable on 32 bit systems.
*/
data->ofs = start_ofs;
data->has_error = false;
return false;
}
taglen = b;
while (n > 1) {
if (!asn1_read_uint8(data, &b)) {
data->ofs = start_ofs;
data->has_error = false;
return false;
}
taglen = (taglen << 8) | b;
n--;
}
} else {
taglen = b;
}
*size = (data->ofs - start_ofs) + taglen;
data->ofs = start_ofs;
data->has_error = false;
return true;
}
/* start reading a nested asn1 structure */
bool asn1_start_tag(struct asn1_data *data, uint8_t tag)
{
uint8_t b;
struct nesting *nesting;
if (!asn1_read_uint8(data, &b))
return false;
if (b != tag) {
data->has_error = true;
return false;
}
nesting = talloc(data, struct nesting);
if (!nesting) {
data->has_error = true;
return false;
}
if (!asn1_read_uint8(data, &b)) {
return false;
}
if (b & 0x80) {
int n = b & 0x7f;
if (!asn1_read_uint8(data, &b))
return false;
nesting->taglen = b;
while (n > 1) {
if (!asn1_read_uint8(data, &b))
return false;
nesting->taglen = (nesting->taglen << 8) | b;
n--;
}
} else {
nesting->taglen = b;
}
nesting->start = data->ofs;
nesting->next = data->nesting;
data->nesting = nesting;
if (asn1_tag_remaining(data) == -1) {
return false;
}
return !data->has_error;
}
/* stop reading a tag */
bool asn1_end_tag(struct asn1_data *data)
{
struct nesting *nesting;
/* make sure we read it all */
if (asn1_tag_remaining(data) != 0) {
data->has_error = true;
return false;
}
nesting = data->nesting;
if (!nesting) {
data->has_error = true;
return false;
}
data->nesting = nesting->next;
talloc_free(nesting);
return true;
}
/* work out how many bytes are left in this nested tag */
int asn1_tag_remaining(struct asn1_data *data)
{
int remaining;
if (data->has_error) {
return -1;
}
if (!data->nesting) {
data->has_error = true;
return -1;
}
remaining = data->nesting->taglen - (data->ofs - data->nesting->start);
if (remaining > (data->length - data->ofs)) {
data->has_error = true;
return -1;
}
return remaining;
}
/**
* Internal implementation for reading binary OIDs
* Reading is done as far in the buffer as valid OID
* till buffer ends or not valid sub-identifier is found.
*/
static bool _ber_read_OID_String_impl(TALLOC_CTX *mem_ctx, DATA_BLOB blob,
char **OID, size_t *bytes_eaten)
{
int i;
uint8_t *b;
unsigned int v;
char *tmp_oid = NULL;
if (blob.length < 2) return false;
b = blob.data;
tmp_oid = talloc_asprintf(mem_ctx, "%u", b[0]/40);
if (!tmp_oid) goto nomem;
tmp_oid = talloc_asprintf_append_buffer(tmp_oid, ".%u", b[0]%40);
if (!tmp_oid) goto nomem;
if (bytes_eaten != NULL) {
*bytes_eaten = 0;
}
for(i = 1, v = 0; i < blob.length; i++) {
v = (v<<7) | (b[i]&0x7f);
if ( ! (b[i] & 0x80)) {
tmp_oid = talloc_asprintf_append_buffer(tmp_oid, ".%u", v);
v = 0;
if (bytes_eaten)
*bytes_eaten = i+1;
}
if (!tmp_oid) goto nomem;
}
*OID = tmp_oid;
return true;
nomem:
return false;
}
/* read an object ID from a data blob */
bool ber_read_OID_String(TALLOC_CTX *mem_ctx, DATA_BLOB blob, char **OID)
{
size_t bytes_eaten;
if (!_ber_read_OID_String_impl(mem_ctx, blob, OID, &bytes_eaten))
return false;
return (bytes_eaten == blob.length);
}
/**
* Deserialize partial OID string.
* Partial OIDs are in the form:
* 1:2.5.6:0x81
* 1:2.5.6:0x8182
*/
bool ber_read_partial_OID_String(TALLOC_CTX *mem_ctx, DATA_BLOB blob,
char **partial_oid)
{
size_t bytes_left;
size_t bytes_eaten;
char *identifier = NULL;
char *tmp_oid = NULL;
if (!_ber_read_OID_String_impl(mem_ctx, blob, &tmp_oid, &bytes_eaten))
return false;
if (bytes_eaten < blob.length) {
bytes_left = blob.length - bytes_eaten;
identifier = hex_encode_talloc(mem_ctx, &blob.data[bytes_eaten], bytes_left);
if (!identifier) goto nomem;
*partial_oid = talloc_asprintf_append_buffer(tmp_oid, ":0x%s", identifier);
if (!*partial_oid) goto nomem;
TALLOC_FREE(identifier);
} else {
*partial_oid = tmp_oid;
}
return true;
nomem:
TALLOC_FREE(identifier);
TALLOC_FREE(tmp_oid);
return false;
}
/* read an object ID from a ASN1 buffer */
bool asn1_read_OID(struct asn1_data *data, TALLOC_CTX *mem_ctx, char **OID)
{
DATA_BLOB blob;
int len;
if (!asn1_start_tag(data, ASN1_OID)) return false;
len = asn1_tag_remaining(data);
if (len < 0) {
data->has_error = true;
return false;
}
blob = data_blob(NULL, len);
if (!blob.data) {
data->has_error = true;
return false;
}
asn1_read(data, blob.data, len);
asn1_end_tag(data);
if (data->has_error) {
data_blob_free(&blob);
return false;
}
if (!ber_read_OID_String(mem_ctx, blob, OID)) {
data->has_error = true;
data_blob_free(&blob);
return false;
}
data_blob_free(&blob);
return true;
}
/* check that the next object ID is correct */
bool asn1_check_OID(struct asn1_data *data, const char *OID)
{
char *id;
if (!asn1_read_OID(data, data, &id)) return false;
if (strcmp(id, OID) != 0) {
talloc_free(id);
data->has_error = true;
return false;
}
talloc_free(id);
return true;
}
/* read a LDAPString from a ASN1 buffer */
bool asn1_read_LDAPString(struct asn1_data *data, TALLOC_CTX *mem_ctx, char **s)
{
int len;
len = asn1_tag_remaining(data);
if (len < 0) {
data->has_error = true;
return false;
}
*s = talloc_array(mem_ctx, char, len+1);
if (! *s) {
data->has_error = true;
return false;
}
asn1_read(data, *s, len);
(*s)[len] = 0;
return !data->has_error;
}
/* read a GeneralString from a ASN1 buffer */
bool asn1_read_GeneralString(struct asn1_data *data, TALLOC_CTX *mem_ctx, char **s)
{
if (!asn1_start_tag(data, ASN1_GENERAL_STRING)) return false;
if (!asn1_read_LDAPString(data, mem_ctx, s)) return false;
return asn1_end_tag(data);
}
/* read a octet string blob */
bool asn1_read_OctetString(struct asn1_data *data, TALLOC_CTX *mem_ctx, DATA_BLOB *blob)
{
int len;
ZERO_STRUCTP(blob);
if (!asn1_start_tag(data, ASN1_OCTET_STRING)) return false;
len = asn1_tag_remaining(data);
if (len < 0) {
data->has_error = true;
return false;
}
*blob = data_blob_talloc(mem_ctx, NULL, len+1);
if (!blob->data) {
data->has_error = true;
return false;
}
asn1_read(data, blob->data, len);
asn1_end_tag(data);
blob->length--;
blob->data[len] = 0;
if (data->has_error) {
data_blob_free(blob);
*blob = data_blob_null;
return false;
}
return true;
}
bool asn1_read_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob)
{
int len;
ZERO_STRUCTP(blob);
if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(num))) return false;
len = asn1_tag_remaining(data);
if (len < 0) {
data->has_error = true;
return false;
}
*blob = data_blob(NULL, len);
if ((len != 0) && (!blob->data)) {
data->has_error = true;
return false;
}
asn1_read(data, blob->data, len);
asn1_end_tag(data);
return !data->has_error;
}
/* read an integer without tag*/
bool asn1_read_implicit_Integer(struct asn1_data *data, int *i)
{
uint8_t b;
bool first_byte = true;
*i = 0;
while (!data->has_error && asn1_tag_remaining(data)>0) {
if (!asn1_read_uint8(data, &b)) return false;
if (first_byte) {
if (b & 0x80) {
/* Number is negative.
Set i to -1 for sign extend. */
*i = -1;
}
first_byte = false;
}
*i = (*i << 8) + b;
}
return !data->has_error;
}
/* read an integer */
bool asn1_read_Integer(struct asn1_data *data, int *i)
{
*i = 0;
if (!asn1_start_tag(data, ASN1_INTEGER)) return false;
if (!asn1_read_implicit_Integer(data, i)) return false;
return asn1_end_tag(data);
}
/* read a BIT STRING */
bool asn1_read_BitString(struct asn1_data *data, TALLOC_CTX *mem_ctx, DATA_BLOB *blob, uint8_t *padding)
{
int len;
ZERO_STRUCTP(blob);
if (!asn1_start_tag(data, ASN1_BIT_STRING)) return false;
len = asn1_tag_remaining(data);
if (len < 0) {
data->has_error = true;
return false;
}
if (!asn1_read_uint8(data, padding)) return false;
*blob = data_blob_talloc(mem_ctx, NULL, len);
if (!blob->data) {
data->has_error = true;
return false;
}
if (asn1_read(data, blob->data, len - 1)) {
blob->length--;
blob->data[len] = 0;
asn1_end_tag(data);
}
if (data->has_error) {
data_blob_free(blob);
*blob = data_blob_null;
*padding = 0;
return false;
}
return true;
}
/* read an integer */
bool asn1_read_enumerated(struct asn1_data *data, int *v)
{
*v = 0;
if (!asn1_start_tag(data, ASN1_ENUMERATED)) return false;
while (!data->has_error && asn1_tag_remaining(data)>0) {
uint8_t b;
asn1_read_uint8(data, &b);
*v = (*v << 8) + b;
}
return asn1_end_tag(data);
}
/* check a enumerated value is correct */
bool asn1_check_enumerated(struct asn1_data *data, int v)
{
uint8_t b;
if (!asn1_start_tag(data, ASN1_ENUMERATED)) return false;
asn1_read_uint8(data, &b);
asn1_end_tag(data);
if (v != b)
data->has_error = false;
return !data->has_error;
}
/* write an enumerated value to the stream */
bool asn1_write_enumerated(struct asn1_data *data, uint8_t v)
{
if (!asn1_push_tag(data, ASN1_ENUMERATED)) return false;
asn1_write_uint8(data, v);
asn1_pop_tag(data);
return !data->has_error;
}
/*
Get us the data just written without copying
*/
bool asn1_blob(const struct asn1_data *asn1, DATA_BLOB *blob)
{
if (asn1->has_error) {
return false;
}
if (asn1->nesting != NULL) {
return false;
}
blob->data = asn1->data;
blob->length = asn1->length;
return true;
}
/*
Fill in an asn1 struct without making a copy
*/
void asn1_load_nocopy(struct asn1_data *data, uint8_t *buf, size_t len)
{
ZERO_STRUCTP(data);
data->data = buf;
data->length = len;
}
/*
check if a ASN.1 blob is a full tag
*/
NTSTATUS asn1_full_tag(DATA_BLOB blob, uint8_t tag, size_t *packet_size)
{
struct asn1_data *asn1 = asn1_init(NULL);
int size;
NT_STATUS_HAVE_NO_MEMORY(asn1);
asn1->data = blob.data;
asn1->length = blob.length;
asn1_start_tag(asn1, tag);
if (asn1->has_error) {
talloc_free(asn1);
return STATUS_MORE_ENTRIES;
}
size = asn1_tag_remaining(asn1) + asn1->ofs;
talloc_free(asn1);
if (size > blob.length) {
return STATUS_MORE_ENTRIES;
}
*packet_size = size;
return NT_STATUS_OK;
}
NTSTATUS asn1_peek_full_tag(DATA_BLOB blob, uint8_t tag, size_t *packet_size)
{
struct asn1_data asn1;
size_t size;
bool ok;
ZERO_STRUCT(asn1);
asn1.data = blob.data;
asn1.length = blob.length;
ok = asn1_peek_tag_needed_size(&asn1, tag, &size);
if (!ok) {
return NT_STATUS_INVALID_BUFFER_SIZE;
}
if (size > blob.length) {
*packet_size = size;
return STATUS_MORE_ENTRIES;
}
*packet_size = size;
return NT_STATUS_OK;
}
| 22.69108 | 104 | 0.668791 | [
"object"
] |
c240dacdb08f703fb646ad8ace9170cea0ee6126 | 69,252 | c | C | m3-tools/gnuemacs/src/lex-yacc/y.tab.c | jaykrell/cm3 | 2aae7d9342b8e26680f6419f9296450fae8cbd4b | [
"BSD-4-Clause-UC",
"BSD-4-Clause",
"BSD-3-Clause"
] | 105 | 2015-03-02T16:58:34.000Z | 2022-03-28T07:17:49.000Z | m3-tools/gnuemacs/src/lex-yacc/y.tab.c | jaykrell/cm3 | 2aae7d9342b8e26680f6419f9296450fae8cbd4b | [
"BSD-4-Clause-UC",
"BSD-4-Clause",
"BSD-3-Clause"
] | 145 | 2015-03-18T10:08:17.000Z | 2022-03-31T01:27:08.000Z | m3-tools/gnuemacs/src/lex-yacc/y.tab.c | jaykrell/cm3 | 2aae7d9342b8e26680f6419f9296450fae8cbd4b | [
"BSD-4-Clause-UC",
"BSD-4-Clause",
"BSD-3-Clause"
] | 26 | 2015-10-10T09:37:44.000Z | 2022-02-23T02:02:05.000Z |
/* A Bison parser, made from ../parse.yacc
by GNU Bison version 1.28 */
#define YYBISON 1 /* Identify Bison output. */
#define ENDOFFILE 257
#define AMPERSAND 258
#define ASSIGN 259
#define ASTERISK 260
#define BAR 261
#define COLON 262
#define COMMA 263
#define DOT 264
#define DOTDOT 265
#define EQUAL 266
#define GREATER 267
#define GREQUAL 268
#define LESS 269
#define LSEQUAL 270
#define MINUS 271
#define SHARP 272
#define PERIOD 273
#define PLUS 274
#define RARROW 275
#define RBRACE 276
#define RBRACKET 277
#define RPAREN 278
#define SEMICOLON 279
#define SLASH 280
#define SUBTYPE 281
#define UPARROW 282
#define LPAREN 283
#define LBRACKET 284
#define LBRACE 285
#define IDENT 286
#define CARD_CONST 287
#define REAL_CONST 288
#define CHAR_CONST 289
#define STR_CONST 290
#define AND 291
#define ANY 292
#define ARRAY 293
#define AS 294
#define BGN 295
#define BITS 296
#define BRANDED 297
#define BY 298
#define CASE 299
#define CONST 300
#define DIV 301
#define DO 302
#define ELSE 303
#define ELSIF 304
#define END 305
#define EVAL 306
#define EXCEPT 307
#define EXCEPTION 308
#define EXIT 309
#define EXPORTS 310
#define FINALLY 311
#define FOR 312
#define FROM 313
#define GENERIC 314
#define IF 315
#define IMPORT 316
#define IN 317
#define INTERFACE 318
#define LOCK 319
#define LOOP 320
#define METHODS 321
#define MOD 322
#define MODULE 323
#define NOT 324
#define OBJECT 325
#define OF 326
#define OR 327
#define OVERRIDES 328
#define PROCEDURE 329
#define RAISE 330
#define RAISES 331
#define READONLY 332
#define RECORD 333
#define REF 334
#define REPEAT 335
#define RETURN 336
#define REVEAL 337
#define ROOT 338
#define SET 339
#define THEN 340
#define TO 341
#define TRY 342
#define TYPE 343
#define TYPECASE 344
#define UNSAFE 345
#define UNTIL 346
#define UNTRACED 347
#define VALUE 348
#define VAR 349
#define WHILE 350
#define WITH 351
#line 39 "../parse.yacc"
#define YYMAXDEPTH 300
/* make yacc's stack larger than the default of 150 */
#include <stdio.h>
extern notypes, novars, noconst, noexcepts, oldstyle, qnames;
int linecnt = 1;
int charcnt;
int charperlinecnt; /* charcnt for current line */
char linebuf[1000]; /* chars of current line */
char lastident[200];/* last identifier encountered */
int comdepth = 0;
/* depth of comments, used only by lexer. */
int pragdepth = 0;
/* depth of pragmas, used only by lexer. */
#ifndef YYSTYPE
#define YYSTYPE int
#endif
#include <stdio.h>
#ifndef __cplusplus
#ifndef __STDC__
#define const
#endif
#endif
#define YYFINAL 544
#define YYFLAG -32768
#define YYNTBASE 98
#define YYTRANSLATE(x) ((unsigned)(x) <= 351 ? yytranslate[x] : 234)
static const char yytranslate[] = { 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 1, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
57, 58, 59, 60, 61, 62, 63, 64, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97
};
#if YYDEBUG != 0
static const short yyprhs[] = { 0,
0, 2, 5, 7, 10, 12, 14, 15, 25, 26,
36, 37, 46, 47, 58, 59, 71, 72, 82, 83,
87, 88, 91, 92, 95, 101, 105, 107, 111, 115,
121, 126, 132, 133, 136, 141, 144, 146, 149, 151,
154, 156, 159, 161, 164, 166, 169, 171, 174, 175,
183, 184, 190, 192, 195, 196, 202, 203, 209, 211,
214, 216, 220, 225, 232, 237, 239, 242, 244, 248,
251, 257, 258, 263, 269, 270, 273, 274, 279, 282,
283, 285, 287, 290, 292, 295, 299, 303, 304, 306,
308, 310, 314, 320, 324, 327, 332, 335, 336, 338,
341, 342, 344, 346, 349, 351, 355, 357, 359, 361,
363, 365, 367, 369, 371, 373, 375, 377, 379, 381,
383, 385, 387, 389, 391, 395, 397, 405, 412, 413,
417, 421, 423, 427, 429, 433, 435, 438, 449, 450,
453, 461, 462, 465, 466, 469, 474, 480, 484, 487,
492, 494, 497, 503, 511, 518, 519, 523, 530, 534,
542, 549, 550, 554, 558, 565, 571, 577, 579, 583,
587, 588, 590, 592, 596, 598, 602, 604, 608, 610,
613, 616, 618, 622, 624, 626, 628, 633, 636, 639,
641, 646, 650, 654, 660, 662, 665, 667, 672, 676,
680, 684, 686, 689, 696, 697, 700, 701, 704, 705,
707, 710, 711, 713, 715, 718, 720, 723, 726, 729,
730, 732, 734, 737, 739, 742, 746, 752, 757, 760,
765, 769, 770, 772, 774, 777, 779, 782, 787, 791,
793, 795, 799, 801, 803, 807, 810, 812, 814, 816,
820, 822, 824, 826, 828, 830, 832, 834, 836, 838,
842, 844, 846, 848, 850, 852, 856, 858, 860, 862,
864, 866, 869, 872, 875, 877, 879, 881, 883, 885,
889, 891, 892, 895, 898, 900, 904, 908, 911, 916,
919, 921, 925, 927, 931, 933, 935, 939, 941, 945,
947, 951, 955, 956, 959, 960, 962, 964
};
static const short yyrhs[] = { 99,
0, 91, 99, 0, 102, 0, 91, 102, 0, 105,
0, 107, 0, 0, 64, 32, 100, 25, 111, 116,
51, 32, 10, 0, 0, 64, 32, 101, 12, 32,
109, 51, 32, 10, 0, 0, 69, 32, 103, 110,
25, 111, 115, 10, 0, 0, 69, 32, 104, 110,
12, 32, 109, 51, 32, 10, 0, 0, 60, 64,
32, 106, 109, 25, 111, 116, 51, 32, 10, 0,
0, 60, 69, 32, 108, 109, 25, 111, 115, 10,
0, 0, 29, 232, 24, 0, 0, 56, 233, 0,
0, 111, 112, 0, 59, 32, 62, 233, 25, 0,
62, 113, 25, 0, 32, 0, 32, 40, 32, 0,
113, 9, 32, 0, 113, 9, 32, 40, 32, 0,
116, 41, 144, 51, 0, 116, 41, 144, 51, 32,
0, 0, 116, 117, 0, 132, 12, 115, 25, 0,
132, 25, 0, 46, 0, 46, 118, 0, 89, 0,
89, 122, 0, 83, 0, 83, 122, 0, 95, 0,
95, 126, 0, 54, 0, 54, 129, 0, 119, 0,
118, 119, 0, 0, 32, 120, 8, 184, 12, 207,
25, 0, 0, 32, 121, 12, 207, 25, 0, 123,
0, 122, 123, 0, 0, 185, 124, 12, 184, 25,
0, 0, 185, 125, 27, 184, 25, 0, 128, 0,
126, 128, 0, 32, 0, 127, 9, 32, 0, 127,
8, 184, 25, 0, 127, 8, 184, 5, 207, 25,
0, 127, 5, 207, 25, 0, 131, 0, 129, 131,
0, 32, 0, 130, 9, 32, 0, 130, 25, 0,
130, 29, 184, 24, 25, 0, 0, 75, 32, 133,
134, 0, 29, 137, 24, 135, 136, 0, 0, 8,
184, 0, 0, 77, 31, 180, 22, 0, 77, 38,
0, 0, 140, 0, 138, 0, 138, 140, 0, 139,
0, 138, 139, 0, 141, 233, 142, 0, 141, 233,
143, 0, 0, 94, 0, 95, 0, 78, 0, 8,
184, 25, 0, 8, 184, 5, 207, 25, 0, 5,
207, 25, 0, 8, 184, 0, 8, 184, 5, 207,
0, 5, 207, 0, 0, 147, 0, 147, 25, 0,
0, 146, 0, 147, 0, 147, 25, 0, 148, 0,
147, 25, 148, 0, 149, 0, 114, 0, 150, 0,
151, 0, 156, 0, 157, 0, 158, 0, 160, 0,
164, 0, 165, 0, 166, 0, 167, 0, 168, 0,
169, 0, 170, 0, 173, 0, 176, 0, 177, 0,
207, 5, 207, 0, 207, 0, 45, 207, 72, 153,
152, 161, 51, 0, 45, 207, 72, 152, 161, 51,
0, 0, 152, 7, 153, 0, 154, 21, 145, 0,
155, 0, 154, 9, 155, 0, 207, 0, 207, 11,
207, 0, 55, 0, 52, 207, 0, 58, 32, 5,
207, 87, 207, 159, 48, 144, 51, 0, 0, 44,
207, 0, 61, 207, 86, 144, 162, 161, 51, 0,
0, 49, 144, 0, 0, 162, 163, 0, 50, 207,
86, 144, 0, 65, 207, 48, 144, 51, 0, 66,
144, 51, 0, 76, 207, 0, 81, 144, 92, 207,
0, 82, 0, 82, 207, 0, 88, 144, 57, 144,
51, 0, 88, 144, 53, 172, 171, 161, 51, 0,
88, 144, 53, 171, 161, 51, 0, 0, 171, 7,
172, 0, 181, 29, 32, 24, 21, 145, 0, 181,
21, 145, 0, 90, 207, 72, 175, 174, 161, 51,
0, 90, 207, 72, 174, 161, 51, 0, 0, 174,
7, 175, 0, 183, 21, 145, 0, 183, 29, 32,
24, 21, 145, 0, 96, 207, 48, 144, 51, 0,
97, 178, 48, 144, 51, 0, 179, 0, 178, 9,
179, 0, 32, 12, 207, 0, 0, 181, 0, 182,
0, 181, 9, 182, 0, 32, 0, 32, 10, 32,
0, 184, 0, 183, 9, 184, 0, 185, 0, 185,
190, 0, 188, 190, 0, 186, 0, 29, 184, 24,
0, 182, 0, 187, 0, 189, 0, 42, 207, 58,
184, 0, 75, 134, 0, 93, 190, 0, 190, 0,
93, 194, 80, 184, 0, 194, 80, 184, 0, 31,
232, 22, 0, 30, 207, 11, 207, 23, 0, 188,
0, 93, 84, 0, 84, 0, 39, 183, 72, 184,
0, 39, 72, 184, 0, 79, 195, 51, 0, 85,
72, 184, 0, 191, 0, 190, 191, 0, 194, 71,
195, 192, 193, 51, 0, 0, 67, 199, 0, 0,
74, 203, 0, 0, 43, 0, 43, 36, 0, 0,
198, 0, 196, 0, 196, 198, 0, 197, 0, 196,
197, 0, 233, 142, 0, 233, 143, 0, 0, 202,
0, 200, 0, 200, 202, 0, 201, 0, 200, 201,
0, 32, 134, 25, 0, 32, 134, 5, 182, 25,
0, 32, 5, 182, 25, 0, 32, 134, 0, 32,
134, 5, 182, 0, 32, 5, 182, 0, 0, 206,
0, 204, 0, 204, 206, 0, 205, 0, 204, 205,
0, 32, 5, 182, 25, 0, 32, 5, 182, 0,
208, 0, 209, 0, 208, 73, 209, 0, 210, 0,
211, 0, 210, 37, 211, 0, 70, 211, 0, 212,
0, 213, 0, 215, 0, 213, 214, 215, 0, 12,
0, 18, 0, 15, 0, 16, 0, 13, 0, 14,
0, 63, 0, 216, 0, 218, 0, 216, 217, 218,
0, 20, 0, 17, 0, 4, 0, 219, 0, 221,
0, 219, 220, 221, 0, 6, 0, 26, 0, 47,
0, 68, 0, 222, 0, 20, 221, 0, 17, 221,
0, 223, 224, 0, 32, 0, 33, 0, 34, 0,
35, 0, 36, 0, 29, 207, 24, 0, 189, 0,
0, 224, 225, 0, 10, 32, 0, 28, 0, 30,
226, 23, 0, 29, 227, 24, 0, 29, 24, 0,
31, 229, 231, 22, 0, 31, 22, 0, 207, 0,
226, 9, 207, 0, 228, 0, 227, 9, 228, 0,
207, 0, 187, 0, 32, 5, 207, 0, 230, 0,
229, 9, 230, 0, 207, 0, 207, 11, 207, 0,
207, 5, 207, 0, 0, 9, 11, 0, 0, 233,
0, 32, 0, 233, 9, 32, 0
};
#endif
#if YYDEBUG != 0
static const short yyrline[] = { 0,
64, 66, 67, 68, 69, 70, 73, 76, 79, 80,
84, 86, 87, 88, 91, 94, 100, 102, 108, 110,
113, 115, 117, 119, 122, 124, 127, 129, 130, 131,
134, 137, 140, 142, 145, 147, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 160, 162, 165, 167,
169, 170, 173, 175, 178, 180, 181, 182, 185, 187,
190, 192, 195, 197, 198, 201, 204, 207, 209, 212,
215, 218, 220, 222, 226, 228, 231, 233, 234, 237,
239, 240, 241, 244, 246, 249, 253, 257, 259, 259,
259, 261, 263, 264, 267, 269, 270, 274, 276, 276,
279, 281, 284, 285, 287, 289, 292, 294, 294, 295,
296, 297, 298, 299, 300, 301, 302, 303, 304, 305,
306, 307, 308, 309, 312, 316, 320, 322, 325, 327,
330, 333, 335, 338, 339, 341, 345, 349, 353, 355,
357, 361, 363, 366, 368, 371, 375, 379, 383, 387,
390, 392, 395, 399, 401, 404, 406, 409, 411, 414,
416, 419, 421, 424, 426, 429, 433, 437, 439, 442,
445, 447, 450, 452, 455, 457, 462, 464, 467, 469,
470, 471, 472, 475, 479, 481, 484, 486, 487, 488,
489, 490, 491, 492, 493, 496, 498, 501, 503, 504,
505, 508, 510, 513, 517, 519, 522, 524, 527, 529,
529, 531, 533, 534, 535, 538, 540, 543, 545, 548,
550, 551, 552, 555, 557, 560, 562, 563, 566, 568,
569, 572, 574, 575, 576, 579, 581, 584, 587, 592,
593, 593, 595, 596, 596, 598, 598, 600, 601, 601,
602, 602, 602, 602, 602, 602, 602, 604, 605, 605,
606, 606, 606, 608, 609, 609, 610, 610, 610, 610,
612, 612, 612, 615, 617, 617, 617, 617, 617, 618,
618, 621, 623, 626, 628, 631, 632, 633, 634, 635,
638, 640, 643, 645, 648, 650, 651, 654, 656, 659,
661, 662, 665, 667, 670, 672, 675, 677
};
#endif
#if YYDEBUG != 0 || defined (YYERROR_VERBOSE)
static const char * const yytname[] = { "$","error","$undefined.","ENDOFFILE",
"AMPERSAND","ASSIGN","ASTERISK","BAR","COLON","COMMA","DOT","DOTDOT","EQUAL",
"GREATER","GREQUAL","LESS","LSEQUAL","MINUS","SHARP","PERIOD","PLUS","RARROW",
"RBRACE","RBRACKET","RPAREN","SEMICOLON","SLASH","SUBTYPE","UPARROW","LPAREN",
"LBRACKET","LBRACE","IDENT","CARD_CONST","REAL_CONST","CHAR_CONST","STR_CONST",
"AND","ANY","ARRAY","AS","BGN","BITS","BRANDED","BY","CASE","CONST","DIV","DO",
"ELSE","ELSIF","END","EVAL","EXCEPT","EXCEPTION","EXIT","EXPORTS","FINALLY",
"FOR","FROM","GENERIC","IF","IMPORT","IN","INTERFACE","LOCK","LOOP","METHODS",
"MOD","MODULE","NOT","OBJECT","OF","OR","OVERRIDES","PROCEDURE","RAISE","RAISES",
"READONLY","RECORD","REF","REPEAT","RETURN","REVEAL","ROOT","SET","THEN","TO",
"TRY","TYPE","TYPECASE","UNSAFE","UNTIL","UNTRACED","VALUE","VAR","WHILE","WITH",
"CompilationUnit","interface","@1","@2","module","@3","@4","generic_interface",
"@5","generic_module","@6","generic_params","exports","import_nl_list","import_nl",
"import_item_list","block","named_block","declaration_nl_list","declaration_nl",
"const_decl_list","const_decl","@7","@8","type_decl_list","type_decl","@9","@10",
"var_decl_list","id_list1","var_decl","exception_decl_list","id_list2","exception_decl",
"procedure_head","@11","signature","return_type","raises","formals","formal_semi_list",
"formal_semi","formal","mode","type_and_or_val_semi","type_and_or_val","stmts",
"stmts_group","stmts1","stmt_list","stmt","assignment_stmt","call_stmt","case_stmt",
"case_list","case","labels_list","labels","exit_stmt","eval_stmt","for_stmt",
"by","if_stmt","else","elsif_list","elsif","lock_stmt","loop_stmt","raise_stmt",
"repeat_stmt","return_stmt","try_finally_stmt","try_stmt","handler_list","handler",
"typecase_stmt","tcase_list","tcase","while_stmt","with_stmt","binding_list",
"binding","opt_qid_list","qid_list","qid","type_list","type","type_name","type_constructor",
"type_constructor1","root_type","type_constructor2","simple_object_type_list",
"simple_object_type","methods_part","overrides_part","brand","fields","field_semi_list",
"field_semi","field","methods","method_semi_list","method_semi","method","overrides",
"override_semi_list","override_semi","override","expr","zexpr","e1","ze1","e2",
"e3","ze3","relop","e4","ze4","addop","e5","ze5","mulop","e6","e7","e8","selector_list",
"selector","expr_list","actual_list","actual","elem_list","elem","elem_tail",
"opt_id_list","id_list", NULL
};
#endif
static const short yyr1[] = { 0,
98, 98, 98, 98, 98, 98, 100, 99, 101, 99,
103, 102, 104, 102, 106, 105, 108, 107, 109, 109,
110, 110, 111, 111, 112, 112, 113, 113, 113, 113,
114, 115, 116, 116, 117, 117, 117, 117, 117, 117,
117, 117, 117, 117, 117, 117, 118, 118, 120, 119,
121, 119, 122, 122, 124, 123, 125, 123, 126, 126,
127, 127, 128, 128, 128, 129, 129, 130, 130, 131,
131, 133, 132, 134, 135, 135, 136, 136, 136, 137,
137, 137, 137, 138, 138, 139, 140, 141, 141, 141,
141, 142, 142, 142, 143, 143, 143, 144, 144, 144,
145, 145, 146, 146, 147, 147, 148, 148, 148, 148,
148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
148, 148, 148, 148, 149, 150, 151, 151, 152, 152,
153, 154, 154, 155, 155, 156, 157, 158, 159, 159,
160, 161, 161, 162, 162, 163, 164, 165, 166, 167,
168, 168, 169, 170, 170, 171, 171, 172, 172, 173,
173, 174, 174, 175, 175, 176, 177, 178, 178, 179,
180, 180, 181, 181, 182, 182, 183, 183, 184, 184,
184, 184, 184, 185, 186, 186, 187, 187, 187, 187,
187, 187, 187, 187, 187, 188, 188, 189, 189, 189,
189, 190, 190, 191, 192, 192, 193, 193, 194, 194,
194, 195, 195, 195, 195, 196, 196, 197, 198, 199,
199, 199, 199, 200, 200, 201, 201, 201, 202, 202,
202, 203, 203, 203, 203, 204, 204, 205, 206, 207,
208, 208, 209, 210, 210, 211, 211, 212, 213, 213,
214, 214, 214, 214, 214, 214, 214, 215, 216, 216,
217, 217, 217, 218, 219, 219, 220, 220, 220, 220,
221, 221, 221, 222, 223, 223, 223, 223, 223, 223,
223, 224, 224, 225, 225, 225, 225, 225, 225, 225,
226, 226, 227, 227, 228, 228, 228, 229, 229, 230,
230, 230, 231, 231, 232, 232, 233, 233
};
static const short yyr2[] = { 0,
1, 2, 1, 2, 1, 1, 0, 9, 0, 9,
0, 8, 0, 10, 0, 11, 0, 9, 0, 3,
0, 2, 0, 2, 5, 3, 1, 3, 3, 5,
4, 5, 0, 2, 4, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 0, 7,
0, 5, 1, 2, 0, 5, 0, 5, 1, 2,
1, 3, 4, 6, 4, 1, 2, 1, 3, 2,
5, 0, 4, 5, 0, 2, 0, 4, 2, 0,
1, 1, 2, 1, 2, 3, 3, 0, 1, 1,
1, 3, 5, 3, 2, 4, 2, 0, 1, 2,
0, 1, 1, 2, 1, 3, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 1, 7, 6, 0, 3,
3, 1, 3, 1, 3, 1, 2, 10, 0, 2,
7, 0, 2, 0, 2, 4, 5, 3, 2, 4,
1, 2, 5, 7, 6, 0, 3, 6, 3, 7,
6, 0, 3, 3, 6, 5, 5, 1, 3, 3,
0, 1, 1, 3, 1, 3, 1, 3, 1, 2,
2, 1, 3, 1, 1, 1, 4, 2, 2, 1,
4, 3, 3, 5, 1, 2, 1, 4, 3, 3,
3, 1, 2, 6, 0, 2, 0, 2, 0, 1,
2, 0, 1, 1, 2, 1, 2, 2, 2, 0,
1, 1, 2, 1, 2, 3, 5, 4, 2, 4,
3, 0, 1, 1, 2, 1, 2, 4, 3, 1,
1, 3, 1, 1, 3, 2, 1, 1, 1, 3,
1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
1, 1, 1, 1, 1, 3, 1, 1, 1, 1,
1, 2, 2, 2, 1, 1, 1, 1, 1, 3,
1, 0, 2, 2, 1, 3, 3, 2, 4, 2,
1, 3, 1, 3, 1, 1, 3, 1, 3, 1,
3, 3, 0, 2, 0, 1, 1, 3
};
static const short yydefact[] = { 0,
0, 0, 0, 0, 1, 3, 5, 6, 0, 0,
7, 11, 2, 4, 15, 17, 0, 0, 21, 21,
19, 19, 23, 0, 0, 0, 0, 305, 0, 0,
33, 19, 307, 22, 23, 0, 0, 306, 23, 23,
0, 0, 24, 0, 0, 0, 33, 19, 20, 33,
33, 0, 27, 0, 37, 0, 45, 0, 41, 39,
43, 34, 0, 0, 308, 0, 0, 0, 0, 0,
0, 0, 0, 26, 49, 38, 47, 0, 68, 46,
0, 66, 72, 175, 42, 53, 184, 55, 40, 61,
44, 0, 59, 33, 36, 0, 12, 33, 0, 0,
18, 0, 28, 29, 0, 0, 48, 8, 67, 0,
70, 209, 0, 0, 54, 0, 0, 60, 0, 209,
0, 0, 10, 0, 0, 0, 275, 276, 277, 278,
279, 209, 0, 0, 136, 0, 0, 0, 33, 0,
0, 212, 33, 151, 0, 33, 0, 0, 0, 108,
0, 0, 99, 105, 107, 109, 110, 111, 112, 113,
114, 115, 116, 117, 118, 119, 120, 121, 122, 123,
124, 281, 126, 240, 241, 243, 244, 247, 248, 249,
258, 259, 264, 265, 271, 282, 0, 0, 25, 0,
209, 0, 69, 209, 0, 305, 0, 210, 0, 197,
209, 0, 179, 182, 185, 195, 186, 190, 202, 0,
80, 73, 176, 209, 209, 0, 0, 62, 35, 273,
272, 0, 209, 0, 177, 0, 137, 0, 0, 0,
0, 246, 149, 0, 214, 216, 213, 0, 0, 152,
209, 0, 0, 0, 0, 0, 168, 33, 0, 33,
0, 0, 0, 251, 255, 256, 253, 254, 252, 257,
0, 263, 262, 261, 0, 267, 268, 269, 270, 0,
274, 14, 16, 30, 0, 0, 0, 0, 0, 0,
211, 188, 196, 189, 0, 0, 180, 0, 181, 203,
212, 209, 91, 89, 90, 0, 82, 84, 81, 0,
0, 0, 65, 0, 63, 280, 199, 209, 209, 129,
0, 33, 33, 148, 200, 217, 215, 0, 209, 218,
219, 0, 201, 156, 33, 162, 33, 0, 0, 33,
0, 32, 106, 125, 242, 245, 250, 260, 266, 0,
285, 209, 0, 0, 283, 0, 52, 183, 0, 193,
209, 209, 71, 205, 192, 75, 85, 83, 0, 56,
58, 0, 178, 198, 142, 129, 0, 132, 134, 0,
144, 0, 97, 95, 150, 142, 156, 0, 173, 0,
142, 162, 0, 0, 170, 169, 0, 31, 284, 288,
275, 296, 195, 295, 0, 293, 291, 0, 290, 300,
303, 298, 0, 0, 187, 191, 220, 207, 209, 77,
86, 87, 64, 0, 33, 0, 142, 0, 33, 0,
0, 142, 147, 94, 0, 92, 0, 0, 142, 0,
33, 0, 153, 209, 0, 142, 33, 0, 166, 167,
0, 209, 287, 0, 286, 0, 0, 0, 0, 50,
194, 0, 206, 222, 224, 221, 232, 0, 76, 0,
74, 130, 143, 128, 0, 133, 131, 102, 103, 135,
139, 0, 0, 145, 96, 157, 155, 0, 174, 159,
0, 163, 161, 0, 164, 0, 297, 294, 292, 302,
301, 304, 299, 289, 0, 229, 225, 223, 0, 208,
234, 236, 233, 204, 171, 79, 127, 33, 0, 0,
0, 141, 93, 154, 0, 160, 0, 231, 0, 226,
0, 237, 235, 0, 172, 140, 33, 33, 33, 33,
228, 230, 239, 78, 0, 146, 158, 165, 227, 238,
138, 0, 0, 0
};
static const short yydefgoto[] = { 542,
5, 17, 18, 6, 19, 20, 7, 21, 8, 22,
29, 26, 31, 43, 54, 150, 66, 151, 62, 76,
77, 105, 106, 85, 86, 116, 117, 91, 92, 93,
80, 81, 82, 63, 113, 212, 410, 461, 296, 297,
298, 299, 300, 320, 321, 152, 467, 468, 153, 154,
155, 156, 157, 365, 366, 367, 368, 158, 159, 160,
510, 161, 416, 422, 474, 162, 163, 164, 165, 166,
167, 168, 376, 377, 169, 381, 382, 170, 171, 246,
247, 524, 378, 87, 383, 225, 203, 204, 205, 206,
172, 208, 209, 408, 458, 210, 234, 235, 236, 237,
453, 454, 455, 456, 500, 501, 502, 503, 173, 174,
175, 176, 177, 178, 179, 261, 180, 181, 265, 182,
183, 270, 184, 185, 186, 271, 345, 398, 395, 396,
401, 402, 449, 37, 238
};
static const short yypact[] = { 103,
-11, 22, 24, 78,-32768,-32768,-32768,-32768, 57, 85,
177, 190,-32768,-32768,-32768,-32768, 193, 225, 183, 183,
217, 217,-32768, 215, 216, 227, 248, 216, 236, 245,
167, 217,-32768, 264,-32768, 250, 257, 264,-32768,-32768,
252, 259,-32768, 98, 243, 266, 167, 217,-32768, 167,
167, 234, 260, 106, 273, 275, 277, 282, 283, 283,
285,-32768, 82, 292,-32768, 316, 843, 280, 879, 326,
216, 306, 309,-32768, 330, 273,-32768, 335,-32768, 277,
83,-32768,-32768, 350, 283,-32768,-32768, 334, 283,-32768,
285, 249,-32768,-32768,-32768, 353,-32768, 653, 332, 333,
-32768, 121,-32768, 327, 358, 357,-32768,-32768,-32768, 338,
-32768, 126, 342, 341,-32768, 364, 352,-32768, 233, 126,
345, 355,-32768, 254, 254, 233,-32768,-32768,-32768,-32768,
-32768, 880, 233, 233,-32768, 351, 233, 233, 653, 233,
233, 216, 719, 233, 310, 587, 233, 233, 354,-32768,
845, 336, 366,-32768,-32768,-32768,-32768,-32768,-32768,-32768,
-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768,
-32768,-32768, 387, 322,-32768, 370,-32768,-32768, 51,-32768,
158,-32768, 14,-32768,-32768,-32768, 391, 393,-32768, 378,
126, 233,-32768, 126, 233, 216, 233, 376, 342,-32768,
-5, 390, -1,-32768,-32768, -1,-32768, -1,-32768, -21,
2,-32768,-32768, 126, 126, 392, 46,-32768,-32768,-32768,
-32768, 402, 126, 12,-32768, 343,-32768, 411, 344, 379,
380,-32768,-32768, 381, 216,-32768,-32768, 311, 337,-32768,
126, 179, 361, 388, 423, 39,-32768, 653, 405, 455,
233, 233, 233,-32768,-32768,-32768,-32768,-32768,-32768,-32768,
254,-32768,-32768,-32768, 254,-32768,-32768,-32768,-32768, 254,
212,-32768,-32768,-32768, 427, 417, 419, 434, 424, 394,
-32768,-32768,-32768, -1, 135, 426, -1, 377, -1,-32768,
216, 126,-32768,-32768,-32768, 425, 2,-32768,-32768, 216,
428, 431,-32768, 233,-32768,-32768,-32768, 126, 126, 233,
233, 521, 653,-32768,-32768,-32768,-32768, 233, 126,-32768,
-32768, 233,-32768, 283, 653, 823, 653, 233, 354, 653,
406,-32768,-32768,-32768,-32768,-32768,-32768,-32768,-32768, 429,
-32768, 788, 233, 315,-32768, 233,-32768,-32768, 233,-32768,
126, 126,-32768, 395,-32768, 450,-32768,-32768, 311,-32768,
-32768, 435,-32768,-32768, 19,-32768, 104,-32768, 452, 382,
-32768, 413, 441, 47,-32768, 26,-32768, 150,-32768, 416,
32,-32768, 187, 422,-32768,-32768, 430,-32768,-32768,-32768,
471,-32768,-32768,-32768, 113,-32768,-32768, 161,-32768, 202,
469,-32768, 457, 460,-32768,-32768, 448, 418, 126, 420,
-32768,-32768,-32768, 233, 653, 442, 19, 233, 323, 233,
233, 127,-32768,-32768, 233,-32768, 283, 444, 26, 283,
323, 464,-32768, 126, 447, 32, 323, 467,-32768,-32768,
233, 808,-32768, 233,-32768, 233, 233, 66, 479,-32768,
-32768, 80,-32768, 448,-32768,-32768, 470, 458,-32768, 197,
-32768,-32768,-32768,-32768, 463,-32768,-32768,-32768, 478,-32768,
473, 233, 468,-32768, 486,-32768,-32768, 472,-32768,-32768,
491,-32768,-32768, 475,-32768, 494,-32768,-32768,-32768,-32768,
-32768,-32768,-32768,-32768, 283, 99,-32768,-32768, 517,-32768,
470,-32768,-32768,-32768, 283,-32768,-32768, 389, 233, 476,
443,-32768,-32768,-32768, 506,-32768, 507, 505, 283,-32768,
283,-32768,-32768, 510, 524,-32768, 653, 521, 323, 323,
-32768, 514, 519,-32768, 484,-32768,-32768,-32768,-32768,-32768,
-32768, 542, 546,-32768
};
static const short yypgoto[] = {-32768,
544,-32768,-32768, 545,-32768,-32768,-32768,-32768,-32768,-32768,
132, 538, 240,-32768,-32768,-32768, -20, -4,-32768,-32768,
483,-32768,-32768, 501, 160,-32768,-32768,-32768,-32768, 474,
-32768,-32768, 482,-32768,-32768, -197,-32768,-32768,-32768,-32768,
267, 270,-32768, 204, 209, -130, -401,-32768, -396, -249,
-32768,-32768,-32768, 203, 163,-32768, 156,-32768,-32768,-32768,
-32768,-32768, -125,-32768,-32768,-32768,-32768,-32768,-32768,-32768,
-32768,-32768, 198, 151,-32768, 199, 146,-32768,-32768,-32768,
255,-32768, 84, -307, 451, -75, 101,-32768, -332, -331,
-88, 107, -196,-32768,-32768, -146, 294,-32768, 359, 360,
-32768,-32768, 134, 136,-32768,-32768, 91, 92, -119,-32768,
346,-32768, -132,-32768,-32768,-32768, 340,-32768,-32768, 331,
-32768,-32768, -120,-32768,-32768,-32768,-32768,-32768,-32768, 157,
-32768, 162,-32768, 409, -22
};
#define YYLAST 974
static const short yytable[] = { 216,
333, 282, 34, 220, 221, 38, 222, 232, 231, 392,
393, 290, 239, 226, 227, 242, 379, 229, 230, 266,
308, 233, 469, 207, 240, 414, 44, 243, 244, 480,
70, 207, 427, -88, 469, 485, 202, 198, 434, 267,
469, 198, 67, 207, 217, 69, 67, 329, 102, 291,
304, 425, 9, 11, 285, 12, 288, 10, 292, 288,
268, 288, 254, 255, 256, 257, 258, 415, 259, -209,
305, 426, 276, 122, 415, 278, 492, 280, 283, 293,
415, 269, 124, 309, 495, 125, 330, 290, 15, 67,
290, 110, 290, 94, 126, 294, 295, 127, 128, 129,
130, 131, 207, 519, 132, 207, 95, 111, 211, 392,
393, 112, 418, 260, 73, 275, 16, 331, 277, 379,
336, 442, 479, 520, 419, 207, 207, 537, 538, 46,
74, 334, 469, 469, 207, 140, 443, 288, 301, 302,
288, 2, 288, 55, 142, 189, 3, 307, 56, 339,
145, 57, 207, 30, 194, 195, 196, 84, 430, 88,
88, 262, 1, 45, 132, 323, 2, 197, 198, 444,
431, 3, 58, 38, 263, 415, 472, 264, 432, 68,
59, 371, 372, 445, 362, 88, 60, 518, -9, 88,
369, 370, 61, 4, 380, 308, 384, 379, 373, 387,
199, -13, 375, 207, 142, 291, 446, 437, 385, 200,
145, 532, 447, 533, 352, 438, 355, 23, 201, 207,
207, 340, 394, 397, 400, 41, 403, 505, 42, 404,
207, 324, 363, 364, 506, 325, 24, 207, 25, 341,
342, 343, 344, 374, 115, 28, 32, 33, 115, 124,
428, 35, 125, 119, 496, 435, 120, 121, 333, 36,
39, 126, 207, 207, 127, 128, 129, 130, 131, 40,
124, 132, 46, 125, 47, 405, 406, 359, 50, 51,
49, 48, 126, 52, 463, 127, 128, 129, 130, 131,
53, 465, 132, 64, 369, 71, 473, 65, 369, 72,
470, 471, 140, 478, 75, 475, 78, 284, 79, 287,
484, 142, 289, 83, 84, 318, 90, 145, 319, 46,
207, 487, 394, 96, 489, 97, 490, 491, 400, -101,
99, 124, 142, 459, 125, 101, 399, 103, 145, 124,
104, -51, 125, 126, 108, 207, 127, 128, 129, 130,
131, 126, 511, 132, 127, 128, 129, 130, 131, 114,
-57, 132, 123, 187, 188, 191, 190, 133, 192, 193,
211, -101, 213, -101, 134, 214, 218, 135, 215, 219,
136, 241, 228, 137, 140, 245, 249, 138, 139, 526,
250, 251, 140, 142, 252, -104, 535, 536, 141, 145,
272, 142, 273, 143, 144, 124, 253, 145, 125, 274,
146, 281, 147, 286, 310, 311, 303, 126, 148, 149,
127, 128, 129, 130, 131, 306, 313, 132, 322, 312,
314, 315, 326, 133, 328, 327, 332, -104, 346, -104,
134, 347, 348, 135, 349, 350, 136, 291, 356, 137,
353, 351, 360, 138, 139, 361, 388, 409, 140, 413,
389, 407, 420, 423, 141, 424, 433, 142, 421, 143,
144, 124, 439, 145, 125, 441, 146, 448, 147, 452,
440, 450, 451, 126, 148, 149, 127, 128, 129, 130,
131, 457, 464, 132, 477, 481, 460, 483, 486, 133,
494, 499, 508, -100, -100, -100, 134, -100, 504, 135,
513, -100, 136, 507, 515, 137, 509, 517, 512, 138,
139, 521, 514, 527, 140, 516, 529, 530, 528, 531,
141, 534, 430, 142, 541, 143, 144, 124, 539, 145,
125, 543, 146, 540, 147, 544, -100, 13, 14, 126,
148, 149, 127, 128, 129, 130, 131, 27, 107, 132,
89, 109, 411, 357, 118, 133, 358, 412, 417, -98,
-98, -98, 134, 466, 429, 135, 462, 476, 136, 482,
436, 137, 224, 386, 354, 138, 139, 497, 525, 498,
140, 522, 523, 316, 317, 338, 141, 335, 488, 142,
337, 143, 144, 124, 279, 145, 125, 0, 146, 493,
147, 0, 0, 0, 0, 126, 148, 149, 127, 128,
129, 130, 131, 0, 0, 132, 0, 0, 0, 0,
0, 133, 0, 0, 0, 0, 0, 0, 134, -98,
0, 135, 0, -98, 136, 0, 0, 137, 0, 0,
0, 138, 139, 0, 0, 0, 140, 0, 0, 0,
0, 0, 141, 0, 0, 142, 0, 143, 144, 124,
0, 145, 125, 0, 146, 0, 147, 0, 0, 0,
0, 126, 148, 149, 127, 128, 129, 130, 131, 0,
0, 132, 0, 0, 0, 0, 0, 133, 0, 0,
0, 0, 0, -98, 134, 0, 0, 135, 0, 0,
136, 0, 0, 137, 0, 0, 0, 138, 139, 0,
0, 0, 140, 0, 0, 0, 0, 0, 141, 0,
0, 142, 0, 143, 144, 124, 0, 145, 125, 0,
146, 0, 147, 0, 0, 0, 0, 126, 148, 149,
127, 128, 129, 130, 131, 0, 0, 132, 0, 0,
0, 0, 0, 133, 0, 0, 0, 0, 0, 0,
134, 0, 0, 135, 0, 0, 136, 0, 0, 137,
0, 0, 0, 138, 139, 0, 0, 0, 140, 0,
0, 0, 0, 0, 141, 0, 0, 142, 0, 143,
144, 0, 0, 145, 124, 0, 146, 125, 147, 0,
-98, 390, 0, 0, 148, 149, 126, 195, 196, 391,
128, 129, 130, 131, 124, 0, 132, 125, 0, 197,
198, 0, 0, 0, 0, 0, 126, 195, 196, 391,
128, 129, 130, 131, 0, 0, 132, 0, 0, 197,
198, 194, 195, 196, 84, 0, 0, 140, 0, 0,
0, 132, 199, 0, 197, 198, 142, 0, 0, 0,
0, 200, 145, 0, 0, 0, 0, 140, 0, 0,
201, 0, 199, 98, 0, 248, 142, 0, 55, 0,
55, 200, 145, -209, 0, 0, 57, 199, 57, 0,
201, 142, -209, 0, 0, 0, 200, 145, 194, 195,
196, 84, 0, 0, 0, 201, 0, 58, 132, 58,
0, 197, 198, 0, 55, 59, 0, 59, 0, 100,
0, 60, 57, 60, 0, 0, 0, 61, 0, 61,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 223, 0, 58, 199, 0, 0, 0, 142, 0,
0, 59, 0, 200, 145, 0, 0, 60, 0, 0,
0, 0, 201, 61
};
static const short yycheck[] = { 119,
250, 199, 25, 124, 125, 28, 126, 140, 139, 342,
342, 208, 143, 133, 134, 146, 324, 137, 138, 6,
9, 141, 419, 112, 144, 7, 31, 147, 148, 431,
51, 120, 7, 32, 431, 437, 112, 43, 7, 26,
437, 43, 47, 132, 120, 50, 51, 9, 71, 71,
5, 5, 64, 32, 201, 32, 203, 69, 80, 206,
47, 208, 12, 13, 14, 15, 16, 49, 18, 71,
25, 25, 192, 94, 49, 195, 11, 197, 84, 78,
49, 68, 17, 72, 5, 20, 48, 284, 32, 94,
287, 9, 289, 12, 29, 94, 95, 32, 33, 34,
35, 36, 191, 5, 39, 194, 25, 25, 29, 442,
442, 29, 9, 63, 9, 191, 32, 248, 194, 427,
253, 9, 430, 25, 21, 214, 215, 529, 530, 9,
25, 251, 529, 530, 223, 70, 24, 284, 214, 215,
287, 64, 289, 46, 79, 25, 69, 223, 51, 270,
85, 54, 241, 22, 29, 30, 31, 32, 9, 59,
60, 4, 60, 32, 39, 241, 64, 42, 43, 9,
21, 69, 75, 196, 17, 49, 50, 20, 29, 48,
83, 312, 313, 23, 304, 85, 89, 495, 12, 89,
310, 311, 95, 91, 325, 9, 327, 505, 318, 330,
75, 12, 322, 292, 79, 71, 5, 21, 328, 84,
85, 519, 11, 521, 80, 29, 292, 25, 93, 308,
309, 10, 342, 343, 344, 59, 346, 31, 62, 349,
319, 53, 308, 309, 38, 57, 12, 326, 56, 28,
29, 30, 31, 319, 85, 29, 32, 32, 89, 17,
376, 25, 20, 5, 452, 381, 8, 9, 508, 12,
25, 29, 351, 352, 32, 33, 34, 35, 36, 25,
17, 39, 9, 20, 35, 351, 352, 300, 39, 40,
24, 32, 29, 32, 415, 32, 33, 34, 35, 36,
32, 417, 39, 51, 414, 62, 422, 32, 418, 40,
420, 421, 70, 429, 32, 425, 32, 201, 32, 203,
436, 79, 206, 32, 32, 5, 32, 85, 8, 9,
409, 441, 442, 32, 444, 10, 446, 447, 448, 7,
51, 17, 79, 409, 20, 10, 22, 32, 85, 17,
32, 12, 20, 29, 10, 434, 32, 33, 34, 35,
36, 29, 472, 39, 32, 33, 34, 35, 36, 10,
27, 39, 10, 32, 32, 8, 40, 45, 12, 32,
29, 49, 32, 51, 52, 12, 32, 55, 27, 25,
58, 72, 32, 61, 70, 32, 51, 65, 66, 509,
25, 5, 70, 79, 73, 7, 527, 528, 76, 85,
10, 79, 10, 81, 82, 17, 37, 85, 20, 32,
88, 36, 90, 24, 72, 5, 25, 29, 96, 97,
32, 33, 34, 35, 36, 24, 48, 39, 92, 86,
51, 51, 72, 45, 12, 48, 32, 49, 12, 51,
52, 25, 24, 55, 11, 22, 58, 71, 24, 61,
25, 58, 25, 65, 66, 25, 51, 8, 70, 25,
32, 67, 11, 51, 76, 25, 51, 79, 87, 81,
82, 17, 51, 85, 20, 5, 88, 9, 90, 32,
51, 25, 23, 29, 96, 97, 32, 33, 34, 35,
36, 74, 51, 39, 51, 32, 77, 51, 32, 45,
22, 32, 25, 49, 50, 51, 52, 53, 51, 55,
25, 57, 58, 51, 24, 61, 44, 24, 51, 65,
66, 5, 51, 48, 70, 51, 21, 21, 86, 25,
76, 22, 9, 79, 51, 81, 82, 17, 25, 85,
20, 0, 88, 25, 90, 0, 92, 4, 4, 29,
96, 97, 32, 33, 34, 35, 36, 20, 76, 39,
60, 80, 359, 297, 91, 45, 297, 359, 366, 49,
50, 51, 52, 418, 377, 55, 414, 427, 58, 434,
382, 61, 132, 329, 291, 65, 66, 454, 505, 454,
70, 501, 501, 235, 235, 265, 76, 252, 442, 79,
261, 81, 82, 17, 196, 85, 20, -1, 88, 448,
90, -1, -1, -1, -1, 29, 96, 97, 32, 33,
34, 35, 36, -1, -1, 39, -1, -1, -1, -1,
-1, 45, -1, -1, -1, -1, -1, -1, 52, 53,
-1, 55, -1, 57, 58, -1, -1, 61, -1, -1,
-1, 65, 66, -1, -1, -1, 70, -1, -1, -1,
-1, -1, 76, -1, -1, 79, -1, 81, 82, 17,
-1, 85, 20, -1, 88, -1, 90, -1, -1, -1,
-1, 29, 96, 97, 32, 33, 34, 35, 36, -1,
-1, 39, -1, -1, -1, -1, -1, 45, -1, -1,
-1, -1, -1, 51, 52, -1, -1, 55, -1, -1,
58, -1, -1, 61, -1, -1, -1, 65, 66, -1,
-1, -1, 70, -1, -1, -1, -1, -1, 76, -1,
-1, 79, -1, 81, 82, 17, -1, 85, 20, -1,
88, -1, 90, -1, -1, -1, -1, 29, 96, 97,
32, 33, 34, 35, 36, -1, -1, 39, -1, -1,
-1, -1, -1, 45, -1, -1, -1, -1, -1, -1,
52, -1, -1, 55, -1, -1, 58, -1, -1, 61,
-1, -1, -1, 65, 66, -1, -1, -1, 70, -1,
-1, -1, -1, -1, 76, -1, -1, 79, -1, 81,
82, -1, -1, 85, 17, -1, 88, 20, 90, -1,
92, 24, -1, -1, 96, 97, 29, 30, 31, 32,
33, 34, 35, 36, 17, -1, 39, 20, -1, 42,
43, -1, -1, -1, -1, -1, 29, 30, 31, 32,
33, 34, 35, 36, -1, -1, 39, -1, -1, 42,
43, 29, 30, 31, 32, -1, -1, 70, -1, -1,
-1, 39, 75, -1, 42, 43, 79, -1, -1, -1,
-1, 84, 85, -1, -1, -1, -1, 70, -1, -1,
93, -1, 75, 41, -1, 41, 79, -1, 46, -1,
46, 84, 85, 71, -1, -1, 54, 75, 54, -1,
93, 79, 80, -1, -1, -1, 84, 85, 29, 30,
31, 32, -1, -1, -1, 93, -1, 75, 39, 75,
-1, 42, 43, -1, 46, 83, -1, 83, -1, 51,
-1, 89, 54, 89, -1, -1, -1, 95, -1, 95,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 72, -1, 75, 75, -1, -1, -1, 79, -1,
-1, 83, -1, 84, 85, -1, -1, 89, -1, -1,
-1, -1, 93, 95
};
/* -*-C-*- Note some compilers choke on comments on `#line' lines. */
#line 3 "/usr/share/bison.simple"
/* This file comes from bison-1.28. */
/* Skeleton output parser for bison,
Copyright (C) 1984, 1989, 1990 Free Software Foundation, Inc.
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, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* As a special exception, when this file is copied by Bison into a
Bison output file, you may use that output file without restriction.
This special exception was added by the Free Software Foundation
in version 1.24 of Bison. */
/* This is the parser code that is written into each bison parser
when the %semantic_parser declaration is not specified in the grammar.
It was written by Richard Stallman by simplifying the hairy parser
used when %semantic_parser is specified. */
#ifndef YYSTACK_USE_ALLOCA
#ifdef alloca
#define YYSTACK_USE_ALLOCA
#else /* alloca not defined */
#ifdef __GNUC__
#define YYSTACK_USE_ALLOCA
#define alloca __builtin_alloca
#else /* not GNU C. */
#if (!defined (__STDC__) && defined (sparc)) || defined (__sparc__) || defined (__sparc) || defined (__sgi) || (defined (__sun) && defined (__i386))
#define YYSTACK_USE_ALLOCA
#include <alloca.h>
#else /* not sparc */
/* We think this test detects Watcom and Microsoft C. */
/* This used to test MSDOS, but that is a bad idea
since that symbol is in the user namespace. */
#if (defined (_MSDOS) || defined (_MSDOS_)) && !defined (__TURBOC__)
#if 0 /* No need for malloc.h, which pollutes the namespace;
instead, just don't use alloca. */
#include <malloc.h>
#endif
#else /* not MSDOS, or __TURBOC__ */
#if defined(_AIX)
/* I don't know what this was needed for, but it pollutes the namespace.
So I turned it off. rms, 2 May 1997. */
/* #include <malloc.h> */
#pragma alloca
#define YYSTACK_USE_ALLOCA
#else /* not MSDOS, or __TURBOC__, or _AIX */
#if 0
#ifdef __hpux /* haible@ilog.fr says this works for HPUX 9.05 and up,
and on HPUX 10. Eventually we can turn this on. */
#define YYSTACK_USE_ALLOCA
#define alloca __builtin_alloca
#endif /* __hpux */
#endif
#endif /* not _AIX */
#endif /* not MSDOS, or __TURBOC__ */
#endif /* not sparc */
#endif /* not GNU C */
#endif /* alloca not defined */
#endif /* YYSTACK_USE_ALLOCA not defined */
#ifdef YYSTACK_USE_ALLOCA
#define YYSTACK_ALLOC alloca
#else
#define YYSTACK_ALLOC malloc
#endif
/* Note: there must be only one dollar sign in this file.
It is replaced by the list of actions, each action
as one case of the switch. */
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY -2
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrlab1
/* Like YYERROR except do call yyerror.
This remains here temporarily to ease the
transition to the new meaning of YYERROR, for GCC.
Once GCC version 2 has supplanted version 1, this can go. */
#define YYFAIL goto yyerrlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(token, value) \
do \
if (yychar == YYEMPTY && yylen == 1) \
{ yychar = (token), yylval = (value); \
yychar1 = YYTRANSLATE (yychar); \
YYPOPSTACK; \
goto yybackup; \
} \
else \
{ yyerror ("syntax error: cannot back up"); YYERROR; } \
while (0)
#define YYTERROR 1
#define YYERRCODE 256
#ifndef YYPURE
#define YYLEX yylex()
#endif
#ifdef YYPURE
#ifdef YYLSP_NEEDED
#ifdef YYLEX_PARAM
#define YYLEX yylex(&yylval, &yylloc, YYLEX_PARAM)
#else
#define YYLEX yylex(&yylval, &yylloc)
#endif
#else /* not YYLSP_NEEDED */
#ifdef YYLEX_PARAM
#define YYLEX yylex(&yylval, YYLEX_PARAM)
#else
#define YYLEX yylex(&yylval)
#endif
#endif /* not YYLSP_NEEDED */
#endif
/* If nonreentrant, generate the variables here */
#ifndef YYPURE
int yychar; /* the lookahead symbol */
YYSTYPE yylval; /* the semantic value of the */
/* lookahead symbol */
#ifdef YYLSP_NEEDED
YYLTYPE yylloc; /* location data for the lookahead */
/* symbol */
#endif
int yynerrs; /* number of parse errors so far */
#endif /* not YYPURE */
#if YYDEBUG != 0
int yydebug; /* nonzero means print parse trace */
/* Since this is uninitialized, it does not stop multiple parsers
from coexisting. */
#endif
/* YYINITDEPTH indicates the initial size of the parser's stacks */
#ifndef YYINITDEPTH
#define YYINITDEPTH 200
#endif
/* YYMAXDEPTH is the maximum size the stacks can grow to
(effective only if the built-in stack extension method is used). */
#if YYMAXDEPTH == 0
#undef YYMAXDEPTH
#endif
#ifndef YYMAXDEPTH
#define YYMAXDEPTH 10000
#endif
/* Define __yy_memcpy. Note that the size argument
should be passed with type unsigned int, because that is what the non-GCC
definitions require. With GCC, __builtin_memcpy takes an arg
of type size_t, but it can handle unsigned int. */
#if __GNUC__ > 1 /* GNU C and GNU C++ define this. */
#define __yy_memcpy(TO,FROM,COUNT) __builtin_memcpy(TO,FROM,COUNT)
#else /* not GNU C or C++ */
#ifndef __cplusplus
/* This is the most reliable way to avoid incompatibilities
in available built-in functions on various systems. */
static void
__yy_memcpy (to, from, count)
char *to;
char *from;
unsigned int count;
{
char *f = from;
char *t = to;
int i = count;
while (i-- > 0)
*t++ = *f++;
}
#else /* __cplusplus */
/* This is the most reliable way to avoid incompatibilities
in available built-in functions on various systems. */
static void
__yy_memcpy (char *to, char *from, unsigned int count)
{
char *t = to;
char *f = from;
int i = count;
while (i-- > 0)
*t++ = *f++;
}
#endif
#endif
#line 217 "/usr/share/bison.simple"
/* The user can define YYPARSE_PARAM as the name of an argument to be passed
into yyparse. The argument should have type void *.
It should actually point to an object.
Grammar actions can access the variable by casting it
to the proper pointer type. */
#ifdef YYPARSE_PARAM
#ifdef __cplusplus
#define YYPARSE_PARAM_ARG void *YYPARSE_PARAM
#define YYPARSE_PARAM_DECL
#else /* not __cplusplus */
#define YYPARSE_PARAM_ARG YYPARSE_PARAM
#define YYPARSE_PARAM_DECL void *YYPARSE_PARAM;
#endif /* not __cplusplus */
#else /* not YYPARSE_PARAM */
#define YYPARSE_PARAM_ARG
#define YYPARSE_PARAM_DECL
#endif /* not YYPARSE_PARAM */
/* Prevent warning if -Wstrict-prototypes. */
#ifdef __GNUC__
#ifdef YYPARSE_PARAM
int yyparse (void *);
#else
int yyparse (void);
#endif
#endif
int
yyparse(YYPARSE_PARAM_ARG)
YYPARSE_PARAM_DECL
{
int yystate;
int yyn;
short *yyssp;
YYSTYPE *yyvsp;
int yyerrstatus; /* number of tokens to shift before error messages enabled */
int yychar1 = 0; /* lookahead token as an internal (translated) token number */
short yyssa[YYINITDEPTH]; /* the state stack */
YYSTYPE yyvsa[YYINITDEPTH]; /* the semantic value stack */
short *yyss = yyssa; /* refer to the stacks thru separate pointers */
YYSTYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */
#ifdef YYLSP_NEEDED
YYLTYPE yylsa[YYINITDEPTH]; /* the location stack */
YYLTYPE *yyls = yylsa;
YYLTYPE *yylsp;
#define YYPOPSTACK (yyvsp--, yyssp--, yylsp--)
#else
#define YYPOPSTACK (yyvsp--, yyssp--)
#endif
int yystacksize = YYINITDEPTH;
int yyfree_stacks = 0;
#ifdef YYPURE
int yychar;
YYSTYPE yylval;
int yynerrs;
#ifdef YYLSP_NEEDED
YYLTYPE yylloc;
#endif
#endif
YYSTYPE yyval; /* the variable used to return */
/* semantic values from the action */
/* routines */
int yylen;
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Starting parse\n");
#endif
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* Initialize stack pointers.
Waste one element of value and location stack
so that they stay on the same level as the state stack.
The wasted elements are never initialized. */
yyssp = yyss - 1;
yyvsp = yyvs;
#ifdef YYLSP_NEEDED
yylsp = yyls;
#endif
/* Push a new state, which is found in yystate . */
/* In all cases, when you get here, the value and location stacks
have just been pushed. so pushing a state here evens the stacks. */
yynewstate:
*++yyssp = yystate;
if (yyssp >= yyss + yystacksize - 1)
{
/* Give user a chance to reallocate the stack */
/* Use copies of these so that the &'s don't force the real ones into memory. */
YYSTYPE *yyvs1 = yyvs;
short *yyss1 = yyss;
#ifdef YYLSP_NEEDED
YYLTYPE *yyls1 = yyls;
#endif
/* Get the current used size of the three stacks, in elements. */
int size = yyssp - yyss + 1;
#ifdef yyoverflow
/* Each stack pointer address is followed by the size of
the data in use in that stack, in bytes. */
#ifdef YYLSP_NEEDED
/* This used to be a conditional around just the two extra args,
but that might be undefined if yyoverflow is a macro. */
yyoverflow("parser stack overflow",
&yyss1, size * sizeof (*yyssp),
&yyvs1, size * sizeof (*yyvsp),
&yyls1, size * sizeof (*yylsp),
&yystacksize);
#else
yyoverflow("parser stack overflow",
&yyss1, size * sizeof (*yyssp),
&yyvs1, size * sizeof (*yyvsp),
&yystacksize);
#endif
yyss = yyss1; yyvs = yyvs1;
#ifdef YYLSP_NEEDED
yyls = yyls1;
#endif
#else /* no yyoverflow */
/* Extend the stack our own way. */
if (yystacksize >= YYMAXDEPTH)
{
yyerror("parser stack overflow");
if (yyfree_stacks)
{
free (yyss);
free (yyvs);
#ifdef YYLSP_NEEDED
free (yyls);
#endif
}
return 2;
}
yystacksize *= 2;
if (yystacksize > YYMAXDEPTH)
yystacksize = YYMAXDEPTH;
#ifndef YYSTACK_USE_ALLOCA
yyfree_stacks = 1;
#endif
yyss = (short *) YYSTACK_ALLOC (yystacksize * sizeof (*yyssp));
__yy_memcpy ((char *)yyss, (char *)yyss1,
size * (unsigned int) sizeof (*yyssp));
yyvs = (YYSTYPE *) YYSTACK_ALLOC (yystacksize * sizeof (*yyvsp));
__yy_memcpy ((char *)yyvs, (char *)yyvs1,
size * (unsigned int) sizeof (*yyvsp));
#ifdef YYLSP_NEEDED
yyls = (YYLTYPE *) YYSTACK_ALLOC (yystacksize * sizeof (*yylsp));
__yy_memcpy ((char *)yyls, (char *)yyls1,
size * (unsigned int) sizeof (*yylsp));
#endif
#endif /* no yyoverflow */
yyssp = yyss + size - 1;
yyvsp = yyvs + size - 1;
#ifdef YYLSP_NEEDED
yylsp = yyls + size - 1;
#endif
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Stack size increased to %d\n", yystacksize);
#endif
if (yyssp >= yyss + yystacksize - 1)
YYABORT;
}
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Entering state %d\n", yystate);
#endif
goto yybackup;
yybackup:
/* Do appropriate processing given the current state. */
/* Read a lookahead token if we need one and don't already have one. */
/* yyresume: */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yyn == YYFLAG)
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* yychar is either YYEMPTY or YYEOF
or a valid token in external form. */
if (yychar == YYEMPTY)
{
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Reading a token: ");
#endif
yychar = YYLEX;
}
/* Convert token to internal form (in yychar1) for indexing tables with */
if (yychar <= 0) /* This means end of input. */
{
yychar1 = 0;
yychar = YYEOF; /* Don't call YYLEX any more */
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Now at end of input.\n");
#endif
}
else
{
yychar1 = YYTRANSLATE(yychar);
#if YYDEBUG != 0
if (yydebug)
{
fprintf (stderr, "Next token is %d (%s", yychar, yytname[yychar1]);
/* Give the individual parser a way to print the precise meaning
of a token, for further debugging info. */
#ifdef YYPRINT
YYPRINT (stderr, yychar, yylval);
#endif
fprintf (stderr, ")\n");
}
#endif
}
yyn += yychar1;
if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1)
goto yydefault;
yyn = yytable[yyn];
/* yyn is what to do for this token type in this state.
Negative => reduce, -yyn is rule number.
Positive => shift, yyn is new state.
New state is final state => don't bother to shift,
just return success.
0, or most negative number => error. */
if (yyn < 0)
{
if (yyn == YYFLAG)
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
else if (yyn == 0)
goto yyerrlab;
if (yyn == YYFINAL)
YYACCEPT;
/* Shift the lookahead token. */
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]);
#endif
/* Discard the token being shifted unless it is eof. */
if (yychar != YYEOF)
yychar = YYEMPTY;
*++yyvsp = yylval;
#ifdef YYLSP_NEEDED
*++yylsp = yylloc;
#endif
/* count tokens shifted since error; after three, turn off error status. */
if (yyerrstatus) yyerrstatus--;
yystate = yyn;
goto yynewstate;
/* Do the default action for the current state. */
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
/* Do a reduction. yyn is the number of a rule to reduce with. */
yyreduce:
yylen = yyr2[yyn];
if (yylen > 0)
yyval = yyvsp[1-yylen]; /* implement default value of the action */
#if YYDEBUG != 0
if (yydebug)
{
int i;
fprintf (stderr, "Reducing via rule %d (line %d), ",
yyn, yyrline[yyn]);
/* Print the symbols being reduced, and their result. */
for (i = yyprhs[yyn]; yyrhs[i] > 0; i++)
fprintf (stderr, "%s ", yytname[yyrhs[i]]);
fprintf (stderr, " -> %s\n", yytname[yyr1[yyn]]);
}
#endif
switch (yyn) {
case 7:
#line 74 "../parse.yacc"
{recordname(lastident, 0); recordQual(lastident); ;
break;}
case 9:
#line 79 "../parse.yacc"
{recordname(lastident, 0); recordQual(lastident); ;
break;}
case 11:
#line 85 "../parse.yacc"
{recordname(lastident, 0); recordQual(lastident);;
break;}
case 13:
#line 87 "../parse.yacc"
{recordname(lastident, 0); recordQual(lastident);;
break;}
case 15:
#line 93 "../parse.yacc"
{recordname(lastident, 0); recordQual(lastident); ;
break;}
case 17:
#line 101 "../parse.yacc"
{recordname(lastident, 0); recordQual(lastident);;
break;}
case 49:
#line 167 "../parse.yacc"
{if (!noconst) recordname(lastident, 1);;
break;}
case 51:
#line 169 "../parse.yacc"
{if (!noconst) recordname(lastident, 1);;
break;}
case 55:
#line 179 "../parse.yacc"
{if (!notypes) recordname(lastident, 1);;
break;}
case 57:
#line 181 "../parse.yacc"
{if (!notypes) recordname(lastident, 1);;
break;}
case 61:
#line 191 "../parse.yacc"
{if (!novars) recordname(lastident, 1);;
break;}
case 62:
#line 192 "../parse.yacc"
{if (!novars) recordname(lastident, 1);;
break;}
case 68:
#line 208 "../parse.yacc"
{if (!novars) recordname(lastident, 1);;
break;}
case 69:
#line 209 "../parse.yacc"
{if (!novars) recordname(lastident, 1);;
break;}
case 72:
#line 219 "../parse.yacc"
{recordname(lastident, 1);;
break;}
}
/* the action file gets copied in in place of this dollarsign */
#line 543 "/usr/share/bison.simple"
yyvsp -= yylen;
yyssp -= yylen;
#ifdef YYLSP_NEEDED
yylsp -= yylen;
#endif
#if YYDEBUG != 0
if (yydebug)
{
short *ssp1 = yyss - 1;
fprintf (stderr, "state stack now");
while (ssp1 != yyssp)
fprintf (stderr, " %d", *++ssp1);
fprintf (stderr, "\n");
}
#endif
*++yyvsp = yyval;
#ifdef YYLSP_NEEDED
yylsp++;
if (yylen == 0)
{
yylsp->first_line = yylloc.first_line;
yylsp->first_column = yylloc.first_column;
yylsp->last_line = (yylsp-1)->last_line;
yylsp->last_column = (yylsp-1)->last_column;
yylsp->text = 0;
}
else
{
yylsp->last_line = (yylsp+yylen-1)->last_line;
yylsp->last_column = (yylsp+yylen-1)->last_column;
}
#endif
/* Now "shift" the result of the reduction.
Determine what state that goes to,
based on the state we popped back to
and the rule number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTBASE] + *yyssp;
if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTBASE];
goto yynewstate;
yyerrlab: /* here on detecting error */
if (! yyerrstatus)
/* If not already recovering from an error, report this error. */
{
++yynerrs;
#ifdef YYERROR_VERBOSE
yyn = yypact[yystate];
if (yyn > YYFLAG && yyn < YYLAST)
{
int size = 0;
char *msg;
int x, count;
count = 0;
/* Start X at -yyn if nec to avoid negative indexes in yycheck. */
for (x = (yyn < 0 ? -yyn : 0);
x < (sizeof(yytname) / sizeof(char *)); x++)
if (yycheck[x + yyn] == x)
size += strlen(yytname[x]) + 15, count++;
msg = (char *) malloc(size + 15);
if (msg != 0)
{
strcpy(msg, "parse error");
if (count < 5)
{
count = 0;
for (x = (yyn < 0 ? -yyn : 0);
x < (sizeof(yytname) / sizeof(char *)); x++)
if (yycheck[x + yyn] == x)
{
strcat(msg, count == 0 ? ", expecting `" : " or `");
strcat(msg, yytname[x]);
strcat(msg, "'");
count++;
}
}
yyerror(msg);
free(msg);
}
else
yyerror ("parse error; also virtual memory exceeded");
}
else
#endif /* YYERROR_VERBOSE */
yyerror("parse error");
}
goto yyerrlab1;
yyerrlab1: /* here on error raised explicitly by an action */
if (yyerrstatus == 3)
{
/* if just tried and failed to reuse lookahead token after an error, discard it. */
/* return failure if at end of input */
if (yychar == YYEOF)
YYABORT;
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]);
#endif
yychar = YYEMPTY;
}
/* Else will try to reuse lookahead token
after shifting the error token. */
yyerrstatus = 3; /* Each real token shifted decrements this */
goto yyerrhandle;
yyerrdefault: /* current state does not do anything special for the error token. */
#if 0
/* This is wrong; only states that explicitly want error tokens
should shift them. */
yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/
if (yyn) goto yydefault;
#endif
yyerrpop: /* pop the current state because it cannot handle the error token */
if (yyssp == yyss) YYABORT;
yyvsp--;
yystate = *--yyssp;
#ifdef YYLSP_NEEDED
yylsp--;
#endif
#if YYDEBUG != 0
if (yydebug)
{
short *ssp1 = yyss - 1;
fprintf (stderr, "Error: state stack now");
while (ssp1 != yyssp)
fprintf (stderr, " %d", *++ssp1);
fprintf (stderr, "\n");
}
#endif
yyerrhandle:
yyn = yypact[yystate];
if (yyn == YYFLAG)
goto yyerrdefault;
yyn += YYTERROR;
if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR)
goto yyerrdefault;
yyn = yytable[yyn];
if (yyn < 0)
{
if (yyn == YYFLAG)
goto yyerrpop;
yyn = -yyn;
goto yyreduce;
}
else if (yyn == 0)
goto yyerrpop;
if (yyn == YYFINAL)
YYACCEPT;
#if YYDEBUG != 0
if (yydebug)
fprintf(stderr, "Shifting error token, ");
#endif
*++yyvsp = yylval;
#ifdef YYLSP_NEEDED
*++yylsp = yylloc;
#endif
yystate = yyn;
goto yynewstate;
yyacceptlab:
/* YYACCEPT comes here. */
if (yyfree_stacks)
{
free (yyss);
free (yyvs);
#ifdef YYLSP_NEEDED
free (yyls);
#endif
}
return 0;
yyabortlab:
/* YYABORT comes here. */
if (yyfree_stacks)
{
free (yyss);
free (yyvs);
#ifdef YYLSP_NEEDED
free (yyls);
#endif
}
return 1;
}
#line 681 "../parse.yacc"
yyerror(s)
char *s;
{
fprintf(stderr, "line %d: %s\n", linecnt, s);
}
#include "hash.h"
#include "lex.yy.c"
#define MAXITEMS 8000 /* X.i3 has a lot of constants! */
int itemcnt, itemcharcnt;
char *items[MAXITEMS];
setinput(fp)
FILE *fp;
{
yyin = fp;
}
char qualifier[200];
recordQual(name)
char *name;
{
strcpy(qualifier, name);
}
recordname(name, qual)
char *name;
{
char buf[200];
recordname1(name);
if (qual && qnames) {
strcpy(buf, qualifier);
strcat(buf, ".");
strcat(buf, name);
recordname1(buf);
}
}
recordname1(name)
char *name;
{
int ln;
char buf[200];
if (oldstyle) {
sprintf(buf, "%s\177%d,%d\n", linebuf, linecnt, charcnt); }
else {
sprintf(buf, "%s\177%s\177%d,%d\n", name, linebuf, linecnt, charcnt); }
ln = strlen(buf);
if (itemcnt >= MAXITEMS) {
fprintf(stderr, "help: too many items\n");
exit(1); }
items[itemcnt] = (char *)malloc(ln+1);
if (items[itemcnt] == 0) {
fprintf (stderr, "help: memory exhausted\n");
exit (1); }
strcpy(items[itemcnt], buf);
itemcnt++;
itemcharcnt += ln;
}
printit(name)
char *name;
{
int i;
printf("\014\n%s,%d\n", name, itemcharcnt);
for (i = 0; i < itemcnt; i++) {
printf("%s", items[i]); }
}
initialize()
{
itemcnt = itemcharcnt = 0;
linecnt = 1;
charcnt = charperlinecnt = 0;
}
| 40.239396 | 148 | 0.460738 | [
"object"
] |
c243c56d427f92440da946d67ea000b703656eef | 1,879 | h | C | media/capture/device_monitor_mac.h | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | media/capture/device_monitor_mac.h | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | media/capture/device_monitor_mac.h | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_CAPTURE_DEVICE_MONITOR_MAC_H_
#define MEDIA_CAPTURE_DEVICE_MONITOR_MAC_H_
#include <memory>
#include "base/macros.h"
#include "base/system_monitor/system_monitor.h"
#include "base/threading/thread_checker.h"
#include "media/base/media_export.h"
namespace {
class DeviceMonitorMacImpl;
}
namespace media {
// Class to track audio/video devices removal or addition via callback to
// base::SystemMonitor ProcessDevicesChanged(). A single object of this class
// is created from the browser main process and lives as long as this one.
class MEDIA_EXPORT DeviceMonitorMac {
public:
DeviceMonitorMac();
~DeviceMonitorMac();
// Registers the observers for the audio/video device removal, connection and
// suspension. The AVFoundation library is also loaded and initialised if the
// OS supports it. The |device_task_runner| argument represents the thread on
// which device enumeration will occur.
void StartMonitoring(
const scoped_refptr<base::SingleThreadTaskRunner>& device_task_runner);
// Method called by the internal DeviceMonitorMacImpl object
// |device_monitor_impl_| when a device of type |type| has been added to or
// removed from the system. This code executes in the notification thread.
void NotifyDeviceChanged(base::SystemMonitor::DeviceType type);
private:
std::unique_ptr<DeviceMonitorMacImpl> device_monitor_impl_;
// |thread_checker_| is used to check that constructor and StartMonitoring()
// are called in the correct thread, the UI thread, that also owns the object.
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(DeviceMonitorMac);
};
} // namespace content
#endif // MEDIA_CAPTURE_DEVICE_MONITOR_MAC_H_
| 34.796296 | 80 | 0.781799 | [
"object"
] |
c251daf036197eae29be250385aa9dfe07b5a110 | 2,853 | h | C | src/gallium/drivers/swr/rasterizer/archrast/eventmanager.h | antmicro/kvm-aosp-external-mesa3d | 9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f | [
"MIT"
] | 1 | 2022-03-26T08:39:34.000Z | 2022-03-26T08:39:34.000Z | src/gallium/drivers/swr/rasterizer/archrast/eventmanager.h | antmicro/kvm-aosp-external-mesa3d | 9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f | [
"MIT"
] | null | null | null | src/gallium/drivers/swr/rasterizer/archrast/eventmanager.h | antmicro/kvm-aosp-external-mesa3d | 9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f | [
"MIT"
] | 2 | 2018-09-19T09:53:12.000Z | 2022-01-27T09:25:20.000Z | /****************************************************************************
* Copyright (C) 2016 Intel Corporation. All Rights Reserved.
*
* 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 (including the next
* paragraph) 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.
*
* @file archrast.h
*
* @brief Definitions for the event manager.
*
******************************************************************************/
#pragma once
#include "common/os.h"
#include "gen_ar_event.hpp"
#include "gen_ar_eventhandler.hpp"
#include <vector>
namespace ArchRast
{
//////////////////////////////////////////////////////////////////////////
/// EventManager - interface to dispatch events to handlers.
/// Event handling occurs only on a single thread.
//////////////////////////////////////////////////////////////////////////
class EventManager
{
public:
EventManager() {}
~EventManager()
{
// Event manager owns destroying handler objects once attached.
///@note See comment for Detach.
for (auto pHandler : mHandlers)
{
delete pHandler;
}
}
void Attach(EventHandler* pHandler)
{
mHandlers.push_back(pHandler);
}
void Dispatch(const Event& event)
{
///@todo Add event filter check here.
for (auto pHandler : mHandlers)
{
event.Accept(pHandler);
}
}
void FlushDraw(uint32_t drawId)
{
for (auto pHandler : mHandlers)
{
pHandler->FlushDraw(drawId);
}
}
private:
// Handlers stay registered for life
void Detach(EventHandler* pHandler) { SWR_INVALID("Should not be called"); }
std::vector<EventHandler*> mHandlers;
};
};
| 32.05618 | 84 | 0.577638 | [
"vector"
] |
c25ae47ce7c636148f1dcdc5905ee342fac010a5 | 1,894 | h | C | ios/Pods/Google/Headers/GGLCore/Public/GGLContext.h | LeyuanAtCcnu/scratchjr | dd6dad1d8fddd6a0da5d70d6e952252507392b65 | [
"BSD-3-Clause"
] | 2 | 2018-10-15T03:01:12.000Z | 2019-01-16T10:49:25.000Z | ios/Pods/Google/Headers/GGLCore/Public/GGLContext.h | LeyuanAtCcnu/scratchjr | dd6dad1d8fddd6a0da5d70d6e952252507392b65 | [
"BSD-3-Clause"
] | 1 | 2018-11-28T10:49:39.000Z | 2018-11-28T10:49:39.000Z | ios/Pods/Google/Headers/GGLCore/Public/GGLContext.h | LeyuanAtCcnu/scratchjr | dd6dad1d8fddd6a0da5d70d6e952252507392b65 | [
"BSD-3-Clause"
] | null | null | null | @import Foundation;
@class GGLConfiguration;
@class GGLIdentity;
/**
* Main entry point for Google API core configuration. Developers should call
* -[[GGLContext sharedInstance] configureWithError:] to configure the integrated services such as
* AdMob, Analytics, AppInvite, CloudMessaging, SignIn, etc. See GGLContext+ServiceName
* for details on the individual APIs. Generally, you will import those files
* directly rather than import the GGLContext.h header itself.
*
* Once the appropriate categories are imported, you can configure all services via the
* |configureWithError:| method, for example:
*
* NSError* configureError;
* [[GGLContext sharedInstance] configureWithError: &configureError];
* if (configureError != nil) {
* NSLog(@"Error configuring the Google context: %@", configureError);
* }
*
* @see GGLContext (AdMob)
* @see GGLContext (Analytics)
* @see GGLContext (AppInvite)
* @see GGLContext (CloudMessaging)
* @see GGLContext (SignIn)
*/
@interface GGLContext : NSObject
/**
* The configuration details for various Google APIs.
*/
@property(nonatomic, readonly, strong) GGLConfiguration *configuration;
/**
* Get the shared instance of the GGLContext.
* @return the shared instance
*/
+ (instancetype)sharedInstance;
/**
* Configures all the Google services integrated. This method should be called after the app is
* launched and before using other Google services. The services will be available in categories
* that extend this class, such as GGLContext+AdMob.
*
* @param error Pointer to an NSError that can be used an out param to report the status of this
* operation. After the call the error object will be nil if the operation is succesful,
* otherwise contains an appropriate NSError value. Parameter cannot be passed as nil
*
* @warning error must not be nil.
*
*/
- (void)configureWithError:(NSError **)error;
@end
| 33.821429 | 98 | 0.750264 | [
"object"
] |
c26122bff5cb357c37ae6fe7533f82c10367d0b2 | 4,394 | h | C | aws-cpp-sdk-braket/include/aws/braket/model/InstanceConfig.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-braket/include/aws/braket/model/InstanceConfig.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-braket/include/aws/braket/model/InstanceConfig.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/braket/Braket_EXPORTS.h>
#include <aws/braket/model/InstanceType.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Braket
{
namespace Model
{
/**
* <p>Configures the resource instances to use while running the Amazon Braket
* hybrid job on Amazon Braket.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/braket-2019-09-01/InstanceConfig">AWS
* API Reference</a></p>
*/
class AWS_BRAKET_API InstanceConfig
{
public:
InstanceConfig();
InstanceConfig(Aws::Utils::Json::JsonView jsonValue);
InstanceConfig& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Configures the number of resource instances to use while running an Amazon
* Braket job on Amazon Braket. The default value is 1.</p>
*/
inline int GetInstanceCount() const{ return m_instanceCount; }
/**
* <p>Configures the number of resource instances to use while running an Amazon
* Braket job on Amazon Braket. The default value is 1.</p>
*/
inline bool InstanceCountHasBeenSet() const { return m_instanceCountHasBeenSet; }
/**
* <p>Configures the number of resource instances to use while running an Amazon
* Braket job on Amazon Braket. The default value is 1.</p>
*/
inline void SetInstanceCount(int value) { m_instanceCountHasBeenSet = true; m_instanceCount = value; }
/**
* <p>Configures the number of resource instances to use while running an Amazon
* Braket job on Amazon Braket. The default value is 1.</p>
*/
inline InstanceConfig& WithInstanceCount(int value) { SetInstanceCount(value); return *this;}
/**
* <p>Configures the type resource instances to use while running an Amazon Braket
* hybrid job.</p>
*/
inline const InstanceType& GetInstanceType() const{ return m_instanceType; }
/**
* <p>Configures the type resource instances to use while running an Amazon Braket
* hybrid job.</p>
*/
inline bool InstanceTypeHasBeenSet() const { return m_instanceTypeHasBeenSet; }
/**
* <p>Configures the type resource instances to use while running an Amazon Braket
* hybrid job.</p>
*/
inline void SetInstanceType(const InstanceType& value) { m_instanceTypeHasBeenSet = true; m_instanceType = value; }
/**
* <p>Configures the type resource instances to use while running an Amazon Braket
* hybrid job.</p>
*/
inline void SetInstanceType(InstanceType&& value) { m_instanceTypeHasBeenSet = true; m_instanceType = std::move(value); }
/**
* <p>Configures the type resource instances to use while running an Amazon Braket
* hybrid job.</p>
*/
inline InstanceConfig& WithInstanceType(const InstanceType& value) { SetInstanceType(value); return *this;}
/**
* <p>Configures the type resource instances to use while running an Amazon Braket
* hybrid job.</p>
*/
inline InstanceConfig& WithInstanceType(InstanceType&& value) { SetInstanceType(std::move(value)); return *this;}
/**
* <p>The size of the storage volume, in GB, that user wants to provision.</p>
*/
inline int GetVolumeSizeInGb() const{ return m_volumeSizeInGb; }
/**
* <p>The size of the storage volume, in GB, that user wants to provision.</p>
*/
inline bool VolumeSizeInGbHasBeenSet() const { return m_volumeSizeInGbHasBeenSet; }
/**
* <p>The size of the storage volume, in GB, that user wants to provision.</p>
*/
inline void SetVolumeSizeInGb(int value) { m_volumeSizeInGbHasBeenSet = true; m_volumeSizeInGb = value; }
/**
* <p>The size of the storage volume, in GB, that user wants to provision.</p>
*/
inline InstanceConfig& WithVolumeSizeInGb(int value) { SetVolumeSizeInGb(value); return *this;}
private:
int m_instanceCount;
bool m_instanceCountHasBeenSet;
InstanceType m_instanceType;
bool m_instanceTypeHasBeenSet;
int m_volumeSizeInGb;
bool m_volumeSizeInGbHasBeenSet;
};
} // namespace Model
} // namespace Braket
} // namespace Aws
| 31.84058 | 125 | 0.686163 | [
"model"
] |
c2628b6b1c6096502263657e7146b2d270d656bb | 3,498 | h | C | Compiler/table.h | NBao01/BUAA-Compiler-2020 | 18995f261eebda05e16e3fa85ab3d64c51cd08b4 | [
"Apache-2.0"
] | 1 | 2021-08-03T06:02:27.000Z | 2021-08-03T06:02:27.000Z | Compiler/table.h | NBao01/BUAA-Compiler-2020 | 18995f261eebda05e16e3fa85ab3d64c51cd08b4 | [
"Apache-2.0"
] | null | null | null | Compiler/table.h | NBao01/BUAA-Compiler-2020 | 18995f261eebda05e16e3fa85ab3d64c51cd08b4 | [
"Apache-2.0"
] | 1 | 2021-11-12T12:49:53.000Z | 2021-11-12T12:49:53.000Z | #ifndef __TABLE_H__
#define __TABLE_H__
#include <string>
#include <vector>
#include "abstractSyntaxTree.h"
class Reg;
// definition for type
#define CONST 0
#define VAR 1
#define FUNC 2
#define PARAM 3
// definition for retType
#define VOID 0
#define INT 1
#define CHAR 2
class TableItem {
private:
std::string* name;
int type; // CONST, VAR, FUNC, PARAM
int retType; // VOID, INT, CHAR
int scope;
int dimension;
int dims[2];
int paramNum;
std::vector<int>* paramsRetType;
std::string* label;
int offset;
bool hasInitialValue;
int initialValue;
std::vector<int>* initialValues;
int scopeInside; // For function, store their inside scope
bool inLine;
Reg* cache;
std::vector<Reg*>* caches;
public:
static int scope_i;
static int offset_i;
TableItem(std::string* name, int type, int retType, int scope);
static TableItem* newConstTableItem(std::string* name, int type, int retType, int initialValue);
static TableItem* newVarTableItem(std::string* name, int type, int retType,
int dimension,int dim0, int dim1, bool hasInitialValue, int initialValue, std::vector<int>* initialValues);
static TableItem* newFuncTableItem(std::string* name, int type, int retType);
static TableItem* newParamTableItem(std::string* name, int type, int retType);
bool isSameScope(int curScope);
bool isSameName(std::string* name);
// Getters
std::string* getName();
int getType();
int getRetType();
int getScope();
int getDimension();
int getDim0();
int getDim1();
int getParamNum();
std::vector<int>* getParamsRetType();
std::string* getLabel();
int getOffset();
bool getHasInitialValue();
int getInitialValue();
std::vector<int>* getInitialValues();
int getScopeInside();
bool isInline();
Reg* getCache();
Reg* getCache(int n);
// Setters
void setDimension(int dimension, int dim0, int dim1);
void setParams(int paramNum, std::vector<int>* paramsRetType);
void setLabel(std::string* label);
void setOffset(int offset);
void setHasInitialValue(bool hasInitialValue);
void setInitialValue(int initialValue);
void setInitialValues(std::vector<int>* initialValues);
void setScopeInside(int scopeInside);
void setInline(bool inLine);
void setCache(Reg* reg);
void setCache(Reg* reg, int n);
};
extern std::vector<TableItem*> table;
class TableTools {
private:
static std::string* name;
static int type;
static int retType;
static int it_prev; // iterator of wordlist, stored to ensure the range of parts of the program.
static std::vector<int> stackSpace; // stack space of each scope, stackSpace[0] is scope_1's space.
public:
// Stack Tools
static void setStackSpaceOfScope(int space);
static int getstackSpaceOfScope(int scope);
static int getstackSpaceOfScope(std::string* funcName);
// Table Construct Tools
static void addConsts(int it);
static void addVars(int it);
static void addFunc(int it);
static int parseInitialValue(int& i);
// Table Search Tools
static bool isVoidFunc(std::string* word);
static bool isCharType(SymbolNode* node);
static bool errorJudgerC(Word* word);
static bool errorJudgerD(Word* word, SymbolNode* node);
static bool errorJudgerE(Word* word, SymbolNode* node);
static bool errorJudgerGH(int stage, int key, int line = 0);
static bool errorJudgerJ(Word* word);
static bool errorJudgerO(SymbolNode* node, int stage);
static TableItem* search(std::string* name, int scope);
static TableItem* searchByLabel(std::string* label);
// Cache Tool
static void cacheFlush();
};
#endif // !__TABLE_H__
| 29.394958 | 109 | 0.74271 | [
"vector"
] |
c267967b2a5ed6d187295ec3fae246846a6c1ba2 | 18,309 | c | C | src/cmdlineflags.c | lukasz-wiecaszek/cmdlineflags | f2a7bbcdb0668cd1e6bd6a2123ff502e1040e730 | [
"MIT"
] | null | null | null | src/cmdlineflags.c | lukasz-wiecaszek/cmdlineflags | f2a7bbcdb0668cd1e6bd6a2123ff502e1040e730 | [
"MIT"
] | null | null | null | src/cmdlineflags.c | lukasz-wiecaszek/cmdlineflags | f2a7bbcdb0668cd1e6bd6a2123ff502e1040e730 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT */
/**
* @file cmdlineflags.c
*
* @author Lukasz Wiecaszek <lukasz.wiecaszek@gmail.com>
*/
/*===========================================================================*\
* system header files
\*===========================================================================*/
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
/*===========================================================================*\
* project header files
\*===========================================================================*/
#include <cmdlineflags.h>
/*===========================================================================*\
* preprocessor #define constants and macros
\*===========================================================================*/
#define PRINT_ERROR(...) \
if (cmdlineflags_cfg.emit_debug_messages) fprintf(stderr, __VA_ARGS__)
/*===========================================================================*\
* local type definitions
\*===========================================================================*/
/*===========================================================================*\
* global (external linkage) object definitions
\*===========================================================================*/
/*===========================================================================*\
* local (internal linkage) function declarations
\*===========================================================================*/
static int cmdlineflags_compare(const struct cmdlineflags* l, const struct cmdlineflags* r);
static void cmdlinefags_add(const struct cmdlineflags** cmdlineflags, size_t n_options, const struct cmdlineflags* it);
static int cmdlinefags_build_help_msg(const struct cmdlineflags** cmdlineflags, size_t n_options, char* msg, unsigned size);
static const struct cmdlineflags** cmdlineflags_combine_options(size_t* n_options, bool sort);
/*===========================================================================*\
* local (internal linkage) object definitions
\*===========================================================================*/
static const struct cmdlineflags cmdlineflags_short_options_0
__attribute__((__section__(CMDLINEFLAGS_SHORTOPTIONS_SECTION_NAME)))
__attribute__((__used__))
__attribute__((aligned(CMDLINEFLAGS_ALIGN))) = {0};
static const struct cmdlineflags cmdlineflags_longoptions_0
__attribute__((__section__(CMDLINEFLAGS_LONGOPTIONS_SECTION_NAME)))
__attribute__((__used__))
__attribute__((aligned(CMDLINEFLAGS_ALIGN))) = {0};
static struct cmdlineflags_cfg cmdlineflags_cfg = {
.emit_debug_messages = 1,
};
/*===========================================================================*\
* static inline (internal linkage) function definitions
\*===========================================================================*/
static inline int cmdlineflags_longoptionscmp(char const* str1, char const* str2)
{
char c1;
char c2;
int d;
do {
c1 = *str1;
if (c1 == '_')
c1 = '-';
c2 = *str2;
if (c2 == '_')
c2 = '-';
d = c1 - c2;
} while (d == 0 && *str1++ && *str2++);
return d;
}
static inline char* cmdlineflags_underscore2dash(char* dest, const char* src, size_t n)
{
if (n != 0) {
char c;
n--;
for (size_t i = 0; (i < n) && (*src != '\0'); ++i) {
c = *src++;
*dest++ = c != '_' ? c : '-'; /* I shouldn't leave it as it is ;-) */
}
*dest = '\0';
}
return dest;
}
static inline const struct cmdlineflags*
cmdlineflags_get_shortoption(const char* module, char shortoption)
{
const struct cmdlineflags* const cmdlineflags_start_addr = &CMDLINEFLAGS_SHORTOPTIONS_SECTION_START;
const struct cmdlineflags* const cmdlineflags_end_addr = &CMDLINEFLAGS_SHORTOPTIONS_SECTION_END;
const struct cmdlineflags* it;
if (module == NULL)
module = CMDLINEFLAGS_XSTR(CMDLINEFLAGS_GLOBAL_MODULE);
for (it = cmdlineflags_start_addr; it < cmdlineflags_end_addr; ++it)
if ((it->module != NULL) && (!strcmp(it->module, module)))
if (it->option.u.shortoption == shortoption)
return it;
return NULL;
}
static inline const struct cmdlineflags*
cmdlineflags_get_longoption(const char* module, const char* longoption)
{
const struct cmdlineflags* const cmdlineflags_start_addr = &CMDLINEFLAGS_LONGOPTIONS_SECTION_START;
const struct cmdlineflags* const cmdlineflags_end_addr = &CMDLINEFLAGS_LONGOPTIONS_SECTION_END;
const struct cmdlineflags* it;
if (module == NULL)
module = CMDLINEFLAGS_XSTR(CMDLINEFLAGS_GLOBAL_MODULE);
for (it = cmdlineflags_start_addr; it < cmdlineflags_end_addr; ++it)
if ((it->module != NULL) && (!strcmp(it->module, module)))
if (!cmdlineflags_longoptionscmp(it->option.u.longoption, longoption))
return it;
return NULL;
}
static inline bool cmdlineflags_is_nonoption(const char* option)
{
return (option[0] != '-') || (option[1] == '\0');
}
static inline bool cmdlineflags_is_longoption(const char* option)
{
return (option[1] == '-');
}
/*===========================================================================*\
* global (external linkage) function definitions
\*===========================================================================*/
int cmdlineflags_parse(int argc, char * const argv[])
{
int argv_index;
const char* module;
if (argc < 1)
return CMDLINEFLAGS_FAILURE;
module = NULL;
/* Start with the ARGV[1] and scan until first non-option argument */
for (argv_index = 1; argv_index < argc; argv_index++) {
const char* arg = argv[argv_index];
if (arg == NULL)
return CMDLINEFLAGS_FAILURE;
if (!strcmp(arg, "--"))
return argv_index + 1; /* The special ARGV-element '--' means end of options */
if (cmdlineflags_is_nonoption(arg)) {
if (!module) /* First non-option is treated as a module option */
module = arg;
else
return argv_index;
}
else {
bool is_longoption = cmdlineflags_is_longoption(arg);
if (is_longoption) {
const char* longoption_start = arg + 2; /* Skip the initial '--' */
const char* longoption_end;
const char* longoption;
const struct cmdlineflags* cmdlineflags;
for (longoption_end = longoption_start;
*longoption_end != '\0' && *longoption_end != '='; longoption_end++);
longoption = strndup(longoption_start, longoption_end - longoption_start);
if (!longoption)
return CMDLINEFLAGS_FAILURE;
cmdlineflags = cmdlineflags_get_longoption(module, longoption);
if (cmdlineflags) {
if (cmdlineflags->flags == CMDLINEFLAGS_NO_ARGUMENT) {
if (*longoption_end == '\0') {
if (cmdlineflags->u.f0(&cmdlineflags->option) != 0)
return free((void*)longoption), argv_index + 1;
}
else
PRINT_ERROR("%s: option '--%s' doesn't allow an argument\n", argv[0], longoption);
}
else {
if (*longoption_end != '\0') {
if (cmdlineflags->u.f1(&cmdlineflags->option, longoption_end + 1) != 0)
return free((void*)longoption), argv_index + 1;
}
else
if ((argv_index + 1) < argc) {
if (cmdlineflags->u.f1(&cmdlineflags->option, argv[++argv_index]) != 0)
return free((void*)longoption), argv_index + 1;
}
else
PRINT_ERROR("%s: option '--%s' requires an argument\n", argv[0], longoption);
}
}
else {
if (module) {
PRINT_ERROR("%s: unrecognized option '--%s' for '%s' module\n", argv[0], longoption, module);
}
else {
PRINT_ERROR("%s: unrecognized option '--%s'\n", argv[0], longoption);
}
}
free((void*)longoption);
}
else {
const char* nextchar = arg + 1; /* Skip the initial '-' */
const struct cmdlineflags* cmdlineflags;
char c;
while ((c = *nextchar++) != '\0') {
cmdlineflags = cmdlineflags_get_shortoption(module, c);
if (cmdlineflags) {
if (cmdlineflags->flags == CMDLINEFLAGS_NO_ARGUMENT) {
if (cmdlineflags->u.f0(&cmdlineflags->option) != 0)
return argv_index + 1;
}
else {
/* This is an option that requires an argument. */
if (*nextchar != '\0') {
if (cmdlineflags->u.f1(&cmdlineflags->option, nextchar) != 0)
return argv_index + 1;
/* If we end this ARGV-element by taking the rest as an argument,
we must advance to the next element now. */
break;
}
else
if ((argv_index + 1) < argc) {
if (cmdlineflags->u.f1(&cmdlineflags->option, argv[++argv_index]) != 0)
return argv_index + 1;
}
else
PRINT_ERROR("%s: option '-%c' requires an argument\n", argv[0], c);
}
}
else {
if (module) {
PRINT_ERROR("%s: unrecognized option '-%c' for '%s' module\n", argv[0], c, module);
}
else {
PRINT_ERROR("%s: unrecognized option '-%c'\n", argv[0], c);
}
}
}
}
}
}
return argv_index;
}
int cmdlineflags_get_help_msg(char* msg, unsigned size, bool sort)
{
int n;
size_t n_options;
char null_msg_buffer[1];
const struct cmdlineflags** cmdlineflags;
if (msg == NULL) {
msg = null_msg_buffer;
}
cmdlineflags = cmdlineflags_combine_options(&n_options, sort);
if (cmdlineflags == NULL)
return CMDLINEFLAGS_FAILURE;
n = cmdlinefags_build_help_msg(cmdlineflags, n_options, msg, size);
free(cmdlineflags);
return n;
}
int cmdlineflags_get_cfg(struct cmdlineflags_cfg* cfg)
{
int retval = CMDLINEFLAGS_FAILURE;
do {
if (cfg == NULL)
break;
*cfg = cmdlineflags_cfg;
retval = CMDLINEFLAGS_SUCCESS;
} while (0);
return retval;
}
int cmdlineflags_set_cfg(const struct cmdlineflags_cfg* cfg)
{
int retval = CMDLINEFLAGS_FAILURE;
do {
if (cfg == NULL)
break;
cmdlineflags_cfg = *cfg;
retval = CMDLINEFLAGS_SUCCESS;
} while (0);
return retval;
}
/*===========================================================================*\
* local (internal linkage) function definitions
\*===========================================================================*/
static int cmdlineflags_compare(const struct cmdlineflags* l, const struct cmdlineflags* r)
{
int status;
status = strcmp(l->module, r->module);
if (status) {
if (!strcmp(l->module, CMDLINEFLAGS_XSTR(CMDLINEFLAGS_GLOBAL_MODULE)))
return -1;
else
if (!strcmp(r->module, CMDLINEFLAGS_XSTR(CMDLINEFLAGS_GLOBAL_MODULE)))
return +1;
else
return status;
}
if ((l->option.type == CMDLINEFLAGS_SHORTOPTION) && ((r->option.type == CMDLINEFLAGS_LONGOPTION)))
status = l->option.u.shortoption - r->option.u.longoption[0];
else
if ((l->option.type == CMDLINEFLAGS_LONGOPTION) && ((r->option.type == CMDLINEFLAGS_SHORTOPTION))) {
status = l->option.u.longoption[0] - r->option.u.shortoption;
}
else
if ((l->option.type == CMDLINEFLAGS_LONGOPTION) && ((r->option.type == CMDLINEFLAGS_LONGOPTION)))
status = strcmp(l->option.u.longoption, r->option.u.longoption);
else
status = l->option.u.shortoption - r->option.u.shortoption;
return status;
}
static void cmdlinefags_add(
const struct cmdlineflags** cmdlineflags, size_t n_options, const struct cmdlineflags* it)
{
size_t i;
for (i = 0; i < n_options; ++i)
if (cmdlineflags_compare(it, cmdlineflags[i]) < 0)
break;
memmove(cmdlineflags + i + 1, cmdlineflags + i, (n_options - i) * sizeof(struct cmdlineflags*));
cmdlineflags[i] = it;
}
static int cmdlinefags_build_help_msg(
const struct cmdlineflags** cmdlineflags, size_t n_options, char* msg, unsigned size)
{
int n;
char prefix[128];
char longoption[sizeof(prefix)];
int status;
size_t remaining;
size_t i;
const char* module;
n = 0;
remaining = size;
module = NULL;
for (i = 0; i < n_options; ++i) {
const struct cmdlineflags* it = cmdlineflags[i];
if (strcmp(it->module, CMDLINEFLAGS_XSTR(CMDLINEFLAGS_GLOBAL_MODULE))) {
if ((module == NULL) || (strcmp(module, it->module))) {
module = it->module;
status = snprintf(msg, remaining, "\n%s\n", it->module);
if (status < 0)
return CMDLINEFLAGS_FAILURE;
n += status;
if (n < size) {
remaining -= status;
msg += status;
}
else
remaining = 0;
}
}
if (it->option.type == CMDLINEFLAGS_SHORTOPTION) {
const struct cmdlineflags* sibbling = it->sibbling;
if (sibbling == NULL) {
if (it->flags == CMDLINEFLAGS_NO_ARGUMENT)
status = snprintf(prefix, sizeof(prefix), "-%c",
it->option.u.shortoption);
else
status = snprintf(prefix, sizeof(prefix), "-%c <arg>",
it->option.u.shortoption);
}
else {
cmdlineflags_underscore2dash(longoption, sibbling->option.u.longoption, sizeof(longoption));
if (it->flags == CMDLINEFLAGS_NO_ARGUMENT)
status = snprintf(prefix, sizeof(prefix), "-%c, --%s",
it->option.u.shortoption, longoption);
else
status = snprintf(prefix, sizeof(prefix), "-%c, --%s <arg>",
it->option.u.shortoption, longoption);
}
}
else
if (it->option.type == CMDLINEFLAGS_LONGOPTION) {
cmdlineflags_underscore2dash(longoption, it->option.u.longoption, sizeof(longoption));
if (it->flags == CMDLINEFLAGS_NO_ARGUMENT)
status = snprintf(prefix, sizeof(prefix), "--%s", longoption);
else
status = snprintf(prefix, sizeof(prefix), "--%s <arg>", longoption);
}
else {
/* do nothing */
}
if (status < 0)
return CMDLINEFLAGS_FAILURE;
status = snprintf(msg, remaining, " %-40s : %s\n", prefix, it->help);
if (status < 0)
return CMDLINEFLAGS_FAILURE;
n += status;
if (n < size) {
remaining -= status;
msg += status;
}
else
remaining = 0;
}
return n;
}
static const struct cmdlineflags** cmdlineflags_combine_options(size_t* n_options, bool sort)
{
const struct cmdlineflags* const shortoptions_start_addr = &CMDLINEFLAGS_SHORTOPTIONS_SECTION_START;
const struct cmdlineflags* const shortoptions_end_addr = &CMDLINEFLAGS_SHORTOPTIONS_SECTION_END;
ptrdiff_t n_shortoptions_distance = shortoptions_end_addr - shortoptions_start_addr;
const struct cmdlineflags* const longoptions_start_addr = &CMDLINEFLAGS_LONGOPTIONS_SECTION_START;
const struct cmdlineflags* const longoptions_end_addr = &CMDLINEFLAGS_LONGOPTIONS_SECTION_END;
ptrdiff_t n_longoptions_distance = longoptions_end_addr - longoptions_start_addr;
if (--n_shortoptions_distance < 0)
return NULL;
if (--n_longoptions_distance < 0)
return NULL;
size_t distance = n_shortoptions_distance + n_longoptions_distance;
size_t n = 0;
const struct cmdlineflags** cmdlineflags =
calloc(distance, sizeof(struct cmdlineflags*));
if (cmdlineflags != NULL) {
const struct cmdlineflags* it;
for (it = shortoptions_start_addr; it < shortoptions_end_addr; ++it) {
if (it->module != NULL) {
if (sort)
cmdlinefags_add(cmdlineflags, n++, it);
else
cmdlineflags[n++] = it;
}
}
for (it = longoptions_start_addr; it < longoptions_end_addr; ++it) {
if ((it->module != NULL) && (it->sibbling != it)) {
if (sort)
cmdlinefags_add(cmdlineflags, n++, it);
else
cmdlineflags[n++] = it;
}
}
if (!sort) {
size_t i;
for (i = 0; i < n / 2; ++i) {
const struct cmdlineflags* it = cmdlineflags[i];
cmdlineflags[i] = cmdlineflags[n - i - 1];
cmdlineflags[n - i - 1] = it;
}
}
}
return *n_options = n, cmdlineflags;
}
| 35.759766 | 124 | 0.502704 | [
"object"
] |
c2739a7fc8bd1f5b11162e8a52b3fce443c80ac2 | 7,420 | h | C | SurgSim/Framework/ObjectFactory.h | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 24 | 2015-01-19T16:18:59.000Z | 2022-03-13T03:29:11.000Z | SurgSim/Framework/ObjectFactory.h | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 3 | 2018-12-21T14:54:08.000Z | 2022-03-14T12:38:07.000Z | SurgSim/Framework/ObjectFactory.h | dbungert/opensurgsim | bd30629f2fd83f823632293959b7654275552fa9 | [
"Apache-2.0"
] | 8 | 2015-04-10T19:45:36.000Z | 2022-02-02T17:00:59.000Z | // This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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.
#ifndef SURGSIM_FRAMEWORK_OBJECTFACTORY_H
#define SURGSIM_FRAMEWORK_OBJECTFACTORY_H
#include "SurgSim/Framework/Macros.h"
#include <string>
#include <map>
#include <boost/function.hpp>
#include <boost/functional/factory.hpp>
#include <boost/thread/mutex.hpp>
namespace SurgSim
{
namespace Framework
{
/// An object factory, once a class is registered with the factory it can
/// be used to create instances of registered classes. All the classes registered
/// need to have a default constructor.
/// \note The names used for registration and the actual c++ class names are independent
/// the className parameter here is just an identifier for the class.
/// \tparam Base the base class for all classes that can be registered with the factory.
template <typename Base>
class ObjectFactory
{
public:
/// Register a class with the factory.
/// \tparam T The specific type of the class to be registered.
/// \param className The name of this class.
/// \return true if the class was added, false if it already existed in the registry.
template <typename Derived>
bool registerClass(const std::string& className);
/// Create an instance of a class based on the specific class name.
/// \param className The class name that was used to register the class.
/// \return a shared pointer to the object of type className, fails with an
/// assertion otherwise.
std::shared_ptr<Base> create(const std::string& className);
/// Check whether the class is registered in the factory.
/// \param className Name of the class to check.
/// \return true if the factory has a constructor for this class.
bool isRegistered(const std::string& className) const;
private:
typedef boost::function<std::shared_ptr<Base>()> Constructor;
/// All the constructors.
std::map<std::string, Constructor> m_constructors;
/// Threadsafety for registration
mutable boost::mutex m_mutex;
};
/// An object factory, once a class is registered with the factory it can
/// be used to create instances of registered classes. All the classes registered
/// need to have a one parameter constructor, the type for that parameter can be
/// passed as a template parameter.
/// \note The names used for registration and the actual c++ class names are independent
/// the className parameter here is just an identifier for the class.
/// \tparam Base The base class for all classes that can be registered with the factory.
/// \tparam Parameter1 The class for the constructor parameter.
template <typename Base, typename Parameter1>
class ObjectFactory1
{
public:
/// Register a class with the factory.
/// \tparam T The specific type of the class to be registered.
/// \param className The name of this class.
/// \return true if the class was added, false if it already existed in the registry.
template <typename Derived>
bool registerClass(const std::string& className);
/// Create an instance of a class based on the specific class name, whose constructor takes 1 parameter.
/// \param className The class name.
/// \param val The value of the parameter.
/// \return a shared pointer to the object of type className instantiated with the given parameter,
/// fails with an assertion otherwise.
std::shared_ptr<Base> create(const std::string& className, const Parameter1& val);
/// Check whether the class is registered in the factory.
/// \param className Name of the class to check.
/// \return true if the factory has a constructor for this class
bool isRegistered(const std::string& className) const;
private:
typedef boost::function<std::shared_ptr<Base>(const Parameter1&)> Constructor;
/// All the constructors.
std::map<std::string, Constructor> m_constructors;
/// Threadsafety for registration
mutable boost::mutex m_mutex;
};
/// CRTP Base class to implement Object Factory functionality on a base class, use this rather than writing
/// your own functions to return the factory
/// \tparam T base class of the generated objects
template <class T>
class FactoryBase
{
public:
typedef ObjectFactory<T> FactoryType;
/// \return a reference to the factory
static FactoryType& getFactory()
{
static FactoryType factory;
return factory;
}
};
/// CRTP Base class to implement Object Factory functionality on a base class, use this rather than writing
/// your own functions to return the factory
/// \tparam T base class of the generated objects
/// \tparam P constructor parameter for object generation
template <class T, class P>
class FactoryBase1
{
public:
typedef ObjectFactory1<T, P> FactoryType;
/// \return a reference to the factory
static FactoryType& getFactory()
{
static FactoryType factory;
return factory;
}
};
};
};
#include "SurgSim/Framework/ObjectFactory-inl.h"
/// Register a class with a factory that is in a base class, DerivedClass has to be of type BaseClass.
/// The assignment is used to enable the execution of registerClass during static initialization time.
/// This macro should be put under the same namespace in which 'ClassName' is, to avoid symbol clashes.
/// 'BaseClass' should be the full name of the base class with namespace prefix,
/// 'DerivedClass' is 'ClassName' with namespace prefixes,
/// and 'ClassName' is the name of the class without namespace prefix.
#define SURGSIM_REGISTER(BaseClass, DerivedClass, ClassName) \
SURGSIM_USED_VARIABLE(bool SURGSIM_CONCATENATE(ClassName, Registered)) = \
BaseClass::getFactory().registerClass<DerivedClass>(#DerivedClass);
/// Force compilation of the boolean symbol SURGSIM_CONCATENATE(ClassName, Registered) in SURGSIM_REGISTER macro,
/// which in turn registers DerivedClass into BaseClass's ObjectFactory.
/// After that, DerivedClass is linked to any code which includes its header.
///
/// Boolean symbol SURGSIM_CONCATENATE(ClassName, Registered) in SURGSIM_REGISTER macro is exposed as an
/// extern variable in DerivedClass's header, and is referenced to initialize the static global variable
/// SURGSIM_CONCATENATE(ClassName, IsRegistered) in the header.
///
/// This forces the compiler to include the definition of SURGSIM_CONCATENATE(ClassName, Registered)
/// (defined most likely in the cpp file).
/// The variable SURGSIM_CONCATENATE(ClassName, IsRegistered) will never be used, so the GCC warning is disabled.
/// This macro should be put in the DerivedClass's header file, under the same namespace in which the DerivedClass is.
/// 'ClassName' should be the name of the class without any prefix.
#define SURGSIM_STATIC_REGISTRATION(ClassName) \
extern bool SURGSIM_CONCATENATE(ClassName, Registered); \
SURGSIM_USED_VARIABLE(static bool SURGSIM_CONCATENATE(ClassName, IsRegistered)) = \
SURGSIM_CONCATENATE(ClassName, Registered);
#endif // SURGSIM_FRAMEWORK_OBJECTFACTORY_H
| 39.679144 | 118 | 0.759838 | [
"object"
] |
c27b243058a3a37008688180b76af4187e25d3b9 | 1,366 | h | C | Sources/Framework/Interface/IResource.h | ViperBling/ProjectEngine | 9447345b78b869597db00e861ade0fc441d92b31 | [
"MIT"
] | null | null | null | Sources/Framework/Interface/IResource.h | ViperBling/ProjectEngine | 9447345b78b869597db00e861ade0fc441d92b31 | [
"MIT"
] | null | null | null | Sources/Framework/Interface/IResource.h | ViperBling/ProjectEngine | 9447345b78b869597db00e861ade0fc441d92b31 | [
"MIT"
] | null | null | null | #pragma once
#include "Framework/Interface/IModule.h"
#include "Framework/Common/Math/MathLib.h"
#include "assimp/scene.h"
namespace ProjectEngine
{
class GraphicsManager;
class World;
class IRenderResource{};
enum VertexFormat
{
None = 0,
VF_P3F,
VF_T2F,
VF_N3F,
VF_C4B,
};
class IVertexBuffer : public IRenderResource
{
public:
virtual void Initialize(void* data, unsigned int count, VertexFormat vf) noexcept = 0;
virtual unsigned int GetVertexSize(VertexFormat vf) noexcept = 0;
virtual void Finalize() noexcept = 0;
};
enum IndexFormat
{
IF_None = 0,
IF_UINT16,
IF_UINT32,
};
class IIndexBuffer : public IRenderResource
{
public:
virtual void Initialize(void* data, unsigned int count, IndexFormat iformat) noexcept = 0;
virtual void Finalize() noexcept = 0;
};
enum PrimitiveType
{
PT_POINT = 1,
PT_LINE,
PT_TRIANGLE,
};
class IMesh : public IRenderResource
{
public:
virtual void Initialize(aiMesh* mesh) noexcept = 0;
virtual void Render(World* world, const Matrix4f& worldMatrix) noexcept = 0;
virtual int GetValidVertexBufferCount() noexcept = 0;
virtual void Finalize() noexcept = 0;
};
} | 22.393443 | 98 | 0.619327 | [
"mesh",
"render"
] |
c27fbbed4a557ea67b66b953cc414b5dce14d7b8 | 3,436 | h | C | stdafx.h | jeon109/Forager-Imitation | c58679801bf50197aa03c1aec8f913e2a9287f86 | [
"MIT"
] | null | null | null | stdafx.h | jeon109/Forager-Imitation | c58679801bf50197aa03c1aec8f913e2a9287f86 | [
"MIT"
] | null | null | null | stdafx.h | jeon109/Forager-Imitation | c58679801bf50197aa03c1aec8f913e2a9287f86 | [
"MIT"
] | 2 | 2021-02-08T02:26:33.000Z | 2021-02-15T08:26:36.000Z | // stdafx.h : 자주 사용하지만 자주 변경되지는 않는
// 표준 시스템 포함 파일 또는 프로젝트 관련 포함 파일이
// 들어 있는 포함 파일입니다.
//
#pragma once
#include <SDKDDKVer.h>
//디버깅용 (주석치면 콘솔창이 사라진다)
//#pragma comment(linker, "/entry:WinMainCRTStartup /subsystem:console")
#define WIN32_LEAN_AND_MEAN // 거의 사용되지 않는 내용은 Windows 헤더에서 제외합니다.
// Windows 헤더 파일:
#include <Windows.h>
// C 런타임 헤더 파일입니다.
#include <crtdbg.h>
#ifdef _DEBUG
#define new new( _CLIENT_BLOCK, __FILE__, __LINE__ )
#endif
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
// C++ 런타임 헤더 파일입니다.
#include <iostream>
using namespace std;
// 자주사용하는 STL
#include <string>
#include <vector>
#include <map>
//=============================================================
// ## 내가 만든 헤더파일을 이곳에 추가한다 ##
//=============================================================
#include "commonMacroFunction.h"
#include "input.h"
#include "random.h"
#include "imageManager.h"
#include "util.h"
using namespace MY_UTIL;
#include "sceneManager.h"
#include "iniData.h"
#include "soundManager.h"
#include "TextManager.h"
#include "EffectManager.h"
#include "cameraManager.h"
#include "timeManager.h"
#include "targetingBox.h"
#include "UnitManager.h"
#include "item_Manager.h"
#include "productionManager.h"
#include "DialogueManager.h"
#include "ForagerStatManager.h"
#include "SpawnManager.h"
#include "Astar.h"
#include "saveManager.h"
#include "ItemDatabase.h"
#include "buildinginteraction.h"
//=============================================================
// ## 싱글톤을 추가한다 ##
//=============================================================
#define INPUT input::getSingleton() //세미콜론 찍으면 작동안함
#define RANDOM random::getSingleton()
#define IMAGEMANAGER imageManager::getSingleton()
#define PLAYERDATA playerData::getSingleton()
#define SCENEMANAGER sceneManager::getSingleton()
#define INIDATA iniData::getSingleton()
#define SOUNDMANAGER soundManager::getSingleton()
#define TEXTMANAGER TextManager::getSingleton()
#define EFFECTMANAGER EffectManager::getSingleton()
#define CAMERA cameraManager::getSingleton()
#define TIME timeManager::getSingleton()
#define UNITMANAGER UnitManager::getSingleton()
#define ITEMMANAGER item_Manager::getSingleton()
#define PRODUCTIONMANAGER productionManager::getSingleton()
#define DIALOGUE DialogueManager::getSingleton()
#define SAVEMANAGER saveManager::getSingleton()
#define STATMANAGER ForagerStatManager::getSingleton()
#define SPAWNMANAGER SpawnManager::getSingleton()
#define ASTAR Astar::getSingleton()
#define DATABASE ItemDatabase::getSingleton()
#define UPGRADEMANAGER buildinginteraction::getSingleton()
//=============================================================
// ## 디파인문 ## (윈도우창 초기화)
//=============================================================
#define WINNAME (LPTSTR)(TEXT("Forager by KGA22 - 김기정, 김으뜸, 전영은, 한유인"))
#define WINSTARTX 0
#define WINSTARTY 0
#define WINSIZEX 1280
#define WINSIZEY 720
#define WINSTYLE WS_CAPTION | WS_SYSMENU
//=============================================================
// ## 매크로함수 ## (클래스에서 동적할당된 부분 해제)
//=============================================================
#define SAFE_DELETE(p) {if(p) {delete (p); (p) = NULL;}}
#define SAFE_DELETE_ARRAY(p) {if(p) {delete[] (p); (p) = NULL;}}
//=============================================================
// ## 전역변수 ##
//=============================================================
extern HINSTANCE _hInstance;
extern HWND _hWnd;
extern POINT _ptMouse; | 32.11215 | 77 | 0.610012 | [
"vector"
] |
c28843f1c21153ea0b9f9cda1564977021dab3e9 | 181 | h | C | utils/Arrayutils.h | CTYKOB/Decima-Explorer | f22ef4cc0696872c412a10ee7c6e36fba5ad1bdc | [
"MIT"
] | 87 | 2019-07-06T17:37:08.000Z | 2022-03-19T18:11:00.000Z | utils/Arrayutils.h | CTYKOB/Decima-Explorer | f22ef4cc0696872c412a10ee7c6e36fba5ad1bdc | [
"MIT"
] | 13 | 2020-07-30T01:25:15.000Z | 2022-02-24T20:50:28.000Z | utils/Arrayutils.h | CTYKOB/Decima-Explorer | f22ef4cc0696872c412a10ee7c6e36fba5ad1bdc | [
"MIT"
] | 15 | 2020-07-20T06:46:55.000Z | 2022-01-05T21:03:13.000Z | #pragma once
#include <vector>
inline
void deletePointerBuffer(std::vector<char*> pointerBuffer) {
for (int i = 0; i < pointerBuffer.size(); i++) {
delete pointerBuffer[i];
}
} | 20.111111 | 60 | 0.690608 | [
"vector"
] |
c2936b05d625c308408154b69f3664d533324829 | 2,046 | h | C | nar/lib/Messaging/MessageTypes/IPCMkdir.h | webcok/nar | fda146f62f43c0d48612716299b132483700abad | [
"MIT"
] | null | null | null | nar/lib/Messaging/MessageTypes/IPCMkdir.h | webcok/nar | fda146f62f43c0d48612716299b132483700abad | [
"MIT"
] | null | null | null | nar/lib/Messaging/MessageTypes/IPCMkdir.h | webcok/nar | fda146f62f43c0d48612716299b132483700abad | [
"MIT"
] | 2 | 2019-01-11T20:14:39.000Z | 2021-04-29T10:23:31.000Z | #ifndef NAR_MESSIPCMKDIR_H
#define NAR_MESSIPCMKDIR_H
#include <string>
#include "IPCBaseRequest.h"
#include "IPCBaseResponse.h"
#include <nar/narnode/utility.h>
#include <nar/lib/nlohJson/json.hpp>
#include <vector>
namespace nar {
namespace MessageTypes {
namespace IPCMkdir {
class Request : public IPCBaseRequest {
private:
std::string _dir_name;
std::string _dest_dir;
public:
std::string get_dir_name();
std::string get_dest_dir();
void set_dir_name(std::string dn);
void set_dest_dir(std::string dd);
Request() : IPCBaseRequest(std::string("mkdir")) {}
Request(std::string dir_name, std::string username, std::string password, std::string curdir) : IPCBaseRequest(std::string("mkdir"), username, password, curdir), _dir_name(dir_name), _dest_dir(std::string("")) {}
Request(std::string dir_name, std::string dest_dir, std::string username, std::string password, std::string curdir) : IPCBaseRequest(std::string("mkdir"), username, password, curdir), _dir_name(dir_name), _dest_dir(dest_dir) {}
nlohmann::json get_myrequestjson();
void send_action(nar::Socket* skt);
/*
* returns the json form of base request
*/
nlohmann::json generate_json();
void populate_object(std::string& jsn);
//char* masctime(const struct tm *timeptr);
void print_loop(nar::Socket* skt);
};
class Response : public IPCBaseResponse {
private:
public:
Response() : IPCBaseResponse(100, std::string("ls"), 200) {}
Response( long int prog, long int sc) : IPCBaseResponse(prog, std::string("mkdir"), sc) {}
nlohmann::json give_myresponsejson();
};
}
}
}
#endif
| 38.603774 | 247 | 0.563539 | [
"vector"
] |
c299d5e847ef5cb497f098c05c648e35eb090f45 | 651,788 | c | C | files/lisp_file_09.c | nptcl/npt-amalgamation | c3cba0ba8ead1542b1227e777a7deb8a3fc24971 | [
"Unlicense"
] | null | null | null | files/lisp_file_09.c | nptcl/npt-amalgamation | c3cba0ba8ead1542b1227e777a7deb8a3fc24971 | [
"Unlicense"
] | null | null | null | files/lisp_file_09.c | nptcl/npt-amalgamation | c3cba0ba8ead1542b1227e777a7deb8a3fc24971 | [
"Unlicense"
] | null | null | null | /*
* npt -- ANSI Common Lisp Programming Language.
* https://github.com/nptcl/npt
* https://github.com/nptcl/npt-amalgamation
*
* File: lisp_file_09.c
*/
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#endif
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#endif
#define LISP_AMALGAMATION
#ifdef __cplusplus
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#endif
#include <errno.h>
#include <locale.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lisp_file.h"
/************************************************************
* subtypep_optimize.c
************************************************************/
/*
* macro
*/
static int type_optimize_(LocalRoot local, addr type, addr *value, int *ret);
static int check_optimize_(addr type, int *ret);
typedef int (*extractcalltype)(addr *, addr);
#define CheckNotDecl(x, type) (RefLispDecl(x) == type && RefNotDecl(x))
#define Return_or_optimize(call, type, ret) { \
Return(call(type, ret)); \
if (*ret) { \
return 0; \
} \
};
#define Return_check_optimize(call, type, ret) { \
Return(call(type, ret)); \
if (*ret == 0) { \
return 0; \
} \
};
#define extractcall(local, call, pos, update) { \
int __check = 0; \
addr __value = 0; \
Check(GetType(pos) != LISPTYPE_TYPE, "type error"); \
for (;;) { \
Return(call(local, pos, &__value, &__check)); \
if (! __check) { \
break; \
} \
update = 1; \
pos = __value; \
} \
}
#define extractcallnot(local, call, pos, update) { \
int __check = 0; \
addr __value = 0; \
Check(GetType(pos) != LISPTYPE_TYPE, "type error"); \
for (;;) { \
Return(call(local, pos, &__value, &__check)); \
if (! __check) { \
break; \
}\
update = 1; \
if (RefNotDecl(pos)) { \
type_revnotdecl(__value); \
} \
pos = __value; \
} \
}
/*
* optimize
*/
static int check_type_error_(addr pos, int *ret)
{
if (RefLispDecl(pos) != LISPDECL_ERROR)
return Result(ret, 0);
GetArrayType(pos, 1, &pos);
if (pos == Nil)
return Result(ret, 1);
return check_optimize_(pos, ret);
}
static int optimize_type_error_(LocalRoot local, addr pos, addr *value, int *ret)
{
Return_check_optimize(check_type_error_, pos, ret);
Return(get_error_type_(Execute_Thread, pos, &pos));
return type_optimize_(local, pos, value, ret);
}
static int check_optimized_(addr right, int *ret)
{
enum LISPDECL type;
GetLispDecl(right, &type);
*ret = (type == LISPDECL_OPTIMIZED || type == LISPDECL_SUBTYPEP);
return 0;
}
static int optimize_optimized_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_optimized_, right, ret);
if (! RefNotDecl(right)) {
GetArrayType(right, 0, value);
}
else {
GetArrayType(right, 0, &right);
type_copy_unsafe_local(local, &right, right);
type_revnotdecl(right);
*value = right;
}
return Result(ret, 1);
}
static int check_not_asterisk_(addr right, int *ret)
{
*ret = CheckNotDecl(right, LISPDECL_ASTERISK);
return 0;
}
static int optimize_not_asterisk_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_not_asterisk_, right, ret);
/* error */
return fmte_("Don't allow to use (not *).", NULL);
}
static int check_not_nil_(addr right, int *ret)
{
*ret = CheckNotDecl(right, LISPDECL_NIL);
return 0;
}
static int optimize_not_nil_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_not_nil_, right, ret);
type0_local(local, LISPDECL_T, value);
return Result(ret, 1);
}
static int check_not_t_(addr right, int *ret)
{
*ret = CheckNotDecl(right, LISPDECL_T);
return 0;
}
static int optimize_not_t_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_not_t_, right, ret);
type0_local(local, LISPDECL_NIL, value);
return Result(ret, 1);
}
/* (mod size) -> (integer 0 (size)) */
static int check_mod_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_MOD);
return 0;
}
static int optimize_mod_(LocalRoot local, addr right, addr *value, int *ret)
{
addr left, pos;
Return_check_optimize(check_mod_, right, ret);
GetArrayType(right, 0, &left);
Check(! integerp(left), "type error");
Check(! plusp_integer_debug(left), "plusp error");
fixnum_local(local, &pos, 0);
type4_local(local, LISPDECL_INTEGER, Nil, pos, T, left, value);
return Result(ret, 1);
}
/* atom -> (not cons) */
static int check_atom_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_ATOM);
return 0;
}
static int optimize_atom_(LocalRoot local, addr right, addr *value, int *ret)
{
addr left;
Return_check_optimize(check_atom_, right, ret);
type2aster_localall(local, LISPDECL_CONS, &left);
SetNotDecl(left, 1);
*value = left;
return Result(ret, 1);
}
/* list -> (or null cons) */
static int check_list_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_LIST);
return 0;
}
static int optimize_list_(LocalRoot local, addr right, addr *value, int *ret)
{
addr pos, array;
Return_check_optimize(check_list_, right, ret);
vector4_local(local, &array, 2);
/* null */
type0_local(local, LISPDECL_NULL, &pos);
SetArrayA4(array, 0, pos);
/* cons */
type2aster_localall(local, LISPDECL_CONS, &pos);
SetArrayA4(array, 1, pos);
/* result */
type1_local(local, LISPDECL_OR, array, value);
return Result(ret, 1);
}
/* boolean -> (or null (eql t)) */
static int check_boolean_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_BOOLEAN);
return 0;
}
static int optimize_boolean_(LocalRoot local, addr right, addr *value, int *ret)
{
addr pos, array;
Return_check_optimize(check_boolean_, right, ret);
vector4_local(local, &array, 2);
/* null */
type0_local(local, LISPDECL_NULL, &pos);
SetArrayA4(array, 0, pos);
/* (eql t) */
type_eql_local(local, T, &pos);
SetArrayA4(array, 1, pos);
/* result */
type1_local(local, LISPDECL_OR, array, value);
return Result(ret, 1);
}
/*
* (... type *) -> (array type 1)
* (... type size) -> (array type (size))
*/
static int extract_vector(LocalRoot local,
addr *ret, enum LISPDECL decl, addr type, addr size)
{
addr array;
if (type_asterisk_p(size)) {
fixnum_local(local, &size, 1);
type2_local(local, decl, type, size, ret);
return 1;
}
if (GetType(size) == LISPTYPE_FIXNUM) {
vector4_local(local, &array, 1);
SetArrayA4(array, 0, size);
type2_local(local, decl, type, array, ret);
return 1;
}
return 0;
}
/* sequence -> (or null cons (array * 1)) */
static int check_sequence_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_SEQUENCE);
return 0;
}
static int optimize_sequence_(LocalRoot local, addr right, addr *value, int *ret)
{
addr pos, array, type;
Return_check_optimize(check_sequence_, right, ret);
vector4_local(local, &array, 3);
/* null */
type0_local(local, LISPDECL_NULL, &pos);
SetArrayA4(array, 0, pos);
/* cons */
type2aster_localall(local, LISPDECL_CONS, &pos);
SetArrayA4(array, 1, pos);
/* (array * 1) */
type0_local(local, LISPDECL_ASTERISK, &type);
fixnum_local(local, &pos, 1);
type2_local(local, LISPDECL_ARRAY, type, pos, &pos);
SetArrayA4(array, 2, pos);
/* result */
type1_local(local, LISPDECL_OR, array, value);
return Result(ret, 1);
}
/* (vector type size) -> (array type (size)) */
static int check_vector_(addr right, int *ret)
{
if (RefLispDecl(right) != LISPDECL_VECTOR)
return Result(ret, 0);
GetArrayType(right, 1, &right);
*ret = (type_asterisk_p(right) || GetType(right) == LISPTYPE_FIXNUM);
return 0;
}
static int optimize_vector_(LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_vector_, right, ret);
GetArrayType(right, 0, &type);
GetArrayType(right, 1, &right);
extract_vector(local, value, LISPDECL_ARRAY, type, right);
return Result(ret, 1);
}
/* (simple-vector size) -> (simple-array t (size)) */
static int check_vector_type(enum LISPDECL decl, addr right)
{
if (RefLispDecl(right) != decl)
return 0;
GetArrayType(right, 0, &right);
return type_asterisk_p(right) || GetType(right) == LISPTYPE_FIXNUM;
}
static int check_simple_vector_(addr right, int *ret)
{
*ret = check_vector_type(LISPDECL_SIMPLE_VECTOR, right);
return 0;
}
static int optimize_simple_vector_(LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_simple_vector_, right, ret);
upgraded_array_t_local(local, &type);
GetArrayType(right, 0, &right);
extract_vector(local, value, LISPDECL_SIMPLE_ARRAY, type, right);
return Result(ret, 1);
}
/* (bit-vector size) -> (array bit (size)) */
static int check_bit_vector_(addr right, int *ret)
{
*ret = check_vector_type(LISPDECL_BIT_VECTOR, right);
return 0;
}
static int optimize_bit_vector_(LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_bit_vector_, right, ret);
upgraded_array_bit_local(local, &type);
GetArrayType(right, 0, &right);
extract_vector(local, value, LISPDECL_ARRAY, type, right);
return Result(ret, 1);
}
/* (simple-bit-vector size) -> (simple-array bit (size)) */
static int check_simple_bit_vector_(addr right, int *ret)
{
*ret = check_vector_type(LISPDECL_SIMPLE_BIT_VECTOR, right);
return 0;
}
static int optimize_simple_bit_vector_(
LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_simple_bit_vector_, right, ret);
upgraded_array_bit_local(local, &type);
GetArrayType(right, 0, &right);
extract_vector(local, value, LISPDECL_SIMPLE_ARRAY, type, right);
return Result(ret, 1);
}
/* extended-char -> (and character (not base-char)) */
static int check_extended_char_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_EXTENDED_CHAR);
return 0;
}
static int optimize_extended_char_(LocalRoot local, addr right, addr *value, int *ret)
{
addr array;
Return_check_optimize(check_extended_char_, right, ret);
vector4_local(local, &array, 2);
/* character */
type0_local(local, LISPDECL_CHARACTER, &right);
SetArrayA4(array, 0, right);
/* (not base-char) */
type0_local(local, LISPDECL_BASE_CHAR, &right);
SetNotDecl(right, 1);
SetArrayA4(array, 1, right);
/* result */
type1_local(local, LISPDECL_AND, array, value);
return Result(ret, 1);
}
/* (string size) -> (vector character size) */
static void extract_string(LocalRoot local, addr *value, addr right, addr type)
{
GetArrayType(right, 0, &right);
type2_local(local, LISPDECL_VECTOR, type, right, value);
}
static int check_string_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_STRING);
return 0;
}
static int optimize_string_(LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_string_, right, ret);
upgraded_array_character_local(local, &type);
extract_string(local, value, right, type);
return Result(ret, 1);
}
/* (base-string size) -> (vector base-char size) */
static int check_base_string_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_BASE_STRING);
return 0;
}
static int optimize_base_string_(LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_base_string_, right, ret);
upgraded_array_character_local(local, &type);
extract_string(local, value, right, type);
return Result(ret, 1);
}
/* (simple-string size) -> (simple-array character (size)) */
static int check_simple_string_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_SIMPLE_STRING);
return 0;
}
static int optimize_simple_string_(LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_simple_string_, right, ret);
upgraded_array_character_local(local, &type);
GetArrayType(right, 0, &right);
extract_vector(local, value, LISPDECL_SIMPLE_ARRAY, type, right);
return Result(ret, 1);
}
/* (simple-base-string size) -> (simple-array base-char (size)) */
static int check_simple_base_string_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_SIMPLE_BASE_STRING);
return 0;
}
static int optimize_simple_base_string_(
LocalRoot local, addr right, addr *value, int *ret)
{
addr type;
Return_check_optimize(check_simple_base_string_, right, ret);
upgraded_array_character_local(local, &type);
GetArrayType(right, 0, &right);
extract_vector(local, value, LISPDECL_SIMPLE_ARRAY, type, right);
return Result(ret, 1);
}
/* (signed-byte *) -> integer */
/* (signed-byte size) -> (integer -2^size-1 2^(size-1)-1) */
static int check_signed_byte_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_SIGNED_BYTE);
return 0;
}
static int optimize_signed_byte_(LocalRoot local, addr type, addr *value, int *ret)
{
addr x, y;
Return_check_optimize(check_signed_byte_, type, ret);
/* asterisk */
GetArrayType(type, 0, &y);
if (type_asterisk_p(y)) {
/* (signed-byte *) */
type4aster_localall(local, LISPDECL_INTEGER, value);
return Result(ret, 1);
}
/* (let ((v (ash 1 (1- value))))
* `(integer ,(- v) ,(1- v)))
*/
fixnum_heap(&x, 1);
Return(oneminus_integer_common_(local, y, &y));
Return(ash_integer_common_(local, x, y, &y));
Return(sign_reverse_integer_common_(y, &x));
Return(oneminus_integer_common_(local, y, &y));
Return(integer_result_local_(local, x, &x));
Return(integer_result_local_(local, y, &y));
type4_local(local, LISPDECL_INTEGER, Nil, x, Nil, y, value);
return Result(ret, 1);
}
/* (unsigned-byte *) -> (integer 0 *) */
/* (unsigned-byte size) -> (integer 0 2^size-1) */
static int check_unsigned_byte_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_UNSIGNED_BYTE);
return 0;
}
static int optimize_unsigned_byte_(LocalRoot local, addr type, addr *value, int *ret)
{
addr x, y;
Return_check_optimize(check_unsigned_byte_, type, ret);
/* asterisk */
GetArrayType(type, 0, &y);
if (type_asterisk_p(y)) {
/* (unsigned-byte *) */
fixnum_local(local, &x, 0);
type4_local(local, LISPDECL_INTEGER, Nil, x, y, y, value);
return Result(ret, 1);
}
/* (let ((v (ash 1 value)))
* `(integer 0 (,v)))
*/
fixnum_heap(&x, 1);
Return(ash_integer_common_(local, x, y, &y));
Return(oneminus_integer_common_(local, y, &y));
Return(integer_result_local_(local, y, &y));
fixnum_heap(&x, 0);
type4_local(local, LISPDECL_INTEGER, Nil, x, Nil, y, value);
return Result(ret, 1);
}
/* bit -> (integer 0 1) */
static int check_bit_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_BIT);
return 0;
}
static int optimize_bit_(LocalRoot local, addr right, addr *value, int *ret)
{
addr left;
Return_check_optimize(check_bit_, right, ret);
fixnum_local(local, &left, 0);
fixnum_local(local, &right, 1);
type4_local(local, LISPDECL_INTEGER, Nil, left, Nil, right, value);
return Result(ret, 1);
}
/* fixnum -> (integer most-negative-fixnum most-positive-fixnum) */
static int check_fixnum_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_FIXNUM);
return 0;
}
static int optimize_fixnum_(LocalRoot local, addr right, addr *value, int *ret)
{
addr left;
Return_check_optimize(check_fixnum_, right, ret);
GetConst(FIXNUM_MIN, &left);
GetConst(FIXNUM_MAX, &right);
Check(GetType(left) != LISPTYPE_FIXNUM, "type left error");
Check(GetType(right) != LISPTYPE_FIXNUM, "type left error");
type4_local(local, LISPDECL_INTEGER, Nil, left, Nil, right, value);
return Result(ret, 1);
}
/* bignum -> (and integer (not fixnum)) */
static int check_bignum_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_BIGNUM);
return 0;
}
static int optimize_bignum_(LocalRoot local, addr right, addr *value, int *ret)
{
int ignore;
addr array, pos;
Return_check_optimize(check_bignum_, right, ret);
vector4_local(local, &array, 2);
/* integer */
type4aster_localall(local, LISPDECL_INTEGER, &pos);
SetArrayA4(array, 0, pos);
/* (not fixnum) */
type0_local(local, LISPDECL_FIXNUM, &pos);
SetNotDecl(pos, 1);
Return(type_optimize_(local, pos, &pos, &ignore));
SetArrayA4(array, 1, pos);
/* bignum */
type1_local(local, LISPDECL_AND, array, value);
return Result(ret, 1);
}
/* (integer (10) (20)) -> (integer 9 19) */
static int check_integer_p(addr pos)
{
return (! type_asterisk_p(pos)) && (pos != Nil);
}
static int check_integer_(addr type, int *ret)
{
addr pos;
if (RefLispDecl(type) != LISPDECL_INTEGER)
return Result(ret, 0);
/* left */
GetArrayType(type, 0, &pos);
if (check_integer_p(pos))
return Result(ret, 1);
/* right */
GetArrayType(type, 2, &pos);
if (check_integer_p(pos))
return Result(ret, 1);
/* else */
return Result(ret, 0);
}
static int optimize_integer_less_p(addr x, addr y, int *ret)
{
if (integerp(x) && integerp(y))
return less_integer_(y, x, ret);
return Result(ret, 0);
}
static int optimize_integer_(LocalRoot local, addr type, addr *value, int *ret)
{
int check;
addr a1, a2, v1, v2, pos;
Return_check_optimize(check_integer_, type, ret);
GetArrayType(type, 0, &a1);
GetArrayType(type, 1, &v1);
GetArrayType(type, 2, &a2);
GetArrayType(type, 3, &v2);
/* left */
GetArrayType(type, 0, &pos);
if (check_integer_p(pos)) {
Return(oneplus_integer_common_(local, v1, &v1));
Return(integer_result_local_(local, v1, &v1));
a1 = Nil;
}
/* right */
GetArrayType(type, 2, &pos);
if (check_integer_p(pos)) {
Return(oneminus_integer_common_(local, v2, &v2));
Return(integer_result_local_(local, v2, &v2));
a2 = Nil;
}
/* result */
Return(optimize_integer_less_p(v1, v2, &check));
if (check)
type0_local(local, LISPDECL_NIL, value);
else
type4_local(local, LISPDECL_INTEGER, a1, v1, a2, v2, value);
type_setnotobject(*value, type);
return Result(ret, 1);
}
/* (eql nil) -> null */
static int check_eql_(addr right, int *ret)
{
if (RefLispDecl(right) != LISPDECL_EQL)
return Result(ret, 0);
GetArrayType(right, 0, &right);
return Result(ret, right == Nil);
}
static int optimize_eql_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_eql_, right, ret);
type0_local(local, LISPDECL_NULL, value);
return Result(ret, 1);
}
/* (eql 10) -> (integer 10 10) */
static void optimize_eql_range_object(
LocalRoot local, enum LISPDECL decl, addr pos, addr *value)
{
type4_local(local, decl, Nil, pos, Nil, pos, value);
}
static int optimize_eql_range_type_(LocalRoot local, addr pos, addr *value, int *ret)
{
switch (GetType(pos)) {
case LISPTYPE_FIXNUM:
case LISPTYPE_BIGNUM:
optimize_eql_range_object(local, LISPDECL_INTEGER, pos, value);
break;
case LISPTYPE_RATIO:
optimize_eql_range_object(local, LISPDECL_RATIONAL, pos, value);
break;
case LISPTYPE_SINGLE_FLOAT:
optimize_eql_range_object(local, LISPDECL_SINGLE_FLOAT, pos, value);
break;
case LISPTYPE_DOUBLE_FLOAT:
optimize_eql_range_object(local, LISPDECL_DOUBLE_FLOAT, pos, value);
break;
case LISPTYPE_LONG_FLOAT:
optimize_eql_range_object(local, LISPDECL_LONG_FLOAT, pos, value);
break;
default:
return Result(ret, 0);
}
return Result(ret, 1);
}
static int check_eql_range_(addr right, int *ret)
{
enum LISPTYPE type;
if (RefLispDecl(right) != LISPDECL_EQL)
return Result(ret, 0);
GetArrayType(right, 0, &right);
type = GetType(right);
*ret = type == LISPTYPE_FIXNUM
|| type == LISPTYPE_BIGNUM
|| type == LISPTYPE_RATIO
|| type == LISPTYPE_SINGLE_FLOAT
|| type == LISPTYPE_DOUBLE_FLOAT
|| type == LISPTYPE_LONG_FLOAT;
return 0;
}
static int optimize_eql_range_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_eql_range_, right, ret);
GetArrayType(right, 0, &right);
return optimize_eql_range_type_(local, right, value, ret);
}
/* (member) -> nil */
static int check_member1_(addr right, int *ret)
{
if (RefLispDecl(right) != LISPDECL_MEMBER)
return Result(ret, 0);
GetArrayType(right, 0, &right);
return Result(ret, LenArrayA4r(right) == 0);
}
static int optimize_member1_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_member1_, right, ret);
type0_local(local, LISPDECL_NIL, value);
return Result(ret, 1);
}
/* (member arg) -> (eql arg) */
static int check_member2_(addr right, int *ret)
{
if (RefLispDecl(right) != LISPDECL_MEMBER)
return Result(ret, 0);
GetArrayType(right, 0, &right);
return Result(ret, LenArrayA4r(right) == 1);
}
static int optimize_member2_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_member2_, right, ret);
GetArrayType(right, 0, &right);
GetArrayA4(right, 0, &right);
type_eql_local(local, right, value);
return Result(ret, 1);
}
/* (member ...) -> (or (eql arg1) (eql arg2) ...) */
static int check_member3_(addr right, int *ret)
{
if (RefLispDecl(right) != LISPDECL_MEMBER)
return Result(ret, 0);
GetArrayType(right, 0, &right);
return Result(ret, 2 <= LenArrayA4r(right));
}
static int optimize_member3_(LocalRoot local, addr right, addr *value, int *ret)
{
addr array, child;
size_t i, size;
Return_check_optimize(check_member3_, right, ret);
GetArrayType(right, 0, &right);
LenArrayA4(right, &size);
vector4_local(local, &array, size);
for (i = 0; i < size; i++) {
GetArrayA4(right, i, &child);
type_eql_local(local, child, &child);
SetArrayA4(array, i, child);
}
type1_local(local, LISPDECL_OR, array, value);
return Result(ret, 1);
}
/* (not x) -> x.not */
static int check_not_(addr right, int *ret)
{
*ret = (RefLispDecl(right) == LISPDECL_NOT);
return 0;
}
static int optimize_not_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_not_, right, ret);
if (RefNotDecl(right)) {
/* not not */
GetArrayType(right, 0, value);
}
else {
/* not */
GetArrayType(right, 0, &right);
type_copy_unsafe_local(local, &right, right);
type_revnotdecl(right);
*value = right;
}
return Result(ret, 1);
}
/* (not (and ... )) -> (or (not ...) (not ...) ...) */
/* (not (or ... )) -> (and (not ...) (not ...) ...) */
static int optimize_result_(LocalRoot local, addr pos, addr *value, int *ret)
{
int check;
addr opt;
Return(type_optimize_(local, pos, &opt, &check));
*value = check? opt: pos;
if (ret)
return Result(ret, check);
else
return 0;
}
static int extract_not_andor_(LocalRoot local,
addr *value, addr right, enum LISPDECL decl)
{
addr array, pos;
size_t size, i;
GetArrayType(right, 0, &right);
LenArrayA4(right, &size);
vector4_local(local, &array, size);
for (i = 0; i < size; i++) {
GetArrayA4(right, i, &pos);
type_copy_unsafe_local(local, &pos, pos);
type_revnotdecl(pos);
Return(optimize_result_(local, pos, &pos, NULL));
SetArrayA4(array, i, pos);
}
type1_local(local, decl, array, value);
return 0;
}
static int extract_array_andor_(LocalRoot local, addr right, addr *value, int *ret)
{
int update, check;
addr array, temp, pos;
size_t size, i;
GetArrayType(right, 0, &array);
LenArrayA4(array, &size);
vector4_local(local, &temp, size);
update = 0;
for (i = 0; i < size; i++) {
GetArrayA4(array, i, &pos);
Return(optimize_result_(local, pos, &pos, &check));
update |= check;
SetArrayA4(temp, i, pos);
}
if (update) {
type_copy_unsafe_local(local, &right, right);
vector4_local(local, &array, size);
for (i = 0; i < size; i++) {
GetArrayA4(temp, i, &pos);
SetArrayA4(array, i, pos);
}
SetArrayType(right, 0, array);
*value = right;
}
return Result(ret, update);
}
static int extract_andor_(LocalRoot local,
addr right, addr *value, int *ret,
enum LISPDECL fromdecl, enum LISPDECL todecl)
{
if (RefLispDecl(right) != fromdecl)
return Result(ret, 0);
if (RefNotDecl(right)) {
Return(extract_not_andor_(local, value, right, todecl));
return Result(ret, 1);
}
return extract_array_andor_(local, right, value, ret);
}
static int check_andor_(enum LISPDECL decl, addr right, int *ret)
{
int check;
addr pos;
size_t size, i;
if (RefLispDecl(right) != decl)
return Result(ret, 0);
if (RefNotDecl(right))
return Result(ret, 1);
GetArrayType(right, 0, &right);
LenArrayA4(right, &size);
for (i = 0; i < size; i++) {
GetArrayA4(right, i, &pos);
Return(check_optimize_(pos, &check));
if (check)
return Result(ret, 1);
}
return Result(ret, 0);
}
static int check_and_(addr right, int *ret)
{
return check_andor_(LISPDECL_AND, right, ret);
}
static int optimize_and_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_and_, right, ret);
return extract_andor_(local, right, value, ret, LISPDECL_AND, LISPDECL_OR);
}
static int check_or_(addr right, int *ret)
{
return check_andor_(LISPDECL_OR, right, ret);
}
static int optimize_or_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_or_, right, ret);
return extract_andor_(local, right, value, ret, LISPDECL_OR, LISPDECL_AND);
}
/*
* and
*/
static int normlispdecl(addr pos, enum LISPDECL type)
{
return RefLispDecl(pos) == type && (! RefNotDecl(pos));
}
static int check_typeand(addr type, addr *array, size_t *size)
{
if (! normlispdecl(type, LISPDECL_AND))
return 1;
GetArrayType(type, 0, array);
LenArrayA4(*array, size);
return 0;
}
/* (and) -> t */
static int check_and1_(addr type, int *ret)
{
if (! normlispdecl(type, LISPDECL_AND))
return Result(ret, 0);
GetArrayType(type, 0, &type);
return Result(ret, LenArrayA4r(type) == 0);
}
static int optimize_and1_(LocalRoot local, addr type, addr *value, int *ret)
{
Return_check_optimize(check_and1_, type, ret);
type0_local(local, LISPDECL_T, value);
return Result(ret, 1);
}
/* (and type) -> type */
static int check_and2_(addr type, int *ret)
{
if (! normlispdecl(type, LISPDECL_AND))
return Result(ret, 0);
GetArrayType(type, 0, &type);
return Result(ret, LenArrayA4r(type) == 1);
}
static int optimize_and2_(LocalRoot local, addr type, addr *value, int *ret)
{
Return_check_optimize(check_and2_, type, ret);
GetArrayType(type, 0, &type);
GetArrayA4(type, 0, value);
return Result(ret, 1);
}
/* (and ... nil ...) -> nil */
static int check_and_vector_(enum LISPDECL decl, addr type, int *ret)
{
addr check;
size_t size, i;
if (check_typeand(type, &type, &size))
return Result(ret, 0);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (normlispdecl(check, decl))
return Result(ret, 1);
}
return Result(ret, 0);
}
static int check_and3_(addr type, int *ret)
{
return check_and_vector_(LISPDECL_NIL, type, ret);
}
static int optimize_and3_(LocalRoot local, addr type, addr *value, int *ret)
{
Return_check_optimize(check_and3_, type, ret);
type0_local(local, LISPDECL_NIL, value);
return Result(ret, 1);
}
/* (and ... t ...) -> (and ...) remove t */
static void remove_type_vector(LocalRoot local,
enum LISPDECL decl, enum LISPDECL checktype,
addr array, size_t size1, size_t size2, addr *value)
{
addr pos, check;
size_t i, k;
vector4_local(local, &pos, size2);
k = 0;
for (i = 0; i < size1; i++) {
GetArrayA4(array, i, &check);
if (! normlispdecl(check, checktype)) {
Check(size2 <= k, "size2 error1");
SetArrayA4(pos, k++, check);
}
}
Check(k != size2, "size2 error2");
type1_local(local, decl, pos, value);
}
static int check_and4_(addr type, int *ret)
{
return check_and_vector_(LISPDECL_T, type, ret);
}
static int optimize_and4_(LocalRoot local, addr type, addr *value, int *ret)
{
addr check;
size_t size, i, count;
Return_check_optimize(check_and4_, type, ret);
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
count = 0;
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (normlispdecl(check, LISPDECL_T))
count++;
}
Check(count == 0, "size error");
remove_type_vector(local, LISPDECL_AND, LISPDECL_T,
type, size, size - count, value);
return Result(ret, 1);
}
/* (and ... (and ...) ...) -> (and ...) */
static int count_andor(addr type, enum LISPDECL decl, size_t *index)
{
int result;
addr check;
size_t size, i;
Check(! normlispdecl(type, decl), "type error");
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
result = 0;
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (normlispdecl(check, decl)) {
result = 1;
count_andor(check, decl, index);
}
else {
(*index)++;
}
}
return result;
}
static void replace_andor(addr type, enum LISPDECL decl, addr array, size_t *index)
{
addr check;
size_t size, i;
Check(! normlispdecl(type, decl), "type error");
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (normlispdecl(check, decl)) {
replace_andor(check, decl, array, index);
}
else {
SetArrayA4(array, (*index)++, check);
}
}
}
static int check_andor_type_(enum LISPDECL decl, addr type, int *ret)
{
addr pos;
size_t size, i;
if (! normlispdecl(type, decl))
return Result(ret, 0);
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &pos);
if (normlispdecl(pos, decl))
return Result(ret, 1);
}
return Result(ret, 0);
}
static int check_and5_(addr type, int *ret)
{
return check_andor_type_(LISPDECL_AND, type, ret);
}
static int optimize_and5_(LocalRoot local, addr type, addr *value, int *ret)
{
addr array;
size_t size;
/* check */
Return_check_optimize(check_and5_, type, ret);
GetArrayType(type, 0, &array);
size = 0;
count_andor(type, LISPDECL_AND, &size);
Check(size == 0, "size error");
/* make type */
vector4_local(local, &array, size);
type1_local(local, LISPDECL_AND, array, value);
size = 0;
replace_andor(type, LISPDECL_AND, array, &size);
return Result(ret, 1);
}
/*
* or
*/
/* (or) -> nil */
static int check_typeor(addr type, addr *array, size_t *size)
{
if (! normlispdecl(type, LISPDECL_OR))
return 1;
GetArrayType(type, 0, array);
LenArrayA4(*array, size);
return 0;
}
static int check_or1_(addr type, int *ret)
{
if (! normlispdecl(type, LISPDECL_OR))
return Result(ret, 0);
GetArrayType(type, 0, &type);
return Result(ret, LenArrayA4r(type) == 0);
}
static int optimize_or1_(LocalRoot local, addr type, addr *value, int *ret)
{
Return_check_optimize(check_or1_, type, ret);
type0_local(local, LISPDECL_NIL, value);
return Result(ret, 1);
}
/* (or type) -> type */
static int check_or2_(addr type, int *ret)
{
if (! normlispdecl(type, LISPDECL_OR))
return Result(ret, 0);
GetArrayType(type, 0, &type);
return Result(ret, LenArrayA4r(type) == 1);
}
static int optimize_or2_(LocalRoot local, addr type, addr *value, int *ret)
{
Return_check_optimize(check_or2_, type, ret);
GetArrayType(type, 0, &type);
GetArrayA4(type, 0, value);
return Result(ret, 1);
}
/* (or ... t ...) -> t */
static int check_or_vector_(enum LISPDECL decl, addr type, int *ret)
{
addr check;
size_t size, i;
if (check_typeor(type, &type, &size))
return Result(ret, 0);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (normlispdecl(check, decl))
return Result(ret, 1);
}
return Result(ret, 0);
}
static int check_or3_(addr type, int *ret)
{
return check_or_vector_(LISPDECL_T, type, ret);
}
static int optimize_or3_(LocalRoot local, addr type, addr *value, int *ret)
{
Return_check_optimize(check_or3_, type, ret);
type0_local(local, LISPDECL_T, value);
return Result(ret, 1);
}
/* (or ... nil ...) -> (or ...) remove nil */
static int check_or4_(addr type, int *ret)
{
return check_or_vector_(LISPDECL_NIL, type, ret);
}
static int optimize_or4_(LocalRoot local, addr type, addr *value, int *ret)
{
addr check;
size_t size, i, count;
Return_check_optimize(check_or4_, type, ret);
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
count = 0;
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (normlispdecl(check, LISPDECL_NIL))
count++;
}
Check(count == 0, "size error");
remove_type_vector(local, LISPDECL_OR, LISPDECL_NIL,
type, size, size - count, value);
return Result(ret, 1);
}
/* (or ... (or ...) ...) -> (or ...) */
static int check_or5_(addr type, int *ret)
{
return check_andor_type_(LISPDECL_OR, type, ret);
}
static int optimize_or5_(LocalRoot local, addr type, addr *value, int *ret)
{
addr array;
size_t size;
/* check */
Return_check_optimize(check_or5_, type, ret);
GetArrayType(type, 0, &array);
LenArrayA4(array, &size);
size = 0;
count_andor(type, LISPDECL_OR, &size);
Check(size == 0, "size error");
/* make type */
vector4_local(local, &array, size);
type1_local(local, LISPDECL_OR, array, value);
size = 0;
replace_andor(type, LISPDECL_OR, array, &size);
return Result(ret, 1);
}
/* range check */
static int range_valid_p_(addr type, int *ret)
{
addr left1, left2, right1, right2;
LocalRoot local;
local = Local_Thread;
GetArrayType(type, 0, &left1);
GetArrayType(type, 1, &left2);
GetArrayType(type, 2, &right1);
GetArrayType(type, 3, &right2);
if (type_asterisk_p(left1) || type_asterisk_p(right1))
return Result(ret, 1);
if (left1 == Nil && right1 == Nil)
return less_equal_real_(local, left2, right2, ret);
else
return less_real_(local, left2, right2, ret);
}
static int check_range_(addr right, int *ret)
{
int check;
if (! type_range_p(right))
return Result(ret, 0);
Return(range_valid_p_(right, &check));
return Result(ret, ! check);
}
static int optimize_range_(LocalRoot local, addr right, addr *value, int *ret)
{
Return_check_optimize(check_range_, right, ret);
if (RefNotDecl(right))
type0_local(local, LISPDECL_T, value);
else
type0_local(local, LISPDECL_NIL, value);
return Result(ret, 1);
}
/*
* wake optimize
*/
static int extract_values_var_(LocalRoot local, addr right, addr *value)
{
addr root, left;
for (root = Nil; right != Nil; ) {
GetCons(right, &left, &right);
Return(optimize_result_(local, left, &left, NULL));
cons_local(local, &root, left, root);
}
nreverse(value, root);
return 0;
}
static int extract_values_rest_(LocalRoot local, addr right, addr *value)
{
int ignore;
if (right == Nil)
return 0;
else
return optimize_result_(local, right, value, &ignore);
}
static int check_some_(addr right, int *ret)
{
int check;
addr pos;
while (right != Nil) {
GetCons(right, &pos, &right);
Return(check_optimize_(pos, &check));
if (check)
return Result(ret, 1);
}
return Result(ret, 0);
}
static int check_values_rest_(addr right, int *ret)
{
if (right == Nil)
return Result(ret, 0);
else
return check_optimize_(right, ret);
}
static int check_values_(addr right, int *ret)
{
int check;
addr value;
if (RefLispDecl(right) != LISPDECL_VALUES)
return Result(ret, 0);
GetArrayType(right, 0, &value);
Return(check_some_(value, &check));
if (check)
return Result(ret, 1);
GetArrayType(right, 1, &value);
Return(check_some_(value, &check));
if (check)
return Result(ret, 1);
GetArrayType(right, 2, &value);
return check_values_rest_(value, ret);
}
static int optimize_values_(LocalRoot local, addr right, addr *value, int *ret)
{
addr var, opt, rest;
/* extract */
Return_check_optimize(check_values_, right, ret);
GetArrayType(right, 0, &var);
GetArrayType(right, 1, &opt);
GetArrayType(right, 2, &rest);
Return(extract_values_var_(local, var, &var));
Return(extract_values_var_(local, opt, &opt));
Return(extract_values_rest_(local, rest, &rest));
/* result */
type_copy_unsafe_local(local, &right, right);
SetArrayType(right, 0, var);
SetArrayType(right, 1, opt);
SetArrayType(right, 2, rest);
*value = right;
return Result(ret, 1);
}
static int extract_function_key_(LocalRoot local, addr right, addr *value)
{
addr root, left, key, type;
if (right == T)
return Result(value, T);
for (root = Nil; right != Nil; ) {
GetCons(right, &left, &right);
GetCons(left, &key, &type);
Return(optimize_result_(local, type, &type, NULL));
cons_local(local, &left, key, type);
cons_local(local, &root, left, root);
}
nreverse(value, root);
return 0;
}
static int extract_function_(LocalRoot local, addr right, addr *value)
{
addr var, opt, rest, key;
/* extract */
if (type_asterisk_p(right))
return 0;
GetArrayA2(right, 0, &var);
GetArrayA2(right, 1, &opt);
GetArrayA2(right, 2, &rest);
GetArrayA2(right, 3, &key);
Return(extract_values_var_(local, var, &var));
Return(extract_values_var_(local, opt, &opt));
Return(extract_values_rest_(local, rest, &rest));
Return(extract_function_key_(local, key, &key));
/* result */
vector2_local(local, &right, 4);
SetArrayA2(right, 0, var);
SetArrayA2(right, 1, opt);
SetArrayA2(right, 2, rest);
SetArrayA2(right, 3, key);
return Result(value, right);
}
static int check_function_key_(addr right, int *ret)
{
int check;
addr type;
if (right == T)
return Result(ret, 0);
while (right != Nil) {
GetCons(right, &type, &right);
GetCdr(type, &type);
Return(check_optimize_(type, &check));
if (check)
return Result(ret, 1);
}
return Result(ret, 0);
}
static int check_function_args_(addr right, int *ret)
{
int check;
addr value;
if (type_asterisk_p(right))
return Result(ret, 0);
GetArrayA2(right, 0, &value);
Return(check_some_(value, &check));
if (check)
return Result(ret, 1);
GetArrayA2(right, 1, &value);
Return(check_some_(value, &check));
if (check)
return Result(ret, 1);
GetArrayA2(right, 2, &value);
Return(check_values_rest_(value, &check));
if (check)
return Result(ret, 1);
GetArrayA2(right, 3, &value);
return check_function_key_(value, ret);
}
static int check_function_(addr right, int *ret)
{
int check;
enum LISPDECL decl;
addr value;
decl = RefLispDecl(right);
if (decl != LISPDECL_FUNCTION && decl != LISPDECL_COMPILED_FUNCTION)
return Result(ret, 0);
GetArrayType(right, 0, &value);
Return(check_function_args_(value, &check));
if (check)
return Result(ret, 1);
GetArrayType(right, 1, &value);
return check_optimize_(value, ret);
}
static int optimize_function_(LocalRoot local, addr right, addr *value, int *ret)
{
addr args, values;
Return_check_optimize(check_function_, right, ret);
GetArrayType(right, 0, &args);
GetArrayType(right, 1, &values);
Return(extract_function_(local, args, &args));
Return(optimize_result_(local, values, &values, NULL));
type_copydecl_unsafe_local(local, &right, right);
SetArrayType(right, 0, args);
SetArrayType(right, 1, values);
*value = right;
return Result(ret, 1);
}
static int check_cons_(addr right, int *ret)
{
int check;
addr value;
if (RefLispDecl(right) != LISPDECL_CONS)
return Result(ret, 0);
GetArrayType(right, 0, &value);
if (! type_asterisk_p(value)) {
Return(check_optimize_(value, &check));
if (check)
return Result(ret, 1);
}
GetArrayType(right, 1, &value);
if (! type_asterisk_p(value)) {
Return(check_optimize_(value, &check));
if (check)
return Result(ret, 1);
}
return Result(ret, 0);
}
static int optimize_cons(LocalRoot local, addr right, addr *value, int *ret)
{
addr car, cdr;
Return_check_optimize(check_cons_, right, ret);
GetArrayType(right, 0, &car);
GetArrayType(right, 1, &cdr);
if (! type_asterisk_p(car)) {
Return(optimize_result_(local, car, &car, NULL));
}
if (! type_asterisk_p(cdr)) {
Return(optimize_result_(local, cdr, &cdr, NULL));
}
type2_local(local, LISPDECL_CONS, car, cdr, value);
return Result(ret, 1);
}
/*
* type-optimize
*/
static int check_optimize_(addr type, int *ret)
{
Return_or_optimize(check_type_error_, type, ret);
Return_or_optimize(check_optimized_, type, ret);
Return_or_optimize(check_not_asterisk_, type, ret);
Return_or_optimize(check_not_nil_, type, ret);
Return_or_optimize(check_not_t_, type, ret);
Return_or_optimize(check_mod_, type, ret);
Return_or_optimize(check_atom_, type, ret);
Return_or_optimize(check_list_, type, ret);
Return_or_optimize(check_boolean_, type, ret);
Return_or_optimize(check_sequence_, type, ret);
Return_or_optimize(check_vector_, type, ret);
Return_or_optimize(check_simple_vector_, type, ret);
Return_or_optimize(check_bit_vector_, type, ret);
Return_or_optimize(check_simple_bit_vector_, type, ret);
Return_or_optimize(check_extended_char_, type, ret);
Return_or_optimize(check_string_, type, ret);
Return_or_optimize(check_base_string_, type, ret);
Return_or_optimize(check_simple_string_, type, ret);
Return_or_optimize(check_simple_base_string_, type, ret);
Return_or_optimize(check_signed_byte_, type, ret);
Return_or_optimize(check_unsigned_byte_, type, ret);
Return_or_optimize(check_bit_, type, ret);
Return_or_optimize(check_fixnum_, type, ret);
Return_or_optimize(check_bignum_, type, ret);
Return_or_optimize(check_integer_, type, ret);
Return_or_optimize(check_eql_, type, ret);
Return_or_optimize(check_eql_range_, type, ret);
Return_or_optimize(check_member1_, type, ret);
Return_or_optimize(check_member2_, type, ret);
Return_or_optimize(check_member3_, type, ret);
Return_or_optimize(check_not_, type, ret);
Return_or_optimize(check_and_, type, ret);
Return_or_optimize(check_or_, type, ret);
Return_or_optimize(check_and1_, type, ret);
Return_or_optimize(check_and2_, type, ret);
Return_or_optimize(check_and3_, type, ret);
Return_or_optimize(check_and4_, type, ret);
Return_or_optimize(check_and5_, type, ret);
Return_or_optimize(check_or1_, type, ret);
Return_or_optimize(check_or2_, type, ret);
Return_or_optimize(check_or3_, type, ret);
Return_or_optimize(check_or4_, type, ret);
Return_or_optimize(check_or5_, type, ret);
Return_or_optimize(check_range_, type, ret);
Return_or_optimize(check_values_, type, ret);
Return_or_optimize(check_function_, type, ret);
Return_or_optimize(check_cons_, type, ret);
return Result(ret, 0);
}
static int type_optimize_(LocalRoot local, addr type, addr *value, int *ret)
{
int update, loop;
CheckType(type, LISPTYPE_TYPE);
for (loop = 0; ; loop |= update) {
update = 0;
/* extract */
extractcall(local, optimize_type_error_, type, update);
extractcall(local, optimize_optimized_, type, update);
extractcall(local, optimize_not_asterisk_, type, update);
extractcall(local, optimize_not_nil_, type, update);
extractcall(local, optimize_not_t_, type, update);
extractcallnot(local, optimize_mod_, type, update);
extractcallnot(local, optimize_atom_, type, update);
extractcallnot(local, optimize_list_, type, update);
extractcallnot(local, optimize_boolean_, type, update);
extractcallnot(local, optimize_sequence_, type, update);
extractcallnot(local, optimize_vector_, type, update);
extractcallnot(local, optimize_simple_vector_, type, update);
extractcallnot(local, optimize_bit_vector_, type, update);
extractcallnot(local, optimize_simple_bit_vector_, type, update);
extractcallnot(local, optimize_extended_char_, type, update);
extractcallnot(local, optimize_string_, type, update);
extractcallnot(local, optimize_base_string_, type, update);
extractcallnot(local, optimize_simple_string_, type, update);
extractcallnot(local, optimize_simple_base_string_, type, update);
extractcallnot(local, optimize_signed_byte_, type, update);
extractcallnot(local, optimize_unsigned_byte_, type, update);
extractcallnot(local, optimize_bit_, type, update);
extractcallnot(local, optimize_fixnum_, type, update);
extractcallnot(local, optimize_bignum_, type, update);
extractcallnot(local, optimize_integer_, type, update);
extractcallnot(local, optimize_eql_, type, update);
extractcallnot(local, optimize_eql_range_, type, update);
extractcallnot(local, optimize_member1_, type, update);
extractcallnot(local, optimize_member2_, type, update);
extractcallnot(local, optimize_member3_, type, update);
extractcall(local, optimize_not_, type, update);
extractcall(local, optimize_and_, type, update);
extractcall(local, optimize_or_, type, update);
extractcall(local, optimize_and1_, type, update);
extractcall(local, optimize_and2_, type, update);
extractcall(local, optimize_and3_, type, update);
extractcall(local, optimize_and4_, type, update);
extractcall(local, optimize_and5_, type, update);
extractcall(local, optimize_or1_, type, update);
extractcall(local, optimize_or2_, type, update);
extractcall(local, optimize_or3_, type, update);
extractcall(local, optimize_or4_, type, update);
extractcall(local, optimize_or5_, type, update);
extractcall(local, optimize_range_, type, update);
extractcallnot(local, optimize_values_, type, update);
extractcallnot(local, optimize_function_, type, update);
extractcallnot(local, optimize_cons, type, update);
if (update == 0)
break;
}
*value = type;
return Result(ret, loop);
}
int type_optimize_local_(LocalRoot local, addr type, addr *value, int *ret)
{
CheckLocal(local);
CheckType(type, LISPTYPE_TYPE);
if (RefLispDecl(type) == LISPDECL_OPTIMIZED) {
*value = type;
return Result(ret, 0);
}
Return(type_optimize_(local, type, &type, ret));
type1_local(local, LISPDECL_OPTIMIZED, type, value);
return 0;
}
int type_optimize_heap_(LocalRoot local, addr type, addr *value, int *ret)
{
LocalStack stack;
CheckLocal(local);
CheckType(type, LISPTYPE_TYPE);
push_local(local, &stack);
Return(type_optimize_local_(local, type, &type, ret));
type_copy_heap(value, type);
rollback_local(local, stack);
return 0;
}
int type_optimized_p(addr type)
{
CheckType(type, LISPTYPE_TYPE);
return RefLispDecl(type) == LISPDECL_OPTIMIZED;
}
void get_type_optimized(addr *ret, addr type)
{
if (type_optimized_p(type)) {
GetArrayType(type, 0, ret);
}
else {
*ret = type;
}
}
int type_optimize_throw_heap_(LocalRoot local, addr type, addr *ret)
{
int check;
Return(type_optimize_heap_(local, type, &type, &check));
get_type_optimized(ret, type);
return 0;
}
/************************************************************
* subtypep_range.c
************************************************************/
/* (integetr * *) */
int range_asterisk_p(addr type)
{
addr check;
GetArrayType(type, 0, &check);
if (! type_asterisk_p(check))
return 0;
GetArrayType(type, 2, &check);
return type_asterisk_p(check);
}
/* (integer 10 *) */
int range_left_p(addr type)
{
addr check;
GetArrayType(type, 0, &check);
if (type_asterisk_p(check))
return 0;
GetArrayType(type, 2, &check);
return type_asterisk_p(check);
}
/* (integer 10 ?) */
int range_left_any_p(addr type)
{
addr check;
GetArrayType(type, 0, &check);
return ! type_asterisk_p(check);
}
/* (integer * 10) */
int range_right_p(addr type)
{
addr check;
GetArrayType(type, 0, &check);
if (! type_asterisk_p(check))
return 0;
GetArrayType(type, 2, &check);
return ! type_asterisk_p(check);
}
/* (integer ? 10) */
int range_any_right_p(addr type)
{
addr check;
GetArrayType(type, 2, &check);
return ! type_asterisk_p(check);
}
/* (integer 10 20) */
int range_between_p(addr type)
{
addr check;
GetArrayType(type, 0, &check);
if (type_asterisk_p(check))
return 0;
GetArrayType(type, 2, &check);
return ! type_asterisk_p(check);
}
void range_left_value(addr value, addr *left1, addr *left2)
{
GetArrayType(value, 0, left1);
GetArrayType(value, 1, left2);
}
void range_right_value(addr value, addr *right1, addr *right2)
{
GetArrayType(value, 2, right1);
GetArrayType(value, 3, right2);
}
/*
* ( 10 *) ( 10 *) -> nil
* ((10) *) ( 10 *) -> nil
* ( 10 *) ((10) *) -> t
* ((10) *) ((10) *) -> nil
*/
int range_left_left_less_(addr left, addr right, int *ret)
{
addr left1, right1;
range_left_value(left, &left1, &left);
range_left_value(right, &right1, &right);
if (left1 == Nil && right1 != Nil)
return less_equal_real_(Local_Thread, left, right, ret);
else
return less_real_(Local_Thread, left, right, ret);
}
/*
* ( 10 *) ( 10 *) -> t
* ((10) *) ( 10 *) -> nil
* ( 10 *) ((10) *) -> t
* ((10) *) ((10) *) -> t
*/
int range_left_left_less_equal_(addr left, addr right, int *ret)
{
addr left1, right1;
range_left_value(left, &left1, &left);
range_left_value(right, &right1, &right);
if (left1 != Nil && right1 == Nil)
return less_real_(Local_Thread, left, right, ret);
else
return less_equal_real_(Local_Thread, left, right, ret);
}
int range_left_left_greater_(addr left, addr right, int *ret)
{
int check;
Return(range_left_left_less_equal_(left, right, &check));
return Result(ret, ! check);
}
int range_left_left_greater_equal_(addr left, addr right, int *ret)
{
int check;
Return(range_left_left_less_(left, right, &check));
return Result(ret, ! check);
}
/*
* ( 10 *) (* 10 ) -> nil
* ((10) *) (* 10 ) -> nil
* ( 10 *) (* (10)) -> nil
* ((10) *) (* (10)) -> nil
*/
int range_left_right_less_(addr left, addr right, int *ret)
{
/* range_left_value(left, &left1, &left); */
GetArrayType(left, 1, &left);
/* range_right_value(right, &right1, &right); */
GetArrayType(right, 3, &right);
return less_real_(Local_Thread, left, right, ret);
}
/*
* ( 10 *) (* 10 ) -> t
* ((10) *) (* 10 ) -> nil
* ( 10 *) (* (10)) -> nil
* ((10) *) (* (10)) -> nil
*/
int range_left_right_less_equal_(addr left, addr right, int *ret)
{
addr left1, right1;
range_left_value(left, &left1, &left);
range_right_value(right, &right1, &right);
if (left1 == Nil && right1 == Nil)
return less_equal_real_(Local_Thread, left, right, ret);
else
return less_real_(Local_Thread, left, right, ret);
}
int range_left_right_greater_(addr left, addr right, int *ret)
{
int check;
Return(range_left_right_less_equal_(left, right, &check));
return Result(ret, ! check);
}
int range_left_right_greater_equal_(addr left, addr right, int *ret)
{
int check;
Return(range_left_right_less_(left, right, &check));
return Result(ret, ! check);
}
/*
* (* 10 ) ( 10 *) -> nil
* (* (10)) ( 10 *) -> t
* (* 10 ) ((10) *) -> t
* (* (10)) ((10) *) -> t
*/
int range_right_left_less_(addr left, addr right, int *ret)
{
addr left1, right1;
range_right_value(left, &left1, &left);
range_left_value(right, &right1, &right);
if (left1 == Nil && right1 == Nil)
return less_real_(Local_Thread, left, right, ret);
else
return less_equal_real_(Local_Thread, left, right, ret);
}
/*
* (* 10 ) ( 10 *) -> t
* (* (10)) ( 10 *) -> t
* (* 10 ) ((10) *) -> t
* (* (10)) ((10) *) -> t
*/
int range_right_left_less_equal_(addr left, addr right, int *ret)
{
/* range_right_value(left, &left1, &left); */
GetArrayType(left, 3, &left);
/* range_left_value(right, &right1, &right); */
GetArrayType(right, 1, &right);
return less_equal_real_(Local_Thread, left, right, ret);
}
int range_right_left_greater_(addr left, addr right, int *ret)
{
int check;
Return(range_right_left_less_equal_(left, right, &check));
return Result(ret, ! check);
}
int range_right_left_greater_equal_(addr left, addr right, int *ret)
{
int check;
Return(range_right_left_less_(left, right, &check));
return Result(ret, ! check);
}
/*
* (* 10 ) (* 10 ) -> nil
* (* (10)) (* 10 ) -> t
* (* 10 ) (* (10)) -> nil
* (* (10)) (* (10)) -> nil
*/
int range_right_right_less_(addr left, addr right, int *ret)
{
addr left1, right1;
range_right_value(left, &left1, &left);
range_right_value(right, &right1, &right);
if (left1 != Nil && right1 == Nil)
return less_equal_real_(Local_Thread, left, right, ret);
else
return less_real_(Local_Thread, left, right, ret);
}
/*
* (* 10 ) (* 10 ) -> t
* (* (10)) (* 10 ) -> t
* (* 10 ) (* (10)) -> nil
* (* (10)) (* (10)) -> t
*/
int range_right_right_less_equal_(addr left, addr right, int *ret)
{
addr left1, right1;
range_right_value(left, &left1, &left);
range_right_value(right, &right1, &right);
if (left1 == Nil && right1 != Nil)
return less_real_(Local_Thread, left, right, ret);
else
return less_equal_real_(Local_Thread, left, right, ret);
}
int range_right_right_greater_(addr left, addr right, int *ret)
{
int check;
Return(range_right_right_less_equal_(left, right, &check));
return Result(ret, ! check);
}
int range_right_right_greater_equal_(addr left, addr right, int *ret)
{
int check;
Return(range_right_right_less_(left, right, &check));
return Result(ret, ! check);
}
/* (10 30) (20 *) -> t */
static int range_and2_call_(
int (*call1)(addr, addr, int *), addr a, addr b,
int (*call2)(addr, addr, int *), addr c, addr d,
int *ret)
{
int check;
Return((*call1)(a, b, &check));
if (! check)
return Result(ret, 0);
return (*call2)(c, d, ret);
}
int range_between_left_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_left_left_less_equal_, left, right,
range_left_right_less_equal_, right, left, ret);
}
/* (20 *) (10 30) -> t */
int range_left_between_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_left_left_less_equal_, right, left,
range_left_right_less_equal_, left, right, ret);
}
/* (10 30) (* 20) -> t */
int range_between_right_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_left_right_less_equal_, left, right,
range_right_right_less_equal_, right, left, ret);
}
/* (* 20) (10 30) -> t */
int range_right_between_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_left_right_less_equal_, right, left,
range_right_right_less_equal_, left, right, ret);
}
/* (10 30) (11 12) -> t */
int range_between_in_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_between_left_, left, right,
range_between_right_, left, right, ret);
}
/* (11 12) (10 30) -> t */
int range_in_between_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_left_between_, left, right,
range_right_between_, left, right, ret);
}
/*
* (? 10 ) ( 10 ?) -> t
* (? (10)) ( 10 ?) -> t
* (? 10 ) ((10) ?) -> t
* (? (10)) ((10) ?) -> nil
*/
int range_connect_right_left_(addr left, addr right, int *ret)
{
addr left1, right1;
range_right_value(left, &left1, &left);
range_left_value(right, &right1, &right);
if (left1 != Nil && right1 != Nil)
return less_real_(Local_Thread, right, left, ret);
else
return less_equal_real_(Local_Thread, right, left, ret);
}
/* (10 20) (20 *) */
int range_connect_between_left_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_left_left_less_equal_, left, right,
range_connect_right_left_, left, right, ret);
}
/* (10 20) (* 10) */
int range_connect_between_right_(addr left, addr right, int *ret)
{
return range_and2_call_(
range_right_right_less_equal_, right, left,
range_connect_right_left_, right, left, ret);
}
/************************************************************
* subtypep_table.c
************************************************************/
static call_type_subtypep TypeSubtypep[LISPDECL_SIZE];
/*
* call error
*/
static int subtypep_call_error_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
infoprint(x);
infoprint(y);
*ret = SUBTYPEP_INVALID;
return fmte_("Invalid subtypep argument.", NULL);
}
/*
* call cons
*/
static int subtypep_call_cons_t_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
if (type_astert_p(y))
return ReturnInclude(ret);
if (type_astert_p(x))
return ReturnFalse(ret);
return subtypep_compound_(ptr, x, y, ret);
}
static int subtypep_call_cons_value_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
SubtypepResult value1, value2;
addr car1, car2, cdr1, cdr2;
GetArrayType(x, 0, &car1);
GetArrayType(y, 0, &car2);
GetArrayType(x, 1, &cdr1);
GetArrayType(y, 1, &cdr2);
/* subtypep */
Return(subtypep_call_cons_t_(ptr, car1, car2, &value1));
ReturnSecondThrow(ret, value1);
Return(subtypep_call_cons_t_(ptr, cdr1, cdr2, &value2));
ReturnSecondThrow(ret, value2);
/* include */
if (value1 == SUBTYPEP_INCLUDE && value2 == SUBTYPEP_INCLUDE)
return ReturnInclude(ret);
/* reverse */
if (value1 == SUBTYPEP_INCLUDE) {
Return(subtypep_call_cons_t_(ptr, car2, car1, &value1));
return ReturnSecondValue(ret, value1);
}
if (value2 == SUBTYPEP_INCLUDE) {
Return(subtypep_call_cons_t_(ptr, cdr2, cdr1, &value2));
return ReturnSecondValue(ret, value2);
}
return ReturnFalse(ret);
}
static int subtypep_call_cons_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
switch (RefLispDecl(x)) {
case LISPDECL_CONS:
return subtypep_call_cons_value_(ptr, x, y, ret);
default:
return ReturnExclude(ret);
}
}
/*
* call complex
*/
static int subtypep_complex_value_(addr x, addr y, SubtypepResult *ret)
{
int check1, check2;
GetArrayType(x, 0, &x);
GetArrayType(y, 0, &y);
if (type_astert_p(y))
return ReturnInclude(ret);
if (type_astert_p(x))
return ReturnFalse(ret);
check1 = (RefLispDecl(x) == RefLispDecl(y));
check2 = (RefNotDecl(x) == RefNotDecl(y));
return ReturnIncludeExclude(ret, check1 && check2);
}
static int subtypep_call_complex_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
switch (RefLispDecl(x)) {
case LISPDECL_NUMBER:
return ReturnFalse(ret);
case LISPDECL_COMPLEX:
return subtypep_complex_value_(x, y, ret);
default:
return ReturnExclude(ret);
}
}
/*
* call function
*/
static int subtypep_ordinary_subtypep_(Execute ptr,
const ordargs *ptr1, const ordtype *type1,
const ordargs *ptr2, const ordtype *type2,
SubtypepResult *ret)
{
SubtypepResult value;
addr x, y;
LocalRoot local;
LocalStack stack;
local = Local_Thread;
push_local(local, &stack);
merge_ordargs(local, &x, ptr1, type1);
merge_ordargs(local, &y, ptr2, type2);
if (type_asterisk_p(y))
return ReturnInclude(ret);
if (type_asterisk_p(x))
return ReturnFalse(ret);
Return(subtypep_compound_(ptr, x, y, &value));
rollback_local(local, stack);
return Result(ret, value);
}
static int subtypep_ordinary_size_(Execute ptr,
const ordargs *ptr1, const ordargs *ptr2,
size_t size, SubtypepResult *ret)
{
SubtypepResult value;
size_t i;
ordtype type1, type2;
for (i = 0; i < size; i++) {
Return(gettype_ordargs_(ptr1, i, &type1));
Return(gettype_ordargs_(ptr2, i, &type2));
if (type1.nil)
break;
if (type2.nil)
return ReturnExclude(ret);
Return(subtypep_ordinary_subtypep_(ptr, ptr1, &type1, ptr2, &type2, &value));
if (value != SUBTYPEP_INCLUDE)
return Result(ret, value);
}
return ReturnInclude(ret);
}
static int subtypep_ordinary_simple_(Execute ptr,
const ordargs *ptr1, const ordargs *ptr2, SubtypepResult *ret)
{
if (ptr1->size > ptr2->size)
return ReturnExclude(ret);
/* short size */
return subtypep_ordinary_size_(ptr, ptr1, ptr2, ptr1->size, ret);
}
static int subtypep_ordinary_simple_left_(Execute ptr,
const ordargs *ptr1, const ordargs *ptr2, SubtypepResult *ret)
{
/* short size */
return subtypep_ordinary_size_(ptr, ptr1, ptr2, ptr1->size, ret);
}
static int subtypep_ordinary_check_(Execute ptr,
const ordargs *ptr1, const ordargs *ptr2, SubtypepResult *ret)
{
/* long size */
return subtypep_ordinary_size_(ptr, ptr1, ptr2,
(ptr1->size > ptr2->size? ptr1->size: ptr2->size),
ret);
}
static int subtypep_function_ordinary_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
int check1, check2;
ordargs ptr1, ptr2;
/* asterisk */
if (type_asterisk_p(y))
return ReturnInclude(ret);
if (type_asterisk_p(x))
return ReturnFalse(ret);
/* list */
make_ordargs(&ptr1, x);
make_ordargs(&ptr2, y);
if (ptr1.size_var < ptr2.size_var)
return ReturnExclude(ret);
check1 = simple_p_ordargs(&ptr1);
check2 = simple_p_ordargs(&ptr2);
if (check1 && check2)
return subtypep_ordinary_simple_(ptr, &ptr1, &ptr2, ret);
if (check1)
return subtypep_ordinary_simple_left_(ptr, &ptr1, &ptr2, ret);
if (check2)
return ReturnExclude(ret);
else
return subtypep_ordinary_check_(ptr, &ptr1, &ptr2, ret);
}
static int subtypep_function_values_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
/* asterisk */
if (type_asterisk_p(y))
return ReturnInclude(ret);
if (type_asterisk_p(x))
return ReturnFalse(ret);
/* type check */
return subtypep_compound_(ptr, x, y, ret);
}
static int subtypep_function_check_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
SubtypepResult value1, value2;
addr arg1, arg2, the1, the2;
GetArrayType(x, 0, &arg1);
GetArrayType(y, 0, &arg2);
GetArrayType(x, 1, &the1);
GetArrayType(y, 1, &the2);
/* subtypep */
Return(subtypep_function_ordinary_(ptr, arg1, arg2, &value1));
ReturnSecondThrow(ret, value1);
Return(subtypep_function_values_(ptr, the1, the2, &value2));
ReturnSecondThrow(ret, value2);
/* include */
if (value1 == SUBTYPEP_INCLUDE && value2 == SUBTYPEP_INCLUDE)
return ReturnInclude(ret);
/* reverse */
if (value1 == SUBTYPEP_INCLUDE) {
Return(subtypep_function_ordinary_(ptr, arg2, arg1, &value1));
return ReturnSecondValue(ret, value1);
}
if (value2 == SUBTYPEP_INCLUDE) {
Return(subtypep_function_values_(ptr, the2, the1, &value2));
return ReturnSecondValue(ret, value2);
}
return ReturnFalse(ret);
}
static int subtypep_call_function_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
switch (RefLispDecl(x)) {
case LISPDECL_FUNCTION:
case LISPDECL_COMPILED_FUNCTION:
return subtypep_function_check_(ptr, x, y, ret);
default:
return ReturnExclude(ret);
}
}
static int subtypep_call_compiled_function_function_(
Execute ptr, addr x, addr y, SubtypepResult *ret)
{
SubtypepResult check;
Return(subtypep_function_check_(ptr, y, x, &check));
return ReturnReverse(ret, check);
}
static int subtypep_call_compiled_function_(
Execute ptr, addr x, addr y, SubtypepResult *ret)
{
switch (RefLispDecl(x)) {
case LISPDECL_FUNCTION:
return subtypep_call_compiled_function_function_(ptr, x, y, ret);
case LISPDECL_COMPILED_FUNCTION:
return subtypep_function_check_(ptr, x, y, ret);
default:
return ReturnExclude(ret);
}
}
/*
* table
*/
int subtypep_table_(Execute ptr, addr x, addr y, SubtypepResult *ret)
{
call_type_subtypep call;
call = TypeSubtypep[(int)RefLispDecl(y)];
if (call)
return (*call)(ptr, x, y, ret);
*ret = SUBTYPEP_INVALID;
return 0;
}
void init_subtypep_table(void)
{
int i;
for (i = 0; i < LISPDECL_SIZE; i++)
TypeSubtypep[i] = subtypep_call_error_;
TypeSubtypep[LISPDECL_INVALID] = subtypep_call_invalid_;
TypeSubtypep[LISPDECL_TYPE] = subtypep_call_error_;
TypeSubtypep[LISPDECL_CLOS] = subtypep_call_clos_;
TypeSubtypep[LISPDECL_ASTERISK] = subtypep_call_asterisk_;
TypeSubtypep[LISPDECL_NIL] = subtypep_call_nil_;
TypeSubtypep[LISPDECL_T] = subtypep_call_t_;
TypeSubtypep[LISPDECL_NULL] = subtypep_call_null_;
TypeSubtypep[LISPDECL_CONS] = subtypep_call_cons_;
TypeSubtypep[LISPDECL_HASH_TABLE] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_SYMBOL] = subtypep_call_symbol_;
TypeSubtypep[LISPDECL_KEYWORD] = subtypep_call_keyword_;
TypeSubtypep[LISPDECL_PACKAGE] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_RANDOM_STATE] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_READTABLE] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_FUNCTION] = subtypep_call_function_;
TypeSubtypep[LISPDECL_COMPILED_FUNCTION] = subtypep_call_compiled_function_;
TypeSubtypep[LISPDECL_PATHNAME] = subtypep_call_pathname_;
TypeSubtypep[LISPDECL_LOGICAL_PATHNAME] = subtypep_call_logical_pathname_;
TypeSubtypep[LISPDECL_ARRAY] = subtypep_call_array_;
TypeSubtypep[LISPDECL_SIMPLE_ARRAY] = subtypep_call_simple_array_;
TypeSubtypep[LISPDECL_CHARACTER] = subtypep_call_character_;
TypeSubtypep[LISPDECL_BASE_CHAR] = subtypep_call_base_char_;
TypeSubtypep[LISPDECL_STANDARD_CHAR] = subtypep_call_standard_char_;
TypeSubtypep[LISPDECL_INTEGER] = subtypep_call_integer_;
TypeSubtypep[LISPDECL_RATIONAL] = subtypep_call_rational_;
TypeSubtypep[LISPDECL_REAL] = subtypep_call_real_;
TypeSubtypep[LISPDECL_NUMBER] = subtypep_call_number_;
TypeSubtypep[LISPDECL_FLOAT] = subtypep_call_float_;
TypeSubtypep[LISPDECL_SHORT_FLOAT] = subtypep_call_short_float_;
TypeSubtypep[LISPDECL_SINGLE_FLOAT] = subtypep_call_single_float_;
TypeSubtypep[LISPDECL_DOUBLE_FLOAT] = subtypep_call_double_float_;
TypeSubtypep[LISPDECL_LONG_FLOAT] = subtypep_call_long_float_;
TypeSubtypep[LISPDECL_RATIO] = subtypep_call_ratio_;
TypeSubtypep[LISPDECL_COMPLEX] = subtypep_call_complex_;
TypeSubtypep[LISPDECL_RESTART] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_ENVIRONMENT] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_STREAM] = subtypep_call_stream_;
TypeSubtypep[LISPDECL_BROADCAST_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_CONCATENATED_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_ECHO_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_FILE_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_STRING_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_SYNONYM_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_TWO_WAY_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_PROMPT_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_PRETTY_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_MEMORY_STREAM] = subtypep_call_stream_type_;
TypeSubtypep[LISPDECL_BYTESPEC] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_PRINT_DISPATCH] = subtypep_call_eqltype_;
TypeSubtypep[LISPDECL_EVAL] = subtypep_call_eqltype_;
}
/************************************************************
* sxhash.c
************************************************************/
/*
* Declarations
*/
#define FixedSize (sizeof(fixed))
#define FIXNUM_BIT1M (LISP_INTEGER_BIT - 1ULL)
#define FIXNUM_MASK_SIGN (1ULL << FIXNUM_BIT1M)
#define FIXNUM_MASK_BODY (FIXNUM_MASK_SIGN - 1ULL)
#define FIXNUM_BODY(x) ((fixnum)((x) & FIXNUM_MASK_BODY))
typedef int (*calltype_sxhash)(addr pos, int depth, fixed *ret);
static calltype_sxhash SxhashTableEqual[LISPTYPE_SIZE];
static calltype_sxhash SxhashTableEqualp[LISPTYPE_SIZE];
static int sxfixed_equal_(addr pos, int depth, fixed *ret);
static int sxfixed_equalp_(addr pos, int depth, fixed *ret);
/*
* eq
*/
#define sxhash_diffshift(x,y,z) ((((uintptr_t)(x)) - ((uintptr_t)(y))) >> (z))
#define sxhash_diffheap(x,s) ((fixed)sxhash_diffshift(heap_alloc, (x), (s)))
static int sxfixed_eq_(addr pos, int depth, fixed *ret)
{
#ifdef LISP_ARCH_64BIT
return Result(ret, sxhash_diffheap(pos, 3));
#else
return Result(ret, sxhash_diffheap(pos, 2));
#endif
}
/*
* character
*/
static int sxfixed_character_(addr pos, int depth, fixed *ret)
{
unicode c;
GetCharacter(pos, &c);
return Result(ret, (fixed)c);
}
static int sxfixed_character_p_(addr pos, int depth, fixed *ret)
{
unicode c;
GetCharacter(pos, &c);
return Result(ret, (fixed)toUpperUnicode(c));
}
/*
* character2
*/
static int sxfixed_character2_(addr pos, int depth, fixed *ret)
{
fixed a, b;
a = (fixed)refcharacter2a(pos);
b = (fixed)refcharacter2b(pos);
return Result(ret, a + b);
}
static int sxfixed_character2_p_(addr pos, int depth, fixed *ret)
{
unicode a, b;
fixed c, d;
getcharacter2a(pos, &a);
getcharacter2b(pos, &b);
c = (fixed)toUpperUnicode(a);
d = (fixed)toUpperUnicode(b);
return Result(ret, c + d);
}
/*
* binary
*/
static int sxfixed_binary_(const byte *u, size_t size, fixed *ret)
{
int m;
size_t i;
fixed p[FixedSize], value;
cleartype(p);
for (i = 0; i < size; i++) {
m = i % FixedSize;
p[m] += u[i];
}
value = (fixed)size;
for (i = 0; i < FixedSize; i++)
value += p[i] << (i * 8);
return Result(ret, value);
}
static int sxhash_binary_equal_(const void *pos, size_t size, fixnum *ret)
{
fixed value;
Return(sxfixed_binary_((const byte *)pos, size, &value));
return Result(ret, FIXNUM_BODY(value));
}
int sxhash_char_equal_(const char *pos, fixnum *ret)
{
return sxhash_binary_equal_((const void *)pos, strlen(pos), ret);
}
static int fixed_binary_p_(const byte *u, size_t size, fixed *ret)
{
int m;
size_t i;
fixed p[FixedSize], value;
cleartype(p);
for (i = 0; i < size; i++) {
m = i % FixedSize;
p[m] += toupperunicode(u[i]);
}
value = (fixed)size;
for (i = 0; i < FixedSize; i++)
value += p[i] << (i * 8);
return Result(ret, value);
}
static int sxhash_binary_equalp_(const void *pos, size_t size, fixnum *ret)
{
fixed value;
Return(fixed_binary_p_((const byte *)pos, size, &value));
return Result(ret, FIXNUM_BODY(value));
}
int sxhash_char_equalp_(const char *pos, fixnum *ret)
{
return sxhash_binary_equalp_((const void *)pos, strlen(pos), ret);
}
/*
* string
*/
static int sxfixed_string_(addr pos, int depth, fixed *ret)
{
int m;
size_t i, len;
fixed p[FixedSize], value;
unicode u;
cleartype(p);
string_length(pos, &len);
for (i = 0; i < len; i++) {
Return(string_getc_(pos, i, &u));
m = i % FixedSize;
p[m] += u;
}
value = (fixed)len;
for (i = 0; i < FixedSize; i++)
value += p[i] << (i * 8);
return Result(ret, value);
}
static int sxfixed_string_p_(addr pos, int depth, fixed *ret)
{
int m;
size_t i, len;
fixed p[FixedSize], value;
unicode u;
cleartype(p);
string_length(pos, &len);
for (i = 0; i < len; i++) {
Return(string_getc_(pos, i, &u));
m = i % FixedSize;
p[m] += toupperunicode(u);
}
value = (fixed)len;
for (i = 0; i < FixedSize; i++)
value += p[i] << (i * 8);
return Result(ret, value);
}
/*
* fixnum
*/
static int sxfixed_fixnum_(addr pos, int depth, fixed *ret)
{
fixnum value;
GetFixnum(pos, &value);
return Result(ret, (fixed)value);
}
/*
* bignum
*/
static int sxfixed_bignum_(addr pos, int depth, fixed *ret)
{
int sign;
bigtype *data;
size_t size, i;
fixed value;
GetSignBignum(pos, &sign);
GetSizeBignum(pos, &size);
GetDataBignum(pos, &data);
value = (fixed)sign;
value += (fixed)size;
for (i = 0; i < size; i++)
value += (fixed)data[i];
return Result(ret, value);
}
/*
* ratio
*/
static int sxfixed_ratio_(addr pos, int depth, fixed *ret)
{
int sign;
addr numer, denom;
fixed value, v;
GetSignRatio(pos, &sign);
GetNumerRatio(pos, &numer);
GetDenomRatio(pos, &denom);
value = (fixed)sign;
Return(sxfixed_bignum_(numer, depth, &v));
value += v;
Return(sxfixed_bignum_(numer, depth, &v));
value += v;
return Result(ret, value);
}
/*
* float
*/
static int sxfixed_single_float_(addr pos, int depth, fixed *ret)
{
single_float value;
GetSingleFloat(pos, &value);
return sxfixed_binary_((const byte *)&value, sizeoft(value), ret);
}
static int sxfixed_double_float_(addr pos, int depth, fixed *ret)
{
double_float value;
GetDoubleFloat(pos, &value);
return sxfixed_binary_((const byte *)&value, sizeoft(value), ret);
}
static int sxfixed_long_float_(addr pos, int depth, fixed *ret)
{
long_float value;
GetLongFloat(pos, &value);
return sxfixed_binary_((const byte *)&value, sizeoft(value), ret);
}
static int sxfixed_pathname_(addr pos, int depth, fixed *ret)
{
int i;
addr child;
fixed result, v;
result = 0;
depth--;
for (i = 0; i < PATHNAME_INDEX_SIZE; i++) {
GetArrayA2(pos, i, &child);
Return(sxfixed_equal_(child, depth, &v));
result += v;
}
return Result(ret, result);
}
static int sxfixed_float_p_(addr pos, int depth, fixed *ret)
{
Execute ptr;
ptr = Execute_Thread;
Return(rationalize_common_(ptr, pos, &pos));
return sxfixed_equalp_(pos, depth, ret);
}
/*
* Global function
*/
static int sxfixed_equal_(addr pos, int depth, fixed *ret)
{
if (pos == Nil)
return Result(ret, 0);
if (pos == T)
return Result(ret, 1);
return (SxhashTableEqual[(size_t)GetType(pos)])(pos, depth, ret);
}
static int sxfixed_equalp_(addr pos, int depth, fixed *ret)
{
if (pos == Nil)
return Result(ret, 0);
if (pos == T)
return Result(ret, 1);
return (SxhashTableEqualp[(size_t)GetType(pos)])(pos, depth, ret);
}
static int sxhash_call_(addr pos, int depth, fixnum *ret, calltype_sxhash call)
{
fixed value;
Return((*call)(pos, depth, &value));
return Result(ret, FIXNUM_BODY(value));
}
int sxhash_equal_depth_(addr pos, int depth, fixnum *ret)
{
return sxhash_call_(pos, depth, ret, sxfixed_equal_);
}
int sxhash_equal_(addr pos, fixnum *ret)
{
return sxhash_call_(pos, -1, ret, sxfixed_equal_);
}
int sxhash_equalp_depth_(addr pos, int depth, fixnum *ret)
{
return sxhash_call_(pos, depth, ret, sxfixed_equalp_);
}
int sxhash_equalp_(addr pos, fixnum *ret)
{
return sxhash_call_(pos, -1, ret, sxfixed_equalp_);
}
int sxhash_eq_(addr pos, fixnum *ret)
{
return sxhash_call_(pos, -1, ret, sxfixed_eq_);
}
int sxhash_unicode_equalp_(unicode pos, fixnum *ret)
{
fixed value;
value = (fixed)toUpperUnicode(pos);
return Result(ret, FIXNUM_BODY(value));
}
int sxhash_unicode_equal_(unicode pos, fixnum *ret)
{
fixnum value;
value = (fixed)pos;
return Result(ret, FIXNUM_BODY(value));
}
int sxhash_character2_equal_(unicode a, unicode b, fixnum *ret)
{
fixed c, d;
c = (fixed)a;
d = (fixed)b;
return Result(ret, FIXNUM_BODY(c + d));
}
int sxhash_character2_equalp_(unicode a, unicode b, fixnum *ret)
{
fixed c, d;
c = (fixed)toUpperUnicode(a);
d = (fixed)toUpperUnicode(b);
return Result(ret, FIXNUM_BODY(c + d));
}
/*
* cons
*/
static int sxfixed_cons_(addr pos, int depth, fixed *ret)
{
addr right;
fixed v1, v2;
if (depth == 0)
return Result(ret, 0);
GetCons(pos, &pos, &right);
depth--;
Return(sxfixed_equal_(pos, depth, &v1));
Return(sxfixed_equal_(right, depth, &v2));
return Result(ret, depth + v1 + (3 * v2));
}
static int sxfixed_cons_p_(addr pos, int depth, fixed *ret)
{
addr right;
fixed v1, v2;
if (depth == 0)
return Result(ret, 0);
GetCons(pos, &pos, &right);
depth--;
Return(sxfixed_equalp_(pos, depth, &v1));
Return(sxfixed_equalp_(right, depth, &v2));
return Result(ret, depth + v1 + (3 * v2));
}
/*
* vector
*/
static int sxfixed_vector_(addr pos, int depth, fixed *ret)
{
size_t len;
lenarray(pos, &len);
return Result(ret, (fixed)len);
}
/*
* array
*/
static int sxfixed_array_(addr pos, int depth, fixed *ret)
{
if (strarrayp(pos))
return sxfixed_string_(pos, depth, ret);
else
return sxfixed_eq_(pos, depth, ret);
}
static int sxfixed_array_p_(addr pos, int depth, fixed *ret)
{
if (strarrayp(pos))
return sxfixed_string_p_(pos, depth, ret);
else
return sxfixed_eq_(pos, depth, ret);
}
/*
* Initialize
*/
static void SetSxhashEqual(enum LISPTYPE type, calltype_sxhash call)
{
SxhashTableEqual[(size_t)type] = call;
}
static void SetSxhashEqualp(enum LISPTYPE type, calltype_sxhash call)
{
SxhashTableEqualp[(size_t)type] = call;
}
void init_sxhash(void)
{
int i;
/*
* equal
*/
for (i = 0; i < LISPTYPE_SIZE; i++)
SxhashTableEqual[i] = sxfixed_eq_;
SetSxhashEqual(LISPTYPE_CONS, sxfixed_cons_);
SetSxhashEqual(LISPTYPE_VECTOR, sxfixed_vector_);
SetSxhashEqual(LISPTYPE_ARRAY, sxfixed_array_);
/* object */
SetSxhashEqual(LISPTYPE_CHARACTER, sxfixed_character_);
SetSxhashEqual(LISPSYSTEM_CHARACTER2, sxfixed_character2_);
SetSxhashEqual(LISPTYPE_STRING, sxfixed_string_);
SetSxhashEqual(LISPTYPE_FIXNUM, sxfixed_fixnum_);
SetSxhashEqual(LISPTYPE_BIGNUM, sxfixed_bignum_);
SetSxhashEqual(LISPTYPE_RATIO, sxfixed_ratio_);
SetSxhashEqual(LISPTYPE_SINGLE_FLOAT, sxfixed_single_float_);
SetSxhashEqual(LISPTYPE_DOUBLE_FLOAT, sxfixed_double_float_);
SetSxhashEqual(LISPTYPE_LONG_FLOAT, sxfixed_long_float_);
SetSxhashEqual(LISPTYPE_PATHNAME, sxfixed_pathname_);
/*
* equlap
*/
for (i = 0; i < LISPTYPE_SIZE; i++)
SxhashTableEqualp[i] = SxhashTableEqual[i];
SetSxhashEqualp(LISPTYPE_CONS, sxfixed_cons_p_);
SetSxhashEqualp(LISPTYPE_ARRAY, sxfixed_array_p_);
/* object */
SetSxhashEqualp(LISPTYPE_CHARACTER, sxfixed_character_p_);
SetSxhashEqualp(LISPSYSTEM_CHARACTER2, sxfixed_character2_p_);
SetSxhashEqualp(LISPTYPE_STRING, sxfixed_string_p_);
SetSxhashEqual(LISPTYPE_SINGLE_FLOAT, sxfixed_float_p_);
SetSxhashEqual(LISPTYPE_DOUBLE_FLOAT, sxfixed_float_p_);
SetSxhashEqual(LISPTYPE_LONG_FLOAT, sxfixed_float_p_);
}
/************************************************************
* symbol.c
************************************************************/
#ifdef LISP_THREAD_ENABLE
#define SYMSTACK_SIZE 4
#else
#define SYMSTACK_SIZE 1
#endif
static int InitObject = 0;
static rwlocklite MutexSymbol;
int init_symbol(void)
{
if (InitObject) {
Debug("InitObject error.");
return 1;
}
if (lispd_make_rwlocklite(&MutexSymbol)) {
Debug("lispd_make_mutexlite error");
return 1;
}
InitObject = 1;
return 0;
}
void free_symbol(void)
{
if (InitObject) {
lispd_destroy_rwlocklite(&MutexSymbol);
InitObject = 0;
}
}
void build_symbol(void)
{
addr symbol, value;
GetConst(SPECIAL_GENSYM_COUNTER, &symbol);
fixnum_heap(&value, 0);
SetValueSymbol(symbol, value);
}
/*
* symbol
*/
void symbol_heap(addr *ret)
{
int i;
addr pos, make;
/* symbol object */
heap_symbol(&pos);
/* Unbound */
SetValueSymbol_Low(pos, Unbound);
SetFunctionSymbol_Low(pos, Unbound);
/* stack */
heap_array4(&make, LISPSYSTEM_SYMSTACK, SYMSTACK_SIZE);
for (i = 0; i < SYMSTACK_SIZE; i++) {
SetArrayA4(make, i, NULL);
}
SetSpecialSymbol_Low(pos, make);
*ret = pos;
}
int symbolp(addr pos)
{
return GetType(pos) == LISPTYPE_SYMBOL || pos == Nil || pos == T;
}
int keywordp(addr pos)
{
addr keyword;
if (GetType(pos) != LISPTYPE_SYMBOL)
return 0;
GetConst(PACKAGE_KEYWORD, &keyword);
Check(GetType(keyword) != LISPTYPE_PACKAGE, "package error");
GetPackageSymbol(pos, &pos);
return pos == keyword;
}
static int setcheck_symbol_(addr symbol, size_t index, addr value)
{
CheckSymbol(symbol);
if (GetStatusReadOnly(symbol))
return fmte_("Cannot set the constant variable ~S.", symbol, NULL);
SetArrayA2(symbol, index, value);
return 0;
}
/* name */
void getname_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetNameSymbol_Low(symbol, ret);
}
void setname_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
Check(GetStatusReadOnly(symbol), "readonly error");
SetNameSymbol_Low(symbol, value);
}
/* value */
void getvalue_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetValueSymbol_Low(symbol, ret);
}
void setvalue_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
Check(GetStatusReadOnly(symbol), "readonly error");
SetValueSymbol_Low(symbol, value);
}
int setvalue_symbol_(addr symbol, addr value)
{
return setcheck_symbol_(symbol, SYMBOL_INDEX_VALUE, value);
}
/* function */
void getfunction_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetFunctionSymbol_Low(symbol, ret);
}
void setfunction_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
Check(GetStatusReadOnly(symbol), "readonly error");
SetFunctionSymbol_Low(symbol, value);
}
int setfunction_symbol_(addr symbol, addr value)
{
return setcheck_symbol_(symbol, SYMBOL_INDEX_FUNCTION, value);
}
/* package */
void getpackage_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetPackageSymbol_Low(symbol, ret);
}
void setpackage_symbol(addr symbol, addr value)
{
Check(value != Nil && GetType(value) != LISPTYPE_PACKAGE, "type error");
/* no-readonly-check */
SetPackageSymbol_Low(symbol, value);
}
/* plist */
void getplist_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetPlistSymbol_Low(symbol, ret);
}
void setplist_symbol(addr symbol, addr value)
{
Check(! listp(value), "type error");
/* no-readonly-check */
SetPlistSymbol_Low(symbol, value);
}
/* info */
static void getinfo_constant(addr symbol, constindex index, addr *ret)
{
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &symbol);
*ret = getplist_constant(symbol, index, &symbol)? Nil: symbol;
}
static void setinfo_constant(addr symbol, constindex index, addr value)
{
addr plist;
CheckSymbol(symbol);
Check(GetStatusReadOnly(symbol), "readonly error");
GetInfoSymbol_Low(symbol, &plist);
if (setplist_constant_heap(plist, index, value, &plist))
SetInfoSymbol_Low(symbol, plist);
}
static void setinfo_nocheck_constant(addr symbol, constindex index, addr value)
{
addr plist;
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &plist);
if (setplist_constant_heap(plist, index, value, &plist))
SetInfoSymbol_Low(symbol, plist);
}
static int setinfo_constant_(addr symbol, constindex index, addr value)
{
addr plist;
CheckSymbol(symbol);
if (GetStatusReadOnly(symbol))
return fmte_("Cannot set the constant variable ~S.", symbol, NULL);
GetInfoSymbol_Low(symbol, &plist);
if (setplist_constant_heap(plist, index, value, &plist))
SetInfoSymbol_Low(symbol, plist);
return 0;
}
static void reminfo_constant(addr symbol, constindex index)
{
addr plist;
CheckSymbol(symbol);
Check(GetStatusReadOnly(symbol), "readonly error");
GetInfoSymbol_Low(symbol, &plist);
if (remplist_constant(plist, index, &plist))
SetInfoSymbol_Low(symbol, plist);
}
static int reminfo_constant_(addr symbol, constindex index)
{
addr plist;
CheckSymbol(symbol);
if (GetStatusReadOnly(symbol))
return fmte_("Cannot set the constant variable ~S.", symbol, NULL);
GetInfoSymbol_Low(symbol, &plist);
if (remplist_constant(plist, index, &plist))
SetInfoSymbol_Low(symbol, plist);
return 0;
}
static void reminfo_nocheck_constant(addr symbol, constindex index)
{
addr plist;
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &plist);
if (remplist_constant(plist, index, &plist))
SetInfoSymbol_Low(symbol, plist);
}
/* type value */
void gettype_value_symbol(addr symbol, addr *ret)
{
getinfo_constant(symbol, CONSTANT_SYSTEM_VALUE, ret);
}
void settype_value_symbol(addr symbol, addr value)
{
Check(GetType(value) != LISPTYPE_TYPE, "type right error");
setinfo_constant(symbol, CONSTANT_SYSTEM_VALUE, value);
}
int settype_value_symbol_(addr symbol, addr value)
{
Check(GetType(value) != LISPTYPE_TYPE, "type right error");
return setinfo_constant_(symbol, CONSTANT_SYSTEM_VALUE, value);
}
void remtype_value_symbol(addr symbol)
{
reminfo_constant(symbol, CONSTANT_SYSTEM_VALUE);
}
/* type function */
void gettype_function_symbol(addr symbol, addr *ret)
{
getinfo_constant(symbol, CONSTANT_SYSTEM_FUNCTION, ret);
}
void settype_function_symbol(addr symbol, addr value)
{
Check(GetType(value) != LISPTYPE_TYPE, "type right error");
setinfo_constant(symbol, CONSTANT_SYSTEM_FUNCTION, value);
}
int settype_function_symbol_(addr symbol, addr value)
{
Check(GetType(value) != LISPTYPE_TYPE, "type right error");
return setinfo_constant_(symbol, CONSTANT_SYSTEM_FUNCTION, value);
}
int remtype_function_symbol_(addr symbol)
{
return reminfo_constant_(symbol, CONSTANT_SYSTEM_FUNCTION);
}
/* type setf */
void gettype_setf_symbol(addr symbol, addr *ret)
{
getinfo_constant(symbol, CONSTANT_SYSTEM_SETF, ret);
}
void settype_setf_symbol(addr symbol, addr value)
{
Check(GetType(value) != LISPTYPE_TYPE, "type right error");
setinfo_constant(symbol, CONSTANT_SYSTEM_SETF, value);
}
int settype_setf_symbol_(addr symbol, addr value)
{
Check(GetType(value) != LISPTYPE_TYPE, "type right error");
return setinfo_constant_(symbol, CONSTANT_SYSTEM_SETF, value);
}
int remtype_setf_symbol_(addr symbol)
{
return reminfo_constant_(symbol, CONSTANT_SYSTEM_SETF);
}
/* inline */
int inlinep_function_symbol(addr symbol)
{
addr check;
getinfo_constant(symbol, CONSTANT_SYSTEM_INLINE_FUNCTION, &symbol);
GetConst(COMMON_INLINE, &check);
return symbol == check;
}
void setinline_function_symbol(addr symbol)
{
addr value;
GetConst(COMMON_INLINE, &value);
setinfo_nocheck_constant(symbol, CONSTANT_SYSTEM_INLINE_FUNCTION, value);
}
int notinlinep_function_symbol(addr symbol)
{
addr check;
getinfo_constant(symbol, CONSTANT_SYSTEM_INLINE_FUNCTION, &symbol);
GetConst(COMMON_NOTINLINE, &check);
return symbol == check;
}
void setnotinline_function_symbol(addr symbol)
{
addr value;
GetConst(COMMON_NOTINLINE, &value);
setinfo_nocheck_constant(symbol, CONSTANT_SYSTEM_INLINE_FUNCTION, value);
}
void reminline_function_symbol(addr symbol)
{
reminfo_nocheck_constant(symbol, CONSTANT_SYSTEM_INLINE_FUNCTION);
}
int inlinep_setf_symbol(addr symbol)
{
addr check;
getinfo_constant(symbol, CONSTANT_SYSTEM_INLINE_SETF, &symbol);
GetConst(COMMON_INLINE, &check);
return symbol == check;
}
void setinline_setf_symbol(addr symbol)
{
addr value;
GetConst(COMMON_INLINE, &value);
setinfo_nocheck_constant(symbol, CONSTANT_SYSTEM_INLINE_SETF, value);
}
int notinlinep_setf_symbol(addr symbol)
{
addr check;
getinfo_constant(symbol, CONSTANT_SYSTEM_INLINE_SETF, &symbol);
GetConst(COMMON_NOTINLINE, &check);
return symbol == check;
}
void setnotinline_setf_symbol(addr symbol)
{
addr value;
GetConst(COMMON_NOTINLINE, &value);
setinfo_nocheck_constant(symbol, CONSTANT_SYSTEM_INLINE_SETF, value);
}
void reminline_setf_symbol(addr symbol)
{
reminfo_nocheck_constant(symbol, CONSTANT_SYSTEM_INLINE_SETF);
}
/* setf */
void getsetf_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &symbol);
*ret = getplist_constant(symbol, CONSTANT_COMMON_SETF, &symbol)? Unbound: symbol;
}
void setsetf_symbol(addr symbol, addr value)
{
setinfo_constant(symbol, CONSTANT_COMMON_SETF, value);
}
int setsetf_symbol_(addr symbol, addr value)
{
return setinfo_constant_(symbol, CONSTANT_COMMON_SETF, value);
}
void remsetf_symbol(addr symbol)
{
reminfo_constant(symbol, CONSTANT_COMMON_SETF);
}
/* setf-macro */
void getsetfmacro_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &symbol);
*ret = getplist_constant(symbol, CONSTANT_COMMON_DEFINE_SETF_EXPANDER,
&symbol)? Unbound: symbol;
}
void setsetfmacro_symbol(addr symbol, addr value)
{
setinfo_constant(symbol, CONSTANT_COMMON_DEFINE_SETF_EXPANDER, value);
}
int setsetfmacro_symbol_(addr symbol, addr value)
{
return setinfo_constant_(symbol, CONSTANT_COMMON_DEFINE_SETF_EXPANDER, value);
}
void remsetfmacro_symbol(addr symbol)
{
reminfo_constant(symbol, CONSTANT_COMMON_DEFINE_SETF_EXPANDER);
}
/* macro */
void getmacro_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &symbol);
*ret = getplist_constant(symbol, CONSTANT_COMMON_DEFMACRO, &symbol)?
Unbound: symbol;
}
void setmacro_symbol(addr symbol, addr value)
{
setinfo_constant(symbol, CONSTANT_COMMON_DEFMACRO, value);
}
int setmacro_symbol_(addr symbol, addr value)
{
return setinfo_constant_(symbol, CONSTANT_COMMON_DEFMACRO, value);
}
void remmacro_symbol(addr symbol)
{
reminfo_constant(symbol, CONSTANT_COMMON_DEFMACRO);
}
/* symbol-macro */
void getsymbol_macro_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
GetInfoSymbol_Low(symbol, &symbol);
*ret = getplist_constant(symbol, CONSTANT_COMMON_DEFINE_SYMBOL_MACRO, &symbol)?
Unbound: symbol;
}
int setsymbol_macro_symbol_(addr symbol, addr value)
{
return setinfo_constant_(symbol, CONSTANT_COMMON_DEFINE_SYMBOL_MACRO, value);
}
void remsymbol_macro_symbol(addr symbol)
{
reminfo_constant(symbol, CONSTANT_COMMON_DEFINE_SYMBOL_MACRO);
}
/* compiler-macro-function */
void get_compiler_macro_symbol(addr symbol, addr *value)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_SYSTEM_COMPILER_MACRO_FUNCTION, value);
}
int set_compiler_macro_symbol_(addr symbol, addr value)
{
CheckSymbol(symbol);
return setinfo_constant_(symbol, CONSTANT_SYSTEM_COMPILER_MACRO_FUNCTION, value);
}
int rem_compiler_macro_symbol_(addr symbol)
{
if (GetStatusReadOnly(symbol))
return fmte_("Cannot set the constant variable ~S.", symbol, NULL);
reminfo_constant(symbol, CONSTANT_SYSTEM_COMPILER_MACRO_FUNCTION);
return 0;
}
void get_setf_compiler_macro_symbol(addr symbol, addr *value)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_SYSTEM_SETF_COMPILER_MACRO_FUNCTION, value);
}
int set_setf_compiler_macro_symbol_(addr symbol, addr value)
{
CheckSymbol(symbol);
return setinfo_constant_(symbol,
CONSTANT_SYSTEM_SETF_COMPILER_MACRO_FUNCTION, value);
}
int rem_setf_compiler_macro_symbol_(addr symbol)
{
if (GetStatusReadOnly(symbol))
return fmte_("Cannot set the constant variable ~S.", symbol, NULL);
reminfo_constant(symbol, CONSTANT_SYSTEM_SETF_COMPILER_MACRO_FUNCTION);
return 0;
}
/* scope */
void getscope_symbol(addr symbol, addr *value)
{
getinfo_constant(symbol, CONSTANT_COMMON_SPECIAL, value);
}
static void setscope_symbol(addr symbol, addr value)
{
setinfo_constant(symbol, CONSTANT_COMMON_SPECIAL, value);
}
void setspecial_symbol(addr symbol)
{
CheckSymbol(symbol);
setscope_symbol(symbol, T);
}
int setspecial_symbol_(addr symbol)
{
return setinfo_constant_(symbol, CONSTANT_COMMON_SPECIAL, T);
}
void setlexical_symbol(addr symbol)
{
CheckSymbol(symbol);
setscope_symbol(symbol, Nil);
}
int specialp_symbol(addr symbol)
{
CheckSymbol(symbol);
getscope_symbol(symbol, &symbol);
return symbol != Nil;
}
int lexicalp_symbol(addr symbol)
{
CheckSymbol(symbol);
getscope_symbol(symbol, &symbol);
return symbol == Nil;
}
/* special-operator */
void set_special_operator(addr symbol)
{
CheckSymbol(symbol);
setinfo_constant(symbol, CONSTANT_COMMON_SPECIAL_OPERATOR_P, T);
}
int get_special_operator(addr symbol)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_COMMON_SPECIAL_OPERATOR_P, &symbol);
return symbol != Nil;
}
/* document */
void getdocument_variable_symbol(addr symbol, addr *ret)
{
getinfo_constant(symbol, CONSTANT_COMMON_VARIABLE, ret);
}
void setdocument_variable_symbol(addr symbol, addr value)
{
setinfo_constant(symbol, CONSTANT_COMMON_VARIABLE, value);
}
void getdocument_type_symbol(addr symbol, addr *ret)
{
getinfo_constant(symbol, CONSTANT_SYSTEM_TYPE_DOCUMENTATION, ret);
}
void setdocument_type_symbol(addr symbol, addr value)
{
setinfo_constant(symbol, CONSTANT_SYSTEM_TYPE_DOCUMENTATION, value);
}
/* deftype */
void getdeftype_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_SYSTEM_DEFTYPE, ret);
}
int setdeftype_symbol_(addr symbol, addr value)
{
CheckSymbol(symbol);
Check(value != Nil && GetType(value) != LISPTYPE_FUNCTION, "type error");
return setinfo_constant_(symbol, CONSTANT_SYSTEM_DEFTYPE, value);
}
void remdeftype_symbol(addr symbol)
{
CheckSymbol(symbol);
reminfo_constant(symbol, CONSTANT_SYSTEM_DEFTYPE);
}
/* type-symbol */
void getsymboltype_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_SYSTEM_TYPE_SYMBOL, ret);
}
void setsymboltype_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
setinfo_nocheck_constant(symbol, CONSTANT_SYSTEM_TYPE_SYMBOL, value);
}
void getlisttype_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_SYSTEM_TYPE_LIST, ret);
}
void setlisttype_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
setinfo_nocheck_constant(symbol, CONSTANT_SYSTEM_TYPE_LIST, value);
}
/* clos */
void getclass_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_COMMON_CLASS, ret);
}
void setclass_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
Check(GetType(value) != LISPTYPE_CLOS, "type error");
setinfo_nocheck_constant(symbol, CONSTANT_COMMON_CLASS, value);
}
void remclass_symbol(addr symbol)
{
CheckSymbol(symbol);
reminfo_nocheck_constant(symbol, CONSTANT_COMMON_CLASS);
}
void getcombination_symbol(addr symbol, addr *ret)
{
CheckSymbol(symbol);
getinfo_constant(symbol, CONSTANT_COMMON_METHOD_COMBINATION, ret);
}
void setcombination_symbol(addr symbol, addr value)
{
CheckSymbol(symbol);
Check(GetType(value) != LISPTYPE_CLOS, "type error");
setinfo_nocheck_constant(symbol, CONSTANT_COMMON_METHOD_COMBINATION, value);
}
/*
* symstack
*/
static void realloc_symbol(addr *stack, size_t size1, size_t size2)
{
addr make, old, temp;
byte32 size32;
size_t i;
old = *stack;
size32 = (byte32)size2;
if ((size_t)size32 <= size1)
Abort("size error");
heap_array4(&make, LISPSYSTEM_SYMSTACK, size32);
for (i = 0; i < size1; i++) {
GetArrayA4(old, i, &temp);
SetArrayA4(make, i, temp);
SetArrayA4(old, i, Nil);
}
for (; i < size2; i++) {
SetArrayA4(make, i, NULL);
}
*stack = make;
}
static void symstack(size_t index, addr symbol, addr *ret)
{
addr stack, child;
size_t i, size, size2;
Check(GetStatusDynamic(symbol), "dynamic error.");
lispd_rdlock_rwlocklite(&MutexSymbol);
GetSpecialSymbol_Low(symbol, &stack);
size = GetLenArrayA4(stack);
if (index < size) {
*ret = stack;
lispd_unrdlock_rwlocklite(&MutexSymbol);
return;
}
/* write lock */
lispd_unrdlock_rwlocklite(&MutexSymbol);
lispd_wrlock_rwlocklite(&MutexSymbol);
/* reload */
GetSpecialSymbol_Low(symbol, &stack);
size = GetLenArrayA4(stack);
if (index < size) {
*ret = stack;
lispd_unwrlock_rwlocklite(&MutexSymbol);
return;
}
/* size extension */
for (size2 = size; size2 <= index; )
size2 <<= 1;
realloc_symbol(&stack, size, size2);
SetSpecialSymbol_Low(symbol, stack);
for (i = size; i < size2; i++) {
consnil_heap(&child);
SetArrayA4(stack, i, child);
}
*ret = stack;
lispd_unwrlock_rwlocklite(&MutexSymbol);
}
void getspecial_unsafe(Execute ptr, addr pos, addr *ret)
{
CheckSymbol(pos);
symstack(ptr->index, pos, &pos);
GetArrayA4(pos, ptr->index, ret);
}
void setspecial_unsafe(Execute ptr, addr pos, addr value)
{
CheckSymbol(pos);
symstack(ptr->index, pos, &pos);
SetArrayA4_force(pos, ptr->index, value);
}
void getspecial_local(Execute ptr, addr pos, addr *ret)
{
CheckSymbol(pos);
if (GetStatusReadOnly(pos)) {
GetValueSymbol(pos, ret);
return;
}
getspecial_unsafe(ptr, pos, ret);
if (*ret == NULL) {
GetValueSymbol(pos, ret);
}
}
int getspecialcheck_local_(Execute ptr, addr pos, addr *ret)
{
getspecial_local(ptr, pos, ret);
if (*ret == Unbound)
return call_unbound_variable_(ptr, pos);
return 0;
}
void setspecial_local(Execute ptr, addr pos, addr value)
{
addr check;
CheckSymbol(pos);
getspecial_unsafe(ptr, pos, &check);
if (check == NULL) {
SetValueSymbol(pos, value);
}
else {
setspecial_unsafe(ptr, pos, value);
}
}
int getfunction_global_(addr pos, addr *ret)
{
GetFunctionSymbol(pos, ret);
if (*ret == Unbound)
return call_undefined_function_(NULL, pos);
return 0;
}
int getsetf_global_(addr pos, addr *ret)
{
addr setf;
getsetf_symbol(pos, ret);
if (*ret == Unbound) {
GetConst(COMMON_SETF, &setf);
list_heap(&pos, setf, pos, NULL);
return call_undefined_function_(NULL, pos);
}
return 0;
}
int alldelete_function_(addr pos)
{
Check(! symbolp(pos), "type error");
if (GetStatusReadOnly(pos))
return fmte_("Cannot set the constant variable ~S.", pos, NULL);
SetFunctionSymbol(pos, Unbound);
remsetf_symbol(pos);
remsetfmacro_symbol(pos);
remmacro_symbol(pos);
Return(remtype_function_symbol_(pos));
Return(remtype_setf_symbol_(pos));
return 0;
}
/*
* gensym
*/
int gensymp(addr pos)
{
if (GetType(pos) != LISPTYPE_SYMBOL)
return 0;
GetPackageSymbol(pos, &pos);
return pos == Nil;
}
void make_symbolchar(addr *ret, const char *str)
{
addr pos, name;
symbol_heap(&pos);
strvect_char_heap(&name, str);
SetNameSymbol(pos, name);
*ret = pos;
}
static int make_gensym_argument_(Execute ptr,
const char *prefix1, addr prefix2, addr counter, addr *ret)
{
addr symbol, value, queue, name, gensym;
LocalRoot local;
LocalStack stack;
/* symbol-name */
local = ptr->local;
push_local(local, &stack);
if (counter == NULL) {
GetConst(SPECIAL_GENSYM_COUNTER, &symbol);
Return(getspecialcheck_local_(ptr, symbol, &value));
}
else {
symbol = NULL;
value = counter;
}
Check(! integerp(value), "type error");
charqueue_local(local, &queue, 1 + 16);
if (prefix1) {
Return(pushchar_charqueue_local_(local, queue, prefix1));
}
else {
Return(pushstring_charqueue_local_(local, queue, prefix2));
}
Return(decimal_charqueue_integer_local_(local, value, queue));
make_charqueue_heap(queue, &name);
rollback_local(local, stack);
/* gensym */
symbol_heap(&gensym);
SetNameSymbol(gensym, name);
*ret = gensym;
/* (1+ *gensym-counter*) */
if (counter == NULL) {
Return(oneplus_integer_common_(local, value, &value));
setspecial_local(ptr, symbol, value);
}
return 0;
}
int make_gensym_(Execute ptr, addr *ret)
{
return make_gensym_argument_(ptr, "G", NULL, NULL, ret);
}
int make_gensym_prefix_(Execute ptr, addr prefix, addr *ret)
{
Check(! stringp(prefix), "type error");
return make_gensym_argument_(ptr, NULL, prefix, NULL, ret);
}
int make_gensym_integer_(Execute ptr, addr value, addr *ret)
{
Check(! integerp(value), "type error");
return make_gensym_argument_(ptr, "G", NULL, value, ret);
}
int make_gensym_char_(Execute ptr, const char *str, addr value, addr *ret)
{
Check(! integerp(value), "type error");
return make_gensym_argument_(ptr, str, NULL, value, ret);
}
void setcounter_gensym(Execute ptr, fixnum value)
{
addr pos, symbol;
Check(value < 0, "value error");
fixnum_heap(&pos, value);
GetConst(SPECIAL_GENSYM_COUNTER, &symbol);
setspecial_local(ptr, symbol, pos);
}
/************************************************************
* syscall.c
************************************************************/
void init_syscall(void)
{
init_syscall_common();
init_syscall_function();
}
void build_syscall(void)
{
build_syscall_common();
build_syscall_function();
}
/************************************************************
* syscall_common.c
************************************************************/
/* (defun redirect-restart (condition list) ...) -> null */
static int syscall_redirect_restart(Execute ptr, addr condition, addr list)
{
Return(redirect_restart_syscode(ptr, condition, list));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_redirect_restart(addr *ret)
{
addr args, values;
GetTypeTable(&args, Condition);
GetTypeTable(&values, List);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_redirect_restart(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_REDIRECT_RESTART, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_redirect_restart);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_redirect_restart(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun define-symbol-macro (symbol form) ...) -> symbol */
static int syscall_define_symbol_macro(Execute ptr, addr symbol, addr form)
{
Return(setsymbol_macro_symbol_(symbol, form));
setresult_control(ptr, symbol);
return 0;
}
static void type_syscall_define_symbol_macro(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
GetTypeTable(&values, T);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Symbol);
type_compiled_heap(args, values, ret);
}
static void defun_define_symbol_macro(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DEFINE_SYMBOL_MACRO, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_define_symbol_macro);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_define_symbol_macro(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun symbol-macro-expander (&rest form) form) */
static int syscall_symbol_macro_expander(Execute ptr, addr form, addr env)
{
setresult_control(ptr, form);
return 0;
}
static void defun_symbol_macro_expander(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SYMBOL_MACRO_EXPANDER, &symbol);
compiled_macro_system(&pos, symbol);
setcompiled_macro(pos, p_defmacro_syscall_symbol_macro_expander);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, MacroFunction);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun defconstant (symbol value document) ...) -> symbol */
static int syscall_defconstant(Execute ptr, addr symbol, addr value, addr doc)
{
Return(defconstant_syscode(symbol, value, doc));
setresult_control(ptr, symbol);
return 0;
}
static void type_syscall_defconstant(addr *ret)
{
addr args, values, type;
GetTypeTable(&args, Symbol);
GetTypeTable(&values, T);
GetTypeTable(&type, StringNull);
typeargs_var3(&args, args, values, type);
GetTypeValues(&values, Symbol);
type_compiled_heap(args, values, ret);
}
static void defun_defconstant(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DEFCONSTANT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var3(pos, p_defun_syscall_defconstant);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_defconstant(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun in-package (string-designer) ...) -> package */
static int syscall_in_package(Execute ptr, addr name)
{
Return(in_package_syscode_(ptr, name, &name));
setresult_control(ptr, name);
return 0;
}
static void type_syscall_in_package(addr *ret)
{
addr args, values;
GetTypeTable(&args, StringDesigner);
typeargs_var1(&args, args);
GetTypeValues(&values, Package);
type_compiled_heap(args, values, ret);
}
static void defun_in_package(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_IN_PACKAGE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_in_package);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_in_package(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun setplist (key value list) ...) -> list */
static int syscall_setplist(Execute ptr, addr key, addr value, addr list)
{
setplist_syscode(key, value, list, &list);
setresult_control(ptr, list);
return 0;
}
static void defun_setplist(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SETPLIST, &symbol);
compiled_system(&pos, symbol);
setcompiled_var3(pos, p_defun_syscall_setplist);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Acons);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun remplist (key list) ...) -> value, check
* key t
* list list
* value list
* check boolean
*/
static int syscall_remplist(Execute ptr, addr key, addr list)
{
Return(remplist_syscode_(key, list, &key, &list));
setvalues_control(ptr, key, list, NULL);
return 0;
}
static void type_syscall_remplist(addr *ret)
{
addr args, values, type;
GetTypeTable(&args, T);
GetTypeTable(&values, List);
typeargs_var2(&args, args, values);
GetTypeTable(&type, Boolean);
typevalues_values2(&values, values, type);
type_compiled_heap(args, values, ret);
}
static void defun_remplist(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_REMPLIST, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_remplist);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_remplist(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-hash-iterator (table) ...) -> hash-iterator */
static int syscall_make_hash_iterator(Execute ptr, addr pos)
{
make_hash_iterator_syscode(pos, &pos);
setresult_control(ptr, pos);
return 0;
}
static void type_make_hash_iterator(addr *ret)
{
addr args, values;
GetTypeTable(&args, Hashtable);
typeargs_var1(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_make_hash_iterator(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_HASH_ITERATOR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_make_hash_iterator);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_hash_iterator(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun next-hash-iterator (iterator) ...) -> (values boolean &rest t) */
static int syscall_next_hash_iterator(Execute ptr, addr pos)
{
addr key, value;
next_hash_iterator_syscode(pos, &pos, &key, &value);
if (pos == Nil)
setresult_control(ptr, Nil);
else
setvalues_control(ptr, pos, key, value, NULL);
return 0;
}
static void type_next_hash_iterator(addr *ret)
{
addr args, values, type;
GetTypeTable(&type, T);
typeargs_var1(&args, type);
/* (values boolean &rest t) */
GetTypeValues(&values, Boolean);
conscar_heap(&values, values);
type_values_heap(values, Nil, type, Nil, &values);
/* result */
type_compiled_heap(args, values, ret);
}
static void defun_next_hash_iterator(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_NEXT_HASH_ITERATOR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_next_hash_iterator);
SetFunctionSymbol(symbol, pos);
/* type */
type_next_hash_iterator(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-package-iterator (table internal external inherited) ...)
* -> package-iterator
* internal t
* external t
* inherited t
*/
static int syscall_make_package_iterator(Execute ptr, addr pos, addr a, addr b, addr c)
{
Return(make_package_iterator_syscode_(pos, a, b, c, &pos));
setresult_control(ptr, pos);
return 0;
}
static void type_make_package_iterator(addr *ret)
{
addr args, values;
GetTypeTable(&args, PackageDesigner);
GetTypeTable(&values, List);
type2or_heap(args, values, &args);
GetTypeTable(&values, T);
typeargs_var4(&args, args, values, values, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_make_package_iterator(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_PACKAGE_ITERATOR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var4(pos, p_defun_syscall_make_package_iterator);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_package_iterator(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun next-package-iterator (iterator) ...) -> * */
static int syscall_next_package_iterator(Execute ptr, addr pos)
{
addr symbol, status, package;
Return(next_package_iterator_syscode_(ptr, pos, &pos, &symbol, &status, &package));
if (pos == Nil)
setresult_control(ptr, Nil);
else
setvalues_control(ptr, pos, symbol, status, package, NULL);
return 0;
}
static void type_next_package_iterator(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
GetTypeTable(&values, Asterisk);
type_compiled_heap(args, values, ret);
}
static void defun_next_package_iterator(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_NEXT_PACKAGE_ITERATOR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_next_package_iterator);
SetFunctionSymbol(symbol, pos);
/* type */
type_next_package_iterator(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun defpackage (name &key size docuemntation nicknames use
* shadow shadowing-import-from import-from export intern)
* -> package
* name string-designer
* :size (or null (integer 0 *))
* :documentation (or null string)
* :nicknames list
* :use list
* :shadow list
* :shadowing-import-from list
* :import-from list
* :export list
* :intern list
*/
static int syscall_defpackage(Execute ptr, addr var, addr rest)
{
Return(defpackage_syscode(ptr, var, rest, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_defpackage(addr *ret)
{
addr args, values;
addr key, key1, key2, key3, key4, key5, key6, key7, key8, key9, key10;
GetTypeTable(&args, StringDesigner);
KeyTypeTable(&key1, SIZE, IntplusNull);
KeyTypeTable(&key2, DOCUMENTATION, StringNull);
KeyTypeTable(&key3, NICKNAMES, List);
KeyTypeTable(&key4, USE, List);
KeyTypeTable(&key5, SHADOW, List);
KeyTypeTable(&key6, SHADOWING_IMPORT_FROM, List);
KeyTypeTable(&key7, SHADOWING_IMPORT_FROM, List);
KeyTypeTable(&key8, IMPORT_FROM, List);
KeyTypeTable(&key9, EXPORT, List);
KeyTypeTable(&key10, INTERN, List);
list_heap(&key, key1, key2, key3, key4, key5, key6, key7, key8, key9, key10, NULL);
typeargs_var1key(&args, args, key);
GetTypeValues(&values, Package);
type_compiled_heap(args, values, ret);
}
static void defun_defpackage(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DEFPACKAGE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_defpackage);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_defpackage(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun do-symbols (function package) ...) -> nil */
static int syscall_do_symbols(Execute ptr, addr call, addr package)
{
Return(do_symbols_syscode(ptr, call, package));
setvalues_nil_control(ptr);
return 0;
}
static void defun_do_symbols(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DO_SYMBOLS, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_do_symbols);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, DoSymbols);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun do-external-symbols (function package) ...) -> nil */
static int syscall_do_external_symbols(Execute ptr, addr call, addr package)
{
Return(do_external_symbols_syscode(ptr, call, package));
setvalues_nil_control(ptr);
return 0;
}
static void defun_do_external_symbols(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DO_EXTERNAL_SYMBOLS, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_do_external_symbols);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, DoSymbols);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun do-all-symbols (function) ...) -> nil */
static int syscall_do_all_symbols(Execute ptr, addr call)
{
Return(do_all_symbols_syscode_(ptr, call));
setvalues_nil_control(ptr);
return 0;
}
static void type_do_all_symbols(addr *ret)
{
/* (function (function) (values &rest nil)) */
addr args, values;
GetTypeTable(&args, Function);
typeargs_var1(&args, args);
GetTypeValues(&values, Nil);
type_compiled_heap(args, values, ret);
}
static void defun_do_all_symbols(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DO_ALL_SYMBOLS, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_do_all_symbols);
SetFunctionSymbol(symbol, pos);
/* type */
type_do_all_symbols(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun getdoc-variable (symbol) ...) -> (or string null) */
static int syscall_getdoc_variable(Execute ptr, addr var)
{
getdoc_variable_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void type_getdoc_variable(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
typeargs_var1(&args, args);
GetTypeValues(&values, StringNull);
type_compiled_heap(args, values, ret);
}
static void defun_getdoc_variable(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_GETDOC_VARIABLE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_getdoc_variable);
SetFunctionSymbol(symbol, pos);
/* type */
type_getdoc_variable(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun setdoc-variable (symbol string) ...) -> string */
static int syscall_setdoc_variable(Execute ptr, addr var, addr value)
{
setdoc_variable_syscode(var, value);
setresult_control(ptr, value);
return 0;
}
static void type_setdoc_variable(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
GetTypeTable(&values, String);
typeargs_var2(&args, args, values);
GetTypeValues(&values, String);
type_compiled_heap(args, values, ret);
}
static void defun_setdoc_variable(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SETDOC_VARIABLE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_setdoc_variable);
SetFunctionSymbol(symbol, pos);
/* type */
type_setdoc_variable(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun ecase-error (value list) ...) -> nil */
static int syscall_ecase_error(Execute ptr, addr value, addr list)
{
Return(ecase_error_syscode_(ptr, value, list));
setvalues_nil_control(ptr);
return 0;
}
static void defun_ecase_error(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ECASE_ERROR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_ecase_error);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, EcaseError);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun etypecase-error (value list) ...) -> nil */
static int syscall_etypecase_error(Execute ptr, addr value, addr list)
{
Return(etypecase_error_syscode_(ptr, value, list));
setvalues_nil_control(ptr);
return 0;
}
static void defun_etypecase_error(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ETYPECASE_ERROR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_etypecase_error);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, EcaseError);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun define-setf-expander (name lambda) ...) -> name */
static int syscall_define_setf_expander(Execute ptr, addr symbol, addr call)
{
Return(define_setf_expander_syscode_(symbol, call));
setresult_control(ptr, symbol);
return 0;
}
static void type_syscall_define_setf_expander(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
GetTypeTable(&values, Function);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Symbol);
type_compiled_heap(args, values, ret);
}
static void defun_define_setf_expander(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DEFINE_SETF_EXPANDER, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_define_setf_expander);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_define_setf_expander(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun end-input-stream (string-stream) -> index */
static int syscall_end_input_stream(Execute ptr, addr var)
{
end_input_stream_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void type_end_input_stream(addr *ret)
{
addr args, values;
GetTypeTable(&args, StringStream);
typeargs_var1(&args, args);
GetTypeValues(&values, Index);
type_compiled_heap(args, values, ret);
}
static void defun_end_input_stream(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_END_INPUT_STREAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_end_input_stream);
SetFunctionSymbol(symbol, pos);
/* type */
type_end_input_stream(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-extend-output-stream (string &key element-type) ...)
* -> string-stream
*/
static int syscall_make_extend_output_stream(Execute ptr, addr var, addr rest)
{
make_extend_output_stream_syscode(var, rest, &var);
setresult_control(ptr, var);
return 0;
}
static void type_make_extend_output_stream(addr *ret)
{
addr args, values;
/* key */
KeyTypeTable(&args, ELEMENT_TYPE, Symbol);
list_heap(&args, args, NULL);
GetTypeTable(&values, String);
/* type */
typeargs_var1key(&args, values, args);
GetTypeTable(&values, StringStream);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_make_extend_output_stream(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_EXTEND_OUTPUT_STREAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_make_extend_output_stream);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_extend_output_stream(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun prompt-for (type &rest args) ...) -> t */
static int syscall_prompt_for(Execute ptr, addr type, addr args)
{
Return(prompt_for_syscode(ptr, type, args, &type));
setresult_control(ptr, type);
return 0;
}
static void type_prompt_for(addr *ret)
{
addr args, values;
GetTypeTable(&args, TypeSpec);
GetTypeTable(&values, T);
typeargs_var1rest(&args, args, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_prompt_for(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PROMPT_FOR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_prompt_for);
SetFunctionSymbol(symbol, pos);
/* type */
type_prompt_for(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun print-unreadable-call (stream pos type identity body) ...) -> null */
static int syscall_print_unreadable_call(Execute ptr,
addr stream, addr pos, addr type, addr identity, addr body)
{
Return(print_unreadable_call_syscode(ptr, stream, pos, type, identity, body));
setresult_control(ptr, Nil);
return 0;
}
static void type_print_unreadable_call(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
GetTypeTable(&values, StreamDesigner);
typeargs_var5(&args, values, args, args, args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_print_unreadable_call(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PRINT_UNREADABLE_CALL, &symbol);
compiled_system(&pos, symbol);
setcompiled_var5(pos, p_defun_syscall_print_unreadable_call);
SetFunctionSymbol(symbol, pos);
/* type */
type_print_unreadable_call(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun write-default (stream object) ...) -> t */
static int syscall_write_default(Execute ptr, addr stream, addr var)
{
Return(write_default_syscode(ptr, stream, var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_write_default(addr *ret)
{
addr args, values;
GetTypeTable(&args, StreamDesigner);
GetTypeTable(&values, T);
typeargs_var2(&args, args, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_write_default(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_WRITE_DEFAULT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_write_default);
SetFunctionSymbol(symbol, pos);
/* type */
type_write_default(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun symbol-deftype (symbol) ...) -> (or null function) */
static int syscall_symbol_deftype(Execute ptr, addr var)
{
symbol_deftype_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void type_symbol_deftype(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
typeargs_var1(&args, args);
GetTypeTable(&values, FunctionNull);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_symbol_deftype(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SYMBOL_DEFTYPE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_symbol_deftype);
SetFunctionSymbol(symbol, pos);
/* type */
type_symbol_deftype(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun delete-deftype (symbol) ...) -> boolean */
static int syscall_delete_deftype(Execute ptr, addr var)
{
delete_deftype_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void type_delete_deftype(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, ret);
}
static void defun_delete_deftype(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DELETE_DEFTYPE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_delete_deftype);
SetFunctionSymbol(symbol, pos);
/* type */
type_delete_deftype(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun ensure-structure (symbol list &rest args &key &allow-other-keys) ...)
* -> symbol
*/
static int syscall_ensure_structure(Execute ptr, addr name, addr slots, addr rest)
{
Return(ensure_structure_syscode_(ptr, name, slots, rest));
setresult_control(ptr, name);
return 0;
}
static void type_ensure_structure(addr *ret)
{
addr args, values, type;
GetTypeTable(&args, Symbol);
GetTypeTable(&values, List);
GetTypeTable(&type, T);
typeargs_var2rest(&args, args, values, type);
GetTypeValues(&values, Symbol);
type_compiled_heap(args, values, ret);
}
static void defun_ensure_structure(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ENSURE_STRUCTURE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2dynamic(pos, p_defun_syscall_ensure_structure);
SetFunctionSymbol(symbol, pos);
/* type */
type_ensure_structure(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun structure-constructor (symbol &rest t &key &other-allow-keys) ...)
* -> structure-object
*/
static int syscall_structure_constructor(Execute ptr, addr symbol, addr rest)
{
Return(structure_constructor_syscode(ptr, symbol, rest, &rest));
setresult_control(ptr, rest);
return 0;
}
static void type_structure_constructor(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
GetTypeTable(&values, T);
typeargs_var1rest(&args, args, values);
GetTypeTable(&values, StructureObject);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_structure_constructor(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_STRUCTURE_CONSTRUCTOR, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_structure_constructor);
SetFunctionSymbol(symbol, pos);
/* type */
type_structure_constructor(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun loop-bind (tree type value) ...) -> tree */
static int syscall_loop_bind(Execute ptr, addr a, addr b, addr c)
{
Return(loop_bind_syscode(ptr, a, b, c, &a));
setresult_control(ptr, a);
return 0;
}
static void type_loop_bind(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
typeargs_var3(&args, args, args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_loop_bind(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_LOOP_BIND, &symbol);
compiled_system(&pos, symbol);
setcompiled_var3(pos, p_defun_syscall_loop_bind);
SetFunctionSymbol(symbol, pos);
/* type */
type_loop_bind(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-pprint-stream (stream object
* prefix per-line-prefix suffix) ...) -> result
* stream stream
* object t
* prefix string
* per-line-prefix string
* suffix string
* result stream-pretty
*/
static int syscall_make_pprint_stream(Execute ptr,
addr stream, addr object, addr prefix, addr perline, addr suffix)
{
Return(make_pprint_stream_syscode_(ptr,
&stream, stream, object, prefix, perline, suffix));
setresult_control(ptr, stream);
return 0;
}
static void type_syscall_make_pprint_stream(addr *ret)
{
addr args, values, type1, type2, type3;
GetTypeTable(&type1, Stream);
GetTypeTable(&type2, T);
GetTypeTable(&type3, StringNull);
typeargs_var5(&args, type1, type2, type3, type3, type3);
GetTypeValues(&values, PrettyStream);
type_compiled_heap(args, values, ret);
}
static void defun_make_pprint_stream(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_PPRINT_STREAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var5(pos, p_defun_syscall_make_pprint_stream);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_make_pprint_stream(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun pprint-gensym (stream-pretty) ...) -> symbol */
static int syscall_pprint_gensym(Execute ptr, addr stream)
{
Return(pprint_gensym_syscode(stream, &stream));
setresult_control(ptr, stream);
return 0;
}
static void type_syscall_pprint_gensym(addr *ret)
{
addr args, values;
GetTypeTable(&args, PrettyStream);
typeargs_var1(&args, args);
GetTypeValues(&values, Symbol);
type_compiled_heap(args, values, ret);
}
static void defun_pprint_gensym(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PPRINT_GENSYM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_pprint_gensym);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_pprint_gensym(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun pprint-exit (stream-pretty) ...) -> null */
static int syscall_pprint_exit(Execute ptr, addr stream)
{
Return(pprint_exit_syscode(ptr, stream));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_pprint_exit(addr *ret)
{
addr args, values;
GetTypeTable(&args, PrettyStream);
typeargs_var1(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_pprint_exit(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PPRINT_EXIT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_pprint_exit);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_pprint_exit(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun pprint-pop (stream-pretty) ...) -> t */
static int syscall_pprint_pop(Execute ptr, addr stream)
{
Return(pprint_pop_syscode(ptr, stream, &stream));
setresult_control(ptr, stream);
return 0;
}
static void type_syscall_pprint_pop(addr *ret)
{
addr args, values;
GetTypeTable(&args, PrettyStream);
typeargs_var1(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_pprint_pop(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PPRINT_POP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_pprint_pop);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_pprint_pop(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun pprint-check (stream-pretty) ...) -> nil */
static int syscall_pprint_check(Execute ptr, addr stream)
{
Return(pprint_check_syscode(ptr, stream));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_pprint_check(addr *ret)
{
addr args, values;
GetTypeTable(&args, PrettyStream);
typeargs_var1(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_pprint_check(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PPRINT_CHECK, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_pprint_check);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_pprint_check(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun pprint-close (stream-pretty) ...) -> nil */
static int syscall_pprint_close(Execute ptr, addr stream)
{
Return(pprint_close_syscode(ptr, stream));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_pprint_close(addr *ret)
{
addr args, values;
GetTypeTable(&args, PrettyStream);
typeargs_var1(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_pprint_close(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PPRINT_CLOSE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_pprint_close);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_pprint_close(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun pprint-pretty (stream-pretty) ...) -> nil */
static int syscall_pprint_pretty(Execute ptr, addr stream, addr call)
{
Return(pprint_pretty_syscode(ptr, stream, call));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_pprint_pretty(addr *ret)
{
addr args, values;
GetTypeTable(&args, PrettyStream);
GetTypeTable(&values, Function);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_pprint_pretty(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PPRINT_PRETTY, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_pprint_pretty);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_pprint_pretty(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun timeinfo () ...) -> (values intplus intplus intplus intplus) */
static int syscall_timeinfo(Execute ptr)
{
addr real, run, size, count;
Return(timeinfo_syscode_(ptr->local, &real, &run, &size, &count));
setvalues_control(ptr, real, run, size, count, NULL);
return 0;
}
static void type_syscall_timeinfo(addr *ret)
{
addr args, values;
GetTypeArgs(&args, Empty);
GetTypeTable(&values, Intplus);
typevalues_values_va(&values, values, values, values, values, NULL);
type_compiled_heap(args, values, ret);
}
static void defun_timeinfo(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_TIMEINFO, &symbol);
compiled_system(&pos, symbol);
setcompiled_empty(pos, p_defun_syscall_timeinfo);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_timeinfo(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defvar *ed-function* (lambda (file) ... null))
* file (or null string)
*/
static int syscall_ed_function(Execute ptr, addr file)
{
Return(ed_function_syscode_(ptr, file));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_ed_function(addr *ret)
{
addr args, values;
GetTypeTable(&args, StringNull);
typeargs_var1(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defvar_ed_function(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ED_FUNCTION, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_ed_function);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_ed_function(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
/* (defvar *ed-function* [function]) */
SetValueSymbol(symbol, pos);
}
/* (defun trace-add (list) ...) -> list */
static int syscall_trace_add(Execute ptr, addr var)
{
Return(trace_add_syscode_(ptr, var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_trace_add(addr *ret)
{
addr args, values;
GetTypeTable(&args, List);
typeargs_var1(&args, args);
GetTypeValues(&values, List);
type_compiled_heap(args, values, ret);
}
static void defun_trace_add(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_TRACE_ADD, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_trace_add);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_trace_add(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun trace-del (list-or-t) ...) -> list */
static int syscall_trace_del(Execute ptr, addr var)
{
Return(trace_del_syscode_(ptr, var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_trace_del(addr *ret)
{
addr args, values;
GetTypeTable(&args, List);
GetTypeTable(&values, EqlT);
type2or_heap(args, values, &args);
typeargs_var1(&args, args);
GetTypeValues(&values, List);
type_compiled_heap(args, values, ret);
}
static void defun_trace_del(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_TRACE_DEL, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_trace_del);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_trace_del(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun with-compilation-unit (override args lambda) ...) -> any */
static void type_syscall_with_compilation_unit(addr *ret)
{
addr args, values, type1, type2, type3;
GetTypeTable(&type1, T);
GetTypeTable(&type2, List);
GetTypeTable(&type3, Function);
typeargs_var3(&args, type1, type2, type3);
GetTypeTable(&values, T);
typevalues_rest(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_with_compilation_unit(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_WITH_COMPILATION_UNIT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var3(pos, p_defun_syscall_with_compilation_unit);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_with_compilation_unit(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun set-slots (instance slots values) ...) -> t */
static int syscall_set_slots(Execute ptr, addr var, addr slots, addr values)
{
Return(set_slots_syscode(var, slots, values));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_set_slots(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
GetTypeTable(&values, List);
typeargs_var3(&args, args, values, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_set_slots(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SET_SLOTS, &symbol);
compiled_system(&pos, symbol);
setcompiled_var3(pos, p_defun_syscall_set_slots);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_set_slots(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun intern-eql-specializer (instance slots values) ...) -> t */
static int syscall_intern_eql_specializer(Execute ptr, addr var)
{
Return(intern_eql_specializer_syscode(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_intern_eql_specializer(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_intern_eql_specializer(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_INTERN_EQL_SPECIALIZER, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_intern_eql_specializer);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_intern_eql_specializer(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun defgeneric-define (symbol &rest &key &allow-other-keys) ...) -> instance */
static int syscall_defgeneric_define(Execute ptr, addr var, addr args)
{
Return(defgeneric_define_syscode_(ptr, var, args, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_defgeneric_define(addr *ret)
{
addr args, values;
addr key, key1, key2, key3, key4, key5, key6, key7;
KeyTypeTable(&key1, ARGUMENT_PRECEDENCE_ORDER, T);
KeyTypeTable(&key2, DECLARE, T);
KeyTypeTable(&key3, DOCUMENTATION, String);
KeyTypeTable(&key4, LAMBDA_LIST, T);
KeyTypeTable(&key5, GENERIC_FUNCTION_CLASS, T);
KeyTypeTable(&key6, METHOD_CLASS, T);
KeyTypeTable(&key7, METHOD_COMBINATION, T);
list_heap(&key, key1, key2, key3, key4, key5, key6, key7, NULL);
/* type */
GetTypeTable(&args, T);
typeargs_var1key(&args, args, key);
GetTypeValues(&values, GenericFunction);
type_compiled_heap(args, values, ret);
}
static void defun_defgeneric_define(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DEFGENERIC_DEFINE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_defgeneric_define);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_defgeneric_define(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun defgeneric-method (instance &rest args) ...) -> instance */
static int syscall_defgeneric_method(Execute ptr, addr var, addr args)
{
Return(defgeneric_method_syscode_(var, args));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_defgeneric_method(addr *ret)
{
addr args, values;
GetTypeTable(&args, GenericFunction);
GetTypeTable(&values, Method);
typeargs_var1rest(&args, args, values);
GetTypeValues(&values, GenericFunction);
type_compiled_heap(args, values, ret);
}
static void defun_defgeneric_method(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DEFGENERIC_METHOD, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_defgeneric_method);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_defgeneric_method(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/*
* function
*/
void init_syscall_common(void)
{
SetPointerSysCall(defun, var2, redirect_restart);
SetPointerSysCall(defun, var2, define_symbol_macro);
SetPointerSysCall(defmacro, macro, symbol_macro_expander);
SetPointerSysCall(defun, var3, defconstant);
SetPointerSysCall(defun, var1, in_package);
SetPointerSysCall(defun, var3, setplist);
SetPointerSysCall(defun, var2, remplist);
SetPointerSysCall(defun, var1, make_hash_iterator);
SetPointerSysCall(defun, var1, next_hash_iterator);
SetPointerSysCall(defun, var4, make_package_iterator);
SetPointerSysCall(defun, var1, next_package_iterator);
SetPointerSysCall(defun, var1dynamic, defpackage);
SetPointerSysCall(defun, var2, do_symbols);
SetPointerSysCall(defun, var2, do_external_symbols);
SetPointerSysCall(defun, var1, do_all_symbols);
SetPointerSysCall(defun, var1, getdoc_variable);
SetPointerSysCall(defun, var2, setdoc_variable);
SetPointerSysCall(defun, var2, ecase_error);
SetPointerSysCall(defun, var2, etypecase_error);
SetPointerSysCall(defun, var2, define_setf_expander);
SetPointerSysCall(defun, var1, end_input_stream);
SetPointerSysCall(defun, var1dynamic, make_extend_output_stream);
SetPointerSysCall(defun, var1dynamic, prompt_for);
SetPointerSysCall(defun, var5, print_unreadable_call);
SetPointerSysCall(defun, var2, write_default);
SetPointerSysCall(defun, var1, symbol_deftype);
SetPointerSysCall(defun, var1, delete_deftype);
SetPointerSysCall(defun, var2dynamic, ensure_structure);
SetPointerSysCall(defun, var1dynamic, structure_constructor);
SetPointerSysCall(defun, var3, loop_bind);
SetPointerSysCall(defun, var5, make_pprint_stream);
SetPointerSysCall(defun, var1, pprint_gensym);
SetPointerSysCall(defun, var1, pprint_exit);
SetPointerSysCall(defun, var1, pprint_pop);
SetPointerSysCall(defun, var1, pprint_check);
SetPointerSysCall(defun, var1, pprint_close);
SetPointerSysCall(defun, var2, pprint_pretty);
SetPointerSysCall(defun, empty, timeinfo);
SetPointerSysCall(defun, var1, ed_function);
SetPointerSysCall(defun, var1, trace_add);
SetPointerSysCall(defun, var1, trace_del);
SetPointerSysCall(defun, var3, with_compilation_unit);
SetPointerSysCall(defun, var3, set_slots);
SetPointerSysCall(defun, var1, intern_eql_specializer);
SetPointerSysCall(defun, var1dynamic, defgeneric_define);
SetPointerSysCall(defun, var1dynamic, defgeneric_method);
}
void build_syscall_common(void)
{
defun_redirect_restart();
defun_define_symbol_macro();
defun_symbol_macro_expander();
defun_defconstant();
defun_in_package();
defun_setplist();
defun_remplist();
defun_make_hash_iterator();
defun_next_hash_iterator();
defun_make_package_iterator();
defun_next_package_iterator();
defun_defpackage();
defun_do_symbols();
defun_do_external_symbols();
defun_do_all_symbols();
defun_getdoc_variable();
defun_setdoc_variable();
defun_ecase_error();
defun_etypecase_error();
defun_define_setf_expander();
defun_end_input_stream();
defun_make_extend_output_stream();
defun_prompt_for();
defun_print_unreadable_call();
defun_write_default();
defun_symbol_deftype();
defun_delete_deftype();
defun_ensure_structure();
defun_structure_constructor();
defun_loop_bind();
defun_make_pprint_stream();
defun_pprint_gensym();
defun_pprint_exit();
defun_pprint_pop();
defun_pprint_check();
defun_pprint_close();
defun_pprint_pretty();
defun_timeinfo();
defvar_ed_function();
defun_trace_add();
defun_trace_del();
defun_with_compilation_unit();
defun_set_slots();
defun_intern_eql_specializer();
defun_defgeneric_define();
defun_defgeneric_method();
}
/************************************************************
* syscall_function.c
************************************************************/
/* (defun abort () ...) -> null */
static int syscall_abort(Execute ptr)
{
Abort("syscall-abort");
setresult_control(ptr, Nil);
return 0;
}
static void defun_syscall_abort(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ABORT, &symbol);
compiled_system(&pos, symbol);
setcompiled_empty(pos, p_defun_syscall_abort);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeTable(&type, CompiledFunction);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun hello () ...) -> null */
static int syscall_hello(Execute ptr)
{
Return(hello_syscode(ptr));
setresult_control(ptr, Nil);
return 0;
}
static void defun_hello(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_HELLO, &symbol);
compiled_system(&pos, symbol);
setcompiled_empty(pos, p_defun_syscall_hello);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeTable(&type, CompiledFunction);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun infobit (&rest args) ...) -> object */
static int syscall_infobit(Execute ptr, addr rest)
{
infobit_syscode(rest, &rest);
setresult_control(ptr, rest);
return 0;
}
static void defun_infobit(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_INFOBIT, &symbol);
compiled_system(&pos, symbol);
setcompiled_dynamic(pos, p_defun_syscall_infobit);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, InfoBit);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun infoprint (&rest args) ...) -> object */
static int syscall_infoprint(Execute ptr, addr rest)
{
infoprint_syscode(rest, &rest);
setresult_control(ptr, rest);
return 0;
}
static void defun_infoprint(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_INFOPRINT, &symbol);
compiled_system(&pos, symbol);
setcompiled_dynamic(pos, p_defun_syscall_infoprint);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, InfoBit);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun gc (&key full) ...) -> null */
static int syscall_gc(Execute ptr, addr rest)
{
gc_syscode(rest);
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_gc(addr *ret)
{
addr args, values;
/* key */
KeyTypeTable(&args, FULL, T);
list_heap(&args, args, NULL);
/* type */
typeargs_key(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_gc(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_GC, &symbol);
compiled_system(&pos, symbol);
setcompiled_dynamic(pos, p_defun_syscall_gc);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_gc(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun savecore (pathname-designer) ...) -> null */
static int syscall_savecore(Execute ptr, addr file)
{
Return(savecore_syscode(ptr, file));
setresult_control(ptr, Nil);
return 0;
}
static void type_syscall_savecore(addr *ret)
{
addr args, values;
GetTypeTable(&args, PathnameDesigner);
typeargs_var1(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, ret);
}
static void defun_savecore(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SAVECORE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_savecore);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_savecore(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun package-export-list (package-designer) ...) -> list */
static int syscall_package_export_list(Execute ptr, addr var)
{
Return(package_export_list_syscode_(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_package_export_list(addr *ret)
{
/* (function (package_designer) (values list &rest nil)) */
addr args, values;
GetTypeTable(&args, PackageDesigner);
typeargs_var1(&args, args);
GetTypeValues(&values, List);
type_compiled_heap(args, values, ret);
}
static void defun_package_export_list(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PACKAGE_EXPORT_LIST, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_package_export_list);
SetFunctionSymbol(symbol, pos);
/* type */
type_package_export_list(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun specialp (symbol) ...) -> boolean */
static int syscall_specialp(Execute ptr, addr var)
{
specialp_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void type_specialp(addr *ret)
{
addr args, values;
GetTypeTable(&args, Symbol);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, ret);
}
static void defun_specialp(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SPECIALP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_specialp);
SetFunctionSymbol(symbol, pos);
/* type */
type_specialp(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun array-general-p (object) ...) -> boolean */
static int syscall_array_general_p(Execute ptr, addr var)
{
array_general_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_array_general_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ARRAY_GENERAL_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_array_general_p);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun array-specialized-p (object) ...) -> boolean */
static int syscall_array_specialized_p(Execute ptr, addr var)
{
array_specialized_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_array_specialized_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_ARRAY_SPECIALIZED_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_array_specialized_p);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun simple-sort (sequence call &key key) ...) -> sequence */
static int syscall_simple_sort(Execute ptr, addr pos, addr call, addr rest)
{
Return(simple_sort_syscode(ptr, pos, call, rest));
setresult_control(ptr, pos);
return 0;
}
static void defun_simple_sort(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SIMPLE_SORT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2dynamic(pos, p_defun_syscall_simple_sort);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Sort);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun bubble-sort (sequence call &key key) ...) -> sequence */
static int syscall_bubble_sort(Execute ptr, addr pos, addr call, addr rest)
{
Return(bubble_sort_syscode(ptr, pos, call, rest));
setresult_control(ptr, pos);
return 0;
}
static void defun_bubble_sort(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_BUBBLE_SORT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2dynamic(pos, p_defun_syscall_bubble_sort);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Sort);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun quick-sort (sequence call &key key) ...) -> sequence */
static int syscall_quick_sort(Execute ptr, addr pos, addr call, addr rest)
{
Return(quick_sort_syscode(ptr, pos, call, rest));
setresult_control(ptr, pos);
return 0;
}
static void defun_quick_sort(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_QUICK_SORT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2dynamic(pos, p_defun_syscall_quick_sort);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Sort);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun merge-sort (sequence call &key key) ...) -> sequence */
static int syscall_merge_sort(Execute ptr, addr pos, addr call, addr rest)
{
Return(merge_sort_syscode(ptr, pos, call, rest));
setresult_control(ptr, pos);
return 0;
}
static void defun_merge_sort(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MERGE_SORT, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2dynamic(pos, p_defun_syscall_merge_sort);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Sort);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun exit/quit (&optional code) ...) -> (values &rest nil) */
static int syscall_exit(Execute ptr, addr code)
{
Return(exit_syscode_(ptr, code));
setvalues_nil_control(ptr);
return 0;
}
static void defun_exit(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_EXIT, &symbol);
compiled_system(&pos, symbol);
setcompiled_opt1(pos, p_defun_syscall_exit);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Exit);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
static void defun_quit(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_QUIT, &symbol);
compiled_system(&pos, symbol);
setcompiled_opt1(pos, p_defun_syscall_exit);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Exit);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun closp (object) ...) -> boolean */
static int syscall_closp(Execute ptr, addr var)
{
closp_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_closp(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_CLOSP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_closp);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun fixnump (object) ...) -> boolean */
static int syscall_fixnump(Execute ptr, addr var)
{
fixnump_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_fixnump(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_FIXNUMP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_fixnump);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun bignump (object) ...) -> boolean */
static int syscall_bignump(Execute ptr, addr var)
{
bignump_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_bignump(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_BIGNUMP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_bignump);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun ratiop (object) ...) -> boolean */
static int syscall_ratiop(Execute ptr, addr var)
{
ratiop_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_ratiop(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_RATIOP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_ratiop);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun short-float-p (object) ...) -> boolean */
static int syscall_short_float_p(Execute ptr, addr var)
{
short_float_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_short_float_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SHORT_FLOAT_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_short_float_p);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun single-float-p (object) ...) -> boolean */
static int syscall_single_float_p(Execute ptr, addr var)
{
single_float_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_single_float_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SINGLE_FLOAT_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_single_float_p);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun double-float-p (object) ...) -> boolean */
static int syscall_double_float_p(Execute ptr, addr var)
{
double_float_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_double_float_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_DOUBLE_FLOAT_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_double_float_p);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun long-float-p (object) ...) -> boolean */
static int syscall_long_float_p(Execute ptr, addr var)
{
long_float_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_long_float_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_LONG_FLOAT_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_long_float_p);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun callnamep (object) ...) -> boolean */
static int syscall_callnamep(Execute ptr, addr var)
{
callnamep_syscall(var, &var);
setresult_control(ptr, var);
return 0;
}
static void defun_callnamep(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_CALLNAMEP, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_callnamep);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, Object_Boolean);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun large-number (value &optional (cardinal t)) ...) -> string
* value (integer 0 fixnum-max)
*/
static int syscall_large_number(Execute ptr, addr var, addr opt)
{
Return(large_number_syscode_(ptr->local, var, opt, &var));
setresult_control(ptr, var);
return 0;
}
static void type_large_number(addr *ret)
{
addr args, values;
type4integer_heap(Nil, 0, Nil, FIXNUM_MAX, &args);
GetTypeTable(&values, T);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, String);
type_compiled_heap(args, values, ret);
}
static void defun_large_number(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_LARGE_NUMBER, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1opt1(pos, p_defun_syscall_large_number);
SetFunctionSymbol(symbol, pos);
/* type */
type_large_number(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-character (x) ...) -> character
* x: (or character integer)
*/
static int syscall_make_character(Execute ptr, addr var)
{
Return(make_character_syscode(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_make_character(addr *ret)
{
addr args, values;
GetTypeTable(&args, Character);
GetTypeTable(&values, Integer);
type2or_heap(args, values, &args);
typeargs_var1(&args, args);
GetTypeValues(&values, Character);
type_compiled_heap(args, values, ret);
}
static void defun_make_character(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_CHARACTER, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_make_character);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_character(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-fixnum (integer) ...) -> fixnum */
static int syscall_make_fixnum(Execute ptr, addr var)
{
Return(make_fixnum_syscode(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_make_fixnum(addr *ret)
{
addr args, values;
GetTypeTable(&values, Fixnum);
typeargs_var1(&args, values);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_make_fixnum(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_FIXNUM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_make_fixnum);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_fixnum(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-bignum (integer) ...) -> bignum */
static int syscall_make_bignum(Execute ptr, addr var)
{
Return(make_bignum_syscode(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_make_bignum(addr *ret)
{
addr args, values;
GetTypeTable(&args, Integer);
typeargs_var1(&args, args);
GetTypeValues(&values, Integer);
type_compiled_heap(args, values, ret);
}
static void defun_make_bignum(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_BIGNUM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_make_bignum);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_bignum(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-ratio (numer denom) ...) -> ratio */
static int syscall_make_ratio(Execute ptr, addr numer, addr denom)
{
Return(make_ratio_syscode(numer, denom, &numer));
setresult_control(ptr, numer);
return 0;
}
static void type_make_ratio(addr *ret)
{
addr args, values;
GetTypeTable(&args, Integer);
typeargs_var2(&args, args, args);
GetTypeValues(&values, Rational);
type_compiled_heap(args, values, ret);
}
static void defun_make_ratio(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_RATIO, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_make_ratio);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_ratio(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-complex (real imag) ...) -> complex */
static int syscall_make_complex(Execute ptr, addr real, addr imag)
{
Return(make_complex_code_(real, imag, &real));
setresult_control(ptr, real);
return 0;
}
static void type_make_complex(addr *ret)
{
addr args, values;
GetTypeTable(&args, Real);
typeargs_var2(&args, args, args);
GetTypeValues(&values, Complex);
type_compiled_heap(args, values, ret);
}
static void defun_make_complex(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_COMPLEX, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_make_complex);
SetFunctionSymbol(symbol, pos);
/* type */
type_make_complex(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun equal-random-state (a b) ...) -> boolean */
static int syscall_equal_random_state(Execute ptr, addr left, addr right)
{
equal_random_state_syscode(left, right, &left);
setresult_control(ptr, left);
return 0;
}
static void type_equal_random_state(addr *ret)
{
addr args, values;
GetTypeTable(&args, RandomState);
typeargs_var2(&args, args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, ret);
}
static void defun_equal_random_state(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_EQUAL_RANDOM_STATE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_equal_random_state);
SetFunctionSymbol(symbol, pos);
/* type */
type_equal_random_state(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun subtypep! (x y &optional env check) ...) -> symbol */
static int syscall_subtypep_extend(Execute ptr, addr x, addr y, addr env, addr check)
{
Return(subtypep_extend_syscode_(ptr, x, y, env, check, &x));
setresult_control(ptr, x);
return 0;
}
static void type_syscall_subtypep_extend(addr *ret)
{
addr args, values, env;
GetTypeTable(&args, TypeSpec);
GetTypeTable(&env, EnvironmentNull);
GetTypeTable(&values, T);
typeargs_var2opt2(&args, args, args, env, values);
GetTypeValues(&values, Symbol);
type_compiled_heap(args, values, ret);
}
static void defun_subtypep_extend(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SUBTYPEP_EXTEND, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2opt2(pos, p_defun_syscall_subtypep_extend);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_subtypep_extend(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun subtypep-number (x) ...) -> type-specifier */
static int syscall_subtypep_number(Execute ptr, addr x)
{
Return(subtypep_number_syscode_(ptr, x, &x));
setresult_control(ptr, x);
return 0;
}
static void type_syscall_subtypep_number(addr *ret)
{
addr args, values;
GetTypeTable(&args, TypeSpec);
typeargs_var1(&args, args);
GetTypeTable(&values, TypeSpec);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_subtypep_number(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SUBTYPEP_NUMBER, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_subtypep_number);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_subtypep_number(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun eastasian-set (string-designer intplus &optional error) ...) -> boolean) */
static int syscall_eastasian_set(Execute ptr, addr var, addr value, addr errorp)
{
Return(eastasian_set_syscode_(var, value, errorp, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_eastasian_set(addr *ret)
{
addr args, values, type;
GetTypeTable(&args, StringDesigner);
GetTypeTable(&values, Intplus);
GetTypeTable(&type, T);
typeargs_var3(&args, args, values, type);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, ret);
}
static void defun_eastasian_set(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_EASTASIAN_SET, &symbol);
compiled_system(&pos, symbol);
setcompiled_var3(pos, p_defun_syscall_eastasian_set);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_eastasian_set(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun eastasian-get (string-designer) ...) -> (values IntplusNull symbol) */
static int syscall_eastasian_get(Execute ptr, addr var)
{
addr symbol;
Return(eastasian_get_syscode_(var, &var, &symbol));
setvalues_control(ptr, var, symbol, NULL);
return 0;
}
static void type_syscall_eastasian_get(addr *ret)
{
addr args, values, type;
GetTypeTable(&args, StringDesigner);
typeargs_var1(&args, args);
GetTypeTable(&values, IntplusNull);
GetTypeTable(&type, Symbol);
typevalues_values2(&values, values, type);
type_compiled_heap(args, values, ret);
}
static void defun_eastasian_get(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_EASTASIAN_GET, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_eastasian_get);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_eastasian_get(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun eastasian-width (var) ...) -> (values IntplusNull boolean)
* var (or integer character string)
*/
static int syscall_eastasian_width(Execute ptr, addr pos)
{
addr value;
Return(eastasian_width_syscode_(pos, &pos, &value));
setvalues_control(ptr, pos, value, NULL);
return 0;
}
static void type_syscall_eastasian_width(addr *ret)
{
addr args, values, type;
GetTypeTable(&args, Integer);
GetTypeTable(&values, Character);
GetTypeTable(&type, String);
type3or_heap(args, values, type, &args);
typeargs_var1(&args, args);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, ret);
}
static void defun_eastasian_width(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_EASTASIAN_WIDTH, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_eastasian_width);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_eastasian_width(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun run-program (program args &rest args) ...) -> t */
static int syscall_run_program(Execute ptr, addr var, addr args, addr rest)
{
Return(run_program_syscode_(ptr, var, args, rest, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_run_program(addr *ret)
{
addr args, values, rest;
GetTypeTable(&args, String);
GetTypeTable(&values, List);
GetTypeTable(&rest, T);
typeargs_var2rest(&args, args, values, rest);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_run_program(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_RUN_PROGRAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var2dynamic(pos, p_defun_syscall_run_program);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_run_program(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-callname (var) ...) -> callname */
static int syscall_make_callname(Execute ptr, addr var)
{
Return(make_callname_syscode_(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_make_callname(addr *ret)
{
addr args, values;
GetTypeTable(&args, FunctionName);
typeargs_var1(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_make_callname(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_CALLNAME, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_make_callname);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_make_callname(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun remove-file (pathname &optional (error t)) ...) -> boolean */
static int syscall_remove_file(Execute ptr, addr var, addr opt)
{
Return(remove_file_syscode(ptr, var, opt, &var));
setresult_control(ptr, var);
return 0;
}
static void defun_remove_file(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_REMOVE_FILE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1opt1(pos, p_defun_syscall_remove_file);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, RemoveFile);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun remove-directory (pathname &optional (error t)) ...) -> boolean */
static int syscall_remove_directory(Execute ptr, addr var, addr opt)
{
Return(remove_directory_syscode(ptr, var, opt, &var));
setresult_control(ptr, var);
return 0;
}
static void defun_remove_directory(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_REMOVE_DIRECTORY, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1opt1(pos, p_defun_syscall_remove_directory);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, RemoveFile);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defmacro declare-parse (symbol) ...) -> integer */
static int syscall_declare_parse(Execute ptr, addr form, addr env)
{
Return(declare_parse_syscode(form, &form));
setresult_control(ptr, form);
return 0;
}
static void defmacro_declare_parse(void)
{
addr symbol, pos, type;
GetConst(SYSTEM_DECLARE_PARSE, &symbol);
compiled_macro_system(&pos, symbol);
setcompiled_macro(pos, p_defmacro_syscall_declare_parse);
setmacro_symbol(symbol, pos);
/* type */
GetTypeCompiled(&type, MacroFunction);
settype_function(pos, type);
}
/* (defun parse-type (object) ...) -> type */
static int syscall_parse_type(Execute ptr, addr var)
{
Return(parse_type_syscode(ptr, var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_parse_type(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
GetTypeTable(&values, TypeSpec);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_parse_type(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_PARSE_TYPE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_parse_type);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_parse_type(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun upgraded-open-element-type (type) ...) -> type */
static int syscall_upgraded_open_element_type(Execute ptr, addr var)
{
Return(upgraded_open_element_type_syscode_(var, &var));
setresult_control(ptr, var);
return 0;
}
static void defun_upgraded_open_element_type(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_UPGRADED_OPEN_ELEMENT_TYPE, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_upgraded_open_element_type);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, UpgradedType);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-memory-input-stream (sequence &key size array cache) ...) -> stream
* sequence sequence
* size (or null (integer 1 *))
* array (or null (integer 1 *))
* cache t ;; boolean
* stream input-memory-stream
*/
static int syscall_make_memory_input_stream(Execute ptr, addr var, addr rest)
{
Return(make_memory_input_stream_syscode_(var, rest, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_make_memory_input_stream(addr *ret)
{
addr args, values, key1, key2, key3, key;
/* key */
KeyTypeTable(&key1, SIZE, Plus1Null);
KeyTypeTable(&key2, ARRAY, Plus1Null);
KeyTypeTable(&key3, CACHE, T);
list_heap(&key, key1, key2, key3, NULL);
/* type */
GetTypeTable(&args, Sequence);
typeargs_var1key(&args, args, key);
GetTypeValues(&values, MemoryStream);
type_compiled_heap(args, values, ret);
}
static void defun_make_memory_input_stream(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_MEMORY_INPUT_STREAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_make_memory_input_stream);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_make_memory_input_stream(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-memroy-output-stream (&key input size array cache) ...) -> stream
* input sequence
* size (or null (integer 1 *))
* array (or null (integer 1 *))
* cache t ;; boolean
* stream output-memory-stream
*/
static int syscall_make_memory_output_stream(Execute ptr, addr rest)
{
Return(make_memory_output_stream_syscode_(rest, &rest));
setresult_control(ptr, rest);
return 0;
}
static void defun_make_memory_output_stream(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_MEMORY_OUTPUT_STREAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_dynamic(pos, p_defun_syscall_make_memory_output_stream);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, MakeMemoryOutputStream);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun make-memroy-io-stream (&key input size array cache) ...) -> stream
* input sequence
* size (or null (integer 1 *))
* array (or null (integer 1 *))
* cache t ;; boolean
* stream io-memory-stream
*/
static int syscall_make_memory_io_stream(Execute ptr, addr rest)
{
Return(make_memory_io_stream_syscode_(rest, &rest));
setresult_control(ptr, rest);
return 0;
}
static void defun_make_memory_io_stream(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MAKE_MEMORY_IO_STREAM, &symbol);
compiled_system(&pos, symbol);
setcompiled_dynamic(pos, p_defun_syscall_make_memory_io_stream);
SetFunctionSymbol(symbol, pos);
/* type */
GetTypeCompiled(&type, MakeMemoryOutputStream);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defmacro with-input-from-memory
* ((stream vector &key size array) declaration* form*) ...)
* -> result
*/
static int syscall_with_input_from_memory(Execute ptr, addr form, addr env)
{
Return(with_input_from_memory_syscode_(ptr, form, &form));
setresult_control(ptr, form);
return 0;
}
static void defmacro_with_input_from_memory(void)
{
addr symbol, pos, type;
GetConst(SYSTEM_WITH_INPUT_FROM_MEMORY, &symbol);
compiled_macro_system(&pos, symbol);
setcompiled_macro(pos, p_defmacro_syscall_with_input_from_memory);
setmacro_symbol(symbol, pos);
/* type */
GetTypeCompiled(&type, MacroFunction);
settype_function(pos, type);
}
/* (defmacro with-output-to-memory
* ((var &key input size array) declaration* form*) ...)
* -> result
*/
static int syscall_with_output_to_memory(Execute ptr, addr form, addr env)
{
Return(with_output_to_memory_syscode_(ptr, form, &form));
setresult_control(ptr, form);
return 0;
}
static void defmacro_with_output_to_memory(void)
{
addr symbol, pos, type;
GetConst(SYSTEM_WITH_OUTPUT_TO_MEMORY, &symbol);
compiled_macro_system(&pos, symbol);
setcompiled_macro(pos, p_defmacro_syscall_with_output_to_memory);
setmacro_symbol(symbol, pos);
/* type */
GetTypeCompiled(&type, MacroFunction);
settype_function(pos, type);
}
/* (defun get-output-stream-memory (stream) ...) -> vector */
static int syscall_get_output_stream_memory(Execute ptr, addr var)
{
Return(get_output_stream_memory_syscode_(var, &var));
setresult_control(ptr, var);
return 0;
}
static void type_syscall_get_output_stream_memory(addr *ret)
{
addr args, values;
GetTypeTable(&args, MemoryStream);
typeargs_var1(&args, args);
GetTypeValues(&values, Vector);
type_compiled_heap(args, values, ret);
}
static void defun_get_output_stream_memory(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_GET_OUTPUT_STREAM_MEMORY, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_get_output_stream_memory);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_get_output_stream_memory(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun memory-stream-p (t) ...) -> (member :input :output :io nil) */
static int syscall_memory_stream_p(Execute ptr, addr var)
{
memory_stream_p_syscode(var, &var);
setresult_control(ptr, var);
return 0;
}
static void type_syscall_memory_stream_p(addr *ret)
{
addr args, values, type1, type2, type3;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
GetConst(KEYWORD_INPUT, &type1);
GetConst(KEYWORD_OUTPUT, &type2);
GetConst(KEYWORD_IO, &type3);
type_member_heap(&values, type1, type2, type3, Nil, NULL);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_memory_stream_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MEMORY_STREAM_P, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_memory_stream_p);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_memory_stream_p(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun (setf memory-stream-p) (result stream) ...) -> result
* stream memory-stream
* result (member :input :output :io)
*/
static int syscall_setf_memory_stream_p(Execute ptr, addr value, addr var)
{
Return(setf_memory_stream_p_syscode_(var, value));
setresult_control(ptr, value);
return 0;
}
static void type_syscall_setf_memory_stream_p(addr *ret)
{
addr args, values, type1, type2, type3;
GetTypeTable(&args, MemoryStream);
GetConst(KEYWORD_INPUT, &type1);
GetConst(KEYWORD_OUTPUT, &type2);
GetConst(KEYWORD_IO, &type3);
type_member_heap(&values, type1, type2, type3, NULL);
typeargs_var2(&args, values, args);
typevalues_result(&values, values);
type_compiled_heap(args, values, ret);
}
static void defun_setf_memory_stream_p(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_MEMORY_STREAM_P, &symbol);
compiled_setf_system(&pos, symbol);
setcompiled_var2(pos, p_defun_syscall_setf_memory_stream_p);
setsetf_symbol(symbol, pos);
/* type */
type_syscall_setf_memory_stream_p(&type);
settype_function(pos, type);
settype_setf_symbol(symbol, type);
}
/* (defun byte-integer (&rest unsigned-byte-8) ...) -> (integer 0 *) */
static int syscall_byte_integer(Execute ptr, addr list)
{
Return(byte_integer_syscode_(list, &list));
setresult_control(ptr, list);
return 0;
}
static void type_syscall_byte_integer(addr *ret)
{
addr args, values;
type4integer_heap(Nil, 0, Nil, 0xFF, &args);
typeargs_rest(&args, args);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, ret);
}
static void defun_byte_integer(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_BYTE_INTEGER, &symbol);
compiled_system(&pos, symbol);
setcompiled_dynamic(pos, p_defun_syscall_byte_integer);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_byte_integer(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun sysctl (object &rest args) ...) -> (values &rest t) */
static int syscall_sysctl(Execute ptr, addr var, addr args)
{
return sysctl_syscode_(ptr, var, args);
}
static void type_syscall_sysctl(addr *ret)
{
addr args, values, type;
GetTypeTable(&type, T);
typeargs_var1rest(&args, type, type);
typevalues_rest(&values, type);
type_compiled_heap(args, values, ret);
}
static void defun_sysctl(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_SYSCTL, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_sysctl);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_sysctl(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun extension (t) ...) -> t */
static int syscall_extension(Execute ptr, addr var)
{
return extension_syscode(ptr, var);
}
static void type_syscall_extension(addr *ret)
{
addr args, values;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, ret);
}
static void defun_extension(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_EXTENSION, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1(pos, p_defun_syscall_extension);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_extension(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/* (defun terme (object &rest args) ...) -> (values &rest t) */
static int syscall_terme(Execute ptr, addr var, addr args)
{
return terme_syscode_(ptr, var, args);
}
static void defun_terme(void)
{
addr symbol, pos, type;
/* function */
GetConst(SYSTEM_TERME, &symbol);
compiled_system(&pos, symbol);
setcompiled_var1dynamic(pos, p_defun_syscall_terme);
SetFunctionSymbol(symbol, pos);
/* type */
type_syscall_sysctl(&type);
settype_function(pos, type);
settype_function_symbol(symbol, type);
}
/*
* function
*/
void init_syscall_function(void)
{
SetPointerSysCall(defun, empty, abort);
SetPointerSysCall(defun, empty, hello);
SetPointerSysCall(defun, dynamic, infobit);
SetPointerSysCall(defun, dynamic, infoprint);
SetPointerSysCall(defun, dynamic, gc);
SetPointerSysCall(defun, var1, savecore);
SetPointerSysCall(defun, var1, package_export_list);
SetPointerSysCall(defun, var1, specialp);
SetPointerSysCall(defun, var1, array_general_p);
SetPointerSysCall(defun, var1, array_specialized_p);
SetPointerSysCall(defun, var2dynamic, simple_sort);
SetPointerSysCall(defun, var2dynamic, bubble_sort);
SetPointerSysCall(defun, var2dynamic, quick_sort);
SetPointerSysCall(defun, var2dynamic, merge_sort);
SetPointerSysCall(defun, opt1, exit);
SetPointerSysCall(defun, var1, closp);
SetPointerSysCall(defun, var1, fixnump);
SetPointerSysCall(defun, var1, bignump);
SetPointerSysCall(defun, var1, ratiop);
SetPointerSysCall(defun, var1, callnamep);
SetPointerSysCall(defun, var1, short_float_p);
SetPointerSysCall(defun, var1, single_float_p);
SetPointerSysCall(defun, var1, double_float_p);
SetPointerSysCall(defun, var1, long_float_p);
SetPointerSysCall(defun, var1opt1, large_number);
SetPointerSysCall(defun, var1, make_character);
SetPointerSysCall(defun, var1, make_fixnum);
SetPointerSysCall(defun, var1, make_bignum);
SetPointerSysCall(defun, var2, make_ratio);
SetPointerSysCall(defun, var2, make_complex);
SetPointerSysCall(defun, var2, equal_random_state);
SetPointerSysCall(defun, var2opt2, subtypep_extend);
SetPointerSysCall(defun, var1, subtypep_number);
SetPointerSysCall(defun, var3, eastasian_set);
SetPointerSysCall(defun, var1, eastasian_get);
SetPointerSysCall(defun, var1, eastasian_width);
SetPointerSysCall(defun, var2dynamic, run_program);
SetPointerSysCall(defun, var1, make_callname);
SetPointerSysCall(defun, var1opt1, remove_file);
SetPointerSysCall(defun, var1opt1, remove_directory);
SetPointerSysCall(defmacro, macro, declare_parse);
SetPointerSysCall(defun, var1, parse_type);
SetPointerSysCall(defun, var1, upgraded_open_element_type);
SetPointerSysCall(defun, var1dynamic, make_memory_input_stream);
SetPointerSysCall(defun, dynamic, make_memory_output_stream);
SetPointerSysCall(defun, dynamic, make_memory_io_stream);
SetPointerSysCall(defmacro, macro, with_input_from_memory);
SetPointerSysCall(defmacro, macro, with_output_to_memory);
SetPointerSysCall(defun, var1, get_output_stream_memory);
SetPointerSysCall(defun, var1, memory_stream_p);
SetPointerSysCall(defun, var2, setf_memory_stream_p);
SetPointerSysCall(defun, dynamic, byte_integer);
SetPointerSysCall(defun, var1dynamic, sysctl);
SetPointerSysCall(defun, var1, extension);
SetPointerSysCall(defun, var1dynamic, terme);
}
void build_syscall_function(void)
{
defun_syscall_abort();
defun_hello();
defun_infobit();
defun_infoprint();
defun_gc();
defun_savecore();
defun_package_export_list();
defun_specialp();
defun_array_general_p();
defun_array_specialized_p();
defun_simple_sort();
defun_bubble_sort();
defun_quick_sort();
defun_merge_sort();
defun_exit();
defun_quit();
defun_closp();
defun_fixnump();
defun_bignump();
defun_ratiop();
defun_short_float_p();
defun_single_float_p();
defun_double_float_p();
defun_long_float_p();
defun_callnamep();
defun_large_number();
defun_make_character();
defun_make_fixnum();
defun_make_bignum();
defun_make_ratio();
defun_make_complex();
defun_equal_random_state();
defun_subtypep_extend();
defun_subtypep_number();
defun_eastasian_set();
defun_eastasian_get();
defun_eastasian_width();
defun_run_program();
defun_make_callname();
defun_remove_file();
defun_remove_directory();
defmacro_declare_parse();
defun_parse_type();
defun_upgraded_open_element_type();
defun_make_memory_input_stream();
defun_make_memory_output_stream();
defun_make_memory_io_stream();
defmacro_with_input_from_memory();
defmacro_with_output_to_memory();
defun_get_output_stream_memory();
defun_memory_stream_p();
defun_setf_memory_stream_p();
defun_byte_integer();
defun_sysctl();
defun_extension();
defun_terme();
}
/************************************************************
* syscode_common.c
************************************************************/
/* redirect-restart */
int redirect_restart_syscode(Execute ptr, addr condition, addr list)
{
addr pos;
Check(! conditionp_debug(condition), "type error");
while (list != Nil) {
Return_getcons(list, &pos, &list);
if (GetType(pos) != LISPTYPE_RESTART)
return fmte_("The argument ~S must be a restart.", pos, NULL);
pushbind_restart_control(ptr, pos, 0);
}
reverse_restart_control(ptr);
return 0;
}
/* defconstant */
int defconstant_syscode(addr symbol, addr value, addr doc)
{
addr check;
Check(! symbolp(symbol), "type symbol error");
Check(doc != Nil && (! stringp(doc)), "type documentation error");
GetValueSymbol(symbol, &check);
if (check != Unbound && (! eql_function(check, value)))
return fmte_("The defconstant cannot setq ~S value.", symbol, NULL);
ResetStatusReadOnly(symbol);
SetValueSymbol(symbol, value);
setdocument_variable_symbol(symbol, doc);
setspecial_symbol(symbol);
SetStatusReadOnly(symbol);
return 0;
}
/* in-package */
int in_package_syscode_(Execute ptr, addr name, addr *ret)
{
return in_package_(ptr, name, ret);
}
/* setplist */
void setplist_syscode(addr key, addr value, addr list, addr *ret)
{
setplist_heap_safe(list, key, value, ret);
}
/* remplist */
int remplist_syscode_(addr key, addr list, addr *ret1, addr *ret2)
{
enum RemPlist check;
Return(remplist_safe_(list, key, &list, &check));
*ret1 = list;
*ret2 = (check != RemPlist_NotFound)? T: Nil;
return 0;
}
/* make-hash-iterator */
void make_hash_iterator_syscode(addr pos, addr *ret)
{
hash_iterator_heap(ret, pos);
}
/* next-hash-iterator */
void next_hash_iterator_syscode(addr pos, addr *ret1, addr *ret2, addr *ret3)
{
int check;
addr key, value;
check = next_hash_iterator(pos, &key, &value);
if (check) {
*ret1 = T;
*ret2 = key;
*ret3 = value;
}
else {
*ret1 = *ret2 = *ret3 = Nil;
}
}
/* make-package-iterator */
int make_package_iterator_syscode_(addr pos, addr a, addr b, addr c, addr *ret)
{
return package_iterator_heap_(ret, pos, (a != Nil), (b != Nil), (c != Nil));
}
/* next-package-iterator */
int next_package_iterator_syscode_(Execute ptr, addr pos,
addr *ret1, addr *ret2, addr *ret3, addr *ret4)
{
enum PACKAGE_TYPE check;
addr symbol, status, package;
Return(next_package_iterator_(pos, &symbol, &package, &check));
if (check == PACKAGE_TYPE_NIL) {
*ret1 = *ret2 = *ret3 = *ret4 = Nil;
}
else {
keyword_packagetype(check, &status);
*ret1 = T;
*ret2 = symbol;
*ret3 = status;
*ret4 = package;
}
return 0;
}
/* defpackage */
int defpackage_syscode(Execute ptr, addr var, addr rest, addr *ret)
{
return defpackage_execute(ptr, var, rest, ret);
}
/* do-symbols */
int do_symbols_syscode(Execute ptr, addr call, addr package)
{
return do_symbols_package(ptr, call, package);
}
/* do-external-symbols */
int do_external_symbols_syscode(Execute ptr, addr call, addr package)
{
return do_external_symbols_package(ptr, call, package);
}
/* do-all-symbols */
int do_all_symbols_syscode_(Execute ptr, addr call)
{
return do_all_symbols_package_(ptr, call);
}
/* getdoc-variable */
void getdoc_variable_syscode(addr var, addr *ret)
{
getdocument_variable_symbol(var, ret);
}
/* setdoc-variable */
void setdoc_variable_syscode(addr var, addr value)
{
setdocument_variable_symbol(var, value);
}
/* ecase-error */
int ecase_error_syscode_(Execute ptr, addr value, addr list)
{
Return(make_vector4_from_list_(&list, list));
type1_heap(LISPDECL_MEMBER, list, &list);
return call_type_error_(ptr, value, list);
}
/* etypecase-error */
int etypecase_error_syscode_(Execute ptr, addr value, addr list)
{
Return(make_vector4_from_list_(&list, list));
type1_heap(LISPDECL_OR, list, &list);
return call_type_error_(ptr, value, list);
}
/* define-setf-expander */
int define_setf_expander_syscode_(addr symbol, addr call)
{
return setsetfmacro_symbol_(symbol, call);
}
/* end-input-stream */
void end_input_stream_syscode(addr var, addr *ret)
{
size_t size;
getindex_input_stream(var, &size);
make_index_integer_heap(ret, size);
}
/* make-extend-output-stream */
void make_extend_output_stream_syscode(addr var, addr rest, addr *ret)
{
/* ignore rest */
open_extend_output_stream(ret, var);
}
/* prompt-for */
int prompt_for_syscode(Execute ptr, addr type, addr args, addr *ret)
{
addr format;
LocalHold hold;
if (args == Nil) {
strvect_char_heap(&format, "Input> ");
}
else {
Return_getcons(args, &format, &args);
Return(format_string_lisp(ptr, format, args, &format));
}
hold = LocalHold_local_push(ptr, format);
Return(prompt_for_stream_(ptr, type, format, &format));
localhold_end(hold);
*ret = format;
return 0;
}
/* print-unreadable-call */
int print_unreadable_call_syscode(Execute ptr,
addr stream, addr pos, addr type, addr identity, addr body)
{
int check1, check2;
check1 = (type != Nil);
check2 = (identity != Nil);
return print_unreadable_common_(ptr, stream, pos, check1, check2, body);
}
/* write-default */
static int write_default_syscode_call_(Execute ptr, addr stream, addr var, addr *ret)
{
LocalHold hold;
Return(output_stream_designer_(ptr, stream, &stream));
hold = LocalHold_local_push(ptr, stream);
Return(write_default_print_(ptr, stream, var));
localhold_end(hold);
return Result(ret, var);
}
int write_default_syscode(Execute ptr, addr stream, addr var, addr *ret)
{
addr control;
Return(output_stream_designer_(ptr, stream, &stream));
push_control(ptr, &control);
(void)write_default_syscode_call_(ptr, stream, var, ret);
return pop_control_(ptr, control);
}
/* symbol-deftype */
void symbol_deftype_syscode(addr var, addr *ret)
{
getdeftype_symbol(var, ret);
}
/* delete-deftype */
void delete_deftype_syscode(addr var, addr *ret)
{
addr check;
getdeftype_symbol(var, &check);
if (check == Nil) {
*ret = Nil;
}
else {
remdeftype_symbol(var);
*ret = T;
}
}
/* ensure-structure */
int ensure_structure_syscode_(Execute ptr, addr name, addr slots, addr rest)
{
return ensure_structure_common_(ptr, name, slots, rest);
}
/* structure-constructor */
int structure_constructor_syscode(Execute ptr, addr symbol, addr rest, addr *ret)
{
return structure_constructor_common(ptr, symbol, rest, ret);
}
/* loop-bind */
int loop_bind_syscode(Execute ptr, addr a, addr b, addr c, addr *ret)
{
return loop_bind_common(ptr, a, b, c, ret);
}
/* make-pprint-stream */
int make_pprint_stream_syscode_(Execute ptr, addr *ret,
addr stream, addr object, addr prefix, addr perline, addr suffix)
{
return open_pretty_stream_(ptr, ret, stream, object, prefix, perline, suffix);
}
/* pprint-gensym */
int pprint_gensym_syscode(addr stream, addr *ret)
{
Check(! pretty_stream_p(stream), "type error");
return gensym_pretty_stream_(stream, ret);
}
/* pprint-exit */
int pprint_exit_syscode(Execute ptr, addr stream)
{
Check(! pretty_stream_p(stream), "type error");
return pprint_exit_common(ptr, stream);
}
/* pprint-pop */
int pprint_pop_syscode(Execute ptr, addr stream, addr *ret)
{
Check(! pretty_stream_p(stream), "type error");
return pprint_pop_common(ptr, stream, ret);
}
/* pprint-check */
int pprint_check_syscode(Execute ptr, addr stream)
{
Check(! pretty_stream_p(stream), "type error");
return check_pretty_stream(ptr, stream);
}
/* pprint-close */
int pprint_close_syscode(Execute ptr, addr stream)
{
Check(! pretty_stream_p(stream), "type error");
return close_pretty_stream_(ptr, stream);
}
/* pprint-pretty */
int pprint_pretty_syscode(Execute ptr, addr stream, addr call)
{
Check(! pretty_stream_p(stream), "type error");
return call_pretty_stream(ptr, stream, call);
}
/* timeinfo */
int timeinfo_syscode_(LocalRoot local,
addr *rreal, addr *rrun, addr *rsize, addr *rcount)
{
Return(get_internal_real_time_common_(local, rreal));
get_internal_run_time_common(rrun);
make_index_integer_heap(rsize, get_heap_object());
make_index_integer_heap(rcount, get_heap_count());
return 0;
}
/* ed-function */
int ed_function_syscode_(Execute ptr, addr file)
{
return ed_process_(ptr, file);
}
/* trace-add */
int trace_add_syscode_(Execute ptr, addr var, addr *ret)
{
return trace_add_common_(ptr, var, ret);
}
/* trace-del */
int trace_del_syscode_(Execute ptr, addr var, addr *ret)
{
return trace_del_common_(ptr, var, ret);
}
/* set-slots */
int set_slots_syscode(addr var, addr slots, addr values)
{
return set_slots_syscall(var, slots, values);
}
/* intern-eql-specializer */
int intern_eql_specializer_syscode(addr var, addr *ret)
{
return clos_intern_specializer_(var, ret);
}
/* defgeneric */
int defgeneric_define_syscode_(Execute ptr, addr name, addr args, addr *ret)
{
return system_generic_define_(ptr, name, args, ret);
}
int defgeneric_method_syscode_(addr inst, addr args)
{
return system_generic_method_(inst, args);
}
/************************************************************
* syscode_function.c
************************************************************/
/* hello */
int hello_syscode(Execute ptr)
{
addr stream;
Return(standard_output_stream_(ptr, &stream));
Return(fresh_line_stream_(stream, NULL));
Return(print_ascii_stream_(stream, "Hello"));
Return(terpri_stream_(stream));
return 0;
}
/* infobit */
void infobit_syscode(addr rest, addr *ret)
{
addr x, y;
for (y = Nil; rest != Nil; y = x) {
GetCons(rest, &x, &rest);
infobit(x);
}
*ret = y;
}
/* infoprint */
void infoprint_syscode(addr rest, addr *ret)
{
addr x, y;
for (y = Nil; rest != Nil; y = x) {
GetCons(rest, &x, &rest);
infoprint(x);
}
*ret = y;
}
/* gc */
void gc_syscode(addr rest)
{
enum GcMode mode;
if (GetKeyArgs(rest, KEYWORD_FULL, &rest))
rest = Nil;
mode = (rest == Nil)? GcMode_Default: GcMode_Full;
gcstate_execute(mode);
}
/* savecore */
int savecore_syscode(Execute ptr, addr file)
{
Return(pathname_designer_local_(ptr, file, &file));
return savecore_execute_(ptr, file);
}
/* package-export-list */
int package_export_list_syscode_(addr var, addr *ret)
{
Return(package_designer_(var, &var));
getexport_package_unsafe(var, ret);
return 0;
}
/* specialp */
void specialp_syscode(addr var, addr *ret)
{
*ret = specialp_symbol(var)? T: Nil;
}
/* array-general-p */
void array_general_p_syscode(addr var, addr *ret)
{
*ret = array_general_p(var)? T: Nil;
}
/* array-specialized-p */
void array_specialized_p_syscode(addr var, addr *ret)
{
*ret = array_specialized_p(var)? T: Nil;
}
/* simple-sort */
int simple_sort_syscode(Execute ptr, addr pos, addr call, addr rest)
{
addr key;
if (GetKeyArgs(rest, KEYWORD_KEY, &key)) key = Nil;
return simple_sort_sequence_(ptr, pos, call, key);
}
/* bubble-sort */
int bubble_sort_syscode(Execute ptr, addr pos, addr call, addr rest)
{
addr key;
if (GetKeyArgs(rest, KEYWORD_KEY, &key)) key = Nil;
return bubble_sort_sequence_(ptr, pos, call, key);
}
/* quick-sort */
int quick_sort_syscode(Execute ptr, addr pos, addr call, addr rest)
{
addr key;
if (GetKeyArgs(rest, KEYWORD_KEY, &key)) key = Nil;
return quick_sort_sequence_(ptr, pos, call, key);
}
/* merge-sort */
int merge_sort_syscode(Execute ptr, addr pos, addr call, addr rest)
{
addr key;
if (GetKeyArgs(rest, KEYWORD_KEY, &key)) key = Nil;
return merge_sort_sequence_(ptr, pos, call, key);
}
/* exit */
int exit_syscode_(Execute ptr, addr code)
{
fixnum value;
/* default 0 */
if (code == Unbound)
fixnum_heap(&code, 0);
/* value */
if (GetFixnum_signed(code, &value))
return fmte_("EXIT code ~S must be a integer type.", code, NULL);
ptr->result = (int)value;
/* invoke */
return call_exit_condition_(ptr, code);
}
/* closp */
void closp_syscode(addr var, addr *ret)
{
*ret = closp(var)? T: Nil;
}
/* fixnump */
void fixnump_syscode(addr var, addr *ret)
{
*ret = fixnump(var)? T: Nil;
}
/* bignump */
void bignump_syscode(addr var, addr *ret)
{
*ret = bignump(var)? T: Nil;
}
/* ratiop */
void ratiop_syscode(addr var, addr *ret)
{
*ret = ratiop(var)? T: Nil;
}
/* short-float-p */
void short_float_p_syscode(addr var, addr *ret)
{
*ret = (GetType(var) == LISPTYPE_SHORT_FLOAT)? T: Nil;
}
/* single-float-p */
void single_float_p_syscode(addr var, addr *ret)
{
*ret = single_float_p(var)? T: Nil;
}
/* double-float-p */
void double_float_p_syscode(addr var, addr *ret)
{
*ret = double_float_p(var)? T: Nil;
}
/* long-float-p */
void long_float_p_syscode(addr var, addr *ret)
{
*ret = long_float_p(var)? T: Nil;
}
/* callnamep */
void callnamep_syscall(addr var, addr *ret)
{
*ret = callnamep(var)? T: Nil;
}
/* large-number */
int large_number_syscode_(LocalRoot local, addr var, addr opt, addr *ret)
{
if (opt == Unbound)
opt = T;
return english_unit_heap_(local, ret, var, opt != Nil);
}
/* make-character */
int make_character_syscode(addr var, addr *ret)
{
unicode c;
if (integerp(var)) {
Return(getunicode_integer_(var, &c));
if (isExtendedType(c)) {
Return(make_extended_char_heap_(ret, c));
}
else {
make_character_heap(ret, c);
}
return 0;
}
if (characterp(var)) {
GetCharacter(var, &c);
make_character_heap(ret, c);
return 0;
}
*ret = Nil;
return TypeError_(var, CHARACTER);
}
/* make-fixnum */
int make_fixnum_syscode(addr var, addr *ret)
{
fixnum value;
switch (GetType(var)) {
case LISPTYPE_FIXNUM:
GetFixnum(var, &value);
make_fixnum_heap(ret, value);
break;
default:
*ret = Nil;
return TypeError_(var, FIXNUM);
}
return 0;
}
/* make-bignum */
int make_bignum_syscode(addr var, addr *ret)
{
switch (GetType(var)) {
case LISPTYPE_FIXNUM:
bignum_fixnum_heap(ret, var);
break;
case LISPTYPE_BIGNUM:
bignum_throw_heap(var, ret);
break;
default:
*ret = Nil;
return TypeError_(var, INTEGER);
}
return 0;
}
/* make-ratio */
static int make_ratio_force_(addr *ret, addr var)
{
switch (GetType(var)) {
case LISPTYPE_FIXNUM:
bignum_fixnum_heap(ret, var);
break;
case LISPTYPE_BIGNUM:
bignum_copy_heap(ret, var);
break;
default:
*ret = Nil;
return TypeError_(var, INTEGER);
}
return 0;
}
int make_ratio_syscode(addr numer, addr denom, addr *ret)
{
int sign1, sign2;
Return(make_ratio_force_(&numer, numer));
Return(make_ratio_force_(&denom, denom));
GetSignBignum(numer, &sign1);
GetSignBignum(denom, &sign2);
SetSignBignum(numer, SignPlus);
SetSignBignum(denom, SignPlus);
sign1 = SignMulti(sign1, sign2);
make_ratio_alloc_unsafe(NULL, &numer, sign1, numer, denom);
*ret = numer;
return 0;
}
/* make-complex */
int make_complex_code_(addr real, addr imag, addr *ret)
{
return complex_force_heap_(ret, real, imag, ComplexType_error);
}
/* equal-random-state */
void equal_random_state_syscode(addr left, addr right, addr *ret)
{
*ret = equal_random_state_addr(left, right)? T: Nil;
}
/* subtypep-extend */
int subtypep_extend_syscode_(Execute ptr,
addr x, addr y, addr env, addr check, addr *ret)
{
if (env == Unbound)
env = Nil;
if (check == Unbound)
check = Nil;
return subtypep_extend_(ptr, x, y, env, check, ret);
}
/* subtypep-number */
int subtypep_number_syscode_(Execute ptr, addr x, addr *ret)
{
Return(parse_type(ptr, &x, x, Nil));
Return(type_subtypep_throw_heap_(ptr->local, x, &x));
get_type_subtypep(&x, x);
Return(type_object_(&x, x));
return Result(ret, x);
}
/* eastasian-set */
int eastasian_set_syscode_(addr var, addr value, addr errorp, addr *ret)
{
return eastasian_set_syscall_(var, value, errorp, ret);
}
/* eastasian-get */
int eastasian_get_syscode_(addr var, addr *ret1, addr *ret2)
{
return eastasian_get_syscall_(var, ret1, ret2);
}
/* eastasian-width */
int eastasian_width_syscode_(addr pos, addr *ret1, addr *ret2)
{
return eastasian_width_syscall_(pos, ret1, ret2);
}
/* run-process */
int run_program_syscode_(Execute ptr, addr var, addr args, addr rest, addr *ret)
{
return run_process_(ptr, var, args, rest, &var);
}
/* make-callname */
int make_callname_syscode_(addr var, addr *ret)
{
return parse_callname_error_(ret, var);
}
/* remove-file */
int remove_file_syscode(Execute ptr, addr var, addr opt, addr *ret)
{
int check;
Return(remove_file_common_(ptr, var, (opt != Nil), &check));
return Result(ret, check? T: Nil);
}
/* remove-directory */
int remove_directory_syscode(Execute ptr, addr var, addr opt, addr *ret)
{
int check;
Return(remove_directory_common_(ptr, var, (opt != Nil), &check));
return Result(ret, check? T: Nil);
}
/* declare-parse */
static int declare_parse_value_(addr symbol, OptimizeType *ret)
{
addr root, check;
getroot_declare(&root);
/* safety */
GetConst(COMMON_SAFETY, &check);
if (symbol == check)
return Result(ret, get_optimize_safety_declare(root));
/* speed */
GetConst(COMMON_SPEED, &check);
if (symbol == check)
return Result(ret, get_optimize_speed_declare(root));
/* space */
GetConst(COMMON_SPACE, &check);
if (symbol == check)
return Result(ret, get_optimize_space_declare(root));
/* debug */
GetConst(COMMON_DEBUG, &check);
if (symbol == check)
return Result(ret, get_optimize_debug_declare(root));
/* compilation */
GetConst(COMMON_COMPILATION_SPEED, &check);
if (symbol == check)
return Result(ret, get_optimize_compilation_declare(root));
/* error */
*ret = 0;
return fmte_("Invalid declare-parse argument ~S.", symbol, NULL);
}
int declare_parse_syscode(addr form, addr *ret)
{
OptimizeType value;
addr symbol, check;
Return_getcdr(form, &form);
if (! consp_getcons(form, &symbol, &check))
goto error;
if (check != Nil)
goto error;
Return(declare_parse_value_(symbol, &value));
fixnum_heap(ret, (fixnum)value);
return 0;
error:
return fmte_("The declare-parse form ~S must be a (symbol).", form, NULL);
}
/* parse-type */
int parse_type_syscode(Execute ptr, addr var, addr *ret)
{
Return(parse_type(ptr, &var, var, Nil));
Return(type_object_(&var, var));
return Result(ret, var);
}
/* upgraded-open-element-type */
int upgraded_open_element_type_syscode_(addr var, addr *ret)
{
return upgrade_open_element_type_stream_(var, ret);
}
/* make-memory-input-stream */
static int getkeyindex_syscode_(addr list, constindex key, size_t *ret)
{
addr pos;
if (getplist_constant_safe(list, key, &pos)) {
*ret = 0;
}
else if (pos == Nil) {
*ret = 0;
}
else {
Return(getindex_integer_(pos, ret));
}
return 0;
}
static int getkeycache_syscode(addr list)
{
if (GetKeyArgs(list, KEYWORD_CACHE, &list)) {
#ifdef LISP_DEBUG
return 1; /* on */
#else
return 0; /* off */
#endif
}
return (list == Nil)? 0: 1;
}
int make_memory_input_stream_syscode_(addr var, addr rest, addr *ret)
{
int cache;
size_t size, array;
/* &key */
Return(getkeyindex_syscode_(rest, CONSTANT_KEYWORD_SIZE, &size));
Return(getkeyindex_syscode_(rest, CONSTANT_KEYWORD_ARRAY, &array));
cache = getkeycache_syscode(rest);
/* call */
Return(open_input_memory_stream_(&var, var, size, array, cache));
return Result(ret, var);
}
/* make-memory-output-stream */
int make_memory_output_stream_syscode_(addr rest, addr *ret)
{
int cache;
addr input;
size_t size, array;
/* &key */
if (GetKeyArgs(rest, KEYWORD_INPUT, &input))
input = Nil;
Return(getkeyindex_syscode_(rest, CONSTANT_KEYWORD_SIZE, &size));
Return(getkeyindex_syscode_(rest, CONSTANT_KEYWORD_ARRAY, &array));
cache = getkeycache_syscode(rest);
/* call */
Return(open_output_memory_stream_(&rest, input, size, array, cache));
return Result(ret, rest);
}
/* make-memory-io-stream */
int make_memory_io_stream_syscode_(addr rest, addr *ret)
{
int cache;
addr input;
size_t size, array;
/* &key */
if (GetKeyArgs(rest, KEYWORD_INPUT, &input))
input = Nil;
Return(getkeyindex_syscode_(rest, CONSTANT_KEYWORD_SIZE, &size));
Return(getkeyindex_syscode_(rest, CONSTANT_KEYWORD_ARRAY, &array));
cache = getkeycache_syscode(rest);
/* call */
Return(open_io_memory_stream_(&rest, input, size, array, cache));
return Result(ret, rest);
}
/* with-input-from-memory */
int with_input_from_memory_syscode_(Execute ptr, addr form, addr *ret)
{
addr args, body, var, vector;
addr let, make, unwind, progn, close, decl, pos;
/* argument */
Return_getcdr(form, &form);
if (! consp_getcons(form, &args, &body))
goto error;
if (! consp_getcons(args, &var, &args))
goto error;
if (! consp_getcons(args, &vector, &args))
goto error;
/* `(let ((,var (system::make-memory-input-stream ,vector)))
* ,@decl
* (unwind-protect
* (progn ,@form)
* (close ,var)))
*/
GetConst(COMMON_LET, &let);
GetConst(SYSTEM_MAKE_MEMORY_INPUT_STREAM, &make);
GetConst(COMMON_UNWIND_PROTECT, &unwind);
GetConst(COMMON_PROGN, &progn);
GetConst(COMMON_CLOSE, &close);
Return(declare_body_form_(body, &decl, &body));
list_heap(&close, close, var, NULL);
cons_heap(&progn, progn, body);
list_heap(&unwind, unwind, progn, close, NULL);
lista_heap(&make, make, vector, args, NULL);
list_heap(&make, var, make, NULL);
conscar_heap(&make, make);
conscar_heap(&let, let);
cons_heap(&let, make, let);
while (decl != Nil) {
GetCons(decl, &pos, &decl);
cons_heap(&let, pos, let);
}
cons_heap(&let, unwind, let);
nreverse(ret, let);
return 0;
error:
return fmte_("WITH-INPUT-FROM-MEMORY form ~S must be a "
"((var vector ...) &body body).", form, NULL);
}
/* with-output-to-memory */
int with_output_to_memory_syscode_(Execute ptr, addr form, addr *ret)
{
addr args, var, body;
addr let, make, unwind, progn, get, close, decl, pos;
/* argument */
Return_getcdr(form, &args);
if (! consp_getcons(args, &args, &body))
goto error;
if (! consp_getcons(args, &var, &args))
goto error;
/* `(let ((,var (make-string-output-stream ...)))
* ,@decl
* (unwind-protect
* (progn ,@body
* (get-output-stream-string ,var))
* (close ,var)))
*/
GetConst(COMMON_LET, &let);
GetConst(SYSTEM_MAKE_MEMORY_OUTPUT_STREAM, &make);
GetConst(COMMON_UNWIND_PROTECT, &unwind);
GetConst(COMMON_PROGN, &progn);
GetConst(SYSTEM_GET_OUTPUT_STREAM_MEMORY, &get);
GetConst(COMMON_CLOSE, &close);
Return(declare_body_form_(body, &decl, &body));
list_heap(&close, close, var, NULL);
list_heap(&get, get, var, NULL);
conscar_heap(&progn, progn);
while (body != Nil) {
GetCons(body, &pos, &body);
cons_heap(&progn, pos, progn);
}
cons_heap(&progn, get, progn);
nreverse(&progn, progn);
list_heap(&unwind, unwind, progn, close, NULL);
cons_heap(&make, make, args);
list_heap(&make, var, make, NULL);
conscar_heap(&make, make);
conscar_heap(&let, let);
cons_heap(&let, make, let);
while (decl != Nil) {
GetCons(decl, &pos, &decl);
cons_heap(&let, pos, let);
}
cons_heap(&let, unwind, let);
nreverse(ret, let);
return 0;
error:
return fmte_("WITH-OUTPUT-TO-MEMORY form ~S must be a "
"((var) &body body).", form, NULL);
}
/* get-output-stream-memory */
int get_output_stream_memory_syscode_(addr var, addr *ret)
{
return memory_stream_heap_(var, ret);
}
/* memory-stream-p */
void memory_stream_p_syscode(addr var, addr *ret)
{
gettype_memory_stream(var, ret);
}
/* (setf memory-stream-p) */
int setf_memory_stream_p_syscode_(addr var, addr value)
{
return settype_memory_stream_(var, value);
}
/* byte-integer */
static int byte_integer_endian_(addr list, int littlep, addr *ret)
{
addr x, y, i, v8;
LocalRoot local;
local = Local_Thread;
fixnum_heap(&x, 0);
fixnum_heap(&i, 0);
fixnum_heap(&v8, 8);
while (list != Nil) {
Return_getcons(list, &y, &list);
if (littlep) {
Return(ash_integer_common_(local, y, i, &y));
}
else {
Return(ash_integer_common_(local, x, i, &x));
}
Return(plus_ii_real_common_(local, x, y, &x));
Return(plus_ii_real_common_(local, i, v8, &i));
}
return Result(ret, x);
}
int byte_integer_syscode_(addr list, addr *ret)
{
union byte_integer_union {
uint16_t u16;
uint8_t u8[2];
} u;
u.u16 = 1;
return byte_integer_endian_(list, u.u8[0] != 0, ret);
}
/* sysctl */
int sysctl_syscode_(Execute ptr, addr var, addr args)
{
return sysctl_values_(ptr, var, args);
}
/* extension */
#ifdef LISP_EXTENSION
#include "ext_eval.h"
#endif
int extension_syscode(Execute ptr, addr var)
{
#ifdef LISP_EXTENSION
return lisps_eval_(ptr, var);
#else
return fmte_("The implementation is not supported.", NULL);
#endif
}
/* terme */
int terme_syscode_(Execute ptr, addr var, addr args)
{
return terme_values_(ptr, var, args);
}
/************************************************************
* sysctl.c
************************************************************/
/*
* recovery
*/
static int sysctl_recovery_no_applicable_method_(Execute ptr)
{
addr pos;
/* fmakunbound */
GetConst(COMMON_NO_APPLICABLE_METHOD, &pos);
SetFunctionSymbol(pos, Unbound);
/* recovery */
Return(defgeneric_no_applicable_method_mop_(ptr));
setvalues_control(ptr, T, T, NULL);
return 0;
}
static int sysctl_recovery_no_next_method_(Execute ptr)
{
addr pos;
/* fmakunbound */
GetConst(COMMON_NO_NEXT_METHOD, &pos);
SetFunctionSymbol(pos, Unbound);
/* recovery */
Return(defgeneric_no_next_method_mop_(ptr));
setvalues_control(ptr, T, T, NULL);
return 0;
}
static int sysctl_recovery_(Execute ptr, addr args)
{
int check;
addr pos;
if (! consp_getcons(args, &pos, &args))
goto error;
/* no-applicable-method */
Return(string_designer_equalp_char_(pos, "no-applicable-method", &check));
if (check)
return sysctl_recovery_no_applicable_method_(ptr);
/* no-next-method */
Return(string_designer_equalp_char_(pos, "no-next-method", &check));
if (check)
return sysctl_recovery_no_next_method_(ptr);
error:
setvalues_control(ptr, Nil, T, NULL);
return 0;
}
/*
* clos
*/
static int sysctl_clos_slots_(Execute ptr, addr pos)
{
clos_getslots_heap(pos, &pos);
setvalues_control(ptr, pos, T, NULL);
return 0;
}
static int sysctl_clos_(Execute ptr, addr pos, addr args)
{
int check;
addr car;
if (! consp_getcons(args, &car, &args))
goto error;
/* slots */
Return(string_designer_equalp_char_(car, "slots", &check));
if (check)
return sysctl_clos_slots_(ptr, pos);
error:
setvalues_control(ptr, Nil, T, NULL);
return 0;
}
/*
* memory-stream
*/
static int sysctl_memory_stream_size_(Execute ptr, addr pos)
{
size_t size;
getsize_memory_stream(pos, &size);
make_index_integer_heap(&pos, size);
setresult_control(ptr, pos);
return 0;
}
static int sysctl_memory_stream_array_(Execute ptr, addr pos)
{
size_t size;
getarray_memory_stream(pos, &size);
make_index_integer_heap(&pos, size);
setresult_control(ptr, pos);
return 0;
}
static int sysctl_memory_stream_cache_(Execute ptr, addr pos)
{
int cache;
cache = getcache_memory_stream(pos);
fixnum_heap(&pos, (fixnum)cache);
setresult_control(ptr, pos);
return 0;
}
static int sysctl_memory_stream_(Execute ptr, addr pos, addr args)
{
int check;
addr car;
if (! consp_getcons(args, &car, &args))
goto error;
/* size */
Return(string_designer_equalp_char_(car, "size", &check));
if (check)
return sysctl_memory_stream_size_(ptr, pos);
/* array */
Return(string_designer_equalp_char_(car, "array", &check));
if (check)
return sysctl_memory_stream_array_(ptr, pos);
/* cache */
Return(string_designer_equalp_char_(car, "cache", &check));
if (check)
return sysctl_memory_stream_cache_(ptr, pos);
/* error */
error:
setvalues_control(ptr, Nil, T, NULL);
return 0;
}
/*
* sysctl
*/
int sysctl_values_(Execute ptr, addr pos, addr args)
{
int check;
/* memory stream */
if (memory_stream_p(pos))
return sysctl_memory_stream_(ptr, pos, args);
/* clos object */
if (closp(pos))
return sysctl_clos_(ptr, pos, args);
/* recovery */
Return(string_designer_equalp_char_(pos, "recovery", &check));
if (check)
return sysctl_recovery_(ptr, args);
/* error */
setresult_control(ptr, Nil);
return 0;
}
/************************************************************
* terme.c
************************************************************/
/*
* interface
*/
void init_terme(void)
{
if (terme_arch_init()) {
Abort("terme_arch_init error.");
}
terme_input_init();
terme_output_init();
}
static void build_terme_object(void)
{
addr symbol, root, value;
/* root */
terme_root_build(&root);
/* data */
terme_data_build(&value);
terme_set(root, terme_root_data, value);
/* screen */
terme_screen_build(&value);
terme_set(root, terme_root_screen, value);
/* display */
terme_display_build(&value);
terme_set(root, terme_root_display, value);
/* history */
terme_history_build(&value);
terme_set(root, terme_root_history, value);
/* special */
GetConst(SYSTEM_SPECIAL_TERME, &symbol);
SetValueSymbol(symbol, root);
}
void build_terme(void)
{
build_terme_object();
terme_arch_build();
}
int begin_terme(void)
{
return terme_arch_begin();
}
int end_terme(void)
{
return terme_arch_end();
}
int prompt_terme_(Execute ptr, addr pos, PromptMode mode)
{
return terme_prompt_set_(ptr, pos, mode);
}
int readline_terme_(Execute ptr, addr *ret)
{
return terme_readline_(ptr, ret);
}
int font_terme(Execute ptr, PrintFont value)
{
return font_arch_terme(ptr, value);
}
int text_color_terme(Execute ptr, PrintColor value)
{
return text_color_arch_terme(ptr, value);
}
int back_color_terme(Execute ptr, PrintColor value)
{
return back_color_arch_terme(ptr, value);
}
/************************************************************
* terme_arch.c
************************************************************/
#if defined(LISP_TERME_UNIX)
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#elif defined(LISP_TERME_WINDOWS)
#include "windows_terme.h"
#endif
static unsigned terme_arch_x;
static unsigned terme_arch_y;
static int terme_arch_textmode_p;
static int terme_arch_enable_p;
/*
* terme-init
*/
#ifdef LISP_TERME_WINDOWS
int terme_arch_init(void)
{
terme_arch_x = 0;
terme_arch_y = 0;
terme_arch_textmode_p = 0;
terme_arch_enable_p = 0;
return terme_windows_init();
}
#else
int terme_arch_init(void)
{
terme_arch_x = 0;
terme_arch_y = 0;
terme_arch_textmode_p = 0;
terme_arch_enable_p = 0;
return 0;
}
#endif
/*
* window size
*/
#if defined(LISP_TERME_UNIX)
int terme_arch_size_update(void)
{
return getwidth_arch(&terme_arch_x, &terme_arch_y);
}
#elif defined(LISP_TERME_WINDOWS)
int terme_arch_size_update(void)
{
return getwidth_arch(&terme_arch_x, &terme_arch_y);
}
#else
int terme_arch_size_update(void)
{
terme_arch_x = 0;
terme_arch_y = 0;
return 0;
}
#endif
void terme_arch_size_get(unsigned *ret_x, unsigned *ret_y)
{
if (ret_x)
*ret_x = terme_arch_x;
if (ret_y)
*ret_y = terme_arch_y;
}
/*
* terme-begin
*/
#if defined(LISP_TERME_UNIX)
static void terme_arch_handler(int sig)
{
if (getwidth_arch(&terme_arch_x, &terme_arch_y)) {
terme_arch_x = 0;
terme_arch_y = 0;
}
}
static int terme_arch_signal(void)
{
struct sigaction act;
act.sa_handler = terme_arch_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART;
if (sigaction(SIGWINCH, &act, NULL))
return 1;
return 0;
}
static struct termios terme_arch_textmode_v;
static struct termios terme_arch_switch_v;
static int terme_arch_get(struct termios *ret)
{
return tcgetattr(STDIN_FILENO, ret);
}
static int terme_arch_set(struct termios *ret)
{
return tcsetattr(STDIN_FILENO, TCSAFLUSH, ret);
}
static int terme_arch_termios(void)
{
struct termios v;
/* backup */
if (terme_arch_get(&v)) {
fprintf(stderr, "tcgetattr value error\n");
return 1;
}
terme_arch_textmode_v = v;
/* set terminal */
v.c_iflag &= ~(PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
v.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
v.c_oflag &= ~OPOST;
v.c_cflag &= ~(CSIZE | PARENB);
v.c_cflag |= CS8;
v.c_cc[VMIN] = 1;
v.c_cc[VTIME] = 0;
terme_arch_switch_v = v;
return 0;
}
int terme_arch_begin(void)
{
terme_arch_enable_p = 0;
#ifndef LISP_TERME
return 0;
#endif
/* terminal size */
if (terme_arch_size_update())
return 1;
/* sigaction */
if (terme_arch_signal())
return 1;
/* termios */
if (terme_arch_termios())
return 1;
/* switch */
terme_arch_textmode_p = 1;
terme_arch_enable_p = 1;
return 0;
}
int terme_arch_end(void)
{
if (! terme_arch_enable_p)
return 0;
return terme_arch_set(&terme_arch_textmode_v);
}
#elif defined(LISP_TERME_WINDOWS)
int terme_arch_begin(void)
{
terme_arch_textmode_p = 1;
terme_arch_enable_p = 1;
return terme_windows_begin();
}
int terme_arch_end(void)
{
return terme_windows_end();
}
#else
int terme_arch_begin(void)
{
terme_arch_textmode_p = 1;
terme_arch_enable_p = 0;
return 0;
}
int terme_arch_end(void)
{
return 0;
}
#endif
/*
* terme-switch
*/
#if defined(LISP_TERME_UNIX)
int terme_arch_textmode(int *ret)
{
if (! terme_arch_enable_p)
return 0;
if (terme_arch_textmode_p) {
if (ret)
*ret = 0;
return 0;
}
if (terme_arch_get(&terme_arch_switch_v)) {
if (ret)
*ret = 0;
return 1;
}
if (ret)
*ret = 1;
terme_arch_textmode_p = 1;
return terme_arch_set(&terme_arch_textmode_v);
}
int terme_arch_rawmode(int *ret)
{
if (! terme_arch_enable_p)
return 0;
if (! terme_arch_textmode_p) {
if (ret)
*ret = 0;
return 0;
}
if (terme_arch_set(&terme_arch_switch_v)) {
if (ret)
*ret = 0;
return 1;
}
if (ret)
*ret = 1;
terme_arch_textmode_p = 0;
memset(&terme_arch_switch_v, '\0', sizeof(terme_arch_switch_v));
return 0;
}
#elif defined(LISP_TERME_WINDOWS)
int terme_arch_textmode(int *ret)
{
if (! terme_arch_enable_p)
return 0;
if (terme_arch_textmode_p) {
if (ret)
*ret = 0;
return 0;
}
if (terme_windows_textmode()) {
if (ret)
*ret = 0;
return 1;
}
if (ret)
*ret = 1;
terme_arch_textmode_p = 1;
return 0;
}
int terme_arch_rawmode(int *ret)
{
if (! terme_arch_enable_p)
return 0;
if (! terme_arch_textmode_p) {
if (ret)
*ret = 0;
return 0;
}
if (terme_windows_rawmode()) {
if (ret)
*ret = 0;
return 1;
}
if (ret)
*ret = 1;
terme_arch_textmode_p = 0;
return 0;
}
#else
int terme_arch_textmode(int *ret)
{
if (! terme_arch_enable_p)
return 0;
terme_arch_textmode_p = 1;
if (ret)
*ret = 0;
return 0;
}
int terme_arch_rawmode(int *ret)
{
if (! terme_arch_enable_p)
return 0;
terme_arch_textmode_p = 0;
if (ret)
*ret = 0;
return 0;
}
#endif
/*
* terme-build
*/
#ifdef LISP_TERME_WINDOWS
void terme_arch_build(void)
{
terme_windows_build();
}
#else
void terme_arch_build(void)
{
}
#endif
/*
* input / output
*/
#if defined(LISP_TERME_UNIX)
int terme_arch_select(int *ret)
{
int fd, reti;
fd_set fdset;
struct timeval tm;
if (! terme_arch_enable_p)
return 0;
fd = STDIN_FILENO;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
tm.tv_sec = 0;
tm.tv_usec = 0;
reti = select(fd + 1, &fdset, NULL, NULL, &tm);
if (reti < 0) {
*ret = 0;
return 1; /* error */
}
if (reti == 0) {
/* empty */
*ret = 0;
return 0;
}
else {
/* can read */
*ret = 1;
return 0;
}
}
int terme_arch_wait(void)
{
int fd, reti;
fd_set fdset;
if (! terme_arch_enable_p)
return 0;
fd = STDIN_FILENO;
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
reti = select(fd + 1, &fdset, NULL, NULL, NULL);
return reti < 0;
}
int terme_arch_read(void *data, size_t size, size_t *ret)
{
ssize_t check;
if (! terme_arch_enable_p)
return 0;
check = read(STDIN_FILENO, data, size);
if (check < 0)
return -1;
*ret = (size_t)check;
return 0;
}
int terme_arch_write(const void *data, size_t size, size_t *ret)
{
ssize_t check;
if (! terme_arch_enable_p)
return 0;
check = write(STDOUT_FILENO, data, size);
if (check < 0)
return -1;
*ret = (size_t)check;
return 0;
}
#elif defined(LISP_TERME_WINDOWS)
int terme_arch_select(int *ret)
{
if (! terme_arch_enable_p)
return 0;
return terme_windows_select(ret);
}
int terme_arch_wait(void)
{
if (! terme_arch_enable_p)
return 0;
return terme_windows_wait();
}
int terme_arch_read(void *data, size_t size, size_t *ret)
{
if (! terme_arch_enable_p)
return 0;
return terme_windows_read(data, size, ret);
}
int terme_arch_write(const void *data, size_t size, size_t *ret)
{
if (! terme_arch_enable_p)
return 0;
return terme_windows_write(data, size, ret);
}
#else
int terme_arch_select(int *ret)
{
if (! terme_arch_enable_p)
return 0;
*ret = 0;
return 0;
}
int terme_arch_wait(void)
{
if (! terme_arch_enable_p)
return 0;
return 0;
}
int terme_arch_read(void *data, size_t size, size_t *ret)
{
if (! terme_arch_enable_p)
return 0;
*ret = 0;
return 1;
}
int terme_arch_write(const void *data, size_t size, size_t *ret)
{
if (! terme_arch_enable_p)
return 0;
*ret = 0;
return 1;
}
#endif
/*
* Ctrl + Z
*/
#ifdef LISP_TERME_UNIX
int terme_arch_terminal_stop_(void)
{
if (! terme_arch_enable_p)
return 0;
return kill(getpid(), SIGTSTP);
}
#else
int terme_arch_terminal_stop_(void)
{
return 0;
}
#endif
int terme_arch_enable(void)
{
return terme_arch_enable_p;
}
/*
* font
*/
int font_arch_terme(Execute ptr, PrintFont value)
{
if (! terme_arch_enable_p)
return 0;
return terme_font(ptr, value)
|| terme_finish_output();
}
int text_color_arch_terme(Execute ptr, PrintColor value)
{
if (! terme_arch_enable_p)
return 0;
return terme_text_color(ptr, value)
|| terme_finish_output();
}
int back_color_arch_terme(Execute ptr, PrintColor value)
{
if (! terme_arch_enable_p)
return 0;
return terme_back_color(ptr, value)
|| terme_finish_output();
}
/************************************************************
* terme_data.c
************************************************************/
#define TERME_DATA_SIZE 4096
/*
* string
*/
struct terme_data_character {
unsigned width : 2;
unicode c : 21;
};
static void terme_string_build(addr *ret)
{
addr pos;
heap_body(&pos, LISPSYSTEM_TERME,
sizeoft(struct terme_data_character) * TERME_DATA_SIZE);
terme_set_type(pos, terme_type_string);
*ret = pos;
}
static struct terme_data_character *struct_data_character(addr pos)
{
Check(! terme_string_p(pos), "type error");
return (struct terme_data_character *)terme_pointer(pos);
}
/*
* data
*/
enum terme_data_index {
terme_data_array,
terme_data_size
};
struct terme_data_struct {
unsigned alloc, size, now;
};
static struct terme_data_struct *struct_terme_data(addr pos)
{
Check(! terme_data_p(pos), "type error");
return (struct terme_data_struct *)terme_pointer(pos);
}
void terme_data_build(addr *ret)
{
addr pos, value;
struct terme_data_struct *str;
heap_smallsize(&pos, LISPSYSTEM_TERME,
terme_data_size,
sizeoft(struct terme_data_struct));
terme_set_type(pos, terme_type_data);
terme_string_build(&value);
terme_set(pos, terme_data_array, value);
str = struct_terme_data(pos);
str->alloc = TERME_DATA_SIZE;
str->size = 0;
str->now = 0;
*ret = pos;
}
static void terme_data_get_body(addr pos, addr *ret)
{
Check(! terme_data_p(pos), "type error");
terme_get(pos, terme_data_array, ret);
}
int terme_data_clear_(Execute ptr)
{
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
str->size = 0;
str->now = 0;
return 0;
}
/*
* insert
*/
static int terme_data_shift_right_(addr pos, unicode c, unsigned width)
{
int i, diff, now, size, src, dst;
addr array;
struct terme_data_struct *str;
struct terme_data_character *body;
/* data */
str = struct_terme_data(pos);
now = str->now;
size = str->size;
if (size <= now)
return 0;
/* string */
terme_data_get_body(pos, &array);
body = struct_data_character(array);
/* loop */
diff = size - now;
for (i = 0; i < diff; i++) {
dst = size - i;
src = dst - 1;
body[dst] = body[src];
}
return 0;
}
static void terme_data_insert_set(addr pos, unsigned now, unicode c, unsigned width)
{
addr array;
struct terme_data_character *body;
terme_data_get_body(pos, &array);
body = struct_data_character(array);
body += now;
body->c = c;
body->width = width;
}
int terme_data_insert_(Execute ptr, unicode c, unsigned *rwidth, int *ret)
{
unsigned width;
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->alloc <= str->size) {
*rwidth = 0;
return Result(ret, 1);
}
if (str->size < str->now) {
*rwidth = 0;
return Result(ret, 1);
}
width = eastasian_width(c);
Return(terme_data_shift_right_(pos, c, width));
terme_data_insert_set(pos, str->now, c, width);
str->size++;
/* result */
*rwidth = width;
return Result(ret, 0);
}
int terme_data_next_(Execute ptr)
{
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->now < str->size)
str->now++;
return 0;
}
int terme_data_push_(Execute ptr, unicode c, unsigned *rwidth, int *ret)
{
int check;
unsigned width;
Return(terme_data_insert_(ptr, c, &width, &check));
if (check) {
*rwidth = 0;
return Result(ret, 1);
}
*rwidth = width;
*ret = 0;
return terme_data_next_(ptr);
}
int terme_data_make_(Execute ptr, addr *ret, int eol)
{
unsigned size, i;
addr pos, array, value;
struct terme_data_struct *str;
struct terme_data_character *body;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
size = str->size;
strvect_heap(&value, size + (eol? 1ULL :0ULL));
terme_data_get_body(pos, &array);
body = struct_data_character(array);
for (i = 0; i < size; i++) {
Return(strvect_setc_(value, i, body[i].c));
}
if (eol) {
Return(strvect_setc_(value, i, 0x0A));
}
return Result(ret, value);
}
int terme_data_copy_(Execute ptr, addr value)
{
addr pos, array;
struct terme_data_struct *str;
struct terme_data_character *body;
unicode c;
size_t size, i;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
terme_data_get_body(pos, &array);
body = struct_data_character(array);
strvect_length(value, &size);
if (str->alloc < size)
size = str->alloc;
for (i = 0; i < size; i++) {
strvect_getc(value, i, &c);
body[i].c = c;
body[i].width = eastasian_width(c);
}
str->size = (unsigned)size;
str->now = 0;
return 0;
}
int terme_data_size_(Execute ptr, unsigned *ret)
{
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
return Result(ret, str->size);
}
/*
* access
*/
void terme_data_get_value(addr pos, unsigned *rnow, unsigned *rsize)
{
struct terme_data_struct *str;
str = struct_terme_data(pos);
if (rnow)
*rnow = str->now;
if (rsize)
*rsize = str->size;
}
int terme_data_get_character_(addr pos, unsigned i, unicode *retc, unsigned *retw)
{
addr array;
struct terme_data_struct *str;
struct terme_data_character *body;
str = struct_terme_data(pos);
if (str->size <= i) {
if (retc)
*retc = 0;
if (retw)
*retw = 0;
return terme_fmte_("terme_data_get_character_ error.", NULL);
}
terme_data_get_body(pos, &array);
body = struct_data_character(array);
body += i;
if (retc)
*retc = body->c;
if (retw)
*retw = body->width;
return 0;
}
/*
* operator
*/
int terme_data_left_(Execute ptr, unsigned *ret)
{
unsigned width;
addr pos, array;
struct terme_data_struct *str;
struct terme_data_character *body;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->now == 0)
return Result(ret, 0); /* error */
/* width */
terme_data_get_body(pos, &array);
body = struct_data_character(array);
str->now--;
width = body[str->now].width;
/* move */
return Result(ret, width);
}
int terme_data_right_(Execute ptr, unsigned *ret)
{
unsigned width;
addr pos, array;
struct terme_data_struct *str;
struct terme_data_character *body;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->size <= str->now)
return Result(ret, 0); /* error */
/* width */
terme_data_get_body(pos, &array);
body = struct_data_character(array);
width = body[str->now].width;
str->now++;
/* move */
return Result(ret, width);
}
int terme_data_first_(Execute ptr)
{
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
str->now = 0;
return 0;
}
int terme_data_last_(Execute ptr)
{
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
str->now = str->size;
return 0;
}
static void terme_data_shift_left_(addr pos, unsigned x, unsigned size, unsigned *ret)
{
addr array;
struct terme_data_character *body;
terme_data_get_body(pos, &array);
body = struct_data_character(array);
*ret = body[x].width;
for (; x < size; x++)
body[x] = body[x + 1];
}
static void terme_data_delete_index(addr pos, unsigned index, unsigned *ret)
{
struct terme_data_struct *str;
str = struct_terme_data(pos);
if (str->size <= index) {
*ret = 0;
return;
}
/* shift */
terme_data_shift_left_(pos, index, str->size, ret);
str->size--;
}
int terme_data_delete_(Execute ptr, int *ret)
{
unsigned width;
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->size <= str->now)
return Result(ret, 0);
terme_data_delete_index(pos, str->now, &width);
return Result(ret, 1);
}
int terme_data_backspace_(Execute ptr, unsigned *ret)
{
unsigned width;
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->now == 0)
return Result(ret, 0);
/* backspace */
terme_data_delete_index(pos, str->now - 1U, &width);
if (width == 0)
return Result(ret, 0);
str->now--;
return Result(ret, width);
}
static int terme_data_rmleft_shift_(addr pos, unsigned index, unsigned size)
{
unsigned i;
addr array;
struct terme_data_character *body;
terme_data_get_body(pos, &array);
body = struct_data_character(array);
for (i = 0; i < size; i++)
body[i] = body[i + index];
return 0;
}
int terme_data_rmleft_(Execute ptr, int *ret)
{
unsigned size;
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
/* do nothing */
if (str->now == 0)
return Result(ret, 0);
/* all delete */
if (str->now == str->size) {
str->size = 0;
str->now = 0;
return Result(ret, 1);
}
/* shift */
size = str->size - str->now;
Return(terme_data_rmleft_shift_(pos, str->now, size));
str->size = size;
str->now = 0;
return Result(ret, 1);
}
int terme_data_rmright_(Execute ptr, int *ret)
{
addr pos;
struct terme_data_struct *str;
Return(terme_root_data_(ptr, &pos));
str = struct_terme_data(pos);
if (str->now < 0 || str->size <= str->now)
return Result(ret, 0);
/* shift */
str->size = str->now;
return Result(ret, 1);
}
/************************************************************
* terme_display.c
************************************************************/
#ifdef LISP_DEBUG
#define TERME_DISPLAY_ALLOC_X 3
#define TERME_DISPLAY_ALLOC_Y 3
#else
#define TERME_DISPLAY_ALLOC_X 64
#define TERME_DISPLAY_ALLOC_Y 64
#endif
#define TERME_DISPLAY_SIZE(x, y) (((x / y) + 1) * y)
/*
* line
*/
struct terme_line_body {
unsigned wide : 1;
unsigned ignore : 1;
PromptMode mode : 5;
unicode c : 21;
};
struct terme_line_root {
unsigned alloc, size, now;
};
static struct terme_line_root *struct_terme_line(addr pos)
{
Check(! terme_line_p(pos), "type error");
return (struct terme_line_root *)terme_pointer(pos);
}
static struct terme_line_body *struct_terme_body(addr pos)
{
Check(! terme_line_p(pos), "type error");
return (struct terme_line_body *)
(terme_pointer(pos) + sizeoft(struct terme_line_root));
}
static void terme_line_heap(addr *ret, unsigned alloc)
{
addr pos;
size_t size;
struct terme_line_root *str;
size = sizeoft(struct terme_line_root);
size += sizeoft(struct terme_line_body) * alloc;
heap_body(&pos, LISPSYSTEM_TERME, size);
terme_set_type(pos, terme_type_line);
str = struct_terme_line(pos);
str->alloc = alloc;
str->size = 0;
str->now = 0;
*ret = pos;
}
static void terme_line_resize_x(addr *ret, addr src_line,
unsigned alloc_x, unsigned new_x)
{
addr new_line;
struct terme_line_root *str;
struct terme_line_body *body1, *body2;
str = struct_terme_line(src_line);
if (alloc_x <= str->alloc) {
*ret = src_line;
return;
}
/* new object */
terme_line_heap(&new_line, alloc_x);
body1 = struct_terme_body(src_line);
body2 = struct_terme_body(new_line);
/* copy */
memcpy(body2, body1, sizeoft(struct terme_line_body) * str->size);
/* set array */
str = struct_terme_line(new_line);
str->alloc = alloc_x;
str->size = new_x;
}
static void terme_line_resize(addr *ret, addr pos, unsigned alloc_x, unsigned new_x)
{
struct terme_line_root *str;
if (pos == Nil)
terme_line_heap(&pos, alloc_x);
else
terme_line_resize_x(&pos, pos, alloc_x, new_x);
str = struct_terme_line(pos);
str->size = new_x;
str->now = 0;
*ret = pos;
}
/*
* display
*/
struct terme_display_struct {
unsigned alloc_x, alloc_y;
unsigned size_x, size_y;
unsigned now_x, now_y;
};
static struct terme_display_struct *struct_terme_display(addr pos)
{
Check(! terme_display_p(pos), "type error");
return (struct terme_display_struct *)terme_pointer(pos);
}
void terme_display_build(addr *ret)
{
addr pos;
struct terme_display_struct *str;
heap_smallsize(&pos, LISPSYSTEM_TERME, 1, sizeoft(struct terme_display_struct));
terme_set_type(pos, terme_type_display);
str = struct_terme_display(pos);
str->alloc_x = 0;
str->alloc_y = 0;
str->size_x = 0;
str->size_y = 0;
str->now_x = 0;
str->now_y = 0;
*ret = pos;
}
static void terme_display_resize_y(addr pos, unsigned new_y)
{
unsigned alloc_y, src_y, y;
addr new_array, src_array, value;
struct terme_display_struct *str;
/* new array */
alloc_y = TERME_DISPLAY_SIZE(new_y, TERME_DISPLAY_ALLOC_Y);
terme_get(pos, 0, &src_array);
vector_heap(&new_array, alloc_y);
/* copy */
str = struct_terme_display(pos);
src_y = str->size_y;
for (y = 0; y < src_y; y++) {
getarray(src_array, y, &value);
setarray(new_array, y, value);
}
/* set array */
terme_set(pos, 0, new_array);
str->alloc_y = alloc_y;
str->size_y = new_y;
}
static void terme_display_resize_x(addr pos, unsigned new_x)
{
unsigned alloc_x, size_y, y;
addr array, value;
struct terme_display_struct *str;
alloc_x = TERME_DISPLAY_SIZE(new_x, TERME_DISPLAY_ALLOC_X);
terme_get(pos, 0, &array);
/* copy */
str = struct_terme_display(pos);
size_y = str->size_y;
for (y = 0; y < size_y; y++) {
getarray(array, y, &value);
terme_line_resize(&value, value, alloc_x, new_x);
setarray(array, y, value);
}
/* set array */
str->alloc_x = alloc_x;
str->size_x = new_x;
}
static void terme_display_resize(addr pos, unsigned x, unsigned y)
{
struct terme_display_struct *str;
/* y */
str = struct_terme_display(pos);
if (str->alloc_y < y)
terme_display_resize_y(pos, y);
str->size_y = y;
/* x */
terme_display_resize_x(pos, x);
str->size_x = x;
/* cursor */
str->now_x = 0;
str->now_y = 0;
}
int terme_display_clear_(Execute ptr)
{
unsigned x, y;
addr pos;
Return(terme_root_display_(ptr, &pos));
terme_arch_size_get(&x, &y);
terme_display_resize(pos, x, y);
return 0;
}
/*
* operator
*/
static void terme_line_ignore(addr pos, unsigned x, PromptMode mode)
{
unsigned first, last, i;
struct terme_line_root *str;
struct terme_line_body *body, *cursor;
str = struct_terme_line(pos);
if (x <= str->now)
return;
first = (str->now < str->size)? str->now: str->size;
last = (x < str->size)? x: str->size;
body = struct_terme_body(pos);
for (i = first; i <= last; i++) {
cursor = body + i;
cursor->wide = 0;
cursor->ignore = 1;
cursor->mode = mode;
cursor->c = 0;
}
}
static void terme_line_write_char(addr pos, unsigned x,
unicode c, unsigned width, PromptMode mode)
{
int wide_p;
struct terme_line_root *str;
struct terme_line_body *body;
str = struct_terme_line(pos);
terme_line_ignore(pos, x, mode);
/* character */
wide_p = (width != 1);
body = struct_terme_body(pos);
body += str->now;
body->wide = wide_p;
body->ignore = 0;
body->mode = mode;
body->c = c;
str->now = x + 1;
/* eastasian width */
if (! wide_p)
return;
if (str->size <= str->now)
return;
body++;
body->wide = 0;
body->ignore = 1;
body->mode = mode;
body->c = 0;
str->now++;
}
int terme_display_write_char_(Execute ptr, unicode c, unsigned width, PromptMode mode)
{
addr pos, array, line;
struct terme_display_struct *str;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
if (str->size_y <= str->now_y) {
str->now_x += width;
return 0;
}
terme_get(pos, 0, &array);
getarray(array, str->now_y, &line);
terme_line_write_char(line, str->now_x, c, width, mode);
str->now_x += width;
return 0;
}
int terme_display_terpri_(Execute ptr)
{
addr pos;
struct terme_display_struct *str;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
if (str->now_y < str->size_y)
str->now_y++;
str->now_x = 0;
return 0;
}
int terme_display_delete_line_right_(Execute ptr)
{
addr pos;
struct terme_display_struct *str;
struct terme_line_root *root;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
if (str->size_y <= str->now_y)
return 0;
/* line */
terme_get(pos, 0, &pos);
getarray(pos, str->now_y, &pos);
root = struct_terme_line(pos);
if (str->now_x < root->now)
root->now = str->now_x;
return 0;
}
int terme_display_left_(Execute ptr, int n)
{
unsigned value;
addr pos;
struct terme_display_struct *str;
if (n <= 0)
return 0;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
value = (unsigned)n;
if (str->now_x <= value)
str->now_x = 0;
else
str->now_x -= value;
return 0;
}
int terme_display_right_(Execute ptr, int n)
{
addr pos;
struct terme_display_struct *str;
if (n <= 0)
return 0;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
str->now_x += (unsigned)n;
return 0;
}
int terme_display_up_(Execute ptr, int n)
{
addr pos;
unsigned value;
struct terme_display_struct *str;
if (n <= 0)
return 0;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
value = (unsigned)n;
if (str->now_y <= value)
str->now_y = 0;
else
str->now_y -= value;
return 0;
}
int terme_display_down_(Execute ptr, int n)
{
addr pos;
struct terme_display_struct *str;
if (n <= 0)
return 0;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
str->now_y += (unsigned)n;
if (str->now_y > str->size_y)
str->now_y = str->size_y;
return 0;
}
int terme_display_first_up_(Execute ptr, int n)
{
unsigned value;
addr pos;
struct terme_display_struct *str;
if (n <= 0)
return 0;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
value = (unsigned)n;
if (str->now_y <= value)
str->now_y = 0;
else
str->now_y -= value;
str->now_x = 0;
return 0;
}
int terme_display_first_down_(Execute ptr, int n)
{
addr pos;
struct terme_display_struct *str;
if (n <= 0)
return 0;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
str->now_y += (unsigned)n;
if (str->now_y > str->size_y)
str->now_y = str->size_y;
str->now_x = 0;
return 0;
}
int terme_display_delete_line_(Execute ptr)
{
addr pos;
struct terme_display_struct *str;
struct terme_line_root *root;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
if (str->size_y <= str->now_y)
return 0;
/* line */
terme_get(pos, 0, &pos);
getarray(pos, str->now_y, &pos);
root = struct_terme_line(pos);
root->now = 0;
return 0;
}
int terme_display_getwidth_(Execute ptr, unsigned *ret)
{
addr pos;
struct terme_display_struct *str;
struct terme_line_body *body;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
if (str->size_y <= str->now_y || str->size_x <= str->now_x)
return Result(ret, 0);
/* line */
terme_get(pos, 0, &pos);
getarray(pos, str->now_y, &pos);
body = struct_terme_body(pos);
body += str->now_x;
return Result(ret, body->wide? 2: 1);
}
int terme_display_previous_(Execute ptr, int *ret)
{
addr pos;
struct terme_display_struct *str;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
/* out of range */
if (str->size_y <= str->now_y)
return Result(ret, -1);
/* previous line */
if (str->now_x == 0) {
return Result(ret, str->now_y? 0: -1);
}
/* current line */
return Result(ret, 1);
}
int terme_display_getlast_(Execute ptr, unsigned *ret)
{
addr pos;
struct terme_display_struct *str;
struct terme_line_root *root;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
if (str->size_y <= str->now_y)
return Result(ret, 0);
/* line */
terme_get(pos, 0, &pos);
getarray(pos, str->now_y, &pos);
root = struct_terme_line(pos);
return Result(ret, root->now);
}
int terme_display_delete_page_(Execute ptr)
{
unsigned y;
addr pos, array, line;
struct terme_display_struct *str;
struct terme_line_root *root;
Return(terme_root_display_(ptr, &pos));
str = struct_terme_display(pos);
terme_get(pos, 0, &array);
for (y = 0; y < str->now_y; y++) {
getarray(array, y, &line);
root = struct_terme_line(line);
root->now = 0;
}
str->now_x = 0;
str->now_y = 0;
return 0;
}
/************************************************************
* terme_error.c
************************************************************/
/*
* error
*/
static int terme_fmte_va_(addr format, addr args)
{
int mode, check;
if (terme_arch_textmode(&mode)) {
Abort("terme_arch_textmode error.");
return 0;
}
check = call_simple_error_(NULL, format, args);
if (mode && terme_arch_rawmode(NULL)) {
Abort("terme_arch_rawmode error.");
return 0;
}
return check;
}
int terme_fmte_(const char *str, ...)
{
addr format, args;
va_list va;
if (terme_fresh_line()) {
Abort("terme_fresh_line error.");
return 0;
}
if (terme_finish_output()) {
Abort("terme_finish_output error.");
return 0;
}
strvect_char_heap(&format, str);
va_start(va, str);
copylocal_list_stdarg(NULL, &args, va);
va_end(va);
return terme_fmte_va_(format, args);
}
/************************************************************
* terme_escape.c
************************************************************/
static int terme_color_enable(Execute ptr)
{
addr symbol, pos;
GetConst(SYSTEM_PROMPT_COLOR, &symbol);
if (ptr == NULL) {
GetValueSymbol(symbol, &pos);
}
else {
getspecial_local(ptr, symbol, &pos);
}
return pos == Unbound || pos != Nil;
}
static int terme_escape_operator(const char *str)
{
byte c;
int i;
for (i = 0; ; i++) {
c = (byte)str[i];
if (c == 0)
break;
if (terme_write_byte(c))
return 1;
}
return 0;
}
int terme_font(Execute ptr, PrintFont value)
{
const char *str;
if (! terme_color_enable(ptr))
return 0;
switch (value) {
case print_font_reset: str = "\x1B[0m"; break;
case print_font_bold: str = "\x1B[1m"; break;
case print_font_faint: str = "\x1B[2m"; break;
case print_font_italic: str = "\x1B[3m"; break;
case print_font_underline: str = "\x1B[4m"; break;
case print_font_blink1: str = "\x1B[5m"; break;
case print_font_blink2: str = "\x1B[6m"; break;
case print_font_reverse: str = "\x1B[7m"; break;
case print_font_hide_in: str = "\x1B[8m"; break;
case print_font_hide_out: str = "\x1B[9m"; break;
default: return 1;
}
return terme_escape_operator(str);
}
int terme_text_color(Execute ptr, PrintColor value)
{
const char *str;
if (! terme_color_enable(ptr))
return 0;
switch (value) {
case print_color_reset: str = "\x1B[0m"; break;
case print_color_black: str = "\x1B[30m"; break;
case print_color_red: str = "\x1B[31m"; break;
case print_color_green: str = "\x1B[32m"; break;
case print_color_yellow: str = "\x1B[33m"; break;
case print_color_blue: str = "\x1B[34m"; break;
case print_color_magenta: str = "\x1B[35m"; break;
case print_color_cyan: str = "\x1B[36m"; break;
case print_color_white: str = "\x1B[37m"; break;
case print_color_bright_black: str = "\x1B[90m"; break;
case print_color_bright_red: str = "\x1B[91m"; break;
case print_color_bright_green: str = "\x1B[92m"; break;
case print_color_bright_yellow: str = "\x1B[93m"; break;
case print_color_bright_blue: str = "\x1B[94m"; break;
case print_color_bright_magenta: str = "\x1B[95m"; break;
case print_color_bright_cyan: str = "\x1B[96m"; break;
case print_color_bright_white: str = "\x1B[97m"; break;
default: return 1;
}
return terme_escape_operator(str);
}
int terme_back_color(Execute ptr, PrintColor value)
{
const char *str;
if (! terme_color_enable(ptr))
return 0;
switch (value) {
case print_color_reset: str = "\x1B[0m"; break;
case print_color_black: str = "\x1B[40m"; break;
case print_color_red: str = "\x1B[41m"; break;
case print_color_green: str = "\x1B[42m"; break;
case print_color_yellow: str = "\x1B[43m"; break;
case print_color_blue: str = "\x1B[44m"; break;
case print_color_magenta: str = "\x1B[45m"; break;
case print_color_cyan: str = "\x1B[46m"; break;
case print_color_white: str = "\x1B[47m"; break;
case print_color_bright_black: str = "\x1B[100m"; break;
case print_color_bright_red: str = "\x1B[101m"; break;
case print_color_bright_green: str = "\x1B[102m"; break;
case print_color_bright_yellow: str = "\x1B[103m"; break;
case print_color_bright_blue: str = "\x1B[104m"; break;
case print_color_bright_magenta: str = "\x1B[105m"; break;
case print_color_bright_cyan: str = "\x1B[106m"; break;
case print_color_bright_white: str = "\x1B[107m"; break;
default: return 1;
}
return terme_escape_operator(str);
}
static int terme_cursor_move_character(int n, byte c)
{
char data[64];
if (n <= 0)
return 0;
if (n == 1) {
if (terme_escape_operator("\x1B["))
return 1;
}
else {
snprintf(data, 64, "\x1B[%d", n);
if (terme_escape_operator(data))
return 1;
}
return terme_write_byte(c);
}
int terme_cursor_left(int n)
{
return terme_cursor_move_character(n, 'D');
}
int terme_cursor_right(int n)
{
return terme_cursor_move_character(n, 'C');
}
int terme_cursor_up(int n)
{
return terme_cursor_move_character(n, 'A');
}
int terme_cursor_down(int n)
{
return terme_cursor_move_character(n, 'B');
}
int terme_cursor_move(int n)
{
char data[64];
snprintf(data, 64, "\x1B[%dG", n + 1);
return terme_escape_operator(data);
}
int terme_cursor_first_up(int n)
{
return terme_cursor_move_character(n, 'F');
}
int terme_cursor_first_down(int n)
{
return terme_cursor_move_character(n, 'E');
}
int terme_cursor_delete_line_left(void)
{
return terme_escape_operator("\x1B[1K");
}
int terme_cursor_delete_line_right(void)
{
return terme_escape_operator("\x1B[K");
}
int terme_cursor_delete_line(void)
{
return terme_escape_operator("\x1B[2K");
}
int terme_cursor_delete_page(void)
{
return terme_escape_operator("\x1B[2J")
|| terme_escape_operator("\x1B[1;1H");
}
/************************************************************
* terme_history.c
************************************************************/
#define TERME_HISTORY_SIZE 64
struct terme_history_struct {
int now, index, size;
};
static struct terme_history_struct *struct_terme_history(addr pos)
{
Check(! terme_history_p(pos), "type error");
return (struct terme_history_struct *)terme_pointer(pos);
}
void terme_history_build(addr *ret)
{
addr pos, array;
struct terme_history_struct *str;
heap_smallsize(&pos, LISPSYSTEM_TERME, 1, sizeoft(struct terme_history_struct));
terme_set_type(pos, terme_type_history);
str = struct_terme_history(pos);
str->now = 0;
str->index = 0;
str->size = TERME_HISTORY_SIZE;
/* array */
vector_heap(&array, str->size);
terme_set(pos, 0, array);
*ret = pos;
}
int terme_history_clear_(Execute ptr)
{
addr pos;
struct terme_history_struct *str;
Return(terme_root_history_(ptr, &pos));
str = struct_terme_history(pos);
str->now = 0;
return 0;
}
/*
* return
*/
int terme_history_return_(Execute ptr)
{
addr value, pos, array;
struct terme_history_struct *str;
/* data */
Return(terme_data_make_(ptr, &value, 0));
/* object */
Return(terme_root_history_(ptr, &pos));
str = struct_terme_history(pos);
terme_get(pos, 0, &array);
setarray(array, str->index, value);
/* index */
str->now = 0;
str->index = (str->index + 1) % str->size;
return 0;
}
/*
* switch
*/
static int terme_history_save_(Execute ptr, addr pos)
{
addr array, value;
struct terme_history_struct *str;
str = struct_terme_history(pos);
terme_get(pos, 0, &array);
Return(terme_data_make_(ptr, &value, 0));
setarray(array, str->index, value);
return 0;
}
static int terme_history_get_(Execute ptr, int now, addr *value, int *ret)
{
addr pos, array;
struct terme_history_struct *str;
Return(terme_root_history_(ptr, &pos));
str = struct_terme_history(pos);
terme_get(pos, 0, &array);
if (now < 0 || str->size <= now) {
*value = Nil;
return Result(ret, 0);
}
now = (str->size + str->index - now) % str->size;
getarray(array, now, value);
return Result(ret, 1);
}
static int terme_history_update_(Execute ptr, int now, int *ret)
{
int check;
addr pos;
Return(terme_history_get_(ptr, now, &pos, &check));
if ((! check) || pos == Nil)
return Result(ret, 0);
Return(terme_data_copy_(ptr, pos));
return Result(ret, 1);
}
int terme_history_select_(Execute ptr, int diff, int *ret)
{
int check, now;
addr pos;
struct terme_history_struct *str;
Return(terme_root_history_(ptr, &pos));
str = struct_terme_history(pos);
if (str->now == 0) {
Return(terme_history_save_(ptr, pos));
}
now = str->now + diff;
Return(terme_history_update_(ptr, now, &check));
if (! check)
return Result(ret, 0);
str->now = now;
/* update */
return Result(ret, 1);
}
/************************************************************
* terme_input.c
************************************************************/
#ifdef LISP_DEBUG
#define TERME_INPUT_SIZE 3
#else
#define TERME_INPUT_SIZE 4096
#endif
#define TERME_INPUT_UNBYTE 64
#define TERME_INPUT_UNREAD 8
/* buffer */
static byte terme_input_buffer[TERME_INPUT_SIZE];
static size_t terme_input_size;
static size_t terme_input_now;
/* unicode */
static byte terme_input_unbyte[TERME_INPUT_UNBYTE];
static int terme_input_unbyte_size;
static int terme_input_unbyte_base;
static int terme_input_unbyte_now;
/* unread */
static unicode terme_input_unread[TERME_INPUT_UNREAD];
static int terme_input_unread_size;
static int terme_input_unread_base;
static int terme_input_unread_now;
void terme_input_init(void)
{
terme_input_size = 0;
terme_input_now = 0;
terme_input_unbyte_size = 0;
terme_input_unbyte_base = 0;
terme_input_unbyte_now = 0;
terme_input_unread_size = 0;
terme_input_unread_base = 0;
terme_input_unread_now = 0;
}
#define TERME_CLEAR_INPUT_STDIN 4096
static int terme_clear_input_stdin(void)
{
byte data[TERME_CLEAR_INPUT_STDIN];
int check;
size_t ignore;
for (;;) {
if (terme_arch_select(&check))
return 1;
if (! check)
break;
check = terme_arch_read(data, TERME_CLEAR_INPUT_STDIN, &ignore);
if (check)
return 1;
}
return 0;
}
int terme_clear_input(void)
{
terme_input_size = 0;
terme_input_now = 0;
terme_input_unbyte_size = 0;
terme_input_unbyte_base = 0;
terme_input_unbyte_now = 0;
terme_input_unread_size = 0;
terme_input_unread_base = 0;
terme_input_unread_now = 0;
return terme_clear_input_stdin();
}
/*
* unbyte
*/
static int terme_unbyte_push(byte c)
{
if (TERME_INPUT_UNBYTE <= terme_input_unbyte_size)
return 1; /* error */
terme_input_unbyte_size++;
terme_input_unbyte[terme_input_unbyte_base] = c;
terme_input_unbyte_base++;
terme_input_unbyte_base %= TERME_INPUT_UNBYTE;
return 0;
}
static void terme_unbyte_pop(byte *value, int *ret)
{
if (terme_input_unbyte_size == 0) {
*value = 0;
*ret = 0;
return;
}
*value = terme_input_unbyte[terme_input_unbyte_now];
terme_input_unbyte_size--;
if (terme_input_unbyte_size) {
terme_input_unbyte_now++;
terme_input_unbyte_now %= TERME_INPUT_UNBYTE;
}
else {
terme_input_unbyte_base = 0;
terme_input_unbyte_now = 0;
}
*ret = 1;
}
/*
* getc
*/
static int terme_getc_buffering(void)
{
int check;
size_t size;
terme_input_size = 0; /* for error */
terme_input_now = 0;
check = terme_arch_read(terme_input_buffer, TERME_INPUT_SIZE, &size);
if (check)
return 1;
terme_input_size = size;
return 0;
}
static int terme_getc_hang(byte *value, int *ret)
{
byte c;
int check;
/* unbyte */
terme_unbyte_pop(&c, &check);
if (check) {
*value = c;
*ret = 1;
return 0;
}
/* input buffer */
if (terme_input_size <= terme_input_now) {
if (terme_arch_select(&check))
goto error;
if (! check) { /* empty */
*value = 0;
*ret = 0;
return 0;
}
if (terme_getc_buffering())
goto error;
}
*ret = 1;
*value = terme_input_buffer[terme_input_now];
terme_input_now++;
return 0;
error:
*value = 0;
*ret = 0;
return 1;
}
static int terme_getc(byte *ret)
{
byte c;
int check;
for (;;) {
if (terme_getc_hang(&c, &check))
goto error;
if (check)
break;
if (terme_arch_wait())
goto error;
return 0;
}
*ret = c;
return 0;
error:
*ret = 0;
return 1;
}
/*
* unread-char
*/
int terme_unread_char(unicode c)
{
if (TERME_INPUT_UNREAD <= terme_input_unread_size)
return 1; /* error */
terme_input_unread_size++;
terme_input_unread[terme_input_unread_base] = c;
terme_input_unread_base++;
terme_input_unread_base %= TERME_INPUT_UNREAD;
return 0;
}
static void terme_unread_pop(unicode *value, int *ret)
{
if (terme_input_unread_size == 0) {
*value = 0;
*ret = 0;
return;
}
*value = terme_input_unread[terme_input_unread_now];
terme_input_unread_size--;
if (terme_input_unread_size) {
terme_input_unread_now++;
terme_input_unread_now %= TERME_INPUT_UNREAD;
}
else {
terme_input_unread_base = 0;
terme_input_unread_now = 0;
}
*ret = 1;
}
/*
* read-char
*/
static int terme_listen_rollback(byte *data, int size)
{
while (size) {
size--;
if (terme_unbyte_push(data[size]))
return 1;
}
return 0;
}
#define terme_listen_utf16(x) (0xD800 <= (x) && (x) < 0xE000)
#define terme_listen_getc() { \
if (terme_getc_hang(&c, &check)) goto error; \
if (! check) goto hang; \
if (c == 0x1B) goto escape; \
data[i++] = c; \
}
static int terme_listen_unicode(void)
{
byte data[8], c;
int i, check;
unicode value;
i = 0;
terme_listen_getc();
/* encode */
if (0x00 <= c && c <= 0x7F)
goto sequence1;
if (0xC2 <= c && c <= 0xDF)
goto sequence2;
if (0xE0 <= c && c <= 0xEF)
goto sequence3;
if (0xF0 <= c && c <= 0xF7)
goto sequence4;
goto invalid;
sequence1:
value = (unicode)c;
goto normal;
sequence2:
value = (0x1F & c) << 6;
terme_listen_getc();
if (c < 0x80 || 0xBF < c)
goto invalid;
value |= 0x3F & c;
if (value < 0x80)
goto invalid;
goto normal;
sequence3:
value = (0x0F & c) << 12;
terme_listen_getc();
if (c < 0x80 || 0xBF < c)
goto invalid;
value |= (0x3F & c) << 6;
terme_listen_getc();
if (c < 0x80 || 0xBF < c)
goto invalid;
value |= 0x3F & c;
if (value < 0x0800)
goto invalid;
if (terme_listen_utf16(value))
goto invalid;
goto normal;
sequence4:
value = (0x07 & c) << 18;
terme_listen_getc();
if (c < 0x80 || 0xBF < c)
goto invalid;
value |= (0x3F & c) << 12;
terme_listen_getc();
if (c < 0x80 || 0xBF < c)
goto invalid;
value |= (0x3F & c) << 6;
terme_listen_getc();
if (c < 0x80 || 0xBF < c)
goto invalid;
value |= 0x3F & c;
if (value < 0x010000)
goto invalid;
if (UnicodeCount <= value)
goto invalid;
goto normal;
normal:
if (terme_unread_char(value))
goto error;
return 0;
invalid:
return 1;
error:
(void)terme_listen_rollback(data, i);
return 1;
hang:
return terme_listen_rollback(data, i);
escape:
if (terme_listen_rollback(data, i))
return 1;
if (terme_unread_char(0x1B))
goto error;
return 0;
}
int terme_listen(int *ret)
{
/* unread */
if (terme_input_unread_size) {
*ret = 1;
return 0;
}
/* listen */
if (terme_listen_unicode()) {
*ret = 0;
return 1; /* error */
}
/* unread */
*ret = (terme_input_unread_size != 0);
return 0;
}
int terme_hang_char(unicode *value, int *ret)
{
int check;
unicode c;
/* unread */
terme_unread_pop(&c, &check);
if (check) {
*value = c;
*ret = 1;
return 0;
}
/* listen */
if (terme_listen_unicode()) {
*value = 0;
*ret = 0;
return 1; /* error */
}
/* unread */
terme_unread_pop(value, ret);
return 0;
}
int terme_read_char(unicode *value, int *ret)
{
int check;
unicode c;
for (;;) {
if (terme_hang_char(&c, &check))
goto error;
if (check)
break;
if (terme_arch_wait())
goto error;
}
*value = c;
*ret = 0; /* normal */
return 0;
error:
*value = 0;
*ret = 0;
return 1;
}
/*
* read-keyboard
*
* Up ^[OA
* Down ^[OB
* Right ^[OC
* Left ^[OD
* PF1 ^[OP
* PF2 ^[OQ
* PF3 ^[OR
* PF4 ^[OS
* F1 ^[[11~ ^[OP
* F2 ^[[12~ ^[OQ
* F3 ^[[13~ ^[OR
* F4 ^[[14~ ^[OS
* F5 ^[[15~ ^[Ot
* F6 ^[[17~ ^[Ou
* F7 ^[[18~ ^[Ov
* F8 ^[[19~ ^[Ol
* F9 ^[[20~ ^[Ow
* F10 ^[[21~ ^[Ox
* F11 ^[[23~
* F12 ^[[24~
*/
static void terme_read_escape(TermeKeyboard *ret)
{
byte c;
if (terme_getc(&c))
goto error;
if (c == 0x4F)
goto third_4F;
if (c == 0x5B)
goto third_5B;
goto error;
third_4F:
if (terme_getc(&c))
goto error;
if (0x50 <= c && c <= 0x53) /* PF1 - PF4 */
goto program;
goto error;
third_5B:
if (terme_getc(&c))
goto error;
if (c == 0x31)
goto forth_31;
if (c == 0x41)
goto escape_up;
if (c == 0x42)
goto escape_down;
if (c == 0x43)
goto escape_right;
if (c == 0x44)
goto escape_left;
goto error;
forth_31:
if (terme_getc(&c))
goto error;
if (0x31 <= c && c <= 0x39) { /* F1 - F9 */
if (terme_getc(&c))
goto error;
if (c == 0x7E) /* \E[[11~: F1 */
goto function1;
}
goto error;
escape_up: /* 0x1B 0x5B 0x41 */
ret->type = terme_escape_up;
return;
escape_down: /* 0x1B 0x5B 0x42 */
ret->type = terme_escape_down;
return;
escape_right: /* 0x1B 0x5B 0x43 */
ret->type = terme_escape_right;
return;
escape_left: /* 0x1B 0x5B 0x44 */
ret->type = terme_escape_left;
return;
program:
ret->type = terme_escape_function;
ret->c = (c - 0x50) + 1; /* PF1 -> 1 */
return;
function1:
ret->type = terme_escape_function;
ret->c = (c - 0x31) + 1; /* F1 -> 1 */
return;
error:
ret->type = terme_escape_error;
return;
}
int terme_read_keyboard(TermeKeyboard *ret)
{
int check;
unicode c;
if (terme_read_char(&c, &check))
return 1;
if (c != 0x1B) {
ret->type = terme_escape_code;
ret->c = c;
return 0;
}
/* escape sequence */
terme_read_escape(ret);
return 0;
}
/************************************************************
* terme_object.c
************************************************************/
byte *terme_pointer(addr pos)
{
CheckType(pos, LISPSYSTEM_TERME);
posbody(pos, &pos);
return (byte *)pos;
}
void terme_get(addr pos, size_t index, addr *ret)
{
CheckType(pos, LISPSYSTEM_TERME);
getarray(pos, index, ret);
}
void terme_set(addr pos, size_t index, addr value)
{
CheckType(pos, LISPSYSTEM_TERME);
setarray(pos, index, value);
}
enum terme_type terme_get_type(addr pos)
{
CheckType(pos, LISPSYSTEM_TERME);
return (enum terme_type)GetUser(pos);
}
void terme_set_type(addr pos, enum terme_type type)
{
CheckType(pos, LISPSYSTEM_TERME);
SetUser(pos, (int)type);
}
int termep(addr pos)
{
return GetType(pos) == LISPSYSTEM_TERME;
}
int terme_root_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_root);
}
int terme_data_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_data);
}
int terme_string_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_string);
}
int terme_screen_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_screen);
}
int terme_display_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_display);
}
int terme_line_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_line);
}
int terme_history_p(addr pos)
{
return termep(pos) && (terme_get_type(pos) == terme_type_history);
}
/*
* terme-root
*/
struct terme_root_struct {
enum prompt_mode mode;
};
static struct terme_root_struct *terme_root_body(addr pos)
{
Check(! terme_root_p(pos), "type error");
return (struct terme_root_struct *)terme_pointer(pos);
}
void terme_root_build(addr *ret)
{
addr root;
struct terme_root_struct *str;
heap_smallsize(&root, LISPSYSTEM_TERME,
terme_root_size,
sizeoft(struct terme_root_struct));
terme_set_type(root, terme_type_root);
str = terme_root_body(root);
str->mode = prompt_input;
*ret = root;
}
static int terme_root_special_(Execute ptr, addr *ret)
{
addr symbol;
GetConst(SYSTEM_SPECIAL_TERME, &symbol);
return getspecialcheck_local_(ptr, symbol, ret);
}
static int terme_root_get_(Execute ptr, enum terme_root_index index, addr *ret)
{
addr pos;
Return(terme_root_special_(ptr, &pos));
terme_get(pos, (size_t)index, ret);
return 0;
}
int terme_root_data_(Execute ptr, addr *ret)
{
return terme_root_get_(ptr, terme_root_data, ret);
}
int terme_root_screen_(Execute ptr, addr *ret)
{
return terme_root_get_(ptr, terme_root_screen, ret);
}
int terme_root_display_(Execute ptr, addr *ret)
{
return terme_root_get_(ptr, terme_root_display, ret);
}
int terme_root_history_(Execute ptr, addr *ret)
{
return terme_root_get_(ptr, terme_root_history, ret);
}
/*
* prompt
*/
int terme_prompt_set_(Execute ptr, addr value, enum prompt_mode mode)
{
addr pos;
struct terme_root_struct *str;
Return(terme_root_special_(ptr, &pos));
terme_set(pos, terme_root_prompt, value);
str = terme_root_body(pos);
str->mode = mode;
return 0;
}
int terme_prompt_get_(Execute ptr, addr *value, enum prompt_mode *mode)
{
addr pos;
struct terme_root_struct *str;
Return(terme_root_special_(ptr, &pos));
if (value) {
terme_get(pos, terme_root_prompt, value);
}
if (mode) {
str = terme_root_body(pos);
*mode = str->mode;
}
return 0;
}
/************************************************************
* terme_output.c
************************************************************/
#ifdef LISP_DEBUG
#define TERME_OUTPUT_SIZE 3
#else
#define TERME_OUTPUT_SIZE 4096
#endif
static byte terme_output_buffer[TERME_OUTPUT_SIZE];
static size_t terme_output_size;
static size_t terme_output_x;
void terme_output_init(void)
{
terme_output_size = 0;
terme_output_x = 0;
}
int terme_finish_output(void)
{
int check;
byte *data;
size_t size, retu;
size = terme_output_size;
data = terme_output_buffer;
while (size) {
check = terme_arch_write(data, size, &retu);
if (check)
return 1; /* error */
if (size <= retu)
break;
size -= retu;
data += retu;
}
terme_output_size = 0;
return 0;
}
int terme_write_byte(byte c)
{
if (TERME_OUTPUT_SIZE <= terme_output_size) {
if (terme_finish_output())
return 1;
}
terme_output_buffer[terme_output_size] = c;
terme_output_size++;
return 0;
}
static int terme_write_memory(const byte *data, size_t size)
{
size_t i;
for (i = 0; i < size; i++) {
if (terme_write_byte(data[i]))
return 1;
}
return 0;
}
static int terme_write_utf8(unicode u, byte *dst, size_t *ret)
{
size_t w;
w = 0;
/* 1 byte */
if (u < 0x80) {
dst[w++] = u;
goto normal;
}
/* 2 byte */
if (u < 0x0800) {
dst[w++] = 0xC2 | (u >> 6);
dst[w++] = 0x80 | (0x3F & u);
goto normal;
}
/* 3 byte */
if (u < 0xD800) {
goto sequence3;
}
/* surrogate pair */
if (u < 0xE000) {
goto error;
}
/* 3 byte */
if (u < 0x010000) {
sequence3:
dst[w++] = 0xE0 | (u >> 12);
dst[w++] = 0x80 | (0x3F & (u >> 6));
dst[w++] = 0x80 | (0x3F & u);
goto normal;
}
/* 4 byte */
if (u < UnicodeCount) {
dst[w++] = 0xF0 | (u >> 18);
dst[w++] = 0x80 | (0x3F & (u >> 12));
dst[w++] = 0x80 | (0x3F & (u >> 6));
dst[w++] = 0x80 | (0x3F & u);
goto normal;
}
/* error */
error:
return 1;
normal:
*ret = w;
return 0;
}
int terme_write_char(unicode c, unsigned width)
{
byte data[8];
size_t size;
if (terme_write_utf8(c, data, &size)) {
/* encode error */
return 0;
}
if (c == 0x0D)
terme_output_x = 0;
else
terme_output_x += width;
/* output */
return terme_write_memory(data, size);
}
/*
* call
*/
int terme_terpri(void)
{
return terme_write_byte(0x0D) || terme_write_byte(0x0A);
}
int terme_fresh_line(void)
{
return terme_output_x? terme_terpri(): 0;
}
/************************************************************
* terme_prompt.c
************************************************************/
/*
* default
*/
static int readline_default_terme_newline_(addr pos, addr *ret)
{
unicode c;
addr value;
size_t size, i;
strvect_length(pos, &size);
strvect_heap(&value, size + 1UL);
for (i = 0; i < size; i++) {
strvect_getc(pos, i, &c);
Return(strvect_setc_(value, i, c));
}
Return(strvect_setc_(value, i, 0x0A));
return Result(ret, value);
}
static int readline_default_terme_(Execute ptr, addr *ret)
{
int check;
addr input, output, prompt, pos;
GetConst(STREAM_STDIN, &input);
GetConst(STREAM_STDOUT, &output);
Return(terme_prompt_get_(ptr, &prompt, NULL));
Return(fresh_line_stream_(output, NULL));
if (prompt != Nil) {
Return(princ_print(ptr, output, prompt));
}
Return(finish_output_stream_(output));
Return(clear_input_stream_(input));
Return(read_line_stream_(ptr, &pos, &check, input, 0, Nil, 0));
if (pos == Nil)
return Result(ret, Nil);
Return(readline_default_terme_newline_(pos, &pos));
return Result(ret, pos);
}
/*
* readline
*/
static int terme_readline_loop_(Execute ptr, TermeKeyboard *, addr *, int *);
static int terme_readline_ctrl_z_(TermeKeyboard *str)
{
int mode;
if (terme_arch_textmode(&mode))
return terme_fmte_("terme_arch_textmode error.", NULL);
if (terme_arch_terminal_stop_())
return terme_fmte_("kill error.", NULL);
if (mode && terme_arch_rawmode(NULL))
return terme_fmte_("terme_arch_rawmode error.", NULL);
/* ignore */
str->type = terme_escape_error;
return 0;
}
static int terme_readline_control_(Execute ptr,
TermeKeyboard *str, addr *value, int *ret)
{
switch (str->c) {
case 0x03: /* C */
return terme_fmte_("Ctrl + C", NULL);
case 0x04: /* D */
str->type = terme_escape_delete;
break;
case 0x0A: /* J */
case 0x0D: /* Return, Enter, Ctrl+M */
str->type = terme_escape_return;
break;
case 0x10: /* P, up */
str->type = terme_escape_up;
break;
case 0x0E: /* N, down */
str->type = terme_escape_down;
break;
case 0x06: /* F, left */
str->type = terme_escape_right;
break;
case 0x02: /* B, right */
str->type = terme_escape_left;
break;
case 0x01: /* A */
str->type = terme_escape_first;
break;
case 0x05: /* E */
str->type = terme_escape_last;
break;
case 0x0C: /* L */
str->type = terme_escape_update;
break;
case 0x08: /* H, backspace */
str->type = terme_escape_backspace;
break;
case 0x15: /* U, rmleft */
str->type = terme_escape_rmleft;
break;
case 0x0B: /* K, rmright */
str->type = terme_escape_rmright;
break;
case 0x09: /* I, tabular */
str->type = terme_escape_tabular;
break;
case 0x12: /* R, search */
str->type = terme_escape_search;
break;
case 0x1A: /* Z */
Return(terme_readline_ctrl_z_(str));
break;
default:
str->type = terme_escape_error;
break;
}
return terme_readline_loop_(ptr, str, value, ret);
}
static int terme_readline_character_(Execute ptr, unicode c, addr *value, int *ret)
{
int check;
unsigned width;
/* value */
Return(terme_data_insert_(ptr, c, &width, &check));
if (check) /* buffer overflow */
return Result(ret, 0);
/* screen */
Return(terme_screen_push_(ptr));
/* next */
return terme_data_next_(ptr);
}
static int terme_readline_code_(Execute ptr, TermeKeyboard *str, addr *value, int *ret)
{
if (str->c < 0x20)
return terme_readline_control_(ptr, str, value, ret);
else
return terme_readline_character_(ptr, str->c, value, ret);
}
static int terme_readline_up_down_(Execute ptr, int diff)
{
int check;
/* select */
Return(terme_history_select_(ptr, diff, &check));
if (! check)
return 0;
/* screen */
Return(terme_screen_history_(ptr));
/* data */
Return(terme_data_last_(ptr));
return 0;
}
static int terme_readline_up_(Execute ptr)
{
return terme_readline_up_down_(ptr, 1);
}
static int terme_readline_down_(Execute ptr)
{
return terme_readline_up_down_(ptr, -1);
}
static int terme_readline_left_(Execute ptr)
{
unsigned width;
Return(terme_data_left_(ptr, &width));
if (width == 0)
return 0;
return terme_screen_left_(ptr, width);
}
static int terme_readline_right_(Execute ptr)
{
unsigned width;
Return(terme_data_right_(ptr, &width));
if (width == 0)
return 0;
return terme_screen_right_(ptr, width);
}
static int terme_readline_return_(Execute ptr, addr *value, int *ret)
{
/* last */
Return(terme_screen_last_(ptr));
Return(terme_data_last_(ptr));
/* history */
Return(terme_history_return_(ptr));
/* result */
Return(terme_data_make_(ptr, value, 1));
return Result(ret, 1);
}
static int terme_readline_delete_(Execute ptr, addr *value, int *ret)
{
unsigned size;
int check;
/* exit */
Return(terme_data_size_(ptr, &size));
if (size == 0) {
*value = Nil;
return Result(ret, 1);
}
/* delete */
*value = Nil;
*ret = 0;
Return(terme_data_delete_(ptr, &check));
if (! check)
return 0;
return terme_screen_delete_(ptr);
}
static int terme_readline_backspace_(Execute ptr)
{
unsigned width;
Return(terme_data_backspace_(ptr, &width));
if (width == 0)
return 0;
return terme_screen_backspace_(ptr, width);
}
static int terme_readline_first_(Execute ptr)
{
Return(terme_data_first_(ptr));
return terme_screen_first_(ptr);
}
static int terme_readline_last_(Execute ptr)
{
Return(terme_screen_last_(ptr));
return terme_data_last_(ptr);
}
static int terme_readline_update_(Execute ptr)
{
return terme_screen_update_(ptr);
}
static int terme_readline_rmleft_(Execute ptr)
{
int check;
Return(terme_data_rmleft_(ptr, &check));
if (! check)
return 0;
return terme_screen_rmleft_(ptr);
}
static int terme_readline_rmright_(Execute ptr)
{
int check;
Return(terme_data_rmright_(ptr, &check));
if (! check)
return 0;
return terme_screen_rmright_(ptr);
}
static int terme_readline_loop_(Execute ptr, TermeKeyboard *str, addr *value, int *ret)
{
*ret = 0;
switch (str->type) {
case terme_escape_error:
break;
case terme_escape_code:
return terme_readline_code_(ptr, str, value, ret);
case terme_escape_up:
return terme_readline_up_(ptr);
case terme_escape_down:
return terme_readline_down_(ptr);
case terme_escape_left:
return terme_readline_left_(ptr);
case terme_escape_right:
return terme_readline_right_(ptr);
case terme_escape_return:
return terme_readline_return_(ptr, value, ret);
case terme_escape_delete:
return terme_readline_delete_(ptr, value, ret);
case terme_escape_backspace:
return terme_readline_backspace_(ptr);
case terme_escape_first:
return terme_readline_first_(ptr);
case terme_escape_last:
return terme_readline_last_(ptr);
case terme_escape_update:
return terme_readline_update_(ptr);
case terme_escape_rmleft:
return terme_readline_rmleft_(ptr);
case terme_escape_rmright:
return terme_readline_rmright_(ptr);
case terme_escape_function:
case terme_escape_tabular:
case terme_escape_search:
break; /* ignore */
default:
return terme_fmte_("terme_readline error.", NULL);
}
return 0;
}
static int terme_readline_call_(Execute ptr, addr *ret)
{
int check;
addr pos;
TermeKeyboard str;
/* begin */
Return(terme_screen_prompt_(ptr));
/* loop */
pos = Nil;
for (;;) {
if (terme_read_keyboard(&str))
continue;
Return(terme_readline_loop_(ptr, &str, &pos, &check));
if (check)
break;
}
/* finish */
if (pos != Nil) {
if (terme_fresh_line())
goto error;
}
if (terme_finish_output())
goto error;
return Result(ret, pos);
error:
*ret = Nil;
return terme_fmte_("terme output error.", NULL);
}
static int terme_readline_module_(Execute ptr, addr *ret)
{
int check, mode;
Return(terme_data_clear_(ptr));
Return(terme_screen_clear_(ptr));
Return(terme_display_clear_(ptr));
Return(terme_history_clear_(ptr));
/* readline */
if (terme_arch_rawmode(&mode)) {
*ret = Nil;
return terme_fmte_("terme_arch_rawmode error.", NULL);
}
check = terme_readline_call_(ptr, ret);
if (mode && terme_arch_textmode(NULL)) {
*ret = Nil;
return terme_fmte_("terme_arch_textmode error.", NULL);
}
return check;
}
int terme_readline_(Execute ptr, addr *ret)
{
if (terme_arch_enable())
return terme_readline_module_(ptr, ret);
else
return readline_default_terme_(ptr, ret);
}
/************************************************************
* terme_screen.c
************************************************************/
/*
* object
*/
struct terme_screen_struct {
unsigned window_x, window_y;
unsigned prompt_x, prompt_y;
unsigned now_x, now_y, last_y;
};
static struct terme_screen_struct *struct_terme_screen(addr pos)
{
Check(! terme_screen_p(pos), "type error");
return (struct terme_screen_struct *)terme_pointer(pos);
}
void terme_screen_build(addr *ret)
{
addr pos;
struct terme_screen_struct *str;
heap_body(&pos, LISPSYSTEM_TERME, sizeoft(struct terme_screen_struct));
terme_set_type(pos, terme_type_screen);
str = struct_terme_screen(pos);
str->window_x = 0;
str->window_y = 0;
str->prompt_x = 0;
str->prompt_y = 0;
str->now_x = 0;
str->now_y = 0;
str->last_y = 0;
*ret = pos;
}
/*
* clear
*/
int terme_screen_clear_(Execute ptr)
{
unsigned screen_x, screen_y;
addr pos;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &pos));
terme_arch_size_get(&screen_x, &screen_y);
str = struct_terme_screen(pos);
str->window_x = screen_x;
str->window_y = screen_y;
str->prompt_x = 0;
str->prompt_y = 0;
str->now_x = 0;
str->now_y = 0;
str->last_y = 0;
return 0;
}
/*
* prompt
*/
static int terme_screen_write_char_(Execute ptr,
unicode c, unsigned width, PromptMode mode)
{
int output_p;
unsigned next;
addr pos;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &pos));
str = struct_terme_screen(pos);
output_p = (str->now_y < str->window_y);
/* eol */
next = str->now_x + width;
if (str->window_x < next) {
if (output_p) {
Return(terme_write_terpri_(ptr));
Return(terme_write_delete_line_right_(ptr));
}
str->now_x = 0;
str->now_y++;
}
/* output */
if (output_p) {
Return(terme_write_char_(ptr, c, width, mode));
}
str->now_x++;
/* width */
if (1 < width) {
if (output_p) {
Return(terme_write_right_(ptr, mode));
}
str->now_x++;
}
return 0;
}
static int terme_screen_prompt_string_(Execute ptr, addr pos, PromptMode mode)
{
unsigned width;
unicode c;
size_t size, i;
string_length(pos, &size);
for (i = 0; i < size; i++) {
Return(string_getc_(pos, i, &c));
width = eastasian_width(c);
Return(terme_screen_write_char_(ptr, c, width, mode));
}
return 0;
}
static PrintColor terme_prompt_color_bright(PromptMode mode)
{
switch (mode) {
case prompt_for:
return print_color_bright_yellow;
case prompt_debugger:
case prompt_inspect:
case prompt_step:
return print_color_bright_blue;
case prompt_eval:
default:
return print_color_bright_green;
}
}
static PrintColor terme_prompt_color_dark(PromptMode mode)
{
switch (mode) {
case prompt_for:
return print_color_yellow;
case prompt_debugger:
case prompt_inspect:
case prompt_step:
return print_color_blue;
case prompt_eval:
default:
return print_color_green;
}
}
static PrintColor terme_prompt_color(Execute ptr, PromptMode mode)
{
addr pos;
GetConst(SYSTEM_PROMPT_BRIGHT, &pos);
getspecial_local(ptr, pos, &pos);
if (pos == Nil)
return terme_prompt_color_dark(mode);
/* unbound or (not nil) */
return terme_prompt_color_bright(mode);
}
static int terme_screen_prompt_output_(Execute ptr)
{
PromptMode mode;
PrintColor color;
addr pos;
/* prompt */
Return(terme_prompt_get_(ptr, &pos, &mode));
if (pos == Nil)
return 0;
/* color */
if (terme_font(ptr, print_font_reset))
return terme_fmte_("terme_font error.", NULL);
color = terme_prompt_color(ptr, mode);
if (terme_text_color(ptr, color))
return terme_fmte_("terme_text_color error.", NULL);
/* output */
Return(terme_screen_prompt_string_(ptr, pos, mode));
/* reset */
if (terme_font(ptr, print_font_reset))
return terme_fmte_("terme_font error.", NULL);
return 0;
}
static int terme_screen_prompt_position_(Execute ptr)
{
addr pos;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &pos));
str = struct_terme_screen(pos);
str->prompt_x = str->now_x;
str->prompt_y = str->now_y;
return 0;
}
int terme_screen_prompt_(Execute ptr)
{
addr pos;
/* fresh-line */
Return(terminal_io_stream_(ptr, &pos));
Return(fresh_line_stream_(pos, NULL));
/* screen */
Return(terme_screen_prompt_output_(ptr));
Return(terme_screen_prompt_position_(ptr));
return terme_write_flush_();
}
/*
* push
*/
static int terme_screen_push_next_(addr data, addr screen, unsigned *rx, unsigned *ry)
{
unsigned now, width, next, x, y;
struct terme_screen_struct *str;
/* width */
terme_data_get_value(data, &now, NULL);
Return(terme_data_get_character_(data, now, NULL, &width));
/* screen */
str = struct_terme_screen(screen);
x = str->now_x;
y = str->now_y;
next = x + width;
if (str->window_x < next) {
x = 0;
y++;
}
x += width;
/* result */
*rx = x;
*ry = y;
return 0;
}
static int terme_screen_push_first_(Execute ptr, addr screen)
{
struct terme_screen_struct *str;
str = struct_terme_screen(screen);
if (str->now_x < str->window_x) {
Return(terme_write_delete_line_right_(ptr));
}
return 0;
}
static int terme_screen_output_(Execute ptr, addr data, addr screen, PromptMode mode)
{
unsigned now, size, width;
unicode c;
struct terme_screen_struct *str;
str = struct_terme_screen(screen);
terme_data_get_value(data, &now, &size);
for (; now < size; now++) {
Return(terme_data_get_character_(data, now, &c, &width));
Return(terme_screen_write_char_(ptr, c, width, mode));
}
if (str->last_y < str->now_y)
str->last_y = str->now_y;
return 0;
}
static int terme_screen_move_(Execute ptr, unsigned x, unsigned y)
{
addr screen;
unsigned now_x, now_y;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
now_x = str->now_x;
now_y = str->now_y;
/* up */
if (y < now_y) {
Return(terme_write_up_(ptr, now_y - y));
}
/* down */
if (y > now_y) {
Return(terme_write_down_(ptr, y - now_y));
}
/* left */
if (x < now_x) {
Return(terme_write_left_(ptr, now_x - x));
}
/* right */
if (x > now_x) {
Return(terme_write_right_(ptr, x - now_x));
}
/* result */
str->now_x = x;
str->now_y = y;
return 0;
}
int terme_screen_push_(Execute ptr)
{
unsigned x, y;
addr data, screen;
Return(terme_root_data_(ptr, &data));
Return(terme_root_screen_(ptr, &screen));
/* next position */
x = y = 0;
Return(terme_screen_push_next_(data, screen, &x, &y));
/* line delete */
Return(terme_screen_push_first_(ptr, screen));
/* output */
Return(terme_screen_output_(ptr, data, screen, prompt_input));
/* move cursor */
Return(terme_screen_move_(ptr, x, y));
return terme_write_flush_();
}
/*
* history
*/
static int terme_screen_history_delete_(Execute ptr, addr screen)
{
unsigned y, now_x, now_y;
struct terme_screen_struct *str;
str = struct_terme_screen(screen);
if (str->last_y <= str->now_y)
return 0;
now_x = str->now_x;
now_y = str->now_y;
str->now_x = 0;
for (y = str->now_y; y < str->last_y; y++) {
Return(terme_write_first_down_(ptr, 1));
Return(terme_write_delete_line_(ptr));
str->now_y++;
}
return terme_screen_move_(ptr, now_x, now_y);
}
int terme_screen_history_(Execute ptr)
{
addr data, screen;
Return(terme_root_data_(ptr, &data));
Return(terme_root_screen_(ptr, &screen));
/* move (0, 0) */
Return(terme_screen_move_(ptr, 0, 0));
/* output prompt */
Return(terme_write_delete_line_(ptr));
Return(terme_screen_prompt_output_(ptr));
/* output data */
Return(terme_screen_output_(ptr, data, screen, prompt_input));
/* delete last line */
Return(terme_screen_history_delete_(ptr, screen));
/* flush */
return terme_write_flush_();
}
/*
* left, right
*/
static int terme_screen_left_line_(Execute ptr, unsigned width)
{
addr screen;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
Check(str->now_x < width, "width error.");
Return(terme_write_left_(ptr, width));
str->now_x -= width;
return 0;
}
static int terme_screen_left_previous_(Execute ptr, unsigned width)
{
unsigned move;
addr screen;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
if (str->now_y == 0)
return 0;
/* first up */
Return(terme_write_first_up_(ptr, 1));
str->now_x = 0;
str->now_y--;
/* right */
Return(terme_display_getlast_(ptr, &move));
if (width < move) {
move -= width;
Return(terme_write_right_(ptr, move));
str->now_x = move;
}
/* left */
return terme_write_flush_();
}
static int terme_screen_left_output_(Execute ptr, unsigned width, int *ret)
{
int check;
Return(terme_display_previous_(ptr, &check));
if (check < 0)
return Result(ret, 0);
if (check) {
Return(terme_screen_left_line_(ptr, width));
}
else {
Return(terme_screen_left_previous_(ptr, width));
}
return Result(ret, 1);
}
int terme_screen_left_(Execute ptr, unsigned width)
{
int check;
Return(terme_screen_left_output_(ptr, width, &check));
if (! check)
return 0;
return terme_write_flush_();
}
static int terme_screen_right_next_(Execute ptr)
{
unsigned now, size, width, next;
addr data, screen;
struct terme_screen_struct *str;
/* data */
Return(terme_root_data_(ptr, &data));
terme_data_get_value(data, &now, &size);
if (size <= now)
return terme_write_flush_();
Return(terme_data_get_character_(data, now, NULL, &width));
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
next = str->now_x + width;
if (str->window_x < next) {
Return(terme_write_first_down_(ptr, 1));
str->now_x = 0;
str->now_y++;
}
return terme_write_flush_();
}
int terme_screen_right_(Execute ptr, unsigned width)
{
unsigned next;
addr screen;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
next = str->now_x + width;
if (str->window_x <= next) {
Return(terme_write_first_down_(ptr, 1));
str->now_x = 0;
str->now_y++;
}
else {
Return(terme_write_right_(ptr, width));
str->now_x += width;
}
return terme_screen_right_next_(ptr);
}
static int terme_screen_delete_last_(Execute ptr, addr screen)
{
unsigned y, now_y, last_y;
struct terme_screen_struct *str;
str = struct_terme_screen(screen);
now_y = str->now_y;
last_y = str->last_y;
for (y = now_y; y < last_y; y++) {
Return(terme_write_first_down_(ptr, 1));
str->now_x = 0;
str->now_y++;
Return(terme_write_delete_line_right_(ptr));
}
return 0;
}
int terme_screen_delete_(Execute ptr)
{
unsigned now_x, now_y;
addr data, screen;
struct terme_screen_struct *str;
Return(terme_root_data_(ptr, &data));
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
now_x = str->now_x;
now_y = str->now_y;
/* line delete */
Return(terme_screen_push_first_(ptr, screen));
/* output */
Return(terme_screen_output_(ptr, data, screen, prompt_input));
/* delete last line */
Return(terme_screen_delete_last_(ptr, screen));
/* move */
Return(terme_screen_move_(ptr, now_x, now_y));
/* flush */
return terme_write_flush_();
}
int terme_screen_backspace_(Execute ptr, unsigned width)
{
int check;
/* left */
Return(terme_screen_left_output_(ptr, width, &check));
if (! check)
return 0;
/* delete */
return terme_screen_delete_(ptr);
}
int terme_screen_first_(Execute ptr)
{
addr screen;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
Return(terme_screen_move_(ptr, str->prompt_x, str->prompt_y));
return terme_write_flush_();
}
static int terme_screen_move_char_(addr screen,
unsigned width, unsigned *rx, unsigned *ry)
{
unsigned next;
struct terme_screen_struct *str;
str = struct_terme_screen(screen);
if (str->window_y <= *ry)
return 0;
/* eol */
next = *rx + width;
if (str->window_x < next) {
*rx = 0;
(*ry)++;
}
/* move */
*rx += width;
return 0;
}
static int terme_screen_last_position_(Execute ptr, unsigned *rx, unsigned *ry)
{
unsigned now, size, width, x, y;
addr screen, data;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
Return(terme_root_data_(ptr, &data));
str = struct_terme_screen(screen);
terme_data_get_value(data, &now, &size);
x = str->now_x;
y = str->now_y;
for (; now < size; now++) {
Return(terme_data_get_character_(data, now, NULL, &width));
Return(terme_screen_move_char_(screen, width, &x, &y));
}
*rx = x;
*ry = y;
return 0;
}
int terme_screen_last_(Execute ptr)
{
unsigned x, y;
x = y = 0;
Return(terme_screen_last_position_(ptr, &x, &y));
Return(terme_screen_move_(ptr, x, y));
return terme_write_flush_();
}
static int terme_screen_update_output_(Execute ptr, addr screen, PromptMode mode)
{
unsigned now, size, width;
unicode c;
addr data;
struct terme_screen_struct *str;
Return(terme_root_data_(ptr, &data));
str = struct_terme_screen(screen);
terme_data_get_value(data, NULL, &size);
for (now = 0; now < size; now++) {
Return(terme_data_get_character_(data, now, &c, &width));
Return(terme_screen_write_char_(ptr, c, width, mode));
}
if (str->last_y < str->now_y)
str->last_y = str->now_y;
return 0;
}
int terme_screen_update_(Execute ptr)
{
unsigned x, y;
addr screen;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
x = str->now_x;
y = str->now_y;
str->now_x = 0;
str->now_y = 0;
Return(terme_write_delete_page_(ptr));
Return(terme_screen_prompt_output_(ptr));
Return(terme_screen_update_output_(ptr, screen, prompt_input));
Return(terme_screen_move_(ptr, x, y));
return terme_write_flush_();
}
int terme_screen_rmleft_(Execute ptr)
{
addr data, screen;
Return(terme_root_data_(ptr, &data));
Return(terme_root_screen_(ptr, &screen));
/* move (0, 0) */
Return(terme_screen_move_(ptr, 0, 0));
/* output prompt */
Return(terme_write_delete_line_(ptr));
Return(terme_screen_prompt_output_(ptr));
/* output data */
Return(terme_screen_output_(ptr, data, screen, prompt_input));
/* delete last line */
Return(terme_screen_history_delete_(ptr, screen));
/* flush */
return terme_screen_first_(ptr);
}
int terme_screen_rmright_(Execute ptr)
{
unsigned x, y;
addr screen;
struct terme_screen_struct *str;
Return(terme_root_screen_(ptr, &screen));
str = struct_terme_screen(screen);
x = str->now_x;
y = str->now_y;
Return(terme_write_delete_line_right_(ptr));
Return(terme_screen_history_delete_(ptr, screen));
Return(terme_screen_move_(ptr, x, y));
return terme_write_flush_();
}
/************************************************************
* terme_values.c
************************************************************/
#ifdef LISP_TERME_WINDOWS
#include "windows_values.h"
#endif
int terme_values_(Execute ptr, addr var, addr args)
{
#ifdef LISP_TERME_WINDOWS
int check;
Return(windows_values_(ptr, var, args, &check));
if (check)
return 0;
#endif
return fmte_("Invalid keyword ~S.", var, NULL);
}
/************************************************************
* terme_write.c
************************************************************/
int terme_write_flush_(void)
{
if (terme_finish_output())
return terme_fmte_("terme_finish_output error.", NULL);
return 0;
}
int terme_write_char_(Execute ptr, unicode c, unsigned width, PromptMode mode)
{
/* display */
Return(terme_display_write_char_(ptr, c, width, mode));
/* terminal */
if (terme_write_char(c, width))
return terme_fmte_("terme_write_char error.", NULL);
return 0;
}
int terme_write_terpri_(Execute ptr)
{
/* display */
Return(terme_display_terpri_(ptr));
/* terminal */
if (terme_terpri())
return terme_fmte_("terme_tepri error.", NULL);
return 0;
}
int terme_write_delete_line_right_(Execute ptr)
{
/* display */
Return(terme_display_delete_line_right_(ptr));
/* terminal */
if (terme_cursor_delete_line_right())
return terme_fmte_("terme_cursor_delete_line_right error.", NULL);
return 0;
}
int terme_write_left_(Execute ptr, int n)
{
/* display */
Return(terme_display_left_(ptr, n));
/* terminal */
if (terme_cursor_left(n))
return terme_fmte_("terme_cursor_left error.", NULL);
return 0;
}
int terme_write_right_(Execute ptr, int n)
{
/* display */
Return(terme_display_right_(ptr, n));
/* terminal */
if (terme_cursor_right(n))
return terme_fmte_("terme_cursor_right error.", NULL);
return 0;
}
int terme_write_up_(Execute ptr, int n)
{
/* display */
Return(terme_display_up_(ptr, n));
/* terminal */
if (terme_cursor_up(n))
return terme_fmte_("terme_cursor_up error.", NULL);
return 0;
}
int terme_write_down_(Execute ptr, int n)
{
/* display */
Return(terme_display_down_(ptr, n));
/* terminal */
if (terme_cursor_down(n))
return terme_fmte_("terme_cursor_down error.", NULL);
return 0;
}
int terme_write_first_up_(Execute ptr, int n)
{
/* display */
Return(terme_display_first_up_(ptr, n));
/* terminal */
if (terme_cursor_first_up(n))
return terme_fmte_("terme_cursor_first_up error.", NULL);
return 0;
}
int terme_write_first_down_(Execute ptr, int n)
{
/* display */
Return(terme_display_first_down_(ptr, n));
/* terminal */
if (terme_cursor_first_down(n))
return terme_fmte_("terme_cursor_first_down error.", NULL);
return 0;
}
int terme_write_delete_line_(Execute ptr)
{
/* display */
Return(terme_display_delete_line_(ptr));
/* terminal */
if (terme_cursor_delete_line())
return terme_fmte_("terme_cursor_delete_line error.", NULL);
return 0;
}
int terme_write_delete_page_(Execute ptr)
{
/* display */
Return(terme_display_delete_page_(ptr));
/* terminal */
if (terme_cursor_delete_page())
return terme_fmte_("terme_cursor_delete_page error.", NULL);
return 0;
}
/************************************************************
* thread.c
************************************************************/
/*
* single
*/
#ifdef LISP_THREAD_SINGLE
/*
* mutexlite
*/
int lispd_make_mutexlite(mutexlite *mutex)
{
*mutex = 0;
return 0;
}
void lispd_destroy_mutexlite(mutexlite *mutex)
{
if (*mutex) {
Debug("lispd_destroy_mutexlite error.");
lispd_threaderror();
}
}
void lispd_lock_mutexlite(mutexlite *mutex)
{
if (*mutex) {
Debug("lispd_lock_mutexlite error.");
lispd_threaderror();
}
*mutex = 1;
}
int lispd_trylock_mutexlite(mutexlite *mutex)
{
if (*mutex) {
Debug("lispd_trylock_mutexlite error.");
lispd_threaderror();
}
return 0;
}
void lispd_unlock_mutexlite(mutexlite *mutex)
{
if (*mutex == 0) {
Debug("lispd_unlock_mutexlite error.");
lispd_threaderror();
}
*mutex = 0;
}
/*
* rwlocklite
*/
int lispd_make_rwlocklite(rwlocklite *lock)
{
*lock = 0;
return 0;
}
void lispd_destroy_rwlocklite(rwlocklite *lock)
{
if (*lock) {
Debug("lispd_destroy_rwlocklite error.");
lispd_threaderror();
}
}
void lispd_rdlock_rwlocklite(rwlocklite *lock)
{
if (*lock == 2) {
Debug("lispd_rdlock_rwlocklite error.");
lispd_threaderror();
}
*lock = 1;
}
void lispd_wrlock_rwlocklite(rwlocklite *lock)
{
if (*lock) {
Debug("lispd_wrlock_rwlocklite error.");
lispd_threaderror();
}
*lock = 2;
}
int lispd_tryrdlock_rwlocklite(rwlocklite *lock)
{
if (*lock == 2) {
Debug("lispd_tryrdlock_rwlocklite error.");
lispd_threaderror();
}
return 0;
}
int lispd_trywrlock_rwlocklite(rwlocklite *lock)
{
if (*lock) {
Debug("lispd_trywrlock_rwlocklite error.");
lispd_threaderror();
}
return 0;
}
void lispd_unrdlock_rwlocklite(rwlocklite *lock)
{
if (*lock != 1) {
Debug("lispd_unrdlock_rwlocklite error.");
lispd_threaderror();
}
}
void lispd_unwrlock_rwlocklite(rwlocklite *lock)
{
if (*lock != 2) {
Debug("lispd_unwrlock_rwlocklite error.");
lispd_threaderror();
}
}
/*
* threadlocal
*/
void lispd_make_threadlocal(threadlocal *key)
{
struct threadlocal_single *ptr;
ptr = malloctype(struct threadlocal_single);
ptr->value = 0;
*key = ptr;
}
void lispd_destroy_threadlocal(threadlocal key)
{
if (key == NULL) {
Debug("lispd_destroy_threadlocal error");
lispd_threaderror();
}
free(key);
}
const void *lispd_get_threadlocal(threadlocal key)
{
if (key == NULL) {
Debug("lispd_get_threadlocal error");
lispd_threaderror();
}
return key->value;
}
void lispd_set_threadlocal(threadlocal key, const void *value)
{
if (key == NULL) {
Debug("lispd_set_threadlocal error");
lispd_threaderror();
}
key->value = value;
}
/*
* binary semaphore
*/
void lispd_make_binsem(binsem *x)
{
*x = 0;
}
void lispd_destroy_binsem(binsem *x)
{
}
void lispd_lock_binsem(binsem *x)
{
if (*x) {
Debug("lispd_lock_binsem error.");
lispd_threaderror();
}
*x = 1;
}
int lispd_trylock_binsem(binsem *x)
{
if (*x) {
Debug("lispd_trylock_binsem error.");
lispd_threaderror();
}
return 0;
}
void lispd_unlock_binsem(binsem *x)
{
if (*x == 0) {
Debug("lispd_unlock_mutexlite error.");
lispd_threaderror();
}
*x = 0;
}
/*
* condition variable
*/
void lispd_make_condlite(condlite *x)
{
*x = 0;
}
void lispd_destroy_condlite(condlite *x)
{
}
void lispd_wait_condlite(condlite *x, mutexlite *m)
{
}
void lispd_signal_condlite(condlite *x)
{
}
void lispd_broadcast_condlite(condlite *x)
{
}
#endif
/*
* disable
*/
#ifdef LISP_THREAD_DISABLE
int create_thread(execfunction proc, Execute arg)
{
fprintf(stderr, "create_thread error\n");
return 1;
}
int join_thread(threadhandle *handle)
{
return 0;
}
#endif
/*
* posix
*/
#ifdef LISP_THREAD_POSIX
/*
* posix semaphore
*/
int lispd_trylock_semposix(semposix *sem)
{
int result;
result = sem_trywait(sem);
if (result) {
if (errno == EAGAIN) return 1;
Debug("sem_trywait error");
lispd_threaderror();
}
return 0;
}
int lispd_get_semposix(semposix *sem)
{
int result;
if (sem_getvalue(sem, &result)) {
Debug("sem_post error");
lispd_threaderror();
}
return result;
}
/*
* thread
*/
static void *start_routine(void *pvoid)
{
Execute arg;
arg = (Execute)pvoid;
set_execute_local(arg);
(*arg->routine)(arg);
setstate_execute(arg, ThreadState_Finish);
return NULL;
}
int create_thread(execfunction proc, Execute arg)
{
if (pthread_create(&arg->handle, NULL, start_routine, (void *)arg)) {
fprintf(stderr, "pthread_create error\n");
return 1;
}
return 0;
}
int join_thread(threadhandle *handle)
{
return pthread_join(*handle, NULL);
}
#endif
/*
* Windows
*/
#ifdef LISP_THREAD_WINDOWS
#undef USE_CLIB
#ifdef USE_CLIB
#define beginth(sec,size,p1,p2,s,id) _beginthreadex(sec,size,p1,p2,s,id)
#define endth(x) _endthreadex(x)
#else
#define beginth(sec,size,p1,p2,s,id) CreateThread(sec,size,p1,p2,s,id)
#define endth(x) ExitThread(x)
#endif
/*
* mutexlite
*/
int lispd_make_mutexlite(mutexlite *ptr)
{
InitializeCriticalSection(ptr);
return 0;
}
int lispd_make_rwlocklite(rwlocklite *ptr)
{
InitializeSRWLock(ptr);
return 0;
}
/*
* semaphore windows
*/
int lispd_trylock_semwindows(semwindows *ptr)
{
DWORD result = WaitForSingleObject(*ptr, 0);
if (result == WAIT_TIMEOUT) return 1;
if (result != WAIT_OBJECT_0) {
Debug("WaitForSingleObject (trylock semaphore) error");
lispd_threaderror();
}
return 0;
}
/*
* binary semaphore [condition variable]
*/
void lispd_make_binsemlite(binsemlite *ptr)
{
lispd_make_mutexlite(&ptr->mutex);
lispd_make_condlite(&ptr->cond);
ptr->value = 1;
}
void lispd_destroy_binsemlite(binsemlite *ptr)
{
lispd_destroy_condlite(&ptr->cond);
lispd_destroy_mutexlite(&ptr->mutex);
}
void lispd_lock_binsemlite(binsemlite *ptr)
{
lispd_lock_mutexlite(&ptr->mutex);
while (ptr->value <= 0)
lispd_wait_condlite(&ptr->cond, &ptr->mutex);
ptr->value--;
lispd_unlock_mutexlite(&ptr->mutex);
}
void lispd_unlock_binsemlite(binsemlite *ptr)
{
lispd_lock_mutexlite(&ptr->mutex);
/* binary semaphore check */
if (1 <= ptr->value) {
lispd_unlock_mutexlite(&ptr->mutex);
Debug("lispd_unlock_binsemlite error");
lispd_threaderror();
}
/* semaphore */
if (ptr->value <= 0)
lispd_signal_condlite(&ptr->cond);
ptr->value++;
lispd_unlock_mutexlite(&ptr->mutex);
}
int lispd_trylock_binsemlite(binsemlite *ptr)
{
int result;
lispd_lock_mutexlite(&ptr->mutex);
if (ptr->value <= 0) {
result = 1;
}
else {
ptr->value--;
result = 0;
}
lispd_unlock_mutexlite(&ptr->mutex);
return result;
}
/*
* thread
*/
static DWORD WINAPI start_routine(LPVOID pvoid)
{
Execute arg;
arg = (Execute)pvoid;
set_execute_local(arg);
(*arg->routine)(arg);
setstate_execute(arg, ThreadState_Finish);
endth(0);
return 0;
}
int create_thread(execfunction proc, Execute arg)
{
HANDLE result;
result = beginth(NULL, 0, start_routine, (LPVOID)arg,
CREATE_SUSPENDED, &arg->handleid);
if (result == NULL) {
fprintf(stderr, "CreateThread error\n");
return 1;
}
arg->handle = result;
if (ResumeThread(result) < 0) {
fprintf(stderr, "ResumeThread error\n");
CloseHandle(result);
return 1;
}
return 0;
}
int join_thread(threadhandle *handle)
{
if (WaitForSingleObject(*handle, INFINITE) == WAIT_FAILED) {
fprintf(stderr, "WaitForSingleObject error\n");
return 1;
}
CloseHandle(*handle);
return 0;
}
#endif
/*
* tools
*/
void lispd_threaderror(void)
{
Abort("thread error");
}
void lispd_wrlock2_rwlocklite(rwlocklite *lock1, rwlocklite *lock2)
{
if (lock1 == lock2) {
lispd_wrlock_rwlocklite(lock1);
return;
}
if (lock2 < lock1)
goto trylock2;
trylock1:
lispd_wrlock_rwlocklite(lock1);
if (lispd_trywrlock_rwlocklite(lock2) == 0) return;
lispd_unwrlock_rwlocklite(lock1);
trylock2:
lispd_wrlock_rwlocklite(lock2);
if (lispd_trywrlock_rwlocklite(lock1) == 0) return;
lispd_unwrlock_rwlocklite(lock2);
goto trylock1;
}
void lispd_unwrlock2_rwlocklite(rwlocklite *lock1, rwlocklite *lock2)
{
if (lock1 == lock2) {
lispd_unwrlock_rwlocklite(lock1);
}
else {
lispd_unwrlock_rwlocklite(lock1);
lispd_unwrlock_rwlocklite(lock2);
}
}
#define SwapVariable(a,b,temp) { temp = a; a = b; b = temp; }
void lispd_wrlock3_rwlocklite(rwlocklite *m1, rwlocklite *m2, rwlocklite *m3)
{
int check1, check2;
rwlocklite *temp;
check1 = (m1 == m2);
check2 = (m2 == m3);
if (check1 && check2) {
lispd_wrlock_rwlocklite(m1);
}
else if (check1) {
lispd_wrlock2_rwlocklite(m2, m3);
}
else if (check2) {
lispd_wrlock2_rwlocklite(m3, m1);
}
else if (m3 == m1) {
lispd_wrlock2_rwlocklite(m1, m2);
}
else {
if (m2 < m1) SwapVariable(m2, m1, temp);
if (m3 < m1) SwapVariable(m3, m1, temp);
if (m3 < m2) SwapVariable(m3, m2, temp);
trylock1: /* m1->m2->m3 */
lispd_wrlock_rwlocklite(m1);
if (lispd_trywrlock_rwlocklite(m2) == 0) {
if (lispd_trywrlock_rwlocklite(m3) == 0) return;
lispd_unwrlock_rwlocklite(m2);
lispd_unwrlock_rwlocklite(m1);
goto trylock3;
}
lispd_unwrlock_rwlocklite(m1);
trylock2: /* m2->m3->m1 */
lispd_wrlock_rwlocklite(m2);
if (lispd_trywrlock_rwlocklite(m3) == 0) {
if (lispd_trywrlock_rwlocklite(m1) == 0) return;
lispd_unwrlock_rwlocklite(m3);
lispd_unwrlock_rwlocklite(m2);
goto trylock1;
}
lispd_unwrlock_rwlocklite(m2);
trylock3: /* m3->m1->m2 */
lispd_wrlock_rwlocklite(m3);
if (lispd_trywrlock_rwlocklite(m1) == 0) {
if (lispd_trywrlock_rwlocklite(m2) == 0) return;
lispd_unwrlock_rwlocklite(m1);
lispd_unwrlock_rwlocklite(m3);
goto trylock2;
}
lispd_unwrlock_rwlocklite(m3);
goto trylock1;
}
}
void lispd_unwrlock3_rwlocklite(rwlocklite *m1, rwlocklite *m2, rwlocklite *m3)
{
int check1, check2;
check1 = (m1 == m2);
check2 = (m2 == m3);
if (check1 && check2) {
lispd_unwrlock_rwlocklite(m1);
}
else if (check1) {
lispd_unwrlock_rwlocklite(m2);
lispd_unwrlock_rwlocklite(m3);
}
else if (check2) {
lispd_unwrlock_rwlocklite(m3);
lispd_unwrlock_rwlocklite(m1);
}
else if (m3 == m1) {
lispd_unwrlock_rwlocklite(m1);
lispd_unwrlock_rwlocklite(m2);
}
else {
lispd_unwrlock_rwlocklite(m1);
lispd_unwrlock_rwlocklite(m2);
lispd_unwrlock_rwlocklite(m3);
}
}
/************************************************************
* token.c
************************************************************/
/*
* token
*/
#define FLOATSIZE 64
#define FLOATBUFFER (FLOATSIZE * 2)
/*
* integer (fixnum, bignum)
*/
int getchar_digit(unsigned v, int upperp, unicode *ret)
{
if (IntegerBaseMax < v)
return 1;
if (v < 10)
*ret = '0' + v;
else
*ret = (upperp? 'A': 'a') + v - 10;
return 0;
}
int getvalue_digit(unsigned base, unicode c, unsigned *ret)
{
unsigned value;
if (('0' <= c) && (c <= '9')) {
value = c - '0';
}
else if ('a' <= c && c <= 'z') {
value = c - 'a' + 10;
}
else if ('A' <= c && c <= 'Z') {
value = c - 'A' + 10;
}
else {
return 1;
}
if (base <= value) {
return 1;
}
*ret = value;
return 0;
}
unicode checkchar_digit(unsigned v, int upperp)
{
unicode value;
if (getchar_digit(v, upperp, &value)) {
Abort("character error");
return 0;
}
return value;
}
unsigned checkvalue_digit(unsigned base, unicode c)
{
unsigned value;
if (getvalue_digit(base, c, &value)) {
Abort("character error");
return 0;
}
return value;
}
void maketoken_integer(LocalRoot local, addr queue, unsigned base, addr *ret)
{
int sign;
size_t i, m, size, max;
addr pos, cons;
unicode u;
LocalStack stack;
GetCharQueueSize(queue, &size);
GetCharQueueMax(queue, &max);
GetCharQueueRoot(queue, &pos);
push_local(local, &stack);
bigcons_local(local, &cons);
sign = 0;
for (i = 0; i < size; i++) {
m = i % max;
if (i && m == 0)
GetCharBitNext(pos, &pos);
GetCharBitChar(pos, m, &u);
if (u == '+' || u == '.')
continue;
if (u == '-') {
sign = 1;
continue;
}
push_bigcons(local, cons, base, checkvalue_digit(base, u));
}
integer_cons_heap(ret, sign, cons);
rollback_local(local, stack);
}
/*
* float
*/
static void makefloat_buffer(int sign, const char *fract, int exp, char *ret)
{
const char *tail;
if (fract[0] == 0) {
snprintf(ret, FLOATBUFFER, "%c0.0e0",
(sign? '-': '+'));
}
else {
tail = fract + 1;
snprintf(ret, FLOATBUFFER, "%c%c.%se%d",
(sign? '-': '+'),
fract[0],
(*fract && *tail)? tail: "0",
exp);
}
}
static int makefloat_single_(const char *ptr, addr *ret)
{
single_float value;
Return(check_strtof_(ptr, NULL, &value));
single_float_heap(ret, value);
return 0;
}
static int makefloat_double_(const char *ptr, addr *ret)
{
double_float value;
Return(check_strtod_(ptr, NULL, &value));
double_float_heap(ret, value);
return 0;
}
static int makefloat_long_(const char *ptr, addr *ret)
{
long_float value;
Return(check_strtold_(ptr, NULL, &value));
long_float_heap(ret, value);
return 0;
}
static int read_default_float_format_(Execute ptr, int *ret)
{
addr symbol, check;
GetConst(SPECIAL_READ_DEFAULT_FLOAT_FORMAT, &symbol);
Return(getspecialcheck_local_(ptr, symbol, &symbol));
GetConst(COMMON_SINGLE_FLOAT, &check);
if (symbol == check)
return Result(ret, 'f');
GetConst(COMMON_DOUBLE_FLOAT, &check);
if (symbol == check)
return Result(ret, 'd');
GetConst(COMMON_LONG_FLOAT, &check);
if (symbol == check)
return Result(ret, 'l');
GetConst(COMMON_SHORT_FLOAT, &check);
if (symbol == check)
return Result(ret, 's');
return Result(ret, 0); /* error */
}
static int makefloat_(Execute ptr,
int sign, const char *fract, int v, int type, addr *ret)
{
char buffer[FLOATBUFFER];
makefloat_buffer(sign, fract, v, buffer);
if (type == 'e') {
Return(read_default_float_format_(ptr, &type));
}
switch (type) {
case 's': /* short */
case 'f': /* single */
return makefloat_single_(buffer, ret);
case 'd': /* double */
return makefloat_double_(buffer, ret);
case 'l': /* long */
return makefloat_long_(buffer, ret);
default: /* error */
return Result(ret, Unbound);
}
}
static int atolcheck(const char *str, long *value)
{
long v;
char *endp;
errno = 0;
v = strtol(str, &endp, 10);
if (errno == ERANGE || errno == EINVAL)
return 1;
if (str == endp)
return 1;
*value = v;
return 0;
}
static int plus_safe(long a, long b, long *result)
{
if (((b > 0) && (a > (LONG_MAX - b)))
|| ((b < 0) && (a < (LONG_MIN - b)))) {
return 1;
}
*result = a + b;
return 0;
}
static int isexponent(unicode c)
{
/* "defslDEFSL" */
if (c == 'e' || c == 'E')
return 'e'; /* default */
if (c == 'f' || c == 'F')
return 'f'; /* single */
if (c == 'd' || c == 'D')
return 'd'; /* double */
if (c == 'l' || c == 'L')
return 'l'; /* long */
if (c == 's' || c == 'S')
return 's'; /* short */
return 0;
}
#define NextChar() (i < size? str[i++]: 0)
static int floattable_(Execute ptr, const unicode *str, size_t size, addr *ret)
{
int w, e, ds, zero, sign, type;
long v;
char fract[FLOATSIZE];
char exp[FLOATSIZE];
unicode c;
size_t i;
i = w = e = ds = 0;
zero = 0;
sign = 0;
type = 'e';
/* start */
c = NextChar();
if (c == '+') {
sign = 0;
c = NextChar();
}
else if (c == '-') {
sign = 1;
c = NextChar();
}
first:
if (c == 0)
goto final;
if (zero == 0 && c == '0') {
c = NextChar();
goto first;
}
if (isDigitCase(c)) {
if (zero == 0)
zero = 1;
else
ds++;
if (w < FLOATSIZE) fract[w] = (char)c;
w++;
c = NextChar();
goto first;
}
if (c == '.') {
goto fract;
}
type = isexponent(c);
if (type)
goto exponent;
goto error;
fract:
c = NextChar();
if (c == 0)
goto final;
if (zero == 0 && c == '0') {
ds--;
goto fract;
}
if (isDigitCase(c)) {
if (zero == 0) {
ds--;
zero = 1;
}
if (w < FLOATSIZE) fract[w] = (char)c;
w++;
goto fract;
}
type = isexponent(c);
if (type)
goto exponent;
goto error;
exponent:
c = NextChar();
if (c == '+') {
if (e < FLOATSIZE) exp[e++] = '+';
c = NextChar();
}
else if (c == '-') {
if (e < FLOATSIZE) exp[e++] = '-';
c = NextChar();
}
if (c == 0) {
if (e < FLOATSIZE) exp[e++] = '0';
goto final;
}
if (isDigitCase(c)) {
if (e < FLOATSIZE) exp[e++] = (char)c;
goto expnext;
}
goto error;
expnext:
c = NextChar();
if (c == 0)
goto final;
if (isDigitCase(c)) {
if (e < FLOATSIZE) exp[e++] = (char)c;
goto expnext;
}
goto error;
error:
return Result(ret, Unbound);
final:
if (zero == 0) {
fract[0] = 0;
return makefloat_(ptr, sign, fract, 0, type, ret);
}
fract[w < FLOATSIZE-1? w: FLOATSIZE-1] = 0;
exp[e] = 0;
v = 0;
if (e && atolcheck(exp, &v)) /* atol(exp) error */
return Result(ret, Unbound);
if (plus_safe(v, ds, &v)) /* v += ds; overflow */
return Result(ret, Unbound);
return makefloat_(ptr, sign, fract, (int)v, type, ret);
}
int maketoken_float_(Execute ptr, addr queue, addr *ret)
{
const unicode *body;
size_t size;
make_charqueue_heap(queue, &queue);
strvect_posbodylen(queue, &body, &size);
Return(floattable_(ptr, body, size, ret));
if (*ret == Unbound)
return fmte_("parse-float error", NULL);
return 0;
}
/*
* ratio: [-+]?\\d+/\\d+
*/
void maketoken_ratio(LocalRoot local, addr queue, unsigned base, addr *ret)
{
int sign;
size_t i, m, size, max;
addr pos, numer, denom, cons;
unicode u;
LocalStack stack;
GetCharQueueSize(queue, &size);
GetCharQueueMax(queue, &max);
GetCharQueueRoot(queue, &pos);
push_local(local, &stack);
bigcons_local(local, &cons);
/* numer */
sign = signplus_bignum;
for (i = 0; ; i++) {
Check(size <= i, "size error");
m = i % max;
if (i && m == 0)
GetCharBitNext(pos, &pos);
GetCharBitChar(pos, m, &u);
if (u == '+')
continue;
if (u == '-') {
sign = signminus_bignum;
continue;
}
if (u == '/') break;
push_bigcons(local, cons, base, checkvalue_digit(base, u));
}
bignum_cons_alloc(local, &numer, signplus_bignum, cons);
/* denom */
clear_bigcons(cons);
for (i++; i < size; i++) {
m = i % max;
if (i && m == 0)
GetCharBitNext(pos, &pos);
GetCharBitChar(pos, m, &u);
push_bigcons(local, cons, base, checkvalue_digit(base, u));
}
bignum_cons_alloc(local, &denom, signplus_bignum, cons);
/* result */
ratio_reduction_heap(local, ret, sign, numer, denom);
rollback_local(local, stack);
}
/************************************************************
* type.c
************************************************************/
/*
* check
*/
static int decl_function_p(LispDecl type)
{
return type == LISPDECL_FUNCTION
|| type == LISPDECL_COMPILED_FUNCTION;
}
static int decl_astert_p(LispDecl type)
{
return type == LISPDECL_ASTERISK
|| type == LISPDECL_T;
}
int decl_character_p(LispDecl type)
{
return type == LISPDECL_CHARACTER
|| type == LISPDECL_BASE_CHAR
|| type == LISPDECL_STANDARD_CHAR
|| type == LISPDECL_EXTENDED_CHAR;
}
int decl_float_p(LispDecl type)
{
return type == LISPDECL_FLOAT
|| type == LISPDECL_SINGLE_FLOAT
|| type == LISPDECL_DOUBLE_FLOAT
|| type == LISPDECL_LONG_FLOAT
|| type == LISPDECL_SHORT_FLOAT;
}
int decl_range_p(LispDecl type)
{
return type == LISPDECL_INTEGER
|| type == LISPDECL_RATIONAL
|| type == LISPDECL_REAL
|| decl_float_p(type);
}
int decl_subtypep_real(LispDecl left, LispDecl right)
{
switch (right) {
case LISPDECL_INTEGER:
return left == LISPDECL_INTEGER;
case LISPDECL_RATIONAL:
return left == LISPDECL_INTEGER
|| left == LISPDECL_RATIONAL;
case LISPDECL_REAL:
return left == LISPDECL_INTEGER
|| left == LISPDECL_RATIONAL
|| left == LISPDECL_REAL
|| decl_float_p(left);
case LISPDECL_FLOAT:
return decl_float_p(left);
case LISPDECL_SINGLE_FLOAT:
case LISPDECL_DOUBLE_FLOAT:
case LISPDECL_LONG_FLOAT:
case LISPDECL_SHORT_FLOAT:
return left == right;
default:
break;
}
return 0;
}
int type_error_p(addr pos)
{
return GetType(pos) == LISPTYPE_TYPE && RefLispDecl(pos) == LISPDECL_ERROR;
}
int type_function_p(addr pos)
{
return GetType(pos) == LISPTYPE_TYPE && decl_function_p(LowLispDecl(pos));
}
int type_astert_p(addr pos)
{
return GetType(pos) == LISPTYPE_TYPE && decl_astert_p(LowLispDecl(pos));
}
int type_function_aster_p(addr pos)
{
LispDecl type;
addr args, values;
if (GetType(pos) != LISPTYPE_TYPE)
return 0;
type = LowLispDecl(pos);
if (type != LISPDECL_FUNCTION && type != LISPDECL_COMPILED_FUNCTION)
return 0;
GetArrayType(pos, 0, &args);
GetArrayType(pos, 1, &values);
return type_asterisk_p(args) && type_asterisk_p(values);
}
int type_asterisk_p(addr pos)
{
return GetType(pos) == LISPTYPE_TYPE && LowLispDecl(pos) == LISPDECL_ASTERISK;
}
int type_range_p(addr pos)
{
CheckType(pos, LISPTYPE_TYPE);
return decl_range_p(LowLispDecl(pos));
}
int type_string_p(addr pos)
{
CheckType(pos, LISPTYPE_TYPE);
switch (LowLispDecl(pos)) {
case LISPDECL_STRING:
case LISPDECL_BASE_STRING:
case LISPDECL_SIMPLE_STRING:
case LISPDECL_SIMPLE_BASE_STRING:
return 1;
default:
return 0;
}
}
/*
* init
*/
void init_type(void)
{
init_type_coerce();
init_type_copy();
init_type_error();
init_type_name();
init_type_object();
init_type_parse();
init_type_symbol();
init_type_typep();
init_type_value();
}
void build_type(void)
{
build_type_table();
build_type_constant();
build_type_upgraded();
build_type_symbol();
build_type_parse();
}
/************************************************************
* type_coerce.c
************************************************************/
static int coerce_type_(Execute ptr, addr pos, addr type, addr *ret);
/*
* type
*/
static int coerce_error(Execute ptr, addr pos, addr type)
{
copyheap(&pos, pos);
copyheap(&type, type);
Return(type_object_(&type, type));
return call_type_error_va_(ptr, pos, type,
"Cannot covert value ~A to a ~S type.", pos, type, NULL);
}
static int coerce_typep(Execute ptr, addr pos, addr value, addr type, addr *ret)
{
int check;
Return(typep_clang_(ptr, value, type, &check));
if (! check)
return coerce_error(ptr, pos, type);
return Result(ret, value);
}
/*
* float
*/
static int coerce_fixnum_single(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_FIXNUM);
single_float_fixnum_heap(&value, pos);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_bignum_single(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_BIGNUM);
Return(single_float_bignum_heap_(&value, pos));
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_ratio_single(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_RATIO);
Return(single_float_ratio_heap_(&value, pos));
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_float(Execute ptr, addr pos, addr type, addr *ret)
{
CheckType(type, LISPTYPE_TYPE);
switch (GetType(pos)) {
case LISPTYPE_SINGLE_FLOAT:
case LISPTYPE_DOUBLE_FLOAT:
case LISPTYPE_LONG_FLOAT:
return coerce_typep(ptr, pos, pos, type, ret);
case LISPTYPE_FIXNUM:
return coerce_fixnum_single(ptr, pos, type, ret);
case LISPTYPE_BIGNUM:
return coerce_bignum_single(ptr, pos, type, ret);
case LISPTYPE_RATIO:
return coerce_ratio_single(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* single-float
*/
static int coerce_double_single(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
single_float v;
CheckType(pos, LISPTYPE_DOUBLE_FLOAT);
Return(cast_ds_value_(pos, &v));
single_float_heap(&value, v);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_long_single(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
single_float v;
CheckType(pos, LISPTYPE_LONG_FLOAT);
Return(cast_ls_value_(pos, &v));
single_float_heap(&value, v);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_single(Execute ptr, addr pos, addr type, addr *ret)
{
CheckType(type, LISPTYPE_TYPE);
switch (GetType(pos)) {
case LISPTYPE_SINGLE_FLOAT:
return coerce_typep(ptr, pos, pos, type, ret);
case LISPTYPE_DOUBLE_FLOAT:
return coerce_double_single(ptr, pos, type, ret);
case LISPTYPE_LONG_FLOAT:
return coerce_long_single(ptr, pos, type, ret);
case LISPTYPE_FIXNUM:
return coerce_fixnum_single(ptr, pos, type, ret);
case LISPTYPE_BIGNUM:
return coerce_bignum_single(ptr, pos, type, ret);
case LISPTYPE_RATIO:
return coerce_ratio_single(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* double-float
*/
static int coerce_single_double(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
double_float v;
CheckType(pos, LISPTYPE_SINGLE_FLOAT);
Return(cast_sd_value_(pos, &v));
double_float_heap(&value, v);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_long_double(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
double_float v;
CheckType(pos, LISPTYPE_LONG_FLOAT);
Return(cast_ld_value_(pos, &v));
double_float_heap(&value, v);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_fixnum_double(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_FIXNUM);
double_float_fixnum_heap(&value, pos);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_bignum_double(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_BIGNUM);
Return(double_float_bignum_heap_(&value, pos));
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_ratio_double(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_RATIO);
Return(double_float_ratio_heap_(&value, pos));
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_double(Execute ptr, addr pos, addr type, addr *ret)
{
CheckType(type, LISPTYPE_TYPE);
switch (GetType(pos)) {
case LISPTYPE_SINGLE_FLOAT:
return coerce_single_double(ptr, pos, type, ret);
case LISPTYPE_DOUBLE_FLOAT:
return coerce_typep(ptr, pos, pos, type, ret);
case LISPTYPE_LONG_FLOAT:
return coerce_long_double(ptr, pos, type, ret);
case LISPTYPE_FIXNUM:
return coerce_fixnum_double(ptr, pos, type, ret);
case LISPTYPE_BIGNUM:
return coerce_bignum_double(ptr, pos, type, ret);
case LISPTYPE_RATIO:
return coerce_ratio_double(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* long-float
*/
static int coerce_single_long(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
long_float v;
CheckType(pos, LISPTYPE_SINGLE_FLOAT);
Return(cast_sl_value_(pos, &v));
long_float_heap(&value, v);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_double_long(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
long_float v;
CheckType(pos, LISPTYPE_DOUBLE_FLOAT);
Return(cast_dl_value_(pos, &v));
long_float_heap(&value, v);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_fixnum_long(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_FIXNUM);
long_float_fixnum_heap(&value, pos);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_bignum_long(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_BIGNUM);
Return(long_float_bignum_heap_(&value, pos));
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_ratio_long(Execute ptr, addr pos, addr type, addr *ret)
{
addr value;
CheckType(pos, LISPTYPE_RATIO);
Return(long_float_ratio_heap_(&value, pos));
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_long(Execute ptr, addr pos, addr type, addr *ret)
{
CheckType(type, LISPTYPE_TYPE);
switch (GetType(pos)) {
case LISPTYPE_SINGLE_FLOAT:
return coerce_single_long(ptr, pos, type, ret);
case LISPTYPE_DOUBLE_FLOAT:
return coerce_double_long(ptr, pos, type, ret);
case LISPTYPE_LONG_FLOAT:
return coerce_typep(ptr, pos, pos, type, ret);
case LISPTYPE_FIXNUM:
return coerce_fixnum_long(ptr, pos, type, ret);
case LISPTYPE_BIGNUM:
return coerce_bignum_long(ptr, pos, type, ret);
case LISPTYPE_RATIO:
return coerce_ratio_long(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* complex
*/
static int coerce_complex_complex(Execute ptr, addr pos, addr type, addr *ret)
{
addr real, imag;
LocalHold hold;
GetArrayType(type, 0, &type);
GetRealComplex(pos, &real);
GetImagComplex(pos, &imag);
Return(coerce_type_(ptr, real, type, &real));
hold = LocalHold_local_push(ptr, real);
Return(coerce_type_(ptr, imag, type, &imag));
localhold_end(hold);
Return(complex_heap_(ret, real, imag));
return 0;
}
static int coerce_complex_real(Execute ptr, addr pos, addr type, addr *ret)
{
GetArrayType(type, 0, &type);
if (! type_asterisk_p(type)) {
Return(coerce_type_(ptr, pos, type, &pos));
}
return complex_heap_(ret, pos, fixnumh(0));
}
static int coerce_complex(Execute ptr, addr pos, addr type, addr *ret)
{
if (complexp(pos))
return coerce_complex_complex(ptr, pos, type, ret);
if (realp(pos))
return coerce_complex_real(ptr, pos, type, ret);
else
return coerce_typep(ptr, pos, pos, type, ret);
}
/*
* charcter
*/
static int coerce_unicode_character(Execute ptr,
addr pos, unicode c, addr type, addr *ret)
{
addr value;
character_heap(&value, c);
return coerce_typep(ptr, pos, value, type, ret);
}
static int coerce_string_character(Execute ptr, addr pos, addr type, addr *ret)
{
unicode c;
size_t size;
string_length(pos, &size);
if (size != 1)
return coerce_error(ptr, pos, type);
Return(string_getc_(pos, 0, &c));
return coerce_unicode_character(ptr, pos, c, type, ret);
}
static int coerce_symbol_character(Execute ptr, addr pos, addr type, addr *ret)
{
addr name;
unicode c;
size_t size;
GetNameSymbol(pos, &name);
string_length(name, &size);
if (size != 1)
return coerce_error(ptr, pos, type);
Return(string_getc_(name, 0, &c));
return coerce_unicode_character(ptr, pos, c, type, ret);
}
static int coerce_character(Execute ptr, addr pos, addr type, addr *ret)
{
/* (or symbol string character) */
if (stringp(pos))
return coerce_string_character(ptr, pos, type, ret);
else if (symbolp(pos))
return coerce_symbol_character(ptr, pos, type, ret);
else
return coerce_typep(ptr, pos, pos, type, ret);
}
/*
* function
*/
static int coerce_function(Execute ptr, addr pos, addr type, addr *ret)
{
addr call;
if (symbolp(pos)) {
Return(getfunction_global_(pos, &call));
return coerce_typep(ptr, pos, call, type, ret);
}
else {
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* list
*/
static int coerce_vector_list(Execute ptr, addr pos, addr type, addr *ret)
{
addr list, x;
size_t size, i;
lenarray(pos, &size);
list = Nil;
for (i = 0; i < size; i++) {
getarray(pos, i, &x);
cons_heap(&list, x, list);
}
nreverse(&list, list);
return coerce_typep(ptr, pos, list, type, ret);
}
static int coerce_string_list(Execute ptr, addr pos, addr type, addr *ret)
{
unicode c;
addr list, x;
size_t size, i;
strvect_length(pos, &size);
list = Nil;
for (i = 0; i < size; i++) {
strvect_getc(pos, i, &c);
character_heap(&x, c);
cons_heap(&list, x, list);
}
nreverse(&list, list);
return coerce_typep(ptr, pos, list, type, ret);
}
static int coerce_array_list(Execute ptr, addr pos, addr type, addr *ret)
{
addr list, x;
size_t size, i;
/* not vector */
if (! array_vector_p(pos))
return coerce_typep(ptr, pos, type, type, ret);
/* cast list */
list = Nil;
Return(array_get_vector_length_(pos, 1, &size));
for (i = 0; i < size; i++) {
Return(array_get_(NULL, pos, i, &x));
cons_heap(&list, x, list);
}
nreverse(&list, list);
return coerce_typep(ptr, pos, list, type, ret);
}
static int coerce_bitvector_list(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr list, x;
size_t size, i;
Return(bitvector_length_(pos, &size));
list = Nil;
for (i = 0; i < size; i++) {
Return(bitvector_getint_(pos, i, &v));
fixnum_heap(&x, (fixnum)v);
cons_heap(&list, x, list);
}
nreverse(&list, list);
return coerce_typep(ptr, pos, list, type, ret);
}
static int coerce_list(Execute ptr, addr pos, addr type, addr *ret)
{
switch (GetType(pos)) {
case LISPTYPE_VECTOR:
return coerce_vector_list(ptr, pos, type, ret);
case LISPTYPE_STRING:
return coerce_string_list(ptr, pos, type, ret);
case LISPTYPE_ARRAY:
return coerce_array_list(ptr, pos, type, ret);
case LISPTYPE_BITVECTOR:
return coerce_bitvector_list(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* array
*/
/* array.bit -> array.t */
static int coerce_aa_bit_t(Execute ptr, addr pos, addr type, addr *ret)
{
int bit, check;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_bit_(pos, i, &bit, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)bit);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.character -> array.t */
static int coerce_aa_character_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
unicode c;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_character_(pos, i, &c, &check));
if (check)
return coerce_error(ptr, pos, type);
character_heap(&value, c);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.signed8 -> array.t */
static int coerce_aa_signed8_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int8_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_signed8_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.signed16 -> array.t */
static int coerce_aa_signed16_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int16_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_signed16_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.signed32 -> array.t */
static int coerce_aa_signed32_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int32_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_signed32_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* array.signed64 -> array.t */
static int coerce_aa_signed64_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int64_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_signed64_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* array.signed -> array.t */
static int coerce_aa_signed_t(Execute ptr,
addr pos, addr type, unsigned size, addr *ret)
{
switch (size) {
case 8:
return coerce_aa_signed8_t(ptr, pos, type, ret);
case 16:
return coerce_aa_signed16_t(ptr, pos, type, ret);
case 32:
return coerce_aa_signed32_t(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_aa_signed64_t(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* array.unsigned8 -> array.t */
static int coerce_aa_unsigned8_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint8_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned8_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.unsigned16 -> array.t */
static int coerce_aa_unsigned16_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint16_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned16_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
fixnum_heap(&value, (fixnum)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.unsigned32 -> array.t */
static int coerce_aa_unsigned32_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint32_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned32_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
#ifdef LISP_64BIT
fixnum_heap(&value, (fixnum)v);
#else
integer_fixed_heap(&value, SignPlus, (fixed)v);
#endif
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* array.unsigned64 -> array.t */
static int coerce_aa_unsigned64_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint64_t v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned64_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
integer_fixed_heap(&value, SignPlus, (fixed)v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* array.unsigned -> array.t */
static int coerce_aa_unsigned_t(Execute ptr,
addr pos, addr type, unsigned size, addr *ret)
{
switch (size) {
case 8:
return coerce_aa_unsigned8_t(ptr, pos, type, ret);
case 16:
return coerce_aa_unsigned16_t(ptr, pos, type, ret);
case 32:
return coerce_aa_unsigned32_t(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_aa_unsigned64_t(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* array.single-float -> array.t */
static int coerce_aa_single_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
single_float v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_single_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
single_float_heap(&value, v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.double-float -> array.t */
static int coerce_aa_double_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
double_float v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_double_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
double_float_heap(&value, v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.long-float -> array.t */
static int coerce_aa_long_t(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
long_float v;
addr array, value;
size_t size, i;
/* make general array */
Return(array_coerce_t_heap_(&array, pos));
array_get_rowlength(pos, &size);
for (i = 0; i < size; i++) {
Return(array_coerce_long_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
long_float_heap(&value, v);
Return(array_set_(array, i, value));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array -> array.t */
static int coerce_aa_t(Execute ptr, addr pos, addr type, addr *ret)
{
struct array_struct *str;
str = ArrayInfoStruct(pos);
switch (str->type) {
case ARRAY_TYPE_T:
return coerce_typep(ptr, pos, pos, type, ret);
case ARRAY_TYPE_BIT:
return coerce_aa_bit_t(ptr, pos, type, ret);
case ARRAY_TYPE_CHARACTER:
return coerce_aa_character_t(ptr, pos, type, ret);
case ARRAY_TYPE_SIGNED:
return coerce_aa_signed_t(ptr, pos, type, str->bytesize, ret);
case ARRAY_TYPE_UNSIGNED:
return coerce_aa_unsigned_t(ptr, pos, type, str->bytesize, ret);
case ARRAY_TYPE_SINGLE_FLOAT:
return coerce_aa_single_t(ptr, pos, type, ret);
case ARRAY_TYPE_DOUBLE_FLOAT:
return coerce_aa_double_t(ptr, pos, type, ret);
case ARRAY_TYPE_LONG_FLOAT:
return coerce_aa_long_t(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.t -> bitvector */
static int coerce_aa_bitvector(Execute ptr, addr pos, addr type, addr *ret)
{
int v, check;
addr vector;
size_t size, i;
array_get_rowlength(pos, &size);
bitmemory_unsafe(NULL, &vector, size);
for (i = 0; i < size; i++) {
Return(array_coerce_bit_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(bitmemory_setint_(vector, i, v));
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* array.* -> array.bit */
static int coerce_aa_type_bit(Execute ptr, addr pos, addr type, addr *ret)
{
int v, check;
addr array;
size_t size, i;
/* bit-vector */
if (array_vector_p(pos))
return coerce_aa_bitvector(ptr, pos, type, ret);
/* array.bit */
array_get_rowlength(pos, &size);
Return(array_coerce_bit_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_bit_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_bit_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array -> array.bit */
static int coerce_aa_bit(Execute ptr, addr pos, addr type, addr *ret)
{
struct array_struct *str;
str = ArrayInfoStruct(pos);
switch (str->type) {
case ARRAY_TYPE_T:
case ARRAY_TYPE_BIT:
case ARRAY_TYPE_SIGNED:
case ARRAY_TYPE_UNSIGNED:
return coerce_aa_type_bit(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.t -> string */
static int coerce_aa_string(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
unicode v;
addr vector;
size_t size, i;
array_get_rowlength(pos, &size);
strvect_heap(&vector, size);
for (i = 0; i < size; i++) {
Return(array_coerce_character_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(strvect_setc_(vector, i, v));
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* array.t -> array.character */
static int coerce_aa_t_character(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
unicode v;
addr array;
size_t size, i;
/* bit-vector */
if (array_vector_p(pos))
return coerce_aa_string(ptr, pos, type, ret);
/* array.bit */
array_get_rowlength(pos, &size);
Return(array_coerce_character_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_character_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_character_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array -> array.character */
static int coerce_aa_character(Execute ptr, addr pos, addr type, addr *ret)
{
struct array_struct *str;
str = ArrayInfoStruct(pos);
switch (str->type) {
case ARRAY_TYPE_T:
return coerce_aa_t_character(ptr, pos, type, ret);
case ARRAY_TYPE_CHARACTER:
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.* -> array.signed8 */
static int coerce_aa_signed8(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int8_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_signed8_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_signed8_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed8_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.* -> array.signed16 */
static int coerce_aa_signed16(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int16_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_signed16_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_signed16_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed16_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.* -> array.signed32 */
static int coerce_aa_signed32(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int32_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_signed32_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_signed32_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed32_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* array.* -> array.signed64 */
static int coerce_aa_signed64(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int64_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_signed64_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_signed64_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed64_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* array.* -> array.signed */
static int coerce_aa_type_signed(Execute ptr,
addr pos, addr type, unsigned size, addr *ret)
{
switch (size) {
case 8:
return coerce_aa_signed8(ptr, pos, type, ret);
case 16:
return coerce_aa_signed16(ptr, pos, type, ret);
case 32:
return coerce_aa_signed32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_aa_signed64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* array -> array.signed */
static int type_second_size(addr type, unsigned *ret)
{
enum LISPDECL decl;
addr check;
size_t size;
/* type check */
decl = LowLispDecl(type);
if (decl != LISPDECL_ARRAY && decl != LISPDECL_SIMPLE_ARRAY)
return 1;
/* upgraded type check */
GetArrayType(type, 0, &check);
decl = LowLispDecl(check);
if (decl != LISPDECL_SIGNED_BYTE && decl != LISPDECL_UNSIGNED_BYTE)
return 1;
/* (array (signed-byte size) *) */
GetArrayType(check, 0, &check);
if (GetIndex_integer(check, &size))
return 1;
switch (size) {
case 8:
case 16:
case 32:
#ifdef LISP_64BIT
case 64:
#endif
*ret = (unsigned)size;
return 0;
default:
return 1;
}
}
static int coerce_aa_signed(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
struct array_struct *str;
str = ArrayInfoStruct(pos);
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (str->type) {
case ARRAY_TYPE_T:
case ARRAY_TYPE_BIT:
case ARRAY_TYPE_SIGNED:
case ARRAY_TYPE_UNSIGNED:
return coerce_aa_type_signed(ptr, pos, type, size, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.* -> array.unsigned8 */
static int coerce_aa_unsigned8(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint8_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_unsigned8_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned8_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned8_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.* -> array.unsigned16 */
static int coerce_aa_unsigned16(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint16_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_unsigned16_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned16_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned16_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array.* -> array.unsigned32 */
static int coerce_aa_unsigned32(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint32_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_unsigned32_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned32_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned32_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* array.* -> array.unsigned64 */
static int coerce_aa_unsigned64(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint64_t v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_unsigned64_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_unsigned64_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned64_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* array.* -> array.unsigned */
static int coerce_aa_type_unsigned(Execute ptr,
addr pos, addr type, unsigned size, addr *ret)
{
switch (size) {
case 8:
return coerce_aa_unsigned8(ptr, pos, type, ret);
case 16:
return coerce_aa_unsigned16(ptr, pos, type, ret);
case 32:
return coerce_aa_unsigned32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_aa_unsigned64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* array -> array.unsigned */
static int coerce_aa_unsigned(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
struct array_struct *str;
str = ArrayInfoStruct(pos);
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (str->type) {
case ARRAY_TYPE_T:
case ARRAY_TYPE_BIT:
case ARRAY_TYPE_SIGNED:
case ARRAY_TYPE_UNSIGNED:
return coerce_aa_type_unsigned(ptr, pos, type, size, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.float -> array.single */
static int coerce_aa_type_single(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
single_float v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_single_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_single_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_single_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array -> array.single-float */
static int coerce_aa_single(Execute ptr, addr pos, addr type, addr *ret)
{
struct array_struct *str;
str = ArrayInfoStruct(pos);
switch (str->type) {
case ARRAY_TYPE_T:
case ARRAY_TYPE_BIT:
case ARRAY_TYPE_SIGNED:
case ARRAY_TYPE_UNSIGNED:
case ARRAY_TYPE_DOUBLE_FLOAT:
case ARRAY_TYPE_LONG_FLOAT:
return coerce_aa_type_single(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.float -> array.double */
static int coerce_aa_type_double(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
double_float v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_double_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_double_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_double_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array -> array.double-float */
static int coerce_aa_double(Execute ptr, addr pos, addr type, addr *ret)
{
struct array_struct *str;
str = ArrayInfoStruct(pos);
switch (str->type) {
case ARRAY_TYPE_T:
case ARRAY_TYPE_BIT:
case ARRAY_TYPE_SIGNED:
case ARRAY_TYPE_UNSIGNED:
case ARRAY_TYPE_SINGLE_FLOAT:
case ARRAY_TYPE_LONG_FLOAT:
return coerce_aa_type_double(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array.float -> array.long */
static int coerce_aa_type_long(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
long_float v;
addr array;
size_t size, i;
array_get_rowlength(pos, &size);
Return(array_coerce_long_heap_(&array, pos));
for (i = 0; i < size; i++) {
Return(array_coerce_long_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_long_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* array -> array.long-float */
static int coerce_aa_long(Execute ptr, addr pos, addr type, addr *ret)
{
struct array_struct *str;
str = ArrayInfoStruct(pos);
switch (str->type) {
case ARRAY_TYPE_T:
case ARRAY_TYPE_BIT:
case ARRAY_TYPE_SIGNED:
case ARRAY_TYPE_UNSIGNED:
case ARRAY_TYPE_SINGLE_FLOAT:
case ARRAY_TYPE_DOUBLE_FLOAT:
return coerce_aa_type_long(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* array -> array */
static int coerce_aa(Execute ptr, addr pos, addr type, addr *ret)
{
addr upg;
/* (array * .) */
GetArrayType(type, 0, &upg);
if (type_asterisk_p(upg))
return coerce_typep(ptr, pos, pos, type, ret);
/* (array upg .) */
switch (LowLispDecl(upg)) {
case LISPDECL_T:
return coerce_aa_t(ptr, pos, type, ret);
case LISPDECL_BIT:
return coerce_aa_bit(ptr, pos, type, ret);
case LISPDECL_CHARACTER:
return coerce_aa_character(ptr, pos, type, ret);
case LISPDECL_SIGNED_BYTE:
return coerce_aa_signed(ptr, pos, type, ret);
case LISPDECL_UNSIGNED_BYTE:
return coerce_aa_unsigned(ptr, pos, type, ret);
case LISPDECL_SINGLE_FLOAT:
return coerce_aa_single(ptr, pos, type, ret);
case LISPDECL_DOUBLE_FLOAT:
return coerce_aa_double(ptr, pos, type, ret);
case LISPDECL_LONG_FLOAT:
return coerce_aa_long(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* vector -> array.bit */
static int coerce_av_bit(Execute ptr, addr pos, addr type, addr *ret)
{
int v, check;
addr vector;
size_t size, i;
lenarray(pos, &size);
bitmemory_unsafe(NULL, &vector, size);
for (i = 0; i < size; i++) {
Return(vector_coerce_bit_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(bitmemory_setint_(vector, i, v));
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* vector -> array.character */
static int coerce_av_character(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
unicode v;
addr vector;
size_t size, i;
lenarray(pos, &size);
strvect_heap(&vector, size);
for (i = 0; i < size; i++) {
Return(vector_coerce_character_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(strvect_setc_(vector, i, v));
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* vector -> array.signed8 */
static int coerce_av_signed8(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int8_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_signed8_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_signed8_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed8_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array.signed16 */
static int coerce_av_signed16(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int16_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_signed16_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_signed16_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed16_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array.signed32 */
static int coerce_av_signed32(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int32_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_signed32_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_signed32_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed32_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* vector -> array.signed64 */
static int coerce_av_signed64(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int64_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_signed64_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_signed64_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed64_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* vector -> array.signed */
static int coerce_av_signed(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (size) {
case 8:
return coerce_av_signed8(ptr, pos, type, ret);
case 16:
return coerce_av_signed16(ptr, pos, type, ret);
case 32:
return coerce_av_signed32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_av_signed64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* vector -> array.unsigned8 */
static int coerce_av_unsigned8(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint8_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_unsigned8_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_unsigned8_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned8_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array.unsigned16 */
static int coerce_av_unsigned16(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint16_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_unsigned16_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_unsigned16_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned16_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array.unsigned32 */
static int coerce_av_unsigned32(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint32_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_unsigned32_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_unsigned32_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned32_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* vector -> array.unsigned64 */
static int coerce_av_unsigned64(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint64_t v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_unsigned64_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_unsigned64_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned64_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* vector -> array.unsigned */
static int coerce_av_unsigned(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (size) {
case 8:
return coerce_av_unsigned8(ptr, pos, type, ret);
case 16:
return coerce_av_unsigned16(ptr, pos, type, ret);
case 32:
return coerce_av_unsigned32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_av_unsigned64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* vector -> array.single-float */
static int coerce_av_single(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
single_float v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_single_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_single_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_single_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array.double-float */
static int coerce_av_double(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
double_float v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_double_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_double_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_double_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array.long-float */
static int coerce_av_long(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
long_float v;
addr array;
size_t size, i;
lenarray(pos, &size);
Return(vector_coerce_long_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(vector_coerce_long_(pos, i, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_long_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* vector -> array */
static int coerce_av(Execute ptr, addr pos, addr type, addr *ret)
{
addr upg;
/* (array * .) */
GetArrayType(type, 0, &upg);
if (type_asterisk_p(upg))
return coerce_typep(ptr, pos, pos, type, ret);
/* (array upg .) */
switch (LowLispDecl(upg)) {
case LISPDECL_T:
return coerce_typep(ptr, pos, pos, type, ret);
case LISPDECL_BIT:
return coerce_av_bit(ptr, pos, type, ret);
case LISPDECL_CHARACTER:
return coerce_av_character(ptr, pos, type, ret);
case LISPDECL_SIGNED_BYTE:
return coerce_av_signed(ptr, pos, type, ret);
case LISPDECL_UNSIGNED_BYTE:
return coerce_av_unsigned(ptr, pos, type, ret);
case LISPDECL_SINGLE_FLOAT:
return coerce_av_single(ptr, pos, type, ret);
case LISPDECL_DOUBLE_FLOAT:
return coerce_av_double(ptr, pos, type, ret);
case LISPDECL_LONG_FLOAT:
return coerce_av_long(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* string -> array.t */
static int coerce_as_t(Execute ptr, addr pos, addr type, addr *ret)
{
unicode c;
addr vector, value;
size_t size, i;
strvect_length(pos, &size);
vector_heap(&vector, size);
for (i = 0; i < size; i++) {
strvect_getc(pos, i, &c);
character_heap(&value, c);
setarray(vector, i, value);
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* string -> array */
static int coerce_as(Execute ptr, addr pos, addr type, addr *ret)
{
addr upg;
/* (array * .) */
GetArrayType(type, 0, &upg);
if (type_asterisk_p(upg))
return coerce_typep(ptr, pos, pos, type, ret);
/* (array upg .) */
switch (LowLispDecl(upg)) {
case LISPDECL_T:
return coerce_as_t(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* bit-vector -> array.t */
static int coerce_ab_t(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr vector, value;
size_t size, i;
bitmemory_length(pos, &size);
vector_heap(&vector, size);
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
fixnum_heap(&value, (fixnum)v);
setarray(vector, i, value);
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* bit-vector -> array.signed8 */
static int coerce_ab_signed8(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_signed8_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_signed8_(array, i, (int8_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* bit-vector -> array.signed16 */
static int coerce_ab_signed16(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_signed16_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_signed16_(array, i, (int16_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* bit-vector -> array.signed32 */
static int coerce_ab_signed32(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_signed32_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_signed32_(array, i, (int32_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* bit-vector -> array.signed64 */
static int coerce_ab_signed64(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_signed64_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_signed64_(array, i, (int64_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* bit-vector -> array.signed */
static int coerce_ab_signed(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (size) {
case 8:
return coerce_ab_signed8(ptr, pos, type, ret);
case 16:
return coerce_ab_signed16(ptr, pos, type, ret);
case 32:
return coerce_ab_signed32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_ab_signed64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* bit-vector -> array.unsigned8 */
static int coerce_ab_unsigned8(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_unsigned8_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_unsigned8_(array, i, (uint8_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* bit-vector -> array.unsigned16 */
static int coerce_ab_unsigned16(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_unsigned16_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_unsigned16_(array, i, (uint16_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* bit-vector -> array.unsigned32 */
static int coerce_ab_unsigned32(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_unsigned32_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_unsigned32_(array, i, (uint32_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* bit-vector -> array.unsigned64 */
static int coerce_ab_unsigned64(Execute ptr, addr pos, addr type, addr *ret)
{
int v;
addr array;
size_t size, i;
bitmemory_length(pos, &size);
Return(vector_coerce_unsigned64_heap_(&array, size));
for (i = 0; i < size; i++) {
Return(bitmemory_getint_(pos, i, &v));
Return(array_set_unsigned64_(array, i, (uint64_t)v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* bit-vector -> array.unsigned */
static int coerce_ab_unsigned(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (size) {
case 8:
return coerce_ab_unsigned8(ptr, pos, type, ret);
case 16:
return coerce_ab_unsigned16(ptr, pos, type, ret);
case 32:
return coerce_ab_unsigned32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_ab_unsigned64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* bit-vector -> array */
static int coerce_ab(Execute ptr, addr pos, addr type, addr *ret)
{
addr upg;
/* (array * .) */
GetArrayType(type, 0, &upg);
if (type_asterisk_p(upg))
return coerce_typep(ptr, pos, pos, type, ret);
/* (array upg .) */
switch (LowLispDecl(upg)) {
case LISPDECL_T:
return coerce_ab_t(ptr, pos, type, ret);
case LISPDECL_SIGNED_BYTE:
return coerce_ab_signed(ptr, pos, type, ret);
case LISPDECL_UNSIGNED_BYTE:
return coerce_ab_unsigned(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* list -> array.bit */
static int coerce_al_t(Execute ptr, addr pos, addr type, addr *ret)
{
addr vector, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
vector_heap(&vector, size);
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
setarray(vector, i, value);
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* list -> array.bit */
static int coerce_al_bit(Execute ptr, addr pos, addr type, addr *ret)
{
int v, check;
addr vector, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
bitmemory_unsafe(NULL, &vector, size);
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_bit_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(bitmemory_setint_(vector, i, v));
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* list -> array.character */
static int coerce_al_character(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
unicode v;
addr vector, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
strvect_heap(&vector, size);
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_character_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(strvect_setc_(vector, i, v));
}
return coerce_typep(ptr, pos, vector, type, ret);
}
/* list -> array.signed8 */
static int coerce_al_signed8(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int8_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_signed8_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_signed8_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed8_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array.signed16 */
static int coerce_al_signed16(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int16_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_signed16_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_signed16_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed16_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array.signed32 */
static int coerce_al_signed32(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int32_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_signed32_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_signed32_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed32_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* list -> array.signed64 */
static int coerce_al_signed64(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
int64_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_signed64_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_signed64_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_signed64_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* list -> array.signed */
static int coerce_al_signed(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (size) {
case 8:
return coerce_al_signed8(ptr, pos, type, ret);
case 16:
return coerce_al_signed16(ptr, pos, type, ret);
case 32:
return coerce_al_signed32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_al_signed64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* list -> array.unsigned8 */
static int coerce_al_unsigned8(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint8_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_unsigned8_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_unsigned8_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned8_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array.unsigned16 */
static int coerce_al_unsigned16(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint16_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_unsigned16_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_unsigned16_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned16_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array.unsigned32 */
static int coerce_al_unsigned32(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint32_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_unsigned32_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_unsigned32_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned32_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#ifdef LISP_64BIT
/* list -> array.unsigned64 */
static int coerce_al_unsigned64(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
uint64_t v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_unsigned64_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_unsigned64_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_unsigned64_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
#endif
/* list -> array.unsigned */
static int coerce_al_unsigned(Execute ptr, addr pos, addr type, addr *ret)
{
unsigned size;
if (type_second_size(type, &size))
return coerce_typep(ptr, pos, pos, type, ret);
switch (size) {
case 8:
return coerce_al_unsigned8(ptr, pos, type, ret);
case 16:
return coerce_al_unsigned16(ptr, pos, type, ret);
case 32:
return coerce_al_unsigned32(ptr, pos, type, ret);
#ifdef LISP_64BIT
case 64:
return coerce_al_unsigned64(ptr, pos, type, ret);
#endif
default:
return coerce_error(ptr, pos, type);
}
}
/* list -> array.single-float */
static int coerce_al_single(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
single_float v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_single_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_single_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_single_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array.double-float */
static int coerce_al_double(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
double_float v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_double_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_double_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_double_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array.long-float */
static int coerce_al_long(Execute ptr, addr pos, addr type, addr *ret)
{
int check;
long_float v;
addr array, value;
size_t size, i;
Return(length_list_safe_(pos, &size));
Return(vector_coerce_long_heap_(&array, size));
for (i = 0; i < size; i++) {
GetCons(pos, &value, &pos);
Return(array_coerce_long_t_(value, &v, &check));
if (check)
return coerce_error(ptr, pos, type);
Return(array_set_long_(array, i, v));
}
return coerce_typep(ptr, pos, array, type, ret);
}
/* list -> array */
static int coerce_al(Execute ptr, addr pos, addr type, addr *ret)
{
addr upg;
/* (array * .) */
GetArrayType(type, 0, &upg);
if (type_asterisk_p(upg))
return coerce_al_t(ptr, pos, type, ret);
/* (array upg .) */
switch (LowLispDecl(upg)) {
case LISPDECL_T:
return coerce_al_t(ptr, pos, type, ret);
case LISPDECL_BIT:
return coerce_al_bit(ptr, pos, type, ret);
case LISPDECL_CHARACTER:
return coerce_al_character(ptr, pos, type, ret);
case LISPDECL_SIGNED_BYTE:
return coerce_al_signed(ptr, pos, type, ret);
case LISPDECL_UNSIGNED_BYTE:
return coerce_al_unsigned(ptr, pos, type, ret);
case LISPDECL_SINGLE_FLOAT:
return coerce_al_single(ptr, pos, type, ret);
case LISPDECL_DOUBLE_FLOAT:
return coerce_al_double(ptr, pos, type, ret);
case LISPDECL_LONG_FLOAT:
return coerce_al_long(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/* ? -> array */
static int coerce_array(Execute ptr, addr pos, addr type, addr *ret)
{
switch (GetType(pos)) {
case LISPTYPE_ARRAY:
return coerce_aa(ptr, pos, type, ret);
case LISPTYPE_VECTOR:
return coerce_av(ptr, pos, type, ret);
case LISPTYPE_STRING:
return coerce_as(ptr, pos, type, ret);
case LISPTYPE_BITVECTOR:
return coerce_ab(ptr, pos, type, ret);
case LISPTYPE_CONS:
case LISPTYPE_NIL:
return coerce_al(ptr, pos, type, ret);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
/*
* table
*/
typedef int (*coerce_call)(Execute ptr, addr pos, addr type, addr *ret);
static coerce_call CoerceTable[LISPDECL_SIZE];
void init_type_coerce(void)
{
cleartype(CoerceTable);
/* number */
CoerceTable[LISPDECL_FLOAT] = coerce_float;
CoerceTable[LISPDECL_SHORT_FLOAT] = coerce_single; /* single */
CoerceTable[LISPDECL_SINGLE_FLOAT] = coerce_single;
CoerceTable[LISPDECL_DOUBLE_FLOAT] = coerce_double;
CoerceTable[LISPDECL_LONG_FLOAT] = coerce_long;
CoerceTable[LISPDECL_COMPLEX] = coerce_complex;
CoerceTable[LISPDECL_CHARACTER] = coerce_character;
CoerceTable[LISPDECL_BASE_CHAR] = coerce_character;
CoerceTable[LISPDECL_STANDARD_CHAR] = coerce_character;
CoerceTable[LISPDECL_EXTENDED_CHAR] = coerce_character;
CoerceTable[LISPDECL_FUNCTION] = coerce_function;
CoerceTable[LISPDECL_COMPILED_FUNCTION] = coerce_function;
/* list */
CoerceTable[LISPDECL_LIST] = coerce_list;
CoerceTable[LISPDECL_CONS] = coerce_list;
/* array */
CoerceTable[LISPDECL_ARRAY] = coerce_array;
CoerceTable[LISPDECL_SIMPLE_ARRAY] = coerce_array;
}
static int coerce_table(Execute ptr, addr pos, addr type, addr *ret)
{
enum LISPDECL decl;
coerce_call call;
CheckType(type, LISPTYPE_TYPE);
if (! RefNotDecl(type)) {
decl = LowLispDecl(type);
/* call table */
call = CoerceTable[(int)decl];
if (call)
return (*call)(ptr, pos, type, ret);
}
/* others */
return Result(ret, Unbound);
}
static int coerce_optimize(Execute ptr, addr pos, addr type, addr *ret)
{
int ignore;
LocalRoot local;
LocalStack stack;
local = Local_Thread;
push_local(local, &stack);
Return(type_optimize_local_(local, type, &type, &ignore));
get_type_optimized(&type, type);
Return(coerce_table(ptr, pos, type, ret));
rollback_local(local, stack);
return 0;
}
static int coerce_type_call(Execute ptr, addr pos, addr type, addr *ret)
{
addr check;
CheckType(type, LISPTYPE_TYPE);
if (! RefNotDecl(type)) {
Return(coerce_table(ptr, pos, type, &check));
if (check != Unbound)
return Result(ret, check);
}
Return(coerce_optimize(ptr, pos, type, &check));
if (check != Unbound)
return Result(ret, check);
return coerce_typep(ptr, pos, pos, type, ret);
}
static int coerce_type_(Execute ptr, addr pos, addr type, addr *ret)
{
LocalHold hold;
hold = LocalHold_local(ptr);
localhold_pushva(hold, pos, type, NULL);
Return(coerce_type_call(ptr, pos, type, ret));
localhold_end(hold);
return 0;
}
static int coerce_parse(Execute ptr, addr pos, addr type, addr *ret)
{
Return(parse_type(ptr, &type, type, Nil));
return coerce_type_(ptr, pos, type, ret);
}
static int coerce_execute_(Execute ptr, addr pos, addr type, addr *ret)
{
switch (GetType(type)) {
case LISPTYPE_NIL:
case LISPTYPE_SYMBOL:
case LISPTYPE_CONS:
return coerce_parse(ptr, pos, type, ret);
case LISPTYPE_TYPE:
return coerce_type_(ptr, pos, type, ret);
case LISPTYPE_T:
return Result(ret, pos);
default:
return coerce_typep(ptr, pos, pos, type, ret);
}
}
int coerce_common(Execute ptr, addr pos, addr type, addr *ret)
{
LocalHold hold;
hold = LocalHold_local(ptr);
localhold_pushva(hold, pos, type, NULL);
Return(coerce_execute_(ptr, pos, type, ret));
localhold_end(hold);
return 0;
}
/************************************************************
* type_constant.c
************************************************************/
/*
* Atomic-Type
*/
static void typetable_type0(enum LISPDECL type, enum TypeTable table)
{
addr pos;
type0_heap(type, &pos);
settypetable(table, pos);
}
static void typetable_type1(enum LISPDECL type, enum TypeTable table)
{
addr pos;
type1aster_heap(type, &pos);
settypetable(table, pos);
}
static void typetable_type2(enum LISPDECL type, enum TypeTable table)
{
addr pos;
type2aster_heap(type, &pos);
settypetable(table, pos);
}
static void typetable_type3(enum LISPDECL type, enum TypeTable table)
{
addr pos;
type3aster_heap(type, &pos);
settypetable(table, pos);
}
static void typetable_type4(enum LISPDECL type, enum TypeTable table)
{
addr pos;
type4aster_heap(type, &pos);
settypetable(table, pos);
}
#define TypeTable0(a,b) typetable_type0(LISPDECL_##a, TypeTable_##b)
#define TypeTable1(a,b) typetable_type1(LISPDECL_##a, TypeTable_##b)
#define TypeTable2(a,b) typetable_type2(LISPDECL_##a, TypeTable_##b)
#define TypeTable3(a,b) typetable_type3(LISPDECL_##a, TypeTable_##b)
#define TypeTable4(a,b) typetable_type4(LISPDECL_##a, TypeTable_##b)
#define DefTypeTable(n,a,b) \
static void typetable_##b(void) { TypeTable##n(a,b); }
DefTypeTable(0, INVALID, Invalid );
DefTypeTable(0, ASTERISK, Asterisk );
DefTypeTable(0, ATOM, Atom );
DefTypeTable(0, LIST, List );
DefTypeTable(0, BOOLEAN, Boolean );
DefTypeTable(1, CLOS, Clos );
DefTypeTable(2, VECTOR, Vector );
DefTypeTable(1, SIMPLE_VECTOR, SimpleVector );
DefTypeTable(1, BIT_VECTOR, BitVector );
DefTypeTable(1, SIMPLE_BIT_VECTOR, SimpleBitVector );
DefTypeTable(0, EXTENDED_CHAR, ExtendedChar );
DefTypeTable(1, STRING, String );
DefTypeTable(1, BASE_STRING, BaseString );
DefTypeTable(1, SIMPLE_STRING, SimpleString );
DefTypeTable(1, SIMPLE_BASE_STRING, SimpleBaseString );
DefTypeTable(1, SIGNED_BYTE, SignedByte );
DefTypeTable(1, UNSIGNED_BYTE, UnsignedByte );
DefTypeTable(0, BIT, Bit );
DefTypeTable(0, FIXNUM, Fixnum );
DefTypeTable(0, BIGNUM, Bignum );
DefTypeTable(2, CONS, Cons );
DefTypeTable(0, HASH_TABLE, Hashtable );
DefTypeTable(0, SYMBOL, Symbol );
DefTypeTable(0, KEYWORD, Keyword );
DefTypeTable(0, PACKAGE, Package );
DefTypeTable(0, RANDOM_STATE, RandomState );
DefTypeTable(0, READTABLE, Readtable );
DefTypeTable(3, FUNCTION, Function ); /* not 2 */
DefTypeTable(3, COMPILED_FUNCTION, CompiledFunction ); /* not 2 */
DefTypeTable(0, PATHNAME, Pathname );
DefTypeTable(0, LOGICAL_PATHNAME, LogicalPathname );
DefTypeTable(0, SEQUENCE, Sequence );
DefTypeTable(2, ARRAY, Array );
DefTypeTable(2, SIMPLE_ARRAY, SimpleArray );
DefTypeTable(0, CHARACTER, Character );
DefTypeTable(0, BASE_CHAR, BaseChar );
DefTypeTable(0, STANDARD_CHAR, StandardChar );
DefTypeTable(0, NUMBER, Number );
DefTypeTable(4, REAL, Real );
DefTypeTable(4, RATIONAL, Rational );
DefTypeTable(0, RATIO, Ratio );
DefTypeTable(4, INTEGER, Integer );
DefTypeTable(1, COMPLEX, Complex );
DefTypeTable(4, FLOAT, Float );
DefTypeTable(4, SHORT_FLOAT, ShortFloat );
DefTypeTable(4, SINGLE_FLOAT, SingleFloat );
DefTypeTable(4, DOUBLE_FLOAT, DoubleFloat );
DefTypeTable(4, LONG_FLOAT, LongFloat );
DefTypeTable(0, RESTART, Restart );
DefTypeTable(0, ENVIRONMENT, Environment );
DefTypeTable(0, STREAM, Stream );
DefTypeTable(0, BROADCAST_STREAM, BroadcastStream );
DefTypeTable(0, CONCATENATED_STREAM, ConcatenatedStream );
DefTypeTable(0, ECHO_STREAM, EchoStream );
DefTypeTable(0, FILE_STREAM, FileStream );
DefTypeTable(0, STRING_STREAM, StringStream );
DefTypeTable(0, SYNONYM_STREAM, SynonymStream );
DefTypeTable(0, TWO_WAY_STREAM, TwoWayStream );
DefTypeTable(0, PROMPT_STREAM, PromptStream );
DefTypeTable(0, PRETTY_STREAM, PrettyStream );
DefTypeTable(0, MEMORY_STREAM, MemoryStream );
DefTypeTable(0, TERMINAL_STREAM, TerminalStream );
DefTypeTable(0, QUOTE, Quote );
DefTypeTable(0, BYTESPEC, ByteSpec );
DefTypeTable(0, PRINT_DISPATCH, PrintDispatch );
DefTypeTable(0, EVAL, Eval );
static void typetable_Nil(void)
{
typetable_type0(LISPDECL_NIL, TypeTable_Nil);
}
static void typetable_T(void)
{
typetable_type0(LISPDECL_T, TypeTable_T);
}
static void typetable_Null(void)
{
typetable_type0(LISPDECL_NULL, TypeTable_Null);
}
/*
* Condition
*/
static void define_type_table_condition(constindex index, enum TypeTable type)
{
addr pos;
GetConstant(index, &pos);
CheckType(pos, LISPTYPE_CLOS);
type_clos_heap(pos, &pos);
settypetable(type, pos);
}
#define DefTypeTableCondition(x,y) \
static void typetable_##y(void) { \
define_type_table_condition(CONSTANT_CONDITION_##x, TypeTable_##y); \
}
DefTypeTableCondition(ARITHMETIC_ERROR, ArithmeticError);
DefTypeTableCondition(CELL_ERROR, CellError);
DefTypeTableCondition(FILE_ERROR, FileError);
DefTypeTableCondition(PACKAGE_ERROR, PackageError);
DefTypeTableCondition(PRINT_NOT_READABLE, PrintNotReadable);
DefTypeTableCondition(SIMPLE_CONDITION, SimpleCondition);
DefTypeTableCondition(STREAM_ERROR, StreamError);
DefTypeTableCondition(TYPE_ERROR, TypeError);
/*
* Type
*/
static void typetable_cons2(addr car, addr cdr, addr *ret)
{
type2_heap(LISPDECL_CONS, car, cdr, ret);
}
static void typetable_cxr(void)
{
/* (or null cons) */
addr pos, type;
GetTypeTable(&pos, Null);
GetTypeTable(&type, Cons);
type2or_heap(pos, type, &pos);
SetTypeTable(Cxr, pos);
}
static void type_cxr_carcdr(addr car, addr cdr, addr *ret)
{
/* (or null (cons car cdr)) */
addr pos, type;
GetTypeTable(&pos, Null);
typetable_cons2(car, cdr, &type);
type2or_heap(pos, type, ret);
}
static addr type_list_car(addr type)
{
addr pos;
GetTypeTable(&pos, Asterisk);
type_cxr_carcdr(type, pos, &pos);
return pos;
}
static addr type_list_cdr(addr type)
{
addr pos;
GetTypeTable(&pos, Asterisk);
type_cxr_carcdr(pos, type, &pos);
return pos;
}
static void typetable_car(void)
{
addr cxr = reftypetable(TypeTable_Cxr);
addr cxar = type_list_car(cxr);
addr cxdr = type_list_cdr(cxr);
addr cxaar = type_list_car(cxar);
addr cxadr = type_list_cdr(cxar);
addr cxdar = type_list_car(cxdr);
addr cxddr = type_list_cdr(cxdr);
addr cxaaar = type_list_car(cxaar);
addr cxaadr = type_list_cdr(cxaar);
addr cxadar = type_list_car(cxadr);
addr cxaddr = type_list_cdr(cxadr);
addr cxdaar = type_list_car(cxdar);
addr cxdadr = type_list_cdr(cxdar);
addr cxddar = type_list_car(cxddr);
addr cxdddr = type_list_cdr(cxddr);
addr fifth = type_list_cdr(cxdddr);
addr sixth = type_list_cdr(fifth);
addr seventh = type_list_cdr(sixth);
addr eighth = type_list_cdr(seventh);
addr ninth = type_list_cdr(eighth);
addr tenth = type_list_cdr(ninth);
SetTypeTable(Cxar, cxar);
SetTypeTable(Cxdr, cxdr);
SetTypeTable(Cxaar, cxaar);
SetTypeTable(Cxadr, cxadr);
SetTypeTable(Cxdar, cxdar);
SetTypeTable(Cxddr, cxddr);
SetTypeTable(Cxaaar, cxaaar);
SetTypeTable(Cxaadr, cxaadr);
SetTypeTable(Cxadar, cxadar);
SetTypeTable(Cxaddr, cxaddr);
SetTypeTable(Cxdaar, cxdaar);
SetTypeTable(Cxdadr, cxdadr);
SetTypeTable(Cxddar, cxddar);
SetTypeTable(Cxdddr, cxdddr);
SetTypeTable(Fifth, fifth);
SetTypeTable(Sixth, sixth);
SetTypeTable(Seventh, seventh);
SetTypeTable(Eighth, eighth);
SetTypeTable(Ninth, ninth);
SetTypeTable(Tenth, tenth);
}
static void type_setf_cxr_carcdr(addr car, addr cdr, addr *ret)
{
/* (cons car cdr) */
typetable_cons2(car, cdr, ret);
}
static addr type_cons_car(addr type)
{
addr pos;
GetTypeTable(&pos, Asterisk);
type_setf_cxr_carcdr(type, pos, &pos);
return pos;
}
static addr type_cons_cdr(addr type)
{
addr pos;
GetTypeTable(&pos, Asterisk);
type_setf_cxr_carcdr(pos, type, &pos);
return pos;
}
static void typetable_setf_car(void)
{
addr cxr = reftypetable(TypeTable_Cons);
addr cxar = type_cons_car(cxr);
addr cxdr = type_cons_cdr(cxr);
addr cxaar = type_cons_car(cxar);
addr cxadr = type_cons_cdr(cxar);
addr cxdar = type_cons_car(cxdr);
addr cxddr = type_cons_cdr(cxdr);
addr cxaaar = type_cons_car(cxaar);
addr cxaadr = type_cons_cdr(cxaar);
addr cxadar = type_cons_car(cxadr);
addr cxaddr = type_cons_cdr(cxadr);
addr cxdaar = type_cons_car(cxdar);
addr cxdadr = type_cons_cdr(cxdar);
addr cxddar = type_cons_car(cxddr);
addr cxdddr = type_cons_cdr(cxddr);
addr fifth = type_cons_cdr(cxdddr);
addr sixth = type_cons_cdr(fifth);
addr seventh = type_cons_cdr(sixth);
addr eighth = type_cons_cdr(seventh);
addr ninth = type_cons_cdr(eighth);
addr tenth = type_cons_cdr(ninth);
SetTypeTable(SetfCxar, cxar);
SetTypeTable(SetfCxdr, cxdr);
SetTypeTable(SetfCxaar, cxaar);
SetTypeTable(SetfCxadr, cxadr);
SetTypeTable(SetfCxdar, cxdar);
SetTypeTable(SetfCxddr, cxddr);
SetTypeTable(SetfCxaaar, cxaaar);
SetTypeTable(SetfCxaadr, cxaadr);
SetTypeTable(SetfCxadar, cxadar);
SetTypeTable(SetfCxaddr, cxaddr);
SetTypeTable(SetfCxdaar, cxdaar);
SetTypeTable(SetfCxdadr, cxdadr);
SetTypeTable(SetfCxddar, cxddar);
SetTypeTable(SetfCxdddr, cxdddr);
SetTypeTable(SetfFifth, fifth);
SetTypeTable(SetfSixth, sixth);
SetTypeTable(SetfSeventh, seventh);
SetTypeTable(SetfEighth, eighth);
SetTypeTable(SetfNinth, ninth);
SetTypeTable(SetfTenth, tenth);
}
static void typetable_ornull(enum TypeTable type, enum TypeTable typenull)
{
addr pos, null;
gettypetable(type, &pos);
GetTypeTable(&null, Null);
type2or_heap(pos, null, &pos);
settypetable(typenull, pos);
}
#define SetTypeTableNull(a) typetable_ornull(TypeTable_##a, TypeTable_##a##Null)
static void typetable_characternull(void)
{
SetTypeTableNull(Character);
}
static void typetable_stringnull(void)
{
SetTypeTableNull(String);
}
static void typetable_streamnull(void)
{
SetTypeTableNull(Stream);
}
static void typetable_condition(void)
{
addr pos;
GetConst(CLOS_CONDITION, &pos);
CheckType(pos, LISPTYPE_CLOS);
type_clos_heap(pos, &pos);
SetTypeTable(Condition, pos);
}
static void typetable_conditionnull(void)
{
SetTypeTableNull(Condition);
}
static void typetable_restartnull(void)
{
SetTypeTableNull(Restart);
}
static void typetable_functionnull(void)
{
SetTypeTableNull(Function);
}
static void typetable_environmentnull(void)
{
SetTypeTableNull(Environment);
}
static void typetable_integernull(void)
{
SetTypeTableNull(Integer);
}
static void typetable_pathnamenull(void)
{
SetTypeTableNull(Pathname);
}
static void typetable_packagenull(void)
{
SetTypeTableNull(Package);
}
static void typetable_printdispatchnull(void)
{
SetTypeTableNull(PrintDispatch);
}
static void typetable_stringdesigner(void)
{
/* (or string symbol character) */
addr type1, type2, type3, pos;
GetTypeTable(&type1, String);
GetTypeTable(&type2, Symbol);
GetTypeTable(&type3, Character);
type3or_heap(type1, type2, type3, &pos);
SetTypeTable(StringDesigner, pos);
}
static void typetable_packagedesigner(void)
{
/* (or package string symbol character) */
addr type1, type2, type3, type4, pos;
GetTypeTable(&type1, Package);
GetTypeTable(&type2, String);
GetTypeTable(&type3, Symbol);
GetTypeTable(&type4, Character);
type4or_heap(type1, type2, type3, type4, &pos);
SetTypeTable(PackageDesigner, pos);
}
static void typetable_packagedesignernull(void)
{
SetTypeTableNull(PackageDesigner);
}
static void typetable_functiondesigner(void)
{
/* (or function symbol) */
addr type1, type2, pos;
GetTypeTable(&type1, Function);
GetTypeTable(&type2, Symbol);
type2or_heap(type1, type2, &pos);
SetTypeTable(FunctionDesigner, pos);
}
static void typetable_restartdesigner(void)
{
/* (or restart (and symbol (not null))) */
addr type1, type2, type3, pos;
GetTypeTable(&type1, Restart);
GetTypeTable(&type2, Symbol);
type0not_heap(LISPDECL_NULL, &type3);
type2and_heap(type2, type3, &type2);
type2or_heap(type1, type2, &pos);
SetTypeTable(RestartDesigner, pos);
}
static void typetable_pathnamedesigner(void)
{
/* (or pathname string stream) */
addr type1, type2, type3, pos;
GetTypeTable(&type1, Pathname);
GetTypeTable(&type2, String);
GetTypeTable(&type3, Stream);
type3or_heap(type1, type2, type3, &pos);
SetTypeTable(PathnameDesigner, pos);
}
static void typetable_streamdesigner(void)
{
/* (or stream boolean) */
addr type1, type2, pos;
GetTypeTable(&type1, Stream);
GetTypeTable(&type2, Boolean);
type2or_heap(type1, type2, &pos);
SetTypeTable(StreamDesigner, pos);
}
static void typetable_readtabledesigner(void)
{
/* (or readtable null) */
addr type1, type2, pos;
GetTypeTable(&type1, Readtable);
GetTypeTable(&type2, Null);
type2or_heap(type1, type2, &pos);
SetTypeTable(ReadtableDesigner, pos);
}
static void typetable_conditiondesigner(void)
{
/* (or string symbol condition) */
addr type1, type2, type3, pos;
GetTypeTable(&type1, String);
GetTypeTable(&type2, Symbol);
GetTypeTable(&type3, Condition);
type3or_heap(type1, type2, type3, &pos);
SetTypeTable(ConditionDesigner, pos);
}
static void typetable_index(void)
{
/* (integer 0 SIZE_MAX) */
addr left, right;
fixnum_heap(&left, 0);
GetConst(INDEX_MAX, &right);
type4_heap(LISPDECL_INTEGER, Nil, left, Nil, right, &left);
SetTypeTable(Index, left);
}
static void typetable_indexnull(void)
{
SetTypeTableNull(Index);
}
static void typetable_plus1(void)
{
addr pos;
type2integer_ab_heap(Nil, 1, &pos);
SetTypeTable(Plus1, pos);
}
static void typetable_plus1null(void)
{
SetTypeTableNull(Plus1);
}
static void typetable_intplus(void)
{
addr pos;
type2integer_ab_heap(Nil, 0, &pos);
SetTypeTable(Intplus, pos);
}
static void typetable_intplusnull(void)
{
SetTypeTableNull(Intplus);
}
static void typetable_input_stream(void)
{
addr pos;
GetConst(COMMON_INPUT_STREAM_P, &pos);
type_satisfies_heap(pos, &pos);
SetTypeTable(InputStream, pos);
}
static void typetable_output_stream(void)
{
addr pos;
GetConst(COMMON_OUTPUT_STREAM_P, &pos);
type_satisfies_heap(pos, &pos);
SetTypeTable(OutputStream, pos);
}
static void typetable_typespec(void)
{
/* (or symbol cons clos) */
addr type1, type2, type3, pos;
GetTypeTable(&type1, Symbol);
GetTypeTable(&type2, Cons);
GetTypeTable(&type3, Clos);
type3or_heap(type1, type2, type3, &pos);
SetTypeTable(TypeSpec, pos);
}
static void typetable_typesymbol(void)
{
/* (or symbol cons) */
addr type1, type2, pos;
GetTypeTable(&type1, Symbol);
GetTypeTable(&type2, Cons);
type2or_heap(type1, type2, &pos);
SetTypeTable(TypeSymbol, pos);
}
static void typetable_bit_array(void)
{
addr pos, aster;
GetTypeTable(&pos, Bit);
GetTypeTable(&aster, Asterisk);
type2_heap(LISPDECL_ARRAY, pos, aster, &pos);
SetTypeTable(BitArray, pos);
}
static void typetable_simple_bit_array(void)
{
addr pos, aster;
GetTypeTable(&pos, Bit);
GetTypeTable(&aster, Asterisk);
type2_heap(LISPDECL_SIMPLE_ARRAY, pos, aster, &pos);
SetTypeTable(SimpleBitArray, pos);
}
static void typetable_keywordstart(void)
{
addr pos;
GetTypeTable(&pos, Index);
SetTypeTable(KeywordStart, pos);
}
static void typetable_keywordend(void)
{
addr pos;
GetTypeTable(&pos, IndexNull);
SetTypeTable(KeywordEnd, pos);
}
static void typetable_keystart1end1(void)
{
/* &key (start keyword-start) (end keyword-end) */
addr key, key1, key2, type;
/* :start1 */
GetConst(KEYWORD_START, &key1);
GetTypeTable(&type, KeywordStart);
cons_heap(&key1, key1, type);
/* :end1 */
GetConst(KEYWORD_END, &key2);
GetTypeTable(&type, KeywordEnd);
cons_heap(&key2, key2, type);
/* &key ... */
list_heap(&key, key1, key2, NULL);
SetTypeTable(KeyStart1End1, key);
}
static void typetable_keystart2end2(void)
{
/* &key (start1 keyword-start) (end1 keyword-end)
* (start2 keyword-start) (end2 keyword-end))
*/
addr key, key1, key2, key3, key4, start, end;
GetTypeTable(&start, KeywordStart);
GetTypeTable(&end, KeywordEnd);
/* :start1 */
GetConst(KEYWORD_START1, &key1);
cons_heap(&key1, key1, start);
/* :end1 */
GetConst(KEYWORD_END1, &key2);
cons_heap(&key2, key2, end);
/* :start2 */
GetConst(KEYWORD_START2, &key3);
cons_heap(&key3, key3, start);
/* :end2 */
GetConst(KEYWORD_END2, &key4);
cons_heap(&key4, key4, end);
/* &key ... */
list_heap(&key, key1, key2, key3, key4, NULL);
SetTypeTable(KeyStart2End2, key);
}
static void typetable_functionname(void)
{
/* (or symbol (setf symbol)) */
/* (or symbol (cons (eql setf) (cons symbol null))) */
addr symbol, setf, pos, cons;
/* (cons symbol null) */
GetTypeTable(&symbol, Symbol);
GetTypeTable(&pos, Null);
typetable_cons2(symbol, pos, &cons);
/* (cons (eql 'setf) [cons]) */
GetConst(COMMON_SETF, &setf);
type_eql_heap(setf, &setf);
typetable_cons2(setf, cons, &pos);
type2or_heap(symbol, pos, &pos);
SetTypeTable(FunctionName, pos);
}
static void typetable_radixinteger(void)
{
/* (integer 2 36) */
addr pos;
type4integer_heap(Nil, 2, Nil, 36, &pos);
SetTypeTable(RadixInteger, pos);
}
static void typetable_floatsymbol(void)
{
addr pos, v1, v2, v3, v4;
/* (member short-float single-float double-float long-float) */
GetConst(COMMON_SINGLE_FLOAT, &v1);
GetConst(COMMON_DOUBLE_FLOAT, &v2);
GetConst(COMMON_LONG_FLOAT, &v3);
GetConst(COMMON_SHORT_FLOAT, &v4);
type_member_heap(&pos, v1, v2, v3, v4, NULL);
SetTypeTable(FloatSymbol, pos);
}
static void typetable_eqlt(void)
{
addr pos;
type_eql_heap(T, &pos);
SetTypeTable(EqlT, pos);
}
static void typetable_case_sensitivity(void)
{
addr pos, v1, v2, v3, v4;
GetConst(KEYWORD_UPCASE, &v1);
GetConst(KEYWORD_DOWNCASE, &v2);
GetConst(KEYWORD_PRESERVE, &v3);
GetConst(KEYWORD_INVERT, &v4);
type_member_heap(&pos, v1, v2, v3, v4, NULL);
SetTypeTable(CaseSensitivity, pos);
}
static void typetable_print_case(void)
{
addr key1, key2, key3;
GetConst(KEYWORD_UPCASE, &key1);
GetConst(KEYWORD_DOWNCASE, &key2);
GetConst(KEYWORD_CAPITALIZE, &key3);
type_member_heap(&key1, key1, key2, key3, NULL);
SetTypeTable(PrintCase, key1);
}
static void typetable_keytestlist(void)
{
/* &key (:key [function-designer])
* (:test [function-designer])
* (:test-not [function-designer])
*/
addr key, key1, key2, key3, type;
GetConst(KEYWORD_KEY, &key1);
GetConst(KEYWORD_TEST, &key2);
GetConst(KEYWORD_TEST_NOT, &key3);
GetTypeTable(&type, FunctionDesigner);
/* key */
cons_heap(&key1, key1, type);
cons_heap(&key2, key2, type);
cons_heap(&key3, key3, type);
list_heap(&key, key1, key2, key3, NULL);
/* result */
SetTypeTable(KeyTestList, key);
}
static void typetable_rehashsize(void)
{
/* (or (integer 1 *) (float (1.0f0) *)) */
addr type1, type2, pos;
type2integer_ab_heap(Nil, 1, &type1);
type2float_ab_heap(T, 1.0f, &type2);
type2or_heap(type1, type2, &pos);
SetTypeTable(RehashSize, pos);
}
static void typetable_rehashthreshold(void)
{
/* (real 0.0 1.0) */
addr pos;
type4realf_heap(Nil, 0.0f, Nil, 1.0f, &pos);
SetTypeTable(RehashThreshold, pos);
}
static void typetable_countkey(void)
{
addr key, key1, key2, key3, key4, key5, key6;
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, START, KeywordStart);
KeyTypeTable(&key3, END, KeywordEnd);
KeyTypeTable(&key4, KEY, FunctionDesigner);
KeyTypeTable(&key5, TEST, FunctionDesigner);
KeyTypeTable(&key6, TEST_NOT, FunctionDesigner);
list_heap(&key, key1, key2, key3, key4, key5, key6, NULL);
SetTypeTable(CountKey, key);
}
static void typetable_countifkey(void)
{
addr key, key1, key2, key3, key4;
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, START, KeywordStart);
KeyTypeTable(&key3, END, KeywordEnd);
KeyTypeTable(&key4, KEY, FunctionDesigner);
list_heap(&key, key1, key2, key3, key4, NULL);
SetTypeTable(CountIfKey, key);
}
static void typetable_pathnamehost(void)
{
/* host (or string symbol) */
addr type1, type2, pos;
GetTypeTable(&type1, Symbol);
GetTypeTable(&type2, String);
type2or_heap(type1, type2, &pos);
SetTypeTable(PathnameHost, pos);
}
static void typetable_pathnamedevice(void)
{
/* device (or string symbol) ;; (eql :unspecific) */
addr type;
GetTypeTable(&type, PathnameHost);
SetTypeTable(PathnameDevice, type);
}
static void typetable_pathnamedirectory(void)
{
/* directory (or list string (member :wild :wild-inferiors :unspecific)) */
addr type, list, string, wild, wild_inferiors, unspec;
GetTypeTable(&list, List);
GetTypeTable(&string, String);
GetConst(KEYWORD_WILD, &wild);
GetConst(KEYWORD_WILD_INFERIORS, &wild_inferiors);
GetConst(KEYWORD_UNSPECIFIC, &unspec);
type_member_heap(&type, wild, wild_inferiors, unspec, NULL);
type3or_heap(list, string, type, &type);
SetTypeTable(PathnameDirectory, type);
}
static void typetable_pathnamename(void)
{
/* name (or string cons (member nil :wild)) */
addr type, string, cons, wild;
GetTypeTable(&string, String);
GetTypeTable(&cons, Cons);
GetConst(KEYWORD_WILD, &wild);
type_member_heap(&type, Nil, wild, NULL);
type3or_heap(string, cons, type, &type);
SetTypeTable(PathnameName, type);
}
static void typetable_pathnametype(void)
{
/* type (or string (member nil :wild :unspecific))) */
addr type, string, wild, unspec;
GetTypeTable(&string, String);
GetConst(KEYWORD_WILD, &wild);
GetConst(KEYWORD_UNSPECIFIC, &unspec);
type_member_heap(&type, Nil, wild, unspec, NULL);
type2or_heap(string, type, &type);
SetTypeTable(PathnameType, type);
}
static void typetable_pathnameversion(void)
{
/* version (or (integer 1 *) (member nil :wild :unspecific :newest)) */
addr type1, type2, newest, wild, unspec, pos;
type2integer_ab_heap(Nil, 0, &type1);
GetConst(KEYWORD_WILD, &wild);
GetConst(KEYWORD_UNSPECIFIC, &unspec);
GetConst(KEYWORD_NEWEST, &newest);
type_member_heap(&type2, Nil, wild, unspec, newest, NULL);
type2or_heap(type1, type2, &pos);
SetTypeTable(PathnameVersion, pos);
}
static void typetable_signed8(void)
{
addr pos;
type_signed_heap(8, &pos);
SetTypeTable(Signed8, pos);
}
static void typetable_signed16(void)
{
addr pos;
type_signed_heap(16, &pos);
SetTypeTable(Signed16, pos);
}
static void typetable_signed32(void)
{
addr pos;
type_signed_heap(32, &pos);
SetTypeTable(Signed32, pos);
}
static void typetable_unsigned8(void)
{
addr pos;
type_unsigned_heap(8, &pos);
SetTypeTable(Unsigned8, pos);
}
static void typetable_unsigned16(void)
{
addr pos;
type_unsigned_heap(16, &pos);
SetTypeTable(Unsigned16, pos);
}
static void typetable_unsigned32(void)
{
addr pos;
type_unsigned_heap(32, &pos);
SetTypeTable(Unsigned32, pos);
}
#ifdef LISP_64BIT
static void typetable_signed64(void)
{
addr pos;
type_signed_heap(64, &pos);
SetTypeTable(Signed64, pos);
}
static void typetable_unsigned64(void)
{
addr pos;
type_unsigned_heap(64, &pos);
SetTypeTable(Unsigned64, pos);
}
#endif
static void typetable_opendirection(void)
{
addr type, input, output, io, probe;
GetConst(KEYWORD_INPUT, &input);
GetConst(KEYWORD_OUTPUT, &output);
GetConst(KEYWORD_IO, &io);
GetConst(KEYWORD_PROBE, &probe);
type_member_heap(&type, input, output, io, probe, NULL);
SetTypeTable(OpenDirection, type);
}
static void typetable_openelementtype(void)
{
addr type, keyword;
GetTypeTable(&type, TypeSpec);
GetConst(KEYWORD_DEFAULT, &keyword);
type_eql_heap(keyword, &keyword);
type2or_heap(type, keyword, &type);
SetTypeTable(OpenElementType, type);
}
static void typetable_openifexists(void)
{
addr type, error, new_version, rename, rename_and_delete;
addr overwrite, append, supersede;
GetConst(KEYWORD_ERROR, &error);
GetConst(KEYWORD_NEW_VERSION, &new_version);
GetConst(KEYWORD_RENAME, &rename);
GetConst(KEYWORD_RENAME_AND_DELETE, &rename_and_delete);
GetConst(KEYWORD_OVERWRITE, &overwrite);
GetConst(KEYWORD_APPEND, &append);
GetConst(KEYWORD_SUPERSEDE, &supersede);
type_member_heap(&type, error, new_version, rename, rename_and_delete,
overwrite, append, supersede, Nil, NULL);
SetTypeTable(OpenIfExists, type);
}
static void typetable_openifdoesnotexist(void)
{
addr type, error, create;
GetConst(KEYWORD_ERROR, &error);
GetConst(KEYWORD_CREATE, &create);
type_member_heap(&type, error, create, Nil, NULL);
SetTypeTable(OpenIfDoesNotExist, type);
}
static void typetable_externalformat(void)
{
addr type1, type2;
GetTypeTable(&type1, Symbol);
GetTypeTable(&type2, String);
type2or_heap(type1, type2, &type1);
SetTypeTable(ExternalFormat, type1);
}
static void typetable_pprint_newline(void)
{
addr type, key1, key2, key3, key4;
GetConst(KEYWORD_LINEAR, &key1);
GetConst(KEYWORD_FILL, &key2);
GetConst(KEYWORD_MISER, &key3);
GetConst(KEYWORD_MANDATORY, &key4);
type_member_heap(&type, key1, key2, key3, key4, NULL);
SetTypeTable(PprintNewline, type);
}
static void typetable_pprint_tabular(void)
{
addr type, key1, key2, key3, key4;
GetConst(KEYWORD_LINE, &key1);
GetConst(KEYWORD_SECTION, &key2);
GetConst(KEYWORD_LINE_RELATIVE, &key3);
GetConst(KEYWORD_SECTION_RELATIVE, &key4);
type_member_heap(&type, key1, key2, key3, key4, NULL);
SetTypeTable(PprintTabular, type);
}
static void typetable_format(void)
{
addr type, null, eqlt, stream, string;
/* (or null (eql t) stream string) */
GetTypeTable(&null, Null);
GetTypeTable(&eqlt, EqlT);
GetTypeTable(&stream, Stream);
GetTypeTable(&string, String);
type4or_heap(null, eqlt, stream, string, &type);
SetTypeTable(Format, type);
}
static void typetable_time_second(void)
{
addr type;
type4integer_heap(Nil, 0, Nil, 59, &type);
SetTypeTable(TimeSecond, type);
}
static void typetable_time_hour(void)
{
addr type;
type4integer_heap(Nil, 0, Nil, 23, &type);
SetTypeTable(TimeHour, type);
}
static void typetable_time_day(void)
{
addr type;
type4integer_heap(Nil, 1, Nil, 31, &type);
SetTypeTable(TimeDay, type);
}
static void typetable_time_month(void)
{
addr type;
type4integer_heap(Nil, 1, Nil, 12, &type);
SetTypeTable(TimeMonth, type);
}
static void typetable_time_zone(void)
{
addr v1, v2, type;
fixnum_heap(&v1, -24);
fixnum_heap(&v2, 24);
type4_heap(LISPDECL_RATIONAL, Nil, v1, Nil, v2, &type);
SetTypeTable(TimeZone, type);
}
static void typetable_orlist(enum TypeTable type, enum TypeTable typelist)
{
addr pos, list;
gettypetable(type, &pos);
GetTypeTable(&list, List);
type2or_heap(pos, list, &pos);
settypetable(typelist, pos);
}
static void typetable_symbol_list(void)
{
typetable_orlist(TypeTable_Symbol, TypeTable_SymbolList);
}
static void typetable_string_list(void)
{
typetable_orlist(TypeTable_String, TypeTable_StringList);
}
static void typetable_string_designer_list(void)
{
typetable_orlist(TypeTable_StringDesigner, TypeTable_StringDesignerList);
}
static void typetable_package_designer_list(void)
{
typetable_orlist(TypeTable_PackageDesigner, TypeTable_PackageDesignerList);
}
static void typetable_method(void)
{
addr pos;
/* method1 */
GetConst(CLOS_METHOD, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(Method, pos);
SetTypeTable(Method1, pos);
/* method2 */
GetTypeTable(&pos, List);
SetTypeTable(Method2, pos);
}
static void typetable_class(void)
{
addr pos;
GetConst(CLOS_CLASS, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(Class, pos);
}
static void typetable_classnull(void)
{
SetTypeTableNull(Class);
}
static void typetable_standardclass(void)
{
addr pos;
GetConst(CLOS_STANDARD_CLASS, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(StandardClass, pos);
}
static void typetable_standardobject(void)
{
addr pos;
GetConst(CLOS_STANDARD_OBJECT, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(StandardObject, pos);
}
static void typetable_structureclass(void)
{
addr pos;
GetConst(CLOS_STRUCTURE_CLASS, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(StructureClass, pos);
}
static void typetable_structureobject(void)
{
addr pos;
GetConst(CLOS_STRUCTURE_OBJECT, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(StructureObject, pos);
}
static void typetable_standard_method(void)
{
addr pos;
GetConst(CLOS_STANDARD_METHOD, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(StandardMethod, pos);
}
static void typetable_methodcombination(void)
{
addr pos;
GetConst(CLOS_METHOD_COMBINATION, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(MethodCombination, pos);
}
static void typetable_generic_function(void)
{
addr pos;
GetConst(CLOS_GENERIC_FUNCTION, &pos);
type_clos_heap(pos, &pos);
SetTypeTable(GenericFunction, pos);
}
/*
* Array
*/
static void typetable_array_t(void)
{
addr pos;
GetTypeTable(&pos, T);
SetTypeTable(Array_T, pos);
}
static void typetable_array_bit(void)
{
addr pos;
GetTypeTable(&pos, Bit);
SetTypeTable(Array_Bit, pos);
}
static void typetable_array_character(void)
{
addr pos;
GetTypeTable(&pos, Character);
SetTypeTable(Array_Character, pos);
}
static void typetable_array_singlefloat(void)
{
addr pos;
GetTypeTable(&pos, SingleFloat);
SetTypeTable(Array_SingleFloat, pos);
}
static void typetable_array_doublefloat(void)
{
addr pos;
GetTypeTable(&pos, DoubleFloat);
SetTypeTable(Array_DoubleFloat, pos);
}
static void typetable_array_longfloat(void)
{
addr pos;
GetTypeTable(&pos, LongFloat);
SetTypeTable(Array_LongFloat, pos);
}
static void typetable_array_signed8(void)
{
addr pos;
GetTypeTable(&pos, Signed8);
SetTypeTable(Array_Signed8, pos);
}
static void typetable_array_signed16(void)
{
addr pos;
GetTypeTable(&pos, Signed16);
SetTypeTable(Array_Signed16, pos);
}
static void typetable_array_signed32(void)
{
addr pos;
GetTypeTable(&pos, Signed32);
SetTypeTable(Array_Signed32, pos);
}
static void typetable_array_unsigned8(void)
{
addr pos;
GetTypeTable(&pos, Unsigned8);
SetTypeTable(Array_Unsigned8, pos);
}
static void typetable_array_unsigned16(void)
{
addr pos;
GetTypeTable(&pos, Unsigned16);
SetTypeTable(Array_Unsigned16, pos);
}
static void typetable_array_unsigned32(void)
{
addr pos;
GetTypeTable(&pos, Unsigned32);
SetTypeTable(Array_Unsigned32, pos);
}
#ifdef LISP_64BIT
static void typetable_array_signed64(void)
{
addr pos;
GetTypeTable(&pos, Signed64);
SetTypeTable(Array_Signed64, pos);
}
static void typetable_array_unsigned64(void)
{
addr pos;
GetTypeTable(&pos, Unsigned64);
SetTypeTable(Array_Unsigned64, pos);
}
#endif
/*
* Arguments
*/
static void typeargs_empty_constant(void)
{
addr pos;
typeargs_empty(&pos);
SetTypeArgs(Empty, pos);
}
static void typeargs_optconditionnull(void)
{
addr pos;
GetTypeTable(&pos, ConditionNull);
typeargs_opt1(&pos, pos);
SetTypeArgs(OptConditionNull, pos);
}
static void typeargs_packagedesigner(void)
{
addr pos;
GetTypeTable(&pos, PackageDesigner);
typeargs_var1(&pos, pos);
SetTypeArgs(PackageDesigner, pos);
}
static void typeargs_pathnamecase(void)
{
addr args, key, symbol, common, keylocal;
/* key */
GetConst(KEYWORD_CASE, &symbol);
GetConst(KEYWORD_COMMON, &common);
GetConst(KEYWORD_LOCAL, &keylocal);
type_member_heap(&key, common, keylocal, NULL);
cons_heap(&key, symbol, key);
conscar_heap(&key, key);
/* type */
GetTypeTable(&args, PathnameDesigner);
typeargs_var1key(&args, args, key);
SetTypeArgs(PathnameCase, args);
}
static void typeargs_error(void)
{
addr args, type;
GetTypeTable(&args, ConditionDesigner);
GetTypeTable(&type, T);
typeargs_var1rest(&args, args, type);
SetTypeArgs(Error, args);
}
/*
* Values
*/
static void deftypevalues(enum TypeTable a, enum TypeTable b)
{
addr pos;
gettypetable(a, &pos);
typevalues_result(&pos, pos);
settypetable(b, pos);
}
#define TypeValues(a) deftypevalues(TypeTable_##a, TypeValues_##a)
#define DefTypeValues(a) static void typevalues_##a(void) { TypeValues(a); }
static void typevalues_Nil(void)
{
addr pos;
GetTypeTable(&pos, Nil);
typevalues_rest(&pos, pos);
SetTypeValues(Nil, pos);
}
static void typevalues_T(void)
{
addr pos;
GetTypeTable(&pos, T);
typevalues_result(&pos, pos);
SetTypeValues(T, pos);
}
DefTypeValues(Null);
DefTypeValues(Cons);
DefTypeValues(List);
DefTypeValues(Boolean);
DefTypeValues(Character);
DefTypeValues(CharacterNull);
DefTypeValues(Symbol);
DefTypeValues(Vector);
DefTypeValues(SimpleVector);
DefTypeValues(String);
DefTypeValues(StringNull);
DefTypeValues(SimpleString);
DefTypeValues(Stream);
DefTypeValues(StreamNull);
DefTypeValues(PrettyStream);
DefTypeValues(MemoryStream);
DefTypeValues(Function);
DefTypeValues(FunctionNull);
DefTypeValues(EqlT);
DefTypeValues(Package);
DefTypeValues(PackageNull);
DefTypeValues(Sequence);
DefTypeValues(Array);
DefTypeValues(Integer);
DefTypeValues(Ratio);
DefTypeValues(Rational);
DefTypeValues(Index);
DefTypeValues(IndexNull);
DefTypeValues(Intplus);
DefTypeValues(IntplusNull);
DefTypeValues(Bit);
DefTypeValues(BitArray);
DefTypeValues(Pathname);
DefTypeValues(PathnameNull);
DefTypeValues(LogicalPathname);
DefTypeValues(Float);
DefTypeValues(Real);
DefTypeValues(Number);
DefTypeValues(Complex);
DefTypeValues(TypeSymbol);
DefTypeValues(Class);
DefTypeValues(ClassNull);
DefTypeValues(MethodCombination);
DefTypeValues(GenericFunction);
/*
* Values
*/
static void typevalues_decode_universal_time(void)
{
addr sec, hour, day, month, year, week, daylight, zone;
addr values;
GetTypeTable(&sec, TimeSecond);
GetTypeTable(&hour, TimeHour);
GetTypeTable(&day, TimeDay);
GetTypeTable(&month, TimeMonth);
GetTypeTable(&year, Intplus);
type4integer_heap(Nil, 0, Nil, 6, &week);
GetTypeTable(&daylight, Boolean);
GetTypeTable(&zone, TimeZone);
typevalues_values_va(&values,
sec, sec, hour, day, month, year, week, daylight, zone, NULL);
SetTypeValues(DecodeUniversalTime, values);
}
static void typevalues_empty(void)
{
addr values;
GetTypeTable(&values, Nil);
typevalues_rest(&values, values);
SetTypeValues(Empty, values);
}
/*
* Compiled-Function
*/
static void typecompiled_object_boolean(void)
{
addr args, values;
GetTypeTable(&args, Asterisk);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Object_Boolean, args);
}
static void typecompiled_symbol_boolean(void)
{
addr args, values;
GetTypeTable(&args, Symbol);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Symbol_Boolean, args);
}
static void typecompiled_stringcase(void)
{
/* (function (string-designer &key (start keyword-start)
* (end keyword-end))
* (values string &rest nil))
*/
addr args, values;
GetTypeTable(&args, StringDesigner);
GetTypeTable(&values, KeyStart1End1);
typeargs_var1key(&args, args, values);
GetTypeValues(&values, String);
type_compiled_heap(args, values, &args);
SetTypeCompiled(StringCase, args);
}
static void typecompiled_nstringcase(void)
{
/* (function (string &key (start keyword-start)
* (end keyword-end))
* (values string &rest nil))
*/
addr args, values;
GetTypeTable(&args, String);
GetTypeTable(&values, KeyStart1End1);
typeargs_var1key(&args, args, values);
GetTypeValues(&values, String);
type_compiled_heap(args, values, &args);
SetTypeCompiled(NStringCase, args);
}
static void typecompiled_stringtrim(void)
{
/* (function (sequence string-designer) (values string &rest nil)) */
addr args, values, type;
GetTypeTable(&args, Sequence);
GetTypeTable(&type, StringDesigner);
typeargs_var2(&args, args, type);
GetTypeValues(&values, String);
type_compiled_heap(args, values, &args);
SetTypeCompiled(StringTrim, args);
}
static void typecompiled_stringequal(void)
{
/* (function (string-designer string-designer &key
* (start1 keyword-start)
* (end1 keyword-end)
* (start2 keyword-start)
* (end2 keyword-end))
* (values boolean &rest null))
*/
addr args, values;
GetTypeTable(&args, StringDesigner);
GetTypeTable(&values, KeyStart2End2);
typeargs_var2key(&args, args, args, values);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(StringEqual, args);
}
static void typecompiled_stringmismatch(void)
{
/* (function (string-designer string-designer &key
* (start1 keyword-start)
* (end1 keyword-end)
* (start2 keyword-start)
* (end2 keyword-end))
* (values keyword-end &rest null))
*/
addr args, values;
GetTypeTable(&args, StringDesigner);
GetTypeTable(&values, KeyStart2End2);
typeargs_var2key(&args, args, args, values);
GetTypeValues(&values, IndexNull);
type_compiled_heap(args, values, &args);
SetTypeCompiled(StringMismatch, args);
}
static void typecompiled_rplaca(void)
{
/* (function cons (values cons &rest nil)) */
addr args, values, type;
GetTypeTable(&args, Cons);
GetTypeTable(&type, Asterisk);
typeargs_var2(&args, args, type);
GetTypeValues(&values, Cons);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Rplaca, args);
}
static void typecompiled_list_list(void)
{
/* (function (list) (values list &rest nil)) */
addr args, values;
GetTypeTable(&args, List);
typeargs_var1(&args, args);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(List_List, args);
}
static void typecompiled_nth(void)
{
/* (function (integer-plus list) (values t &rest nil)) */
addr args, values, type;
GetTypeTable(&args, Intplus);
GetTypeTable(&type, List);
typeargs_var2(&args, args, type);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Nth, args);
}
static void typecompiled_nconc(void)
{
/* (function (&rest t) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
typeargs_rest(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Nconc, args);
}
static void typecompiled_renconc(void)
{
/* (function (list t) (values t &rest nil)) */
addr args, values, type;
GetTypeTable(&args, List);
GetTypeTable(&type, T);
typeargs_var2(&args, args, type);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Nreconc, args);
}
static void typecompiled_butlast(void)
{
/* (function (list &optional intplus) (values list &rest nil)) */
addr args, values, type;
GetTypeTable(&args, List);
GetTypeTable(&type, Intplus);
typeargs_var1opt1(&args, args, type);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(ButLast, args);
}
static void typecompiled_macrofunction(void)
{
/* (function (t (or null environment)) t) */
addr args, values, env;
GetTypeTable(&args, T);
GetTypeTable(&env, EnvironmentNull);
typeargs_var2(&args, args, env);
GetTypeTable(&values, Asterisk);
type_compiled_heap(args, values, &args);
SetTypeCompiled(MacroFunction, args);
}
static void typecompiled_macroexpand(void)
{
/* (function (t &optional (or null environment))
* (values t boolean &rest nil))
*/
addr args, values, pos1, pos2;
GetTypeTable(&pos1, T);
GetTypeTable(&pos2, EnvironmentNull);
typeargs_var1opt1(&args, pos1, pos2);
GetTypeTable(&pos2, Boolean);
typevalues_values2(&values, pos1, pos2);
type_compiled_heap(args, values, &args);
SetTypeCompiled(MacroExpand, args);
}
static void typecompiled_abort(void)
{
addr args, values;
/* (function (&optional (or condition null)) nil) */
GetTypeArgs(&args, OptConditionNull);
GetTypeTable(&values, Nil);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Abort, args);
}
static void typecompiled_continue(void)
{
addr args, values;
/* (function (&optional (or condition null)) null) */
GetTypeArgs(&args, OptConditionNull);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Continue, args);
}
static void typecompiled_storevalue(void)
{
addr args, values;
/* (function (t &optional (or condition null)) null) */
GetTypeTable(&args, T);
GetTypeTable(&values, ConditionNull);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, &args);
SetTypeCompiled(StoreValue, args);
}
static void typecompiled_macroreader(void)
{
/* (function (stream character) *) */
addr args, values, type;
GetTypeTable(&args, Stream);
GetTypeTable(&type, Character);
typeargs_var2(&args, args, type);
GetTypeTable(&values, Asterisk);
type_compiled_heap(args, values, &args);
SetTypeCompiled(MacroReader, args);
}
static void typecompiled_macrodispatch(void)
{
/* (function (stream character intplus-null) *) */
addr args, values, type, intplus;
GetTypeTable(&args, Stream);
GetTypeTable(&type, Character);
GetTypeTable(&intplus, IntplusNull);
typeargs_var3(&args, args, type, intplus);
GetTypeTable(&values, Asterisk);
type_compiled_heap(args, values, &args);
SetTypeCompiled(MacroDispatch, args);
}
static void typecompiled_read(void)
{
addr args, values, type;
/* (function (&optional input-stream-designer t t t) (values t &rest nil)) */
GetTypeTable(&args, StreamDesigner);
GetTypeTable(&type, T);
list_heap(&args, args, type, type, type, NULL);
typeargs_full(&args, Nil, args, Nil, Nil);
typevalues_result(&values, type);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Read, args);
}
static void typecompiled_sublis(void)
{
/* (function
* (list list
* &key (:key (or (function (t &rest t) *) symbol))
* (:test (or (function (t t &rest t) *) symbol))
* (:test-not (or (function (t t &rest t) *) symbol)))
* (values list &rest nil))
*/
addr args, values, list, tree;
GetTypeTable(&list, List);
GetTypeTable(&tree, T);
GetTypeTable(&args, KeyTestList);
typeargs_var2key(&args, list, tree, args);
typevalues_result(&values, list);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Sublis, args);
}
static void typecompiled_subst(void)
{
/* (function
* (t t t
* &key (:key (or (function (t &rest t) *) symbol))
* (:test (or (function (t t &rest t) *) symbol))
* (:test-not (or (function (t t &rest t) *) symbol)))
* (values t &rest nil))
*/
addr args, values, type;
GetTypeTable(&type, T);
GetTypeTable(&args, KeyTestList);
typeargs_var3key(&args, type, type, type, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Subst, args);
}
static void typecompiled_subst_if(void)
{
/* (function
* (t (or (function (t &rest t) *) symbol) t
* &key (:key (or (function (t &rest t) *) symbol)))
* (values t &rest nil))
*/
addr args, values, type, call, key;
GetTypeTable(&type, T);
GetTypeTable(&call, FunctionDesigner);
GetConst(KEYWORD_KEY, &key);
cons_heap(&key, key, call);
conscar_heap(&key, key);
typeargs_var3key(&args, type, call, type, key);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(SubstIf, args);
}
static void typecompiled_eq(void)
{
/* (function (t t) boolean) */
addr args, values;
GetTypeTable(&args, T);
typeargs_var2(&args, args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Eq, args);
}
static void typecompiled_every(void)
{
/* (function (function-designer sequence &rest sequence)
* (values boolean &rest nil))
*/
addr args, values, call, sequence;
GetTypeTable(&call, FunctionDesigner);
GetTypeTable(&sequence, Sequence);
typeargs_var2rest(&args, call, sequence, sequence);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Every, args);
}
static void typecompiled_number_equal(void)
{
/* (function (number &rest number) (values boolean &rest nil)) */
addr args, values;
GetTypeTable(&args, Number);
typeargs_var1rest(&args, args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Number_Equal, args);
}
static void typecompiled_number_compare(void)
{
/* (function (real &rest real) (values boolean &rest nil)) */
addr args, values;
GetTypeTable(&args, Real);
typeargs_var1rest(&args, args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Number_Compare, args);
}
static void typecompiled_max(void)
{
/* (function (real &rest real) (values real &rest nil)) */
addr args, values;
GetTypeTable(&values, Real);
typeargs_var1rest(&args, values, values);
GetTypeValues(&values, Real);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Max, args);
}
static void typecompiled_minusp(void)
{
/* (function (real) (values boolean &rest nil)) */
addr args, values;
GetTypeTable(&args, Real);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Minusp, args);
}
static void typecompiled_zerop(void)
{
/* (function (number) (values boolean &rest nil)) */
addr args, values;
GetTypeTable(&args, Number);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Zerop, args);
}
static void typecompiled_plus(void)
{
/* (function (&rest number) (values number &rest nil)) */
addr args, values;
GetTypeTable(&values, Number);
typeargs_rest(&args, values);
GetTypeValues(&values, Number);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Plus, args);
}
static void typecompiled_minus(void)
{
/* (function (number &rest number) (values number &rest nil)) */
addr args, values;
GetTypeTable(&values, Number);
typeargs_var1rest(&args, values, values);
GetTypeValues(&values, Number);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Minus, args);
}
static void typecompiled_oneplus(void)
{
/* (function (number) (values number &rest nil)) */
addr args, values;
GetTypeTable(&values, Number);
typeargs_var1(&args, values);
GetTypeValues(&values, Number);
type_compiled_heap(args, values, &args);
SetTypeCompiled(OnePlus, args);
}
static void typecompiled_hashtablecount(void)
{
/* (function (hash-table) (values Index &rest nil)) */
addr args, values;
GetTypeTable(&args, Hashtable);
typeargs_var1(&args, args);
GetTypeTable(&values, Index);
typevalues_result(&values, values);
type_compiled_heap(args, values, &args);
SetTypeCompiled(HashTableCount, args);
}
static void typecompiled_evenp(void)
{
/* (function (integer) (values boolean &res nil) */
addr args, values;
GetTypeTable(&args, Integer);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Evenp, args);
}
static void typecompiled_export(void)
{
/* (function
* ((or list symbol) &optional package-designer)
* (values (eql t) &rest nil))
*/
addr args, values;
GetTypeTable(&args, SymbolList);
GetTypeTable(&values, PackageDesigner);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, EqlT);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Export, args);
}
static void typecompiled_usepackage(void)
{
/* (function
* ((or list package-designer) &optional package-designer)
* (values (eql t) &rest nil))
*/
addr args, values;
GetTypeTable(&args, List);
GetTypeTable(&values, PackageDesigner);
type2or_heap(args, values, &args);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, EqlT);
type_compiled_heap(args, values, &args);
SetTypeCompiled(UsePackage, args);
}
static void typecompiled_intern(void)
{
/* (function
* (string &optional package-designer)
* (values symbol (member :internal :external :inherited nil) &rest nil))
*/
addr args, values, symbol, key1, key2, key3, status;
/* args */
GetTypeTable(&args, String);
GetTypeTable(&values, PackageDesigner);
typeargs_var1opt1(&args, args, values);
/* values */
GetTypeTable(&symbol, Symbol);
GetConst(KEYWORD_INTERNAL, &key1);
GetConst(KEYWORD_EXTERNAL, &key2);
GetConst(KEYWORD_INHERITED, &key3);
type_member_heap(&status, key1, key2, key3, Nil, NULL);
typevalues_values2(&values, symbol, status);
/* result */
type_compiled_heap(args, values, &args);
SetTypeCompiled(Intern, args);
}
static void typecompiled_packagenicknames(void)
{
/* (function
* (package-designer)
* (values list &rest nil))
*/
addr args, values;
GetTypeArgs(&args, PackageDesigner);
GetTypeTable(&values, List);
typevalues_result(&values, values);
type_compiled_heap(args, values, &args);
SetTypeCompiled(PackageNicknames, args);
}
static void typecompiled_prin1(void)
{
/* (function
* (t &optional stream-designer)
* (values t &rest nil))
*/
addr args, values;
GetTypeTable(&args, T);
GetTypeTable(&values, StreamDesigner);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Prin1, args);
}
static void typecompiled_prin1tostring(void)
{
/* (function (t) (values string &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
GetTypeValues(&values, String);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Prin1ToString, args);
}
static void typecompiled_reverse(void)
{
/* (function (sequence) (values sequence &rest nil)) */
addr args, values;
GetTypeTable(&values, Sequence);
typeargs_var1(&args, values);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Reverse, args);
}
static void typecompiled_member(void)
{
/* (function (t list &key [KeyTestList]) (values list &rest nil)) */
addr args, values, key;
GetTypeTable(&args, T);
GetTypeTable(&values, List);
GetTypeTable(&key, KeyTestList);
typeargs_var2key(&args, args, values, key);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Member, args);
}
static void typecompiled_memberif(void)
{
/* (function (function-designer list &key (key function-designer))
* (values list &rest nil))
*/
addr args, values, type, key;
GetTypeTable(&type, FunctionDesigner);
GetTypeTable(&args, List);
GetConst(KEYWORD_KEY, &key);
cons_heap(&key, key, type);
conscar_heap(&key, key);
typeargs_var2key(&args, type, args, key);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(MemberIf, args);
}
static void typecompiled_mapc(void)
{
/* (function (function-designer list &rest list)
* (values list &rest nil))
*/
addr args, values, type;
GetTypeTable(&type, FunctionDesigner);
GetTypeTable(&args, List);
typeargs_var2rest(&args, type, args, args);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Mapc, args);
}
static void typecompiled_acons(void)
{
/* (function (t t list) (values list &rest nil)) */
addr args, values, type;
GetTypeTable(&args, T);
GetTypeTable(&type, List);
typeargs_var3(&args, args, args, type);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Acons, args);
}
static void typecompiled_intersection(void)
{
/* (function (list list &key key test test-not) (values list &rest nil)) */
addr args, values;
GetTypeTable(&args, List);
GetTypeTable(&values, KeyTestList);
typeargs_var2key(&args, args, args, values);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Intersection, args);
}
static void typecompiled_ecaseerror(void)
{
/* (function (T list) (values &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
GetTypeTable(&values, List);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Nil);
type_compiled_heap(args, values, &args);
SetTypeCompiled(EcaseError, args);
}
static void typecompiled_dosymbols(void)
{
/* (function (function package-designer) (values &rest nil)) */
addr args, values;
GetTypeTable(&args, Function);
GetTypeTable(&values, PackageDesigner);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Nil);
type_compiled_heap(args, values, &args);
SetTypeCompiled(DoSymbols, args);
}
static void typecompiled_arrayboolean(void)
{
/* (function (array) (values boolean &rest nil)) */
addr args, values;
GetTypeTable(&args, Array);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(ArrayBoolean, args);
}
static void typecompiled_arrayindex(void)
{
/* (function (array) (values index &rest nil)) */
addr args, values;
GetTypeTable(&args, Array);
typeargs_var1(&args, args);
GetTypeValues(&values, Index);
type_compiled_heap(args, values, &args);
SetTypeCompiled(ArrayIndex, args);
}
static void typecompiled_bitand(void)
{
/* (function (bit-array bit-array
* &optional (or boolean bit-array))
* (values bit-array &rest nil))
*/
addr args, values;
GetTypeTable(&args, BitArray);
GetTypeTable(&values, Boolean);
type2or_heap(args, values, &values);
typeargs_var2opt1(&args, args, args, values);
GetTypeValues(&values, BitArray);
type_compiled_heap(args, values, &args);
SetTypeCompiled(BitAnd, args);
}
static void typecompiled_countif(void)
{
/* (function (function-designer sequence
* &key (:from-end t)
* (:start (integer 0 *))
* (:end (or (integer 0 *) null))
* (:key function-designer))
* (values index &rest nil))
*/
addr args, values, key;
GetTypeTable(&args, FunctionDesigner);
GetTypeTable(&values, Sequence);
GetTypeTable(&key, CountIfKey);
typeargs_var2key(&args, args, values, key);
GetTypeValues(&values, Index);
type_compiled_heap(args, values, &args);
SetTypeCompiled(CountIf, args);
}
static void typecompiled_sort(void)
{
/* (function (sequence call &key key) (values sequence &rest nil)) */
addr args, values, type, key;
/* key */
GetConst(KEYWORD_KEY, &key);
GetTypeTable(&type, FunctionDesigner);
cons_heap(&key, key, type);
conscar_heap(&key, key);
/* type */
GetTypeTable(&args, Sequence);
typeargs_var2key(&args, args, type, key);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Sort, args);
}
static void typecompiled_findif(void)
{
/* (function (function-designer sequence
* &key (:from-end t)
* (:start (integer 0 *))
* (:end (or (integer 0 *) null))
* (:key function-designer))
* (values t &rest nil))
*/
addr args, values, key;
GetTypeTable(&args, FunctionDesigner);
GetTypeTable(&values, Sequence);
GetTypeTable(&key, CountIfKey);
typeargs_var2key(&args, args, values, key);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(FindIf, args);
}
static void typecompiled_positionif(void)
{
/* (function (function-designer sequence
* &key (:from-end t)
* (:start (integer 0 *))
* (:end (or (integer 0 *) null))
* (:key function-designer))
* (values index-null &rest nil))
*/
addr args, values, key;
GetTypeTable(&args, FunctionDesigner);
GetTypeTable(&values, Sequence);
GetTypeTable(&key, CountIfKey);
typeargs_var2key(&args, args, values, key);
GetTypeValues(&values, IndexNull);
type_compiled_heap(args, values, &args);
SetTypeCompiled(PositionIf, args);
}
static void typecompiled_search(void)
{
/* (function (sequence1 sequence2
* &key from-end test test-not key start1 start2 end1 end2)
* (values index-null &rest nil))
*/
addr args, values, key;
addr key1, key2, key3, key4, key5, key6, key7, key8;
/* key */
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, TEST, FunctionDesigner);
KeyTypeTable(&key3, TEST_NOT, FunctionDesigner);
KeyTypeTable(&key4, KEY, FunctionDesigner);
KeyTypeTable(&key5, START1, KeywordStart);
KeyTypeTable(&key6, START2, KeywordStart);
KeyTypeTable(&key7, END1, KeywordEnd);
KeyTypeTable(&key8, END2, KeywordEnd);
list_heap(&key, key1, key2, key3, key4, key5, key6, key7, key8, NULL);
/* type */
GetTypeTable(&args, Sequence);
typeargs_var2key(&args, args, args, key);
GetTypeValues(&values, IndexNull);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Search, args);
}
static void typecompiled_substitute(void)
{
/* (function (t t sequence
* &key from-end test test-not key start end count)
* (values sequence &rest nil))
*/
addr args, values, key;
addr key1, key2, key3, key4, key5, key6, key7;
/* key */
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, TEST, FunctionDesigner);
KeyTypeTable(&key3, TEST_NOT, FunctionDesigner);
KeyTypeTable(&key4, KEY, FunctionDesigner);
KeyTypeTable(&key5, START, KeywordStart);
KeyTypeTable(&key6, END, KeywordEnd);
KeyTypeTable(&key7, COUNT, IntegerNull);
list_heap(&key, key1, key2, key3, key4, key5, key6, key7, NULL);
/* type */
GetTypeTable(&args, T);
GetTypeTable(&values, Sequence);
typeargs_var3key(&args, args, args, values, key);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Substitute, args);
}
static void typecompiled_substituteif(void)
{
/* (function (t call sequence
* &key from-end key start end count)
* (values sequence &rest nil))
*/
addr args, values, type, key;
addr key1, key2, key3, key4, key5;
/* key */
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, KEY, FunctionDesigner);
KeyTypeTable(&key3, START, KeywordStart);
KeyTypeTable(&key4, END, KeywordEnd);
KeyTypeTable(&key5, COUNT, IntegerNull);
list_heap(&key, key1, key2, key3, key4, key5, NULL);
/* type */
GetTypeTable(&args, T);
GetTypeTable(&values, FunctionDesigner);
GetTypeTable(&type, Sequence);
typeargs_var3key(&args, args, values, type, key);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(SubstituteIf, args);
}
static void typecompiled_remove(void)
{
/* (function (t sequence
* &key from-end test test-not key start end count)
* (values sequence &rest nil))
*/
addr args, values, key;
addr key1, key2, key3, key4, key5, key6, key7;
/* key */
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, TEST, FunctionDesigner);
KeyTypeTable(&key3, TEST_NOT, FunctionDesigner);
KeyTypeTable(&key4, KEY, FunctionDesigner);
KeyTypeTable(&key5, START, KeywordStart);
KeyTypeTable(&key6, END, KeywordEnd);
KeyTypeTable(&key7, COUNT, IntegerNull);
list_heap(&key, key1, key2, key3, key4, key5, key6, key7, NULL);
/* type */
GetTypeTable(&args, T);
GetTypeTable(&values, Sequence);
typeargs_var2key(&args, args, values, key);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Remove, args);
}
static void typecompiled_removeif(void)
{
/* (function (call sequence
* &key from-end key start end count)
* (values sequence &rest nil))
*/
addr args, values, key;
addr key1, key2, key3, key4, key5;
/* key */
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, KEY, FunctionDesigner);
KeyTypeTable(&key3, START, KeywordStart);
KeyTypeTable(&key4, END, KeywordEnd);
KeyTypeTable(&key5, COUNT, IntegerNull);
list_heap(&key, key1, key2, key3, key4, key5, NULL);
/* type */
GetTypeTable(&args, FunctionDesigner);
GetTypeTable(&values, Sequence);
typeargs_var2key(&args, args, values, key);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(RemoveIf, args);
}
static void typecompiled_removeduplicates(void)
{
/* (function (sequence
* &key from-end test test-not start end key)
* (values sequence &rest nil))
*/
addr args, values, key;
addr key1, key2, key3, key4, key5, key6;
/* key */
KeyTypeTable(&key1, FROM_END, T);
KeyTypeTable(&key2, TEST, FunctionDesigner);
KeyTypeTable(&key3, TEST_NOT, FunctionDesigner);
KeyTypeTable(&key4, KEY, FunctionDesigner);
KeyTypeTable(&key5, START, KeywordStart);
KeyTypeTable(&key6, END, KeywordEnd);
list_heap(&key, key1, key2, key3, key4, key5, key6, NULL);
/* type */
GetTypeTable(&args, Sequence);
typeargs_var1key(&args, args, key);
GetTypeValues(&values, Sequence);
type_compiled_heap(args, values, &args);
SetTypeCompiled(RemoveDuplicates, args);
}
static void typecompiled_namestring(void)
{
/* (function (pathname-designer) (values string &rest nil)) */
addr args, values;
GetTypeTable(&args, PathnameDesigner);
typeargs_var1(&args, args);
GetTypeValues(&values, StringNull);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Namestring, args);
}
static void typecompiled_pathname(void)
{
/* (function (pathname-designer) (values pathname &rest nil)) */
addr args, values;
GetTypeTable(&args, PathnameDesigner);
typeargs_var1(&args, args);
GetTypeValues(&values, Pathname);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Pathname, args);
}
static void typecompiled_inputstreamp(void)
{
/* (function (stream) (values boolean &rest nil)) */
addr args, values;
GetTypeTable(&args, Stream);
typeargs_var1(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(InputStreamP, args);
}
static void typecompiled_exit(void)
{
/* (function (&optional Intplus) (values &rest nil)) */
addr args, values;
GetTypeTable(&args, Intplus);
typeargs_opt1(&args, args);
GetTypeValues(&values, Nil);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Exit, args);
}
static void typecompiled_readchar(void)
{
/* (function (&optional stream-designer t t t) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, StreamDesigner);
GetTypeTable(&values, T);
typeargs_opt4(&args, args, values, values, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(ReadChar, args);
}
static void typecompiled_writestring(void)
{
/* (function (string &optional stream-designer &key start end)
* (values string &rest nil))
*/
addr args, values, var, opt, key, key1, key2;
/* var */
GetTypeTable(&var, String);
conscar_heap(&var, var);
/* opt */
GetTypeTable(&opt, StreamDesigner);
conscar_heap(&opt, opt);
/* key */
KeyTypeTable(&key1, START, KeywordStart);
KeyTypeTable(&key2, END, KeywordEnd);
list_heap(&key, key1, key2, NULL);
/* args */
typeargs_full(&args, var, opt, Nil, key);
/* values */
GetTypeValues(&values, String);
type_compiled_heap(args, values, &args);
SetTypeCompiled(WriteString, args);
}
static void typecompiled_finishoutput(void)
{
/* (function (&optional output-stream) (values null &rest nil)) */
addr args, values;
GetTypeTable(&args, OutputStream);
typeargs_opt1(&args, args);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, &args);
SetTypeCompiled(FinishOutput, args);
}
static void typecompiled_yesornop(void)
{
/* (function (&optional (or string null) &rest t)
* (values boolean &rest nil))
*/
addr args, values;
GetTypeTable(&args, StringNull);
conscar_heap(&args, args);
GetTypeTable(&values, T);
typeargs_full(&args, Nil, args, values, Nil);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(YesOrNoP, args);
}
static void typecompiled_floor(void)
{
/* (function (real &optional real) (values integer real &rest nil) */
addr args, values, type;
GetTypeTable(&type, Real);
typeargs_var1opt1(&args, type, type);
GetTypeTable(&values, Integer);
typevalues_values2(&values, values, type);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Floor, args);
}
static void typecompiled_ffloor(void)
{
/* (function (real &optional real) (values real real &rest nil) */
addr args, values, type;
GetTypeTable(&type, Real);
typeargs_var1opt1(&args, type, type);
typevalues_values2(&values, type, type);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Ffloor, args);
}
static void typecompiled_envinfo(void)
{
/* (function () (values (or string null) &rest nil)) */
addr args, values;
typeargs_empty(&args);
GetTypeValues(&values, StringNull);
type_compiled_heap(args, values, &args);
SetTypeCompiled(EnvInfo, args);
}
static void typecompiled_sin(void)
{
/* (function (number) (values number &rest nil)) */
addr args, values;
GetTypeTable(&args, Number);
typeargs_var1(&args, args);
GetTypeValues(&values, Number);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Sin, args);
}
static void typecompiled_realpart(void)
{
/* (function (number) (values real &rest nil)) */
addr args, values;
GetTypeTable(&args, Number);
typeargs_var1(&args, args);
GetTypeValues(&values, Real);
type_compiled_heap(args, values, &args);
SetTypeCompiled(RealPart, args);
}
static void typecompiled_gcd(void)
{
/* (function (&rest integer) (values (integer 0 *) &rest nil)) */
addr args, values;
GetTypeTable(&args, Integer);
typeargs_rest(&args, args);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Gcd, args);
}
static void typecompiled_mod(void)
{
/* (function (real real) (values real &rest nil)) */
addr args, values;
GetTypeTable(&args, Real);
typeargs_var2(&args, args, args);
GetTypeValues(&values, Real);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Mod, args);
}
static void typecompiled_float_digits(void)
{
/* (function (float) (values (integer 0 *) &rest nil)) */
addr args, values;
GetTypeTable(&args, Float);
typeargs_var1(&args, args);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, &args);
SetTypeCompiled(FloatDigits, args);
}
static void typecompiled_rational(void)
{
/* (function (real) (values rational &rest nil)) */
addr args, values;
GetTypeTable(&args, Real);
typeargs_var1(&args, args);
GetTypeValues(&values, Rational);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Rational, args);
}
static void typecompiled_logand(void)
{
/* (function (&rest integer) (values integer &rest nil)) */
addr args, values;
GetTypeTable(&args, Integer);
typeargs_rest(&args, args);
GetTypeValues(&values, Integer);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Logand, args);
}
static void typecompiled_logandc1(void)
{
/* (function (integer integer) (values integer &rest nil)) */
addr args, values;
GetTypeTable(&args, Integer);
typeargs_var2(&args, args, args);
GetTypeValues(&values, Integer);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Logandc1, args);
}
static void typecompiled_byte_size(void)
{
/* (function (byte) (values (integer 0 *) &rest nil)) */
addr args, values;
GetTypeTable(&args, ByteSpec);
typeargs_var1(&args, args);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, &args);
SetTypeCompiled(ByteSize, args);
}
static void typecompiled_deposit_field(void)
{
/* (function (integer byte integer) (values integer &rest nil)) */
addr args, values;
GetTypeTable(&args, Integer);
GetTypeTable(&values, ByteSpec);
typeargs_var3(&args, args, values, args);
GetTypeValues(&values, Integer);
type_compiled_heap(args, values, &args);
SetTypeCompiled(DepositField, args);
}
static void typecompiled_ldb(void)
{
/* (function (bytespec integer) (values (integer 0 *) &rest nil)) */
addr args, values;
GetTypeTable(&args, ByteSpec);
GetTypeTable(&values, Integer);
typeargs_var2(&args, args, values);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Ldb, args);
}
static void typecompiled_upgraded_type(void)
{
/* (function (typespec &optional environment) (values type &rest nil)) */
addr args, values;
GetTypeTable(&args, TypeSpec);
GetTypeTable(&values, EnvironmentNull);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, TypeSymbol);
type_compiled_heap(args, values, &args);
SetTypeCompiled(UpgradedType, args);
}
static void typecompiled_slot_boundp(void)
{
/* (function (clos symbol) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, Clos);
GetTypeTable(&values, Symbol);
typeargs_var2(&args, args, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(SlotBoundp, args);
}
static void typecompiled_slot_boundp_method(void)
{
/* (function (t t t t symbol) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
GetTypeTable(&values, Symbol);
typeargs_var3(&args, args, args, values);
typeargs_method(args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(SlotBoundp_Method, args);
}
static void typecompiled_reader_method(void)
{
/* (function (t t t) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
typeargs_var1(&args, args);
typeargs_method(args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Reader_Method, args);
}
static void typecompiled_writer_method(void)
{
/* (function (t t t t) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
typeargs_var2(&args, args, args);
typeargs_method(args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Writer_Method, args);
}
static void typecompiled_signal(void)
{
addr args, values;
GetTypeArgs(&args, Error);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, &args);
SetTypeCompiled(Signal, args);
}
static void typecompiled_print_object_method(void)
{
/* (function (t t t stream) (values t &rest nil)) */
addr args, values;
GetTypeTable(&args, T);
GetTypeTable(&values, Stream);
typeargs_var2(&args, args, values);
typeargs_method(args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(PrintObject_Method, args);
}
static void typecompiled_pprint_fill(void)
{
/* (function (output-stream-designer t &optional t t)
* (values null &rest nil))
*/
addr args, values;
GetTypeTable(&args, StreamDesigner);
GetTypeTable(&values, T);
typeargs_var2opt2(&args, args, values, values, values);
GetTypeValues(&values, Null);
type_compiled_heap(args, values, &args);
SetTypeCompiled(PprintFill, args);
}
static void typecompiled_dispatch_function(void)
{
/* (function (output-stream-designer t) (values T &rest nil)) */
addr args, values;
GetTypeTable(&args, StreamDesigner);
GetTypeTable(&values, T);
typeargs_var2(&args, args, values);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(DispatchFunction, args);
}
static void typecompiled_formatter_function(void)
{
addr args, values;
GetTypeTable(&args, Stream);
GetTypeTable(&values, T);
typeargs_var1rest(&args, args, values);
GetTypeValues(&values, List);
type_compiled_heap(args, values, &args);
SetTypeCompiled(FormatterFunction, args);
}
static void typecompiled_get_internal_real_time(void)
{
addr args, values;
GetTypeArgs(&args, Empty);
GetTypeValues(&values, Intplus);
type_compiled_heap(args, values, &args);
SetTypeCompiled(GetInternalRealTime, args);
}
static void typecompiled_remove_file(void)
{
addr args, values;
GetTypeTable(&args, PathnameDesigner);
GetTypeTable(&values, T);
typeargs_var1opt1(&args, args, values);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(RemoveFile, args);
}
static void typecompiled_infobit(void)
{
addr args, values;
GetTypeTable(&args, T);
typeargs_rest(&args, args);
GetTypeValues(&values, T);
type_compiled_heap(args, values, &args);
SetTypeCompiled(InfoBit, args);
}
static void typecompiled_chareql(void)
{
addr args, values;
GetTypeTable(&args, Character);
typeargs_rest(&args, args);
GetTypeValues(&values, Boolean);
type_compiled_heap(args, values, &args);
SetTypeCompiled(CharEql, args);
}
static void typecompiled_make_memory_output_stream(void)
{
addr args, values, key1, key2, key3, key4, key;
/* key */
KeyTypeTable(&key1, INPUT, Sequence);
KeyTypeTable(&key2, SIZE, Plus1Null);
KeyTypeTable(&key3, ARRAY, Plus1Null);
KeyTypeTable(&key4, CACHE, T);
list_heap(&key, key1, key2, key3, key4, NULL);
/* type */
typeargs_key(&args, key);
GetTypeValues(&values, MemoryStream);
type_compiled_heap(args, values, &args);
SetTypeCompiled(MakeMemoryOutputStream, args);
}
/*
* Interface
*/
void build_type_constant(void)
{
/* Atomic-Type */
typetable_Invalid();
typetable_Asterisk();
typetable_Atom();
typetable_List();
typetable_Boolean();
typetable_Clos();
typetable_Vector();
typetable_SimpleVector();
typetable_BitVector();
typetable_ExtendedChar();
typetable_SimpleBitVector();
typetable_String();
typetable_BaseString();
typetable_SimpleString();
typetable_SimpleBaseString();
typetable_SignedByte();
typetable_UnsignedByte();
typetable_Bit();
typetable_Fixnum();
typetable_Bignum();
typetable_Nil();
typetable_T();
typetable_Null();
typetable_Cons();
typetable_Hashtable();
typetable_Symbol();
typetable_Keyword();
typetable_Package();
typetable_RandomState();
typetable_Readtable();
typetable_Function();
typetable_CompiledFunction();
typetable_Pathname();
typetable_LogicalPathname();
typetable_Sequence();
typetable_Array();
typetable_SimpleArray();
typetable_Character();
typetable_BaseChar();
typetable_StandardChar();
typetable_Number();
typetable_Real();
typetable_Rational();
typetable_Ratio();
typetable_Integer();
typetable_Complex();
typetable_Float();
typetable_ShortFloat();
typetable_SingleFloat();
typetable_DoubleFloat();
typetable_LongFloat();
typetable_Restart();
typetable_Environment();
typetable_Stream();
typetable_BroadcastStream();
typetable_ConcatenatedStream();
typetable_EchoStream();
typetable_FileStream();
typetable_StringStream();
typetable_SynonymStream();
typetable_TwoWayStream();
typetable_PromptStream();
typetable_PrettyStream();
typetable_MemoryStream();
typetable_TerminalStream();
typetable_Quote();
typetable_ByteSpec();
typetable_PrintDispatch();
typetable_Eval();
/* Condition */
typetable_ArithmeticError();
typetable_CellError();
typetable_FileError();
typetable_PackageError();
typetable_PrintNotReadable();
typetable_SimpleCondition();
typetable_StreamError();
typetable_TypeError();
/* Type */
typetable_cxr();
typetable_car();
typetable_setf_car();
typetable_characternull();
typetable_stringnull();
typetable_streamnull();
typetable_condition();
typetable_conditionnull();
typetable_restartnull();
typetable_functionnull();
typetable_environmentnull();
typetable_integernull();
typetable_pathnamenull();
typetable_packagenull();
typetable_printdispatchnull();
typetable_stringdesigner();
typetable_packagedesigner();
typetable_packagedesignernull();
typetable_functiondesigner();
typetable_restartdesigner();
typetable_pathnamedesigner();
typetable_streamdesigner();
typetable_readtabledesigner();
typetable_conditiondesigner();
typetable_index();
typetable_indexnull();
typetable_plus1();
typetable_plus1null();
typetable_intplus();
typetable_intplusnull();
typetable_input_stream();
typetable_output_stream();
typetable_typespec();
typetable_typesymbol();
typetable_bit_array();
typetable_simple_bit_array();
typetable_keywordstart();
typetable_keywordend();
typetable_keystart1end1();
typetable_keystart2end2();
typetable_functionname();
typetable_radixinteger();
typetable_floatsymbol();
typetable_eqlt();
typetable_case_sensitivity();
typetable_print_case();
typetable_keytestlist();
typetable_rehashsize();
typetable_rehashthreshold();
typetable_countkey();
typetable_countifkey();
typetable_pathnamehost();
typetable_pathnamedevice();
typetable_pathnamedirectory();
typetable_pathnamename();
typetable_pathnametype();
typetable_pathnameversion();
typetable_signed8();
typetable_signed16();
typetable_signed32();
typetable_unsigned8();
typetable_unsigned16();
typetable_unsigned32();
#ifdef LISP_64BIT
typetable_signed64();
typetable_unsigned64();
#endif
typetable_opendirection();
typetable_openelementtype();
typetable_openifexists();
typetable_openifdoesnotexist();
typetable_externalformat();
typetable_pprint_newline();
typetable_pprint_tabular();
typetable_format();
typetable_time_second();
typetable_time_hour();
typetable_time_day();
typetable_time_month();
typetable_time_zone();
typetable_symbol_list();
typetable_string_list();
typetable_string_designer_list();
typetable_package_designer_list();
typetable_method();
typetable_class();
typetable_classnull();
typetable_standardclass();
typetable_standardobject();
typetable_structureclass();
typetable_structureobject();
typetable_standard_method();
typetable_methodcombination();
typetable_generic_function();
/* Array */
typetable_array_t();
typetable_array_bit();
typetable_array_character();
typetable_array_singlefloat();
typetable_array_doublefloat();
typetable_array_longfloat();
typetable_array_signed8();
typetable_array_signed16();
typetable_array_signed32();
typetable_array_unsigned8();
typetable_array_unsigned16();
typetable_array_unsigned32();
#ifdef LISP_64BIT
typetable_array_signed64();
typetable_array_unsigned64();
#endif
/* Arguments */
typeargs_empty_constant();
typeargs_optconditionnull();
typeargs_packagedesigner();
typeargs_pathnamecase();
typeargs_error();
/* Values */
typevalues_Nil();
typevalues_T();
typevalues_Null();
typevalues_Cons();
typevalues_List();
typevalues_Boolean();
typevalues_Character();
typevalues_CharacterNull();
typevalues_Symbol();
typevalues_Vector();
typevalues_SimpleVector();
typevalues_String();
typevalues_StringNull();
typevalues_SimpleString();
typevalues_Stream();
typevalues_StreamNull();
typevalues_PrettyStream();
typevalues_MemoryStream();
typevalues_Function();
typevalues_FunctionNull();
typevalues_EqlT();
typevalues_Package();
typevalues_PackageNull();
typevalues_Sequence();
typevalues_Array();
typevalues_Integer();
typevalues_Ratio();
typevalues_Rational();
typevalues_Index();
typevalues_IndexNull();
typevalues_Intplus();
typevalues_IntplusNull();
typevalues_Bit();
typevalues_BitArray();
typevalues_Pathname();
typevalues_PathnameNull();
typevalues_LogicalPathname();
typevalues_Float();
typevalues_Real();
typevalues_Number();
typevalues_Complex();
typevalues_TypeSymbol();
typevalues_Class();
typevalues_ClassNull();
typevalues_MethodCombination();
typevalues_GenericFunction();
typevalues_decode_universal_time();
typevalues_empty();
/* Compiled-Function */
typecompiled_object_boolean();
typecompiled_symbol_boolean();
typecompiled_stringcase();
typecompiled_nstringcase();
typecompiled_stringtrim();
typecompiled_stringequal();
typecompiled_stringmismatch();
typecompiled_rplaca();
typecompiled_list_list();
typecompiled_nth();
typecompiled_nconc();
typecompiled_renconc();
typecompiled_butlast();
typecompiled_macrofunction();
typecompiled_macroexpand();
typecompiled_abort();
typecompiled_continue();
typecompiled_storevalue();
typecompiled_macroreader();
typecompiled_macrodispatch();
typecompiled_read();
typecompiled_sublis();
typecompiled_subst();
typecompiled_subst_if();
typecompiled_eq();
typecompiled_every();
typecompiled_number_equal();
typecompiled_number_compare();
typecompiled_max();
typecompiled_minusp();
typecompiled_zerop();
typecompiled_plus();
typecompiled_minus();
typecompiled_oneplus();
typecompiled_hashtablecount();
typecompiled_evenp();
typecompiled_export();
typecompiled_usepackage();
typecompiled_intern();
typecompiled_packagenicknames();
typecompiled_prin1();
typecompiled_prin1tostring();
typecompiled_reverse();
typecompiled_member();
typecompiled_memberif();
typecompiled_mapc();
typecompiled_acons();
typecompiled_intersection();
typecompiled_ecaseerror();
typecompiled_dosymbols();
typecompiled_arrayboolean();
typecompiled_arrayindex();
typecompiled_bitand();
typecompiled_countif();
typecompiled_sort();
typecompiled_findif();
typecompiled_positionif();
typecompiled_search();
typecompiled_substitute();
typecompiled_substituteif();
typecompiled_remove();
typecompiled_removeif();
typecompiled_removeduplicates();
typecompiled_namestring();
typecompiled_pathname();
typecompiled_inputstreamp();
typecompiled_exit();
typecompiled_readchar();
typecompiled_writestring();
typecompiled_finishoutput();
typecompiled_yesornop();
typecompiled_floor();
typecompiled_ffloor();
typecompiled_envinfo();
typecompiled_sin();
typecompiled_realpart();
typecompiled_gcd();
typecompiled_mod();
typecompiled_float_digits();
typecompiled_rational();
typecompiled_logand();
typecompiled_logandc1();
typecompiled_byte_size();
typecompiled_deposit_field();
typecompiled_ldb();
typecompiled_upgraded_type();
typecompiled_slot_boundp();
typecompiled_slot_boundp_method();
typecompiled_reader_method();
typecompiled_writer_method();
typecompiled_signal();
typecompiled_print_object_method();
typecompiled_pprint_fill();
typecompiled_dispatch_function();
typecompiled_formatter_function();
typecompiled_get_internal_real_time();
typecompiled_remove_file();
typecompiled_infobit();
typecompiled_chareql();
typecompiled_make_memory_output_stream();
}
/************************************************************
* type_copy.c
************************************************************/
typedef void (*call_type_copy)(LocalRoot, addr *, addr);
static call_type_copy TypeCopyTable[LISPDECL_SIZE];
static void type_copy_error(LocalRoot local, addr *ret, addr type)
{
infobit(type);
Abort("Invalid type.");
}
static void getset_arraytype(LocalRoot local, addr dst, addr src, size_t index)
{
Check(GetType(dst) != LISPTYPE_TYPE, "type left error");
Check(GetType(src) != LISPTYPE_TYPE, "type right error");
GetArrayType(src, index, &src);
copylocal_object(local, &src, src);
SetArrayType(dst, index, src);
}
static void getsettype_arraytype(LocalRoot local, addr dst, addr src, size_t index)
{
Check(GetType(dst) != LISPTYPE_TYPE, "type left error");
Check(GetType(src) != LISPTYPE_TYPE, "type right error");
GetArrayType(src, index, &src);
type_copy_alloc(local, &src, src);
SetArrayType(dst, index, src);
}
static void getset_array4(LocalRoot local, addr dst, addr src, size_t index)
{
Check(GetStatusSize(dst) != LISPSIZE_ARRAY4, "size dst error");
Check(GetStatusSize(src) != LISPSIZE_ARRAY4, "size src error");
GetArrayA4(src, index, &src);
copylocal_object(local, &src, src);
SetArrayA4(dst, index, src);
}
static void getsettype_array4(LocalRoot local, addr dst, addr src, size_t index)
{
Check(GetStatusSize(dst) != LISPSIZE_ARRAY4, "size dst error");
Check(GetStatusSize(src) != LISPSIZE_ARRAY4, "size src error");
GetArrayA4(src, index, &src);
type_copy_alloc(local, &src, src);
SetArrayA4(dst, index, src);
}
static void typecopy_empty(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
GetLispDecl(type, &decl);
Check(lenarrayr(type) != 0, "length error");
type0_alloc(local, decl, ret);
}
static void typecopy_allobject(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr pos;
size_t size, i;
GetLispDecl(type, &decl);
LenArrayType(type, &size);
type_alloc(local, &pos, decl, (byte)size);
for (i = 0; i < size; i++)
getset_arraytype(local, pos, type, i);
*ret = pos;
}
static void typecopy_alltype(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr pos;
size_t size, i;
GetLispDecl(type, &decl);
LenArrayType(type, &size);
type_alloc(local, &pos, decl, (byte)size);
for (i = 0; i < size; i++)
getsettype_arraytype(local, pos, type, i);
*ret = pos;
}
static void typecopy_vector_alltype(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr src, dst, pos;
size_t size, i;
GetLispDecl(type, &decl);
GetArrayType(type, 0, &src);
LenArrayA4(src, &size);
vector4_alloc(local, &dst, size);
for (i = 0; i < size; i++)
getsettype_array4(local, dst, src, i);
type_alloc(local, &pos, decl, 1);
SetArrayType(pos, 0, dst);
*ret = pos;
}
static void typecopy_error_object(LocalRoot local, addr *ret, addr type)
{
addr expr;
GetArrayType(type, 0, &expr);
GetArrayType(type, 1, &type);
if (type != Nil)
type_copy_alloc(local, &type, type);
copylocal_object(local, &expr, expr);
type2_alloc(local, LISPDECL_ERROR, expr, type, &type);
*ret = type;
}
static void typecopy_clos(LocalRoot local, addr *ret, addr type)
{
addr check;
if (local == NULL && GetStatusDynamic(type)) {
GetArrayType(type, 0, &check);
if (GetStatusDynamic(check))
Abort("dynamic scope error");
}
GetArrayType(type, 0, &type);
type1_alloc(local, LISPDECL_CLOS, type, &type);
*ret = type;
}
static void typecopy_eql(LocalRoot local, addr *ret, addr type)
{
GetArrayType(type, 0, &type);
copylocal_object(local, &type, type);
type1_alloc(local, LISPDECL_EQL, type, &type);
*ret = type;
}
static void typecopy_member(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr src, dst, pos;
size_t size, i;
GetLispDecl(type, &decl);
GetArrayType(type, 0, &src);
LenArrayA4(src, &size);
vector4_alloc(local, &dst, size);
for (i = 0; i < size; i++)
getset_array4(local, dst, src, i);
type_alloc(local, &pos, decl, 1);
SetArrayType(pos, 0, dst);
*ret = pos;
}
static void copylist_type(LocalRoot local, addr *ret, addr cons)
{
addr root, child;
for (root = Nil; cons != Nil; ) {
GetCons(cons, &child, &cons);
type_copy_alloc(local, &child, child);
cons_alloc(local, &root, child, root);
}
nreverse(ret, root);
}
static void copylist_arraytype(LocalRoot local, addr dst, addr src, size_t index)
{
GetArrayType(src, index, &src);
copylist_type(local, &src, src);
SetArrayType(dst, index, src);
}
static void typecopy_values(LocalRoot local, addr *ret, addr type)
{
addr pos, check;
type_alloc(local, &pos, LISPDECL_VALUES, 4);
/* var */
copylist_arraytype(local, pos, type, 0);
/* opt */
copylist_arraytype(local, pos, type, 1);
/* rest */
GetArrayType(type, 2, &check);
if (check != Nil) {
type_copy_alloc(local, &check, check);
SetArrayType(pos, 2, check);
}
/* allow */
getset_arraytype(local, pos, type, 3);
*ret = pos;
}
static void typecopy_vector(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr pos, child;
GetLispDecl(type, &decl);
type_alloc(local, &pos, decl, 2);
/* type */
getsettype_arraytype(local, pos, type, 0);
/* dimension */
GetArrayType(type, 1, &child);
if (GetType(child) == LISPTYPE_FIXNUM)
copylocal_object(local, &child, child);
else
type_copy_alloc(local, &child, child);
SetArrayType(pos, 1, child);
*ret = pos;
}
static void typecopy_size(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr pos, child;
GetLispDecl(type, &decl);
type_alloc(local, &pos, decl, 1);
GetArrayType(type, 0, &child);
if (integerp(child))
copylocal_object(local, &child, child);
else
type_copy_alloc(local, &child, child);
SetArrayType(pos, 0, child);
*ret = pos;
}
static void typecopy_function_key(LocalRoot local, addr *ret, addr list)
{
addr root, name, type;
if (list == T) {
*ret = T;
return;
}
for (root = Nil; list != Nil; ) {
GetCons(list, &name, &list);
GetCons(name, &name, &type);
type_copy_alloc(local, &type, type);
cons_alloc(local, &name, name, type);
cons_alloc(local, &root, name, root);
}
nreverse(ret, root);
}
static void typecopy_function_arguments(LocalRoot local, addr *ret, addr src)
{
addr dst, pos;
if (type_asterisk_p(src)) {
type_copy_alloc(local, ret, src);
return;
}
vector2_alloc(local, &dst, 4);
/* var */
GetArrayA2(src, 0, &pos);
copylist_type(local, &pos, pos);
SetArrayA2(dst, 0, pos);
/* opt */
GetArrayA2(src, 1, &pos);
copylist_type(local, &pos, pos);
SetArrayA2(dst, 1, pos);
/* rest */
GetArrayA2(src, 2, &pos);
if (pos != Nil)
type_copy_alloc(local, &pos, pos);
SetArrayA2(dst, 2, pos);
/* key */
GetArrayA2(src, 3, &pos);
typecopy_function_key(local, &pos, pos);
SetArrayA2(dst, 3, pos);
*ret = dst;
}
static void typecopy_function(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr pos, child;
GetLispDecl(type, &decl);
type_alloc(local, &pos, decl, 3);
/* arguments */
GetArrayType(type, 0, &child);
typecopy_function_arguments(local, &child, child);
SetArrayType(pos, 0, child);
/* result */
getsettype_arraytype(local, pos, type, 1);
/* check */
getset_arraytype(local, pos, type, 2);
*ret = pos;
}
static void typecopy_array_dimension(LocalRoot local, addr *ret, addr src)
{
addr dst, pos;
size_t size, i;
if (type_asterisk_p(src)) {
type_copy_alloc(local, ret, src);
return;
}
if (GetType(src) == LISPTYPE_FIXNUM) {
copylocal_object(local, ret, src);
return;
}
Check(GetType(src) != LISPTYPE_VECTOR, "type error");
LenArrayA4(src, &size);
vector4_alloc(local, &dst, size);
for (i = 0; i < size; i++) {
GetArrayA4(src, i, &pos);
if (GetType(pos) == LISPTYPE_TYPE)
type_copy_alloc(local, &pos, pos);
else
copylocal_object(local, &pos, pos);
SetArrayA4(dst, i, pos);
}
*ret = dst;
}
static void typecopy_array(LocalRoot local, addr *ret, addr type)
{
enum LISPDECL decl;
addr pos, child;
GetLispDecl(type, &decl);
type_alloc(local, &pos, decl, 2);
/* arguments */
getsettype_arraytype(local, pos, type, 0);
/* dimension */
GetArrayType(type, 1, &child);
typecopy_array_dimension(local, &child, child);
SetArrayType(pos, 1, child);
*ret = pos;
}
void init_type_copy(void)
{
int i;
for (i = 0; i < LISPDECL_SIZE; i++)
TypeCopyTable[i] = type_copy_error;
TypeCopyTable[LISPDECL_ERROR] = typecopy_error_object;
TypeCopyTable[LISPDECL_INVALID] = typecopy_empty;
TypeCopyTable[LISPDECL_TYPE] = typecopy_empty;
TypeCopyTable[LISPDECL_CLOS] = typecopy_clos;
TypeCopyTable[LISPDECL_ASTERISK] = typecopy_allobject;
TypeCopyTable[LISPDECL_OPTIMIZED] = typecopy_alltype;
TypeCopyTable[LISPDECL_SUBTYPEP] = typecopy_alltype;
/* Compound-type */
TypeCopyTable[LISPDECL_AND] = typecopy_vector_alltype;
TypeCopyTable[LISPDECL_OR] = typecopy_vector_alltype;
TypeCopyTable[LISPDECL_EQL] = typecopy_eql;
TypeCopyTable[LISPDECL_MEMBER] = typecopy_member;
TypeCopyTable[LISPDECL_MOD] = typecopy_allobject;
TypeCopyTable[LISPDECL_NOT] = typecopy_alltype;
TypeCopyTable[LISPDECL_SATISFIES] = typecopy_allobject;
TypeCopyTable[LISPDECL_VALUES] = typecopy_values;
/* Extract-type */
TypeCopyTable[LISPDECL_ATOM] = typecopy_empty;
TypeCopyTable[LISPDECL_LIST] = typecopy_empty;
TypeCopyTable[LISPDECL_BOOLEAN] = typecopy_empty;
TypeCopyTable[LISPDECL_VECTOR] = typecopy_vector;
TypeCopyTable[LISPDECL_SIMPLE_VECTOR] = typecopy_size;
TypeCopyTable[LISPDECL_BIT_VECTOR] = typecopy_size;
TypeCopyTable[LISPDECL_SIMPLE_BIT_VECTOR] = typecopy_size;
TypeCopyTable[LISPDECL_EXTENDED_CHAR] = typecopy_empty;
TypeCopyTable[LISPDECL_STRING] = typecopy_size;
TypeCopyTable[LISPDECL_BASE_STRING] = typecopy_size;
TypeCopyTable[LISPDECL_SIMPLE_STRING] = typecopy_size;
TypeCopyTable[LISPDECL_SIMPLE_BASE_STRING] = typecopy_size;
TypeCopyTable[LISPDECL_SIGNED_BYTE] = typecopy_size;
TypeCopyTable[LISPDECL_UNSIGNED_BYTE] = typecopy_size;
TypeCopyTable[LISPDECL_BIT] = typecopy_empty;
TypeCopyTable[LISPDECL_FIXNUM] = typecopy_empty;
TypeCopyTable[LISPDECL_BIGNUM] = typecopy_empty;
/* Atomic-type */
TypeCopyTable[LISPDECL_NIL] = typecopy_empty;
TypeCopyTable[LISPDECL_T] = typecopy_empty;
TypeCopyTable[LISPDECL_NULL] = typecopy_empty;
TypeCopyTable[LISPDECL_CONS] = typecopy_alltype;
TypeCopyTable[LISPDECL_HASH_TABLE] = typecopy_empty;
TypeCopyTable[LISPDECL_SYMBOL] = typecopy_empty;
TypeCopyTable[LISPDECL_KEYWORD] = typecopy_empty;
TypeCopyTable[LISPDECL_PACKAGE] = typecopy_empty;
TypeCopyTable[LISPDECL_RANDOM_STATE] = typecopy_empty;
TypeCopyTable[LISPDECL_READTABLE] = typecopy_empty;
TypeCopyTable[LISPDECL_FUNCTION] = typecopy_function;
TypeCopyTable[LISPDECL_COMPILED_FUNCTION] = typecopy_function;
TypeCopyTable[LISPDECL_PATHNAME] = typecopy_empty;
TypeCopyTable[LISPDECL_LOGICAL_PATHNAME] = typecopy_empty;
TypeCopyTable[LISPDECL_SEQUENCE] = typecopy_empty;
TypeCopyTable[LISPDECL_ARRAY] = typecopy_array;
TypeCopyTable[LISPDECL_SIMPLE_ARRAY] = typecopy_array;
TypeCopyTable[LISPDECL_CHARACTER] = typecopy_empty;
TypeCopyTable[LISPDECL_BASE_CHAR] = typecopy_empty;
TypeCopyTable[LISPDECL_STANDARD_CHAR] = typecopy_empty;
TypeCopyTable[LISPDECL_NUMBER] = typecopy_empty;
TypeCopyTable[LISPDECL_REAL] = typecopy_allobject;
TypeCopyTable[LISPDECL_RATIO] = typecopy_allobject;
TypeCopyTable[LISPDECL_INTEGER] = typecopy_allobject;
TypeCopyTable[LISPDECL_RATIONAL] = typecopy_allobject;
TypeCopyTable[LISPDECL_COMPLEX] = typecopy_alltype;
TypeCopyTable[LISPDECL_FLOAT] = typecopy_allobject;
TypeCopyTable[LISPDECL_SHORT_FLOAT] = typecopy_allobject;
TypeCopyTable[LISPDECL_SINGLE_FLOAT] = typecopy_allobject;
TypeCopyTable[LISPDECL_DOUBLE_FLOAT] = typecopy_allobject;
TypeCopyTable[LISPDECL_LONG_FLOAT] = typecopy_allobject;
TypeCopyTable[LISPDECL_RESTART] = typecopy_empty;
TypeCopyTable[LISPDECL_ENVIRONMENT] = typecopy_empty;
TypeCopyTable[LISPDECL_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_BROADCAST_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_CONCATENATED_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_ECHO_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_FILE_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_STRING_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_SYNONYM_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_TWO_WAY_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_PROMPT_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_PRETTY_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_MEMORY_STREAM] = typecopy_empty;
TypeCopyTable[LISPDECL_QUOTE] = typecopy_empty;
TypeCopyTable[LISPDECL_BYTESPEC] = typecopy_empty;
TypeCopyTable[LISPDECL_PRINT_DISPATCH] = typecopy_empty;
TypeCopyTable[LISPDECL_EVAL] = typecopy_empty;
}
/*
* type-copy
*/
void type_copy_alloc(LocalRoot local, addr *ret, addr type)
{
call_type_copy call;
addr pos;
CheckType(type, LISPTYPE_TYPE);
call = TypeCopyTable[(int)RefLispDecl(type)];
Check(call == NULL, "build error");
call(local, &pos, type);
type_setnotobject(pos, type);
*ret = pos;
}
void type_copy_local(LocalRoot local, addr *ret, addr type)
{
Check(local == NULL, "local error");
type_copy_alloc(local, ret, type);
}
void type_copy_heap(addr *ret, addr type)
{
type_copy_alloc(NULL, ret, type);
}
/*
* type-throw
*/
void type_throw_alloc(LocalRoot local, addr pos, addr *ret)
{
if (local)
type_throw_local(local, pos, ret);
else
type_throw_heap(pos, ret);
}
void type_throw_local(LocalRoot local, addr pos, addr *ret)
{
CheckLocal(local);
if (GetStatusDynamic(pos))
*ret = pos;
else
type_copy_local(local, ret, pos);
}
void type_throw_heap(addr pos, addr *ret)
{
if (GetStatusDynamic(pos))
type_copy_heap(ret, pos);
else
*ret = pos;
}
/************************************************************
* type_deftype.c
************************************************************/
void getdeftype(addr symbol, addr *ret)
{
CheckSymbol(symbol);
getdeftype_symbol(symbol, ret);
}
int setdeftype_(addr symbol, addr pos)
{
CheckSymbol(symbol);
return setdeftype_symbol_(symbol, pos);
}
int symbol_deftypep(addr symbol)
{
CheckSymbol(symbol);
getdeftype(symbol, &symbol);
return symbol != Nil;
}
int execute_list_deftype(Execute ptr, addr *ret, addr list, addr env)
{
addr call, symbol;
CheckType(list, LISPTYPE_CONS);
GetCar(list, &symbol);
CheckSymbol(symbol);
getdeftype(symbol, &call);
if (call == Nil)
return Result(ret, NULL);
return callclang_funcall(ptr, ret, call, list, env, NULL);
}
int execute_symbol_deftype(Execute ptr, addr *ret, addr symbol, addr env)
{
addr call;
CheckSymbol(symbol);
getdeftype(symbol, &call);
if (call == Nil)
return Result(ret, NULL);
/* name -> (call `(name ,@args) env) */
cons_heap(&symbol, symbol, Nil);
return callclang_funcall(ptr, ret, call, symbol, env, NULL);
}
/*
* deftype
*/
int deftype_common(Execute ptr, addr form, addr env, addr *ret)
{
addr right, eval, name, args, decl, doc;
/* (deftype . form) */
Return_getcdr(form, &right);
if (right == Nil)
return fmte_("deftype form must have at least a name and body.", NULL);
if (! consp(right))
return fmte_("Invalid deftype form.", NULL);
/* name */
Return_getcons(right, &name, &right);
if (! symbolp(name))
return fmte_("deftype name ~S must be a symbol.", name, NULL);
if (right == Nil)
return fmte_("deftype form must have at least a name and body.", NULL);
if (! consp(right))
return fmte_("Invalid deftype form.", NULL);
/* args */
Return_getcons(right, &args, &right);
if (! IsList(right))
return fmte_("Invalid deftype form.", NULL);
/* parse */
Return(lambda_deftype_(ptr->local, &args, args, Nil));
Return(declare_body_documentation_(ptr, env, right, &doc, &decl, &right));
/* (eval::deftype name args decl doc body) */
GetConst(SYSTEM_DEFTYPE, &eval);
list_heap(ret, eval, name, args, decl, doc, right, NULL);
return 0;
}
/************************************************************
* type_error.c
************************************************************/
static int get_error_type_no_error(Execute ptr, addr pos, addr *ret)
{
int notp;
addr expr, type;
CheckType(pos, LISPTYPE_TYPE);
Check(RefLispDecl(pos) != LISPDECL_ERROR, "decl error");
GetArrayType(pos, 1, &type);
if (type != Nil)
return Result(ret, type);
/* parse-type */
GetNotDecl(pos, ¬p);
GetArrayType(pos, 0, &expr);
if (notp) {
Return(parse_type_not(ptr, &type, expr, Nil));
}
else {
Return(parse_type(ptr, &type, expr, Nil));
}
/* error check */
if (type_error_p(type))
return Result(ret, Nil);
/* Result */
if (notp) {
SetNotDecl(pos, 0);
}
SetArrayType(pos, 1, type);
return Result(ret, type);
}
int get_error_type_(Execute ptr, addr pos, addr *ret)
{
addr check;
Return(get_error_type_no_error(ptr, pos, &check));
if (check != Nil)
return Result(ret, check);
/* error */
*ret = Nil;
GetArrayType(pos, 0, &check);
return call_type_error_va_(ptr, check, Nil, "Invalid type-spec ~S.", check, NULL);
}
/*
* check-error-type
*/
typedef int (*type_error_calltype)(Execute, addr, int, int *);
static type_error_calltype TypeErrorCall[LISPDECL_SIZE];
static int check_error_call_(Execute ptr, addr pos, int errorp, int *ret)
{
LispDecl decl;
type_error_calltype call_;
CheckType(pos, LISPTYPE_TYPE);
GetLispDecl(pos, &decl);
call_ = TypeErrorCall[decl];
if (call_ == NULL)
return Result(ret, 1);
return (*call_)(ptr, pos, errorp ,ret);
}
static int check_error_type_error_(Execute ptr, addr pos, int errorp, int *ret)
{
addr check;
Return(get_error_type_no_error(ptr, pos, &check));
if (check != Nil)
return Result(ret, 1);
if (! errorp)
return Result(ret, 0);
/* type-error */
*ret = 0;
GetArrayType(pos, 0, &check);
return call_type_error_va_(ptr, check, Nil, "Invalid type-spec ~S.", check, NULL);
}
static int check_error_type_get1_(Execute ptr, addr pos, int errorp, int *ret)
{
GetArrayType(pos, 0, &pos);
return check_error_call_(ptr, pos, errorp, ret);
}
static int check_error_type_loop1_(Execute ptr, addr pos, int errorp, int *ret)
{
int check;
addr vector;
size_t size, i;
GetArrayType(pos, 0, &vector);
LenArrayA4(vector, &size);
for (i = 0; i < size; i++) {
GetArrayA4(vector, i, &pos);
Return(check_error_call_(ptr, pos, errorp, &check));
if (! check)
return Result(ret, 0);
}
return Result(ret, 1);
}
static int check_error_type_cons_(Execute ptr, addr pos, int errorp, int *ret)
{
int check;
addr x;
/* car */
GetArrayType(pos, 0, &x);
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
/* cdr */
GetArrayType(pos, 1, &x);
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
return Result(ret, 1);
}
static int check_error_type_loop_(Execute ptr, addr list, int errorp, int *ret)
{
int check;
addr x;
while (list != Nil) {
GetCons(list, &x, &list);
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
}
return Result(ret, 1);
}
static int check_error_type_values_(Execute ptr, addr pos, int errorp, int *ret)
{
int check;
addr x;
/* var */
GetArrayType(pos, 0, &x);
Return(check_error_type_loop_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
/* opt */
GetArrayType(pos, 1, &x);
Return(check_error_type_loop_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
/* rest */
GetArrayType(pos, 2, &x);
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
return Result(ret, 1);
}
static int check_error_type_function_key_(Execute ptr, addr list, int errorp, int *ret)
{
int check;
addr x;
if (list == T)
return Result(ret, 1);
while (list != Nil) {
GetCons(list, &x, &list);
GetCdr(x, &x);
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
}
return Result(ret, 1);
}
static int check_error_type_function_arguments_(Execute ptr,
addr pos, int errorp, int *ret)
{
int check;
addr x;
if (type_astert_p(pos))
return Result(ret, 1);
/* var */
GetArrayA2(pos, 0, &x);
Return(check_error_type_loop_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
/* opt */
GetArrayA2(pos, 1, &x);
Return(check_error_type_loop_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
/* rest */
GetArrayA2(pos, 2, &x);
if (x != Nil) {
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
}
/* key */
GetArrayA2(pos, 3, &x);
Return(check_error_type_function_key_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
return 0;
}
static int check_error_type_function_(Execute ptr, addr pos, int errorp, int *ret)
{
int check;
addr x;
/* arguments */
GetArrayType(pos, 0, &x);
Return(check_error_type_function_arguments_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
/* values */
GetArrayType(pos, 1, &x);
Return(check_error_call_(ptr, x, errorp, &check));
if (! check)
return Result(ret, 0);
return Result(ret, 1);
}
int check_error_type_(Execute ptr, addr pos, int *ret)
{
return check_error_call_(ptr, pos, 0, ret);
}
int execute_error_type_(Execute ptr, addr pos)
{
int ignore;
return check_error_call_(ptr, pos, 1, &ignore);
}
void init_type_error(void)
{
cleartype(TypeErrorCall);
TypeErrorCall[LISPDECL_ERROR] = check_error_type_error_;
TypeErrorCall[LISPDECL_OPTIMIZED] = check_error_type_get1_;
TypeErrorCall[LISPDECL_SUBTYPEP] = check_error_type_get1_;
TypeErrorCall[LISPDECL_AND] = check_error_type_loop1_;
TypeErrorCall[LISPDECL_OR] = check_error_type_loop1_;
TypeErrorCall[LISPDECL_NOT] = check_error_type_get1_;
TypeErrorCall[LISPDECL_CONS] = check_error_type_cons_;
TypeErrorCall[LISPDECL_VECTOR] = check_error_type_get1_;
TypeErrorCall[LISPDECL_ARRAY] = check_error_type_get1_;
TypeErrorCall[LISPDECL_SIMPLE_ARRAY] = check_error_type_get1_;
TypeErrorCall[LISPDECL_VALUES] = check_error_type_values_;
TypeErrorCall[LISPDECL_FUNCTION] = check_error_type_function_;
TypeErrorCall[LISPDECL_COMPILED_FUNCTION] = check_error_type_function_;
}
/************************************************************
* type_function.c
************************************************************/
void make_ordargs(ordargs *ptr, addr pos)
{
int check1, check2;
clearpoint(ptr);
GetArrayA2(pos, 0, &(ptr->var));
GetArrayA2(pos, 1, &(ptr->opt));
GetArrayA2(pos, 2, &(ptr->rest));
GetArrayA2(pos, 3, &(ptr->key));
ptr->size_var = length_list_unsafe(ptr->var);
ptr->size_opt = length_list_unsafe(ptr->opt);
ptr->size_key = (ptr->key == T)? 0: length_list_unsafe(ptr->key);
ptr->pos_rest = ptr->size = ptr->size_var + ptr->size_opt;
check1 = (ptr->rest != Nil);
check2 = (ptr->key != Nil);
if (check2) /* (rest key) or (key) */
ptr->size += 2;
else if (check1) /* (rest) */
ptr->size++;
}
int gettype_ordargs_(const ordargs *ptr, size_t index, ordtype *ret)
{
int check1, check2;
memset(ret, 0, sizeoft(ordtype));
ret->type = Nil;
/* var */
if (index < ptr->size_var) {
Return(getnth_(ptr->var, index, &(ret->type)));
ret->var = 1;
return 0;
}
index -= ptr->size_var;
/* opt */
if (index < ptr->size_opt) {
Return(getnth_(ptr->opt, index, &(ret->type)));
ret->var = 1;
return 0;
}
index -= ptr->size_opt;
/* rest */
check1 = (ptr->rest == Nil);
check2 = (ptr->key == Nil);
if (check1 && check2) {
ret->nil = 1;
return 0;
}
if (! check1) {
ret->type = ptr->rest;
ret->var = 1;
ret->rest = 1;
}
/* key */
if (! check2) {
if ((index % 2) == 0) {
ret->key = 1;
ret->value = 0;
}
else {
ret->key = 0;
ret->value = 1;
}
}
return 0;
}
int simple_p_ordargs(const ordargs *ptr)
{
return ptr->rest == Nil && ptr->key == Nil;
}
static void merge_key_ordargs(LocalRoot local, addr *ret, const ordargs *ptr)
{
addr cons, array, pos;
size_t size, i;
/* &allow-other-keys */
if (ptr->key == T) {
GetTypeTable(ret, Symbol);
return;
}
/* (eql key) */
cons = ptr->key;
if (singlep(cons)) {
GetCar(cons, &pos);
GetCar(pos, &pos);
type_eql_local(local, pos, ret);
return;
}
/* (or (eql key1) (eql key2) ...) */
size = length_list_unsafe(cons);
vector4_alloc(local, &array, size);
for (i = 0; i < size; i++) {
GetCons(cons, &pos, &cons);
GetCar(pos, &pos);
type_eql_local(local, pos, &pos);
SetArrayA4(array, i, pos);
}
type1_local(local, LISPDECL_OR, array, ret);
}
static void merge_value_ordargs(LocalRoot local, addr *ret, const ordargs *ptr)
{
addr cons, array, pos;
size_t size, i;
/* &allow-other-keys */
if (ptr->key == T) {
GetTypeTable(ret, T);
return;
}
/* type */
cons = ptr->key;
if (singlep(cons)) {
GetCar(cons, &pos);
GetCdr(pos, ret);
return;
}
/* (or type1 type2 ...) */
size = length_list_unsafe(cons);
vector4_alloc(local, &array, size);
for (i = 0; i < size; i++) {
GetCons(cons, &pos, &cons);
GetCdr(pos, &pos);
SetArrayA4(array, i, pos);
}
type1_local(local, LISPDECL_OR, array, ret);
}
void merge_ordargs(LocalRoot local, addr *ret, const ordargs *ptr, const ordtype *type)
{
addr pos;
/* var -> type */
/* rest -> type */
/* key -> (and key1 key2 ...) */
/* rest + key -> (or rest (and key1 key2 ...)) */
/* &allow-other-keys -> (symbol t) */
Check(type->nil, "nil error");
/* var only */
if (type->var && (! type->rest)) {
*ret = type->type;
return;
}
/* rest only */
if (type->rest && (! type->key) && (! type->value)) {
*ret = type->type;
return;
}
/* key */
if (type->key) {
merge_key_ordargs(local, &pos, ptr);
if (type->rest)
type2and_local(local, type->type, pos, &pos);
*ret = pos;
return;
}
/* value */
if (type->value) {
merge_value_ordargs(local, &pos, ptr);
if (type->rest)
type2and_local(local, type->type, pos, &pos);
*ret = pos;
return;
}
/* error */
*ret = 0;
Abort("type error");
}
/*
* size_check
*/
static int size_check_recursive_ordcall_(addr pos, int value, size_t size, int *ret);
static int size_check_optimized_ordcall_(addr pos, int value, size_t size, int *ret)
{
get_type_optimized(&pos, pos);
return size_check_recursive_ordcall_(pos, value, size, ret);
}
static int size_check_subtypep_ordcall_(addr pos, int value, size_t size, int *ret)
{
get_type_subtypep(&pos, pos);
return size_check_recursive_ordcall_(pos, value, size, ret);
}
static int size_check_t_ordcall_(addr pos, int value, size_t size, int *ret)
{
return Result(ret, value);
}
static int size_check_nil_ordcall_(addr pos, int value, size_t size, int *ret)
{
return Result(ret, ! value);
}
static int size_check_not_ordcall_(addr pos, int value, size_t size, int *ret)
{
GetArrayType(pos, 0, &pos);
return size_check_recursive_ordcall_(pos, ! value, size, ret);
}
static int size_check_function_ordcall_(addr pos, int value, size_t size, int *ret)
{
size_t check;
addr x;
Check(! type_function_p(pos), "type error");
GetArrayType(pos, 0, &pos); /* args */
/* asterisk */
if (type_asterisk_p(pos))
return Result(ret, value);
/* var */
GetArrayA2(pos, 0, &x);
check = length_list_unsafe(x);
if (size == check)
return Result(ret, value);
if (size < check)
goto error;
/* opt */
GetArrayA2(pos, 1, &x);
check += length_list_unsafe(x);
if (size <= check)
return Result(ret, value);
/* key */
GetArrayA2(pos, 3, &x);
if (x != Nil) {
check -= size;
if (check % 2)
return fmte_("There is no value in &key argument.", NULL);
return Result(ret, value);
}
/* rest */
GetArrayA2(pos, 2, &x);
if (x != Nil)
return Result(ret, value);
error:
return Result(ret, ! value);
}
static int size_check_and_ordcall_(addr pos, int value, size_t size, int *ret)
{
int loop_check, check;
addr x;
size_t loop, i;
GetArrayType(pos, 0, &pos);
LenArrayA4(pos, &loop);
loop_check = 1;
for (i = 0; i < loop; i++) {
GetArrayA4(pos, i, &x);
Return(size_check_recursive_ordcall_(x, 1, size, &check));
if (! check)
loop_check = 0;
}
if (! loop_check)
value = ! value;
return Result(ret, value);
}
static int size_check_or_ordcall_(addr pos, int value, size_t size, int *ret)
{
int loop_check, check;
addr x;
size_t loop, i;
GetArrayType(pos, 0, &pos);
LenArrayA4(pos, &loop);
loop_check = 0;
for (i = 0; i < loop; i++) {
GetArrayA4(pos, i, &x);
Return(size_check_recursive_ordcall_(x, 1, size, &check));
if (check)
loop_check = 1;
}
if (! loop_check)
value = ! value;
return Result(ret, value);
}
static int size_check_recursive_ordcall_(addr pos, int value, size_t size, int *ret)
{
int notp;
enum LISPDECL decl;
CheckType(pos, LISPTYPE_TYPE);
GetLispDecl(pos, &decl);
GetNotDecl(pos, ¬p);
if (notp)
value = ! value;
switch (decl) {
case LISPDECL_OPTIMIZED:
return size_check_optimized_ordcall_(pos, value, size, ret);
case LISPDECL_SUBTYPEP:
return size_check_subtypep_ordcall_(pos, value, size, ret);
case LISPDECL_ASTERISK:
case LISPDECL_T:
return size_check_t_ordcall_(pos, value, size, ret);
case LISPDECL_NIL:
return size_check_nil_ordcall_(pos, value, size, ret);
case LISPDECL_NOT:
return size_check_not_ordcall_(pos, value, size, ret);
case LISPDECL_FUNCTION:
case LISPDECL_COMPILED_FUNCTION:
return size_check_function_ordcall_(pos, value, size, ret);
case LISPDECL_AND:
return size_check_and_ordcall_(pos, value, size, ret);
case LISPDECL_OR:
return size_check_or_ordcall_(pos, value, size, ret);
default:
return fmte_("Invalid type-specifier ~S.", pos, NULL);
}
}
int size_check_ordcall_(addr pos, size_t size, int *ret)
{
CheckType(pos, LISPTYPE_TYPE);
*ret = 0;
return size_check_recursive_ordcall_(pos, 1, size, ret);
}
/*
* gettype_ordcall
*/
static void reverse_ordcall(addr pos, int notp)
{
CheckType(pos, LISPTYPE_TYPE);
if (notp == 0)
return;
GetNotDecl(pos, ¬p);
notp = ! notp;
SetNotDecl(pos, notp);
}
static int gettype_optimized_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
GetNotDecl(pos, ¬p);
get_type_optimized(&pos, pos);
Return(gettype_ordcall_(pos, i, &pos));
reverse_ordcall(pos, notp);
return Result(ret, pos);
}
static int gettype_subtypep_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
GetNotDecl(pos, ¬p);
get_type_subtypep(&pos, pos);
Return(gettype_ordcall_(pos, i, &pos));
reverse_ordcall(pos, notp);
return Result(ret, pos);
}
static void gettype_bool_ordcall(int value, addr *ret)
{
if (value)
type0_heap(LISPDECL_T, ret);
else
type0_heap(LISPDECL_NIL, ret);
}
static int gettype_t_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
GetNotDecl(pos, ¬p);
gettype_bool_ordcall(! notp, ret);
return 0;
}
static int gettype_nil_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
GetNotDecl(pos, ¬p);
gettype_bool_ordcall(notp, ret);
return 0;
}
static int gettype_not_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
GetNotDecl(pos, ¬p);
notp = ! notp;
GetArrayType(pos, 0, &pos);
get_type_optimized(&pos, pos);
Return(gettype_ordcall_(pos, i, &pos));
reverse_ordcall(pos, notp);
return Result(ret, pos);
}
static int gettype_function_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
ordargs str;
ordtype type;
LocalRoot local;
LocalStack stack;
Check(! type_function_p(pos), "type error");
GetNotDecl(pos, ¬p);
GetArrayType(pos, 0, &pos); /* args */
/* asterisk */
if (type_asterisk_p(pos)) {
gettype_bool_ordcall(! notp, ret);
return 0;
}
/* ordargs */
make_ordargs(&str, pos);
Return(gettype_ordargs_(&str, i, &type));
if (type.nil) {
gettype_bool_ordcall(notp, ret);
return 0;
}
local = Local_Thread;
push_local(local, &stack);
merge_ordargs(local, &pos, &str, &type);
type_copy_heap(&pos, pos);
reverse_ordcall(pos, notp);
rollback_local(local, stack);
return Result(ret, pos);
}
static int gettype_vector_ordcall_(enum LISPDECL decl, addr pos, size_t i, addr *ret)
{
int notp;
addr type, vector, x;
size_t size, index;
GetNotDecl(pos, ¬p);
GetArrayType(pos, 0, &pos);
LenArrayA4(pos, &size);
vector4_heap(&vector, size);
type1_heap(decl, vector, &type);
SetNotDecl(type, notp);
for (index = 0; index < size; index++) {
GetArrayA4(pos, index, &x);
Return(gettype_ordcall_(x, index, &x));
SetArrayA4(vector, index, x);
}
return Result(ret, type);
}
static int gettype_and_ordcall_(addr pos, size_t i, addr *ret)
{
return gettype_vector_ordcall_(LISPDECL_OR, pos, i, ret);
}
static int gettype_or_ordcall_(addr pos, size_t i, addr *ret)
{
return gettype_vector_ordcall_(LISPDECL_AND, pos, i, ret);
}
static int gettype_error_ordcall_(addr pos, size_t i, addr *ret)
{
int notp;
GetNotDecl(pos, ¬p);
if (notp) {
type0_heap(LISPDECL_T, ret);
return 0;
}
*ret = Nil;
return fmte_("Invalid type-specifier ~S in function type.", pos, NULL);
}
int gettype_ordcall_(addr pos, size_t i, addr *ret)
{
CheckType(pos, LISPTYPE_TYPE);
switch (RefLispDecl(pos)) {
case LISPDECL_OPTIMIZED:
return gettype_optimized_ordcall_(pos, i, ret);
case LISPDECL_SUBTYPEP:
return gettype_subtypep_ordcall_(pos, i, ret);
case LISPDECL_ASTERISK:
case LISPDECL_T:
return gettype_t_ordcall_(pos, i, ret);
case LISPDECL_NIL:
return gettype_nil_ordcall_(pos, i, ret);
case LISPDECL_NOT:
return gettype_not_ordcall_(pos, i, ret);
case LISPDECL_FUNCTION:
case LISPDECL_COMPILED_FUNCTION:
return gettype_function_ordcall_(pos, i, ret);
case LISPDECL_AND:
return gettype_and_ordcall_(pos, i, ret);
case LISPDECL_OR:
return gettype_or_ordcall_(pos, i, ret);
default:
return gettype_error_ordcall_(pos, i, ret);
}
}
/*
* function values
*/
enum OrdValues_Type {
OrdValues_Var,
OrdValues_Opt,
OrdValues_Rest
};
typedef enum OrdValues_Type ordvalues;
static void make_recursive_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype);
static void make_optimized_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
int notp;
GetNotDecl(pos, ¬p);
get_type_optimized(&pos, pos);
make_recursive_ordvalues(pos, i, &pos, rtype);
reverse_ordcall(pos, notp);
*ret = pos;
}
static void make_subtypep_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
int notp;
GetNotDecl(pos, ¬p);
get_type_subtypep(&pos, pos);
make_recursive_ordvalues(pos, i, &pos, rtype);
reverse_ordcall(pos, notp);
*ret = pos;
}
static void make_t_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
int notp;
GetNotDecl(pos, ¬p);
gettype_bool_ordcall(! notp, ret);
*rtype = (i == 0)? OrdValues_Var: OrdValues_Rest;
}
static void make_nil_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
int notp;
GetNotDecl(pos, ¬p);
gettype_bool_ordcall(notp, ret);
*rtype = (i == 0)? OrdValues_Var: OrdValues_Rest;
}
static void make_not_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
int notp;
GetNotDecl(pos, ¬p);
notp = ! notp;
GetArrayType(pos, 0, &pos);
get_type_optimized(&pos, pos);
make_recursive_ordvalues(pos, i, &pos, rtype);
reverse_ordcall(pos, notp);
*ret = pos;
}
static void make_function_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
int notp;
addr x;
size_t size;
Check(! type_function_p(pos), "type error");
GetNotDecl(pos, ¬p);
GetArrayType(pos, 1, &pos); /* values */
/* asterisk */
if (RefLispDecl(pos) != LISPDECL_VALUES) {
make_recursive_ordvalues(pos, i, ret, rtype);
return;
}
/* var */
GetArrayA2(pos, 0, &x);
size = length_list_unsafe(x);
if (i < size) {
getnth_unsafe(x, i, &x);
*rtype = OrdValues_Var;
goto result;
}
/* opt */
GetArrayA2(pos, 1, &x);
i -= size;
size = length_list_unsafe(x);
if (i < size) {
getnth_unsafe(x, i, &x);
*rtype = OrdValues_Opt;
goto result;
}
/* rest */
GetArrayA2(pos, 2, &x);
*rtype = OrdValues_Rest;
result:
type_copy_heap(&x, x);
reverse_ordcall(x, notp);
*ret = x;
}
static void make_vector_ordvalues(enum LISPDECL decl,
addr pos, size_t i, addr *ret, ordvalues *rtype)
{
ordvalues v, check;
int notp;
addr type, vector, x;
size_t size, index;
GetNotDecl(pos, ¬p);
GetArrayType(pos, 0, &pos);
LenArrayA4(pos, &size);
vector4_heap(&vector, size);
type1_heap(decl, vector, &type);
SetNotDecl(type, notp);
v = OrdValues_Rest;
for (index = 0; index < size; index++) {
GetArrayA4(pos, index, &x);
make_recursive_ordvalues(x, i, &x, &check);
SetArrayA4(vector, index, x);
/* valeus check */
if (check == OrdValues_Var)
v = OrdValues_Var;
else if (check == OrdValues_Opt && v == OrdValues_Rest)
v = OrdValues_Opt;
}
*rtype = v;
*ret = type;
}
static void make_and_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
make_vector_ordvalues(LISPDECL_AND, pos, i, ret, rtype);
}
static void make_or_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
make_vector_ordvalues(LISPDECL_OR, pos, i, ret, rtype);
}
static void make_type_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
if (i == 0) {
type_copy_heap(ret, pos);
*rtype = OrdValues_Var;
}
else {
make_t_ordvalues(pos, i, ret, rtype);
}
}
static void make_recursive_ordvalues(addr pos, size_t i, addr *ret, ordvalues *rtype)
{
CheckType(pos, LISPTYPE_TYPE);
switch (RefLispDecl(pos)) {
case LISPDECL_OPTIMIZED:
make_optimized_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_SUBTYPEP:
make_subtypep_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_ASTERISK:
case LISPDECL_T:
make_t_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_NIL:
make_nil_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_NOT:
make_not_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_FUNCTION:
case LISPDECL_COMPILED_FUNCTION:
make_function_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_AND:
make_and_ordvalues(pos, i, ret, rtype);
break;
case LISPDECL_OR:
make_or_ordvalues(pos, i, ret, rtype);
break;
default:
make_type_ordvalues(pos, i, ret, rtype);
break;
}
}
void make_ordvalues_heap(addr pos, addr *ret)
{
ordvalues type;
addr x, var, opt, rest;
size_t i;
var = opt = rest = Nil;
for (i = 0; ; i++) {
make_recursive_ordvalues(pos, i, &x, &type);
/* var */
if (type == OrdValues_Var) {
cons_heap(&var, x, var);
continue;
}
/* opt */
if (type == OrdValues_Opt) {
cons_heap(&opt, x, opt);
continue;
}
/* rest */
rest = x;
break;
}
nreverse(&var, var);
nreverse(&opt, opt);
/* type */
type4_heap(LISPDECL_VALUES, var, opt, rest, Nil, ret);
}
/************************************************************
* type_memory.c
************************************************************/
/*
* allocate
*/
void type_alloc(LocalRoot local, addr *ret, LispDecl type, size_t size)
{
addr pos;
Check(LISPDECL_SIZE <= type, "type too large.");
alloc_array2(local, &pos, LISPTYPE_TYPE, size);
SetUser(pos, (byte)type);
*ret = pos;
}
void type_local(LocalRoot local, addr *ret, LispDecl type, size_t size)
{
CheckLocal(local);
type_alloc(local, ret, type, size);
}
void type_heap(addr *ret, LispDecl type, size_t size)
{
type_alloc(NULL, ret, type, size);
}
/*
* access
*/
LispDecl type_lowlispdecl(addr pos)
{
CheckType(pos, LISPTYPE_TYPE);
return LowLispDecl_Low(pos);
}
LispDecl type_reflispdecl(addr pos)
{
CheckType(pos, LISPTYPE_TYPE);
return RefLispDecl_Low(pos);
}
void type_getlispdecl(addr pos, LispDecl *ret)
{
CheckType(pos, LISPTYPE_TYPE);
GetLispDecl_Low(pos, ret);
}
void type_setlispdecl(addr pos, LispDecl value)
{
CheckType(pos, LISPTYPE_TYPE);
Check(GetStatusReadOnly(pos), "readonly error");
SetLispDecl_Low(pos, value);
}
int type_refnotdecl(addr pos)
{
CheckType(pos, LISPTYPE_TYPE);
return RefNotDecl_Low(pos);
}
void type_getnotdecl(addr pos, int *ret)
{
CheckType(pos, LISPTYPE_TYPE);
GetNotDecl_Low(pos, ret);
}
void type_setnotdecl(addr pos, int value)
{
byte user;
CheckType(pos, LISPTYPE_TYPE);
Check(GetStatusReadOnly(pos), "readonly error");
user = GetUser(pos);
if (value)
SetUser(pos, 0x80 | user);
else
SetUser(pos, 0x7F & user);
}
void type_revnotdecl(addr pos)
{
type_setnotdecl(pos, RefNotDecl(pos) == 0);
}
void type_setnotobject(addr pos, addr value)
{
SetNotDecl(pos, RefNotDecl(value));
}
addr type_refarraytype(addr pos, size_t index)
{
CheckType(pos, LISPTYPE_TYPE);
return RefArrayType_Low(pos, index);
}
void type_getarraytype(addr pos, size_t index, addr *ret)
{
CheckType(pos, LISPTYPE_TYPE);
GetArrayType_Low(pos, index, ret);
}
void type_setarraytype(addr pos, size_t index, addr value)
{
CheckType(pos, LISPTYPE_TYPE);
Check(GetStatusReadOnly(pos), "readonly error");
SetArrayType_Low(pos, index, value);
}
void type_lenarraytype(addr pos, size_t *ret)
{
CheckType(pos, LISPTYPE_TYPE);
LenArrayType_Low(pos, ret);
}
void type_getvalues1(addr type, addr *ret)
{
addr check;
CheckType(type, LISPTYPE_TYPE);
/* normal type */
if (RefLispDecl(type) != LISPDECL_VALUES) {
*ret = type;
return;
}
/* var */
GetArrayType(type, 0, &check);
if (check != Nil) {
GetCar(check, ret);
return;
}
/* opt */
GetArrayType(type, 1, &check);
if (check != Nil) {
GetCar(check, ret);
return;
}
/* rest */
GetArrayType(type, 2, ret);
}
/*
* object
*/
void type0_alloc(LocalRoot local, LispDecl type, addr *ret)
{
addr pos;
type_alloc(local, &pos, type, 0);
*ret = pos;
}
void type1_alloc(LocalRoot local, LispDecl type, addr a, addr *ret)
{
addr pos;
type_alloc(local, &pos, type, 1);
SetArrayType(pos, 0, a);
*ret = pos;
}
void type2_alloc(LocalRoot local, LispDecl type, addr a, addr b, addr *ret)
{
addr pos;
type_alloc(local, &pos, type, 2);
SetArrayType(pos, 0, a);
SetArrayType(pos, 1, b);
*ret = pos;
}
void type3_alloc(LocalRoot local, LispDecl type, addr a, addr b, addr c, addr *ret)
{
addr pos;
type_alloc(local, &pos, type, 3);
SetArrayType(pos, 0, a);
SetArrayType(pos, 1, b);
SetArrayType(pos, 2, c);
*ret = pos;
}
void type4_alloc(LocalRoot local, LispDecl type,
addr a, addr b, addr c, addr d, addr *ret)
{
addr pos;
type_alloc(local, &pos, type, 4);
SetArrayType(pos, 0, a);
SetArrayType(pos, 1, b);
SetArrayType(pos, 2, c);
SetArrayType(pos, 3, d);
*ret = pos;
}
void type0_local(LocalRoot local, LispDecl type, addr *ret)
{
CheckLocal(local);
type0_alloc(local, type, ret);
}
void type1_local(LocalRoot local, LispDecl type, addr a, addr *ret)
{
CheckLocal(local);
type1_alloc(local, type, a, ret);
}
void type2_local(LocalRoot local, LispDecl type, addr a, addr b, addr *ret)
{
CheckLocal(local);
type2_alloc(local, type, a, b, ret);
}
void type3_local(LocalRoot local, LispDecl type, addr a, addr b, addr c, addr *ret)
{
CheckLocal(local);
type3_alloc(local, type, a, b, c, ret);
}
void type4_local(LocalRoot local, LispDecl type,
addr a, addr b, addr c, addr d, addr *ret)
{
CheckLocal(local);
type4_alloc(local, type, a, b, c, d, ret);
}
void type0_heap(LispDecl type, addr *ret)
{
type0_alloc(NULL, type, ret);
}
void type1_heap(LispDecl type, addr a, addr *ret)
{
type1_alloc(NULL, type, a, ret);
}
void type2_heap(LispDecl type, addr a, addr b, addr *ret)
{
type2_alloc(NULL, type, a, b, ret);
}
void type3_heap(LispDecl type, addr a, addr b, addr c, addr *ret)
{
type3_alloc(NULL, type, a, b, c, ret);
}
void type4_heap(LispDecl type, addr a, addr b, addr c, addr d, addr *ret)
{
type4_alloc(NULL, type, a, b, c, d, ret);
}
void type0not_alloc(LocalRoot local, LispDecl type, addr *ret)
{
type0_alloc(local, type, ret);
SetNotDecl(*ret, 1);
}
void type1not_alloc(LocalRoot local, LispDecl type, addr a, addr *ret)
{
type1_alloc(local, type, a, ret);
SetNotDecl(*ret, 1);
}
void type2not_alloc(LocalRoot local, LispDecl type, addr a, addr b, addr *ret)
{
type2_alloc(local, type, a, b, ret);
SetNotDecl(*ret, 1);
}
void type3not_alloc(LocalRoot local, LispDecl type,
addr a, addr b, addr c, addr *ret)
{
type3_alloc(local, type, a, b, c, ret);
SetNotDecl(*ret, 1);
}
void type4not_alloc(LocalRoot local, LispDecl type,
addr a, addr b, addr c, addr d, addr *ret)
{
type4_alloc(local, type, a, b, c, d, ret);
SetNotDecl(*ret, 1);
}
void type0not_local(LocalRoot local, LispDecl type, addr *ret)
{
CheckLocal(local);
type0not_alloc(local, type, ret);
}
void type1not_local(LocalRoot local, LispDecl type, addr a, addr *ret)
{
CheckLocal(local);
type1not_alloc(local, type, a, ret);
}
void type2not_local(LocalRoot local, LispDecl type, addr a, addr b, addr *ret)
{
CheckLocal(local);
type2not_alloc(local, type, a, b, ret);
}
void type3not_local(LocalRoot local, LispDecl type, addr a, addr b, addr c, addr *ret)
{
CheckLocal(local);
type3not_alloc(local, type, a, b, c, ret);
}
void type4not_local(LocalRoot local, LispDecl type,
addr a, addr b, addr c, addr d, addr *ret)
{
CheckLocal(local);
type4not_alloc(local, type, a, b, c, d, ret);
}
void type0not_heap(LispDecl type, addr *ret)
{
type0not_alloc(NULL, type, ret);
}
void type1not_heap(LispDecl type, addr a, addr *ret)
{
type1not_alloc(NULL, type, a, ret);
}
void type2not_heap(LispDecl type, addr a, addr b, addr *ret)
{
type2not_alloc(NULL, type, a, b, ret);
}
void type3not_heap(LispDecl type, addr a, addr b, addr c, addr *ret)
{
type3not_alloc(NULL, type, a, b, c, ret);
}
void type4not_heap(LispDecl type, addr a, addr b, addr c, addr d, addr *ret)
{
type4not_alloc(NULL, type, a, b, c, d, ret);
}
static void type_aster_local(LocalRoot local, addr *ret)
{
CheckLocal(local);
type0_local(local, LISPDECL_ASTERISK, ret);
}
void type1aster_localall(LocalRoot local, LispDecl type, addr *ret)
{
addr a1;
CheckLocal(local);
type_aster_local(local, &a1);
type1_local(local, type, a1, ret);
}
void type2aster_localall(LocalRoot local, LispDecl type, addr *ret)
{
addr a1, a2;
CheckLocal(local);
type_aster_local(local, &a1);
type_aster_local(local, &a2);
type2_local(local, type, a1, a2, ret);
}
void type3aster_localall(LocalRoot local, LispDecl type, addr *ret)
{
addr a1, a2, a3;
CheckLocal(local);
type_aster_local(local, &a1);
type_aster_local(local, &a2);
type_aster_local(local, &a3);
type3_local(local, type, a1, a2, a3, ret);
}
void type4aster_localall(LocalRoot local, LispDecl type, addr *ret)
{
addr a1, a2, a3, a4;
CheckLocal(local);
type_aster_local(local, &a1);
type_aster_local(local, &a2);
type_aster_local(local, &a3);
type_aster_local(local, &a4);
type4_local(local, type, a1, a2, a3, a4, ret);
}
/*
* copy
*/
static void type_copy_unsafe(LocalRoot local, addr *ret, addr left, byte value)
{
addr right, one;
size_t size, i;
Check(GetType(left) != LISPTYPE_TYPE, "type error");
LenArrayType(left, &size);
type_alloc(local, &right, LISPDECL_EMPTY, (byte)size);
SetUser(right, value);
for (i = 0; i < size; i++) {
GetArrayType(left, i, &one);
SetArrayType(right, i, one);
}
*ret = right;
}
void type_copy_unsafe_alloc(LocalRoot local, addr *ret, addr left)
{
type_copy_unsafe(local, ret, left, GetUser(left));
}
void type_copy_unsafe_local(LocalRoot local, addr *ret, addr left)
{
CheckLocal(local);
type_copy_unsafe_alloc(local, ret, left);
}
void type_copy_unsafe_heap(addr *ret, addr left)
{
type_copy_unsafe_alloc(NULL, ret, left);
}
void type_copydecl_unsafe_alloc(LocalRoot local, addr *ret, addr left)
{
type_copy_unsafe(local, ret, left, RefLispDecl(left));
}
void type_copydecl_unsafe_local(LocalRoot local, addr *ret, addr left)
{
CheckLocal(local);
type_copydecl_unsafe_alloc(local, ret, left);
}
void type_copydecl_unsafe_heap(addr *ret, addr left)
{
type_copydecl_unsafe_alloc(NULL, ret, left);
}
/*
* make
*/
void type_eql_alloc(LocalRoot local, addr pos, addr *ret)
{
type1_alloc(local, LISPDECL_EQL, pos, ret);
}
void type_eql_local(LocalRoot local, addr pos, addr *ret)
{
type1_local(local, LISPDECL_EQL, pos, ret);
}
void type_eql_heap(addr pos, addr *ret)
{
type1_heap(LISPDECL_EQL, pos, ret);
}
static void vector4_va_heap(addr *ret, va_list args)
{
va_list temp;
addr pos, array;
size_t size, i;
/* length args */
va_copy(temp, args);
for (size = 0; ; size++) {
pos = va_arg(temp, addr);
if (pos == NULL) break;
}
/* make vector4 */
vector4_heap(&array, size);
for (i = 0; i < size; i++) {
pos = va_arg(args, addr);
if (pos == NULL) break;
SetArrayA4(array, i, pos);
}
*ret = array;
}
void type_member_heap(addr *ret, ...)
{
addr array;
va_list args;
va_start(args, ret);
vector4_va_heap(&array, args);
va_end(args);
type1_heap(LISPDECL_MEMBER, array, ret);
}
void type_satisfies_heap(addr call, addr *ret)
{
Check((! symbolp(call)) && (! functionp(call)), "type error");
type1_heap(LISPDECL_SATISFIES, call, ret);
}
void type_values_local(LocalRoot local, addr v1, addr v2, addr v3, addr v4, addr *ret)
{
type4_local(local, LISPDECL_VALUES, v1, v2, v3, v4, ret);
}
void type_values_heap(addr v1, addr v2, addr v3, addr v4, addr *ret)
{
type4_heap(LISPDECL_VALUES, v1, v2, v3, v4, ret);
}
void type_signed_alloc(LocalRoot local, fixnum value, addr *ret)
{
addr pos;
Check(value <= 0, "size error");
fixnum_alloc(local, &pos, value);
type1_alloc(local, LISPDECL_SIGNED_BYTE, pos, ret);
}
void type_signed_local(LocalRoot local, fixnum value, addr *ret)
{
CheckLocal(local);
type_signed_alloc(local, value, ret);
}
void type_signed_heap(fixnum value, addr *ret)
{
type_signed_alloc(NULL, value, ret);
}
void type_unsigned_alloc(LocalRoot local, fixnum value, addr *ret)
{
addr pos;
Check(value <= 0, "size error");
fixnum_alloc(local, &pos, value);
type1_alloc(local, LISPDECL_UNSIGNED_BYTE, pos, ret);
}
void type_unsigned_local(LocalRoot local, fixnum value, addr *ret)
{
CheckLocal(local);
type_unsigned_alloc(local, value, ret);
}
void type_unsigned_heap(fixnum value, addr *ret)
{
type_unsigned_alloc(NULL, value, ret);
}
/*
* function / compiled-function
* function -> (function * * [*])
* (function) -> (function * * [nil])
* (function * *) -> (function * * [nil])
* (function * * *) -> ERROR
*
* (typep value 'function) -> ok
* (typep value '(function)) -> ERROR
* (declare (type function a b)) -> ok
* (declare (type (function) a b)) -> ok
*/
void type_function_heap(addr args, addr values, addr *ret)
{
type3_heap(LISPDECL_FUNCTION, args, values, Nil, ret);
}
void type_compiled_heap(addr args, addr values, addr *ret)
{
type3_heap(LISPDECL_COMPILED_FUNCTION, args, values, Nil, ret);
}
void type_clos_heap(addr clos, addr *ret)
{
CheckType(clos, LISPTYPE_CLOS);
type1_heap(LISPDECL_CLOS, clos, ret);
}
void type_error_heap(addr pos, addr *ret)
{
type2_heap(LISPDECL_ERROR, pos, Nil, ret);
}
/************************************************************
* type_name.c
************************************************************/
static constindex TypeNameTable[LISPTYPE_SIZE];
#define DefTypeName(x,y) (TypeNameTable[x] = CONSTANT_##y)
static int type_name_clos_(addr pos, addr *value, int *ret)
{
Return(clos_class_of_(pos, &pos));
Return(stdget_class_name_(pos, value));
return Result(ret, 0);
}
static int type_name_symbol_(addr pos, addr *value, int *ret)
{
if (keywordp(pos))
GetConst(COMMON_KEYWORD, value);
else
GetConst(COMMON_SYMBOL, value);
return Result(ret, 0);
}
static int type_name_function_(addr pos, addr *value, int *ret)
{
if (interpreted_funcall_function_p(pos)) {
GetConst(COMMON_FUNCTION, value);
goto normal;
}
if (interpreted_macro_function_p(pos)) {
GetConst(COMMON_MACRO_FUNCTION, value);
goto normal;
}
if (compiled_funcall_function_p(pos)) {
GetConst(COMMON_COMPILED_FUNCTION, value);
goto normal;
}
if (compiled_macro_function_p(pos)) {
GetConst(SYSTEM_COMPILED_MACRO_FUNCTION, value);
goto normal;
}
else {
GetConst(COMMON_FUNCTION, value);
goto normal;
}
normal:
return Result(ret, 0);
}
static int type_name_stream_(addr pos, addr *value, int *ret)
{
switch (getstreamtype(pos)) {
case StreamType_StringInput:
case StreamType_StringOutput:
GetConst(COMMON_STRING_STREAM, value);
goto normal;
case StreamType_Synonym:
GetConst(COMMON_SYNONYM_STREAM, value);
goto normal;
case StreamType_BroadCast:
GetConst(COMMON_BROADCAST_STREAM, value);
goto normal;
case StreamType_Concatenated:
GetConst(COMMON_CONCATENATED_STREAM, value);
goto normal;
case StreamType_Echo:
GetConst(COMMON_ECHO_STREAM, value);
goto normal;
case StreamType_TwoWay:
GetConst(COMMON_TWO_WAY_STREAM, value);
goto normal;
case StreamType_Prompt:
GetConst(SYSTEM_PROMPT_STREAM, value);
goto normal;
case StreamType_Pretty:
GetConst(SYSTEM_PRETTY_STREAM, value);
goto normal;
case StreamType_MemoryInput:
case StreamType_MemoryOutput:
case StreamType_MemoryIO:
GetConst(SYSTEM_MEMORY_STREAM, value);
goto normal;
case StreamType_Terminal:
GetConst(SYSTEM_TERMINAL_STREAM, value);
goto normal;
default:
break;
}
GetPathnameStream(pos, &pos);
if (pos != Nil) {
GetConst(COMMON_FILE_STREAM, value);
goto normal;
}
GetConst(COMMON_STREAM, value);
goto normal;
normal:
return Result(ret, 0);
}
int type_name_p_(addr pos, addr *value, int *ret)
{
enum LISPTYPE type;
constindex index;
/* table */
type = GetType(pos);
index = TypeNameTable[(int)type];
if (index != CONSTANT_EMPTY) {
GetConstant(index, value);
return Result(ret, 0);
}
/* others */
switch (type) {
case LISPTYPE_CLOS:
return type_name_clos_(pos, value, ret);
case LISPTYPE_SYMBOL:
return type_name_symbol_(pos, value, ret);
case LISPTYPE_FUNCTION:
return type_name_function_(pos, value, ret);
case LISPTYPE_STREAM:
return type_name_stream_(pos, value, ret);
default:
*value = Nil;
return Result(ret, 1);
}
}
int type_name_(addr pos, addr *value)
{
int check;
Return(type_name_p_(pos, value, &check));
if (check) {
*value = Nil;
return fmte_("The type ~S don't have a name.", pos, NULL);
}
return 0;
}
void init_type_name(void)
{
int i;
for (i = 0; i < LISPTYPE_SIZE; i++)
TypeNameTable[i] = CONSTANT_EMPTY;
DefTypeName(LISPTYPE_NIL, COMMON_NIL);
DefTypeName(LISPTYPE_T, COMMON_T);
DefTypeName(LISPTYPE_TYPE, COMMON_TYPE);
/*DefTypeName(LISPTYPE_CLOS, COMMON_EMPTY);*/
DefTypeName(LISPTYPE_CONS, COMMON_CONS);
DefTypeName(LISPTYPE_ARRAY, COMMON_ARRAY);
DefTypeName(LISPTYPE_VECTOR, COMMON_VECTOR);
DefTypeName(LISPTYPE_CHARACTER, COMMON_CHARACTER);
DefTypeName(LISPTYPE_STRING, COMMON_STRING);
DefTypeName(LISPTYPE_HASHTABLE, COMMON_HASH_TABLE);
DefTypeName(LISPTYPE_READTABLE, COMMON_READTABLE);
/*DefTypeName(LISPTYPE_SYMBOL, COMMON_EMPTY);*/
DefTypeName(LISPTYPE_FIXNUM, COMMON_INTEGER);
DefTypeName(LISPTYPE_BIGNUM, COMMON_INTEGER);
DefTypeName(LISPTYPE_RATIO, COMMON_RATIO);
DefTypeName(LISPTYPE_SHORT_FLOAT, COMMON_FLOAT);
DefTypeName(LISPTYPE_SINGLE_FLOAT, COMMON_FLOAT);
DefTypeName(LISPTYPE_DOUBLE_FLOAT, COMMON_FLOAT);
DefTypeName(LISPTYPE_LONG_FLOAT, COMMON_FLOAT);
DefTypeName(LISPTYPE_COMPLEX, COMMON_COMPLEX);
DefTypeName(LISPTYPE_CONTROL, SYSTEM_CONTROL);
DefTypeName(LISPTYPE_CODE, SYSTEM_CODE);
DefTypeName(LISPTYPE_CALLNAME, SYSTEM_CALLNAME);
/*DefTypeName(LISPTYPE_FUNCTION, COMMON_EMPTY);*/
DefTypeName(LISPTYPE_INDEX, SYSTEM_INDEX);
DefTypeName(LISPTYPE_PACKAGE, COMMON_PACKAGE);
DefTypeName(LISPTYPE_RANDOM_STATE, COMMON_RANDOM_STATE);
DefTypeName(LISPTYPE_PATHNAME, COMMON_PATHNAME);
/*DefTypeName(LISPTYPE_STREAM, COMMON_EMPTY);*/
DefTypeName(LISPTYPE_QUOTE, SYSTEM_QUOTE);
DefTypeName(LISPTYPE_RESTART, COMMON_RESTART);
DefTypeName(LISPTYPE_EVAL, SYSTEM_EVAL);
DefTypeName(LISPTYPE_ENVIRONMENT, SYSTEM_ENVIRONMENT);
DefTypeName(LISPTYPE_BITVECTOR, COMMON_BIT_VECTOR);
DefTypeName(LISPTYPE_BYTESPEC, SYSTEM_BYTESPEC);
DefTypeName(LISPTYPE_PRINT_DISPATCH, SYSTEM_PRINT_DISPATCH);
DefTypeName(LISPTYPE_EVAL, SYSTEM_EVAL);
DefTypeName(LISPSYSTEM_CHARACTER2, SYSTEM_CHARACTER2);
DefTypeName(LISPSYSTEM_CHARQUEUE, SYSTEM_CHARQUEUE);
DefTypeName(LISPSYSTEM_CHARBIT, SYSTEM_CHARBIT);
DefTypeName(LISPSYSTEM_SYMSTACK, SYSTEM_SYMSTACK);
DefTypeName(LISPSYSTEM_BITTYPE, SYSTEM_BITTYPE);
DefTypeName(LISPSYSTEM_READLABEL, SYSTEM_READLABEL);
DefTypeName(LISPSYSTEM_READINFO, SYSTEM_READINFO_SYMBOL);
DefTypeName(LISPSYSTEM_READTYPE, SYSTEM_READTYPE);
DefTypeName(LISPSYSTEM_BITCONS, SYSTEM_BITCONS);
DefTypeName(LISPSYSTEM_BITBUFFER, SYSTEM_BITBUFFER);
DefTypeName(LISPSYSTEM_HASHITERATOR, SYSTEM_HASHITERATOR);
DefTypeName(LISPSYSTEM_PACKAGEITERATOR, SYSTEM_PACKAGEITERATOR);
DefTypeName(LISPSYSTEM_TAGINFO, SYSTEM_TAGINFO);
DefTypeName(LISPSYSTEM_ARRAY_DIMENSION, SYSTEM_ARRAY_DIMENSION);
DefTypeName(LISPSYSTEM_ARRAY_GENERAL, SYSTEM_ARRAY_GENERAL);
DefTypeName(LISPSYSTEM_ARRAY_SPECIALIZED, SYSTEM_ARRAY_SPECIALIZED);
DefTypeName(LISPSYSTEM_UNBOUND, SYSTEM_UNBOUND);
DefTypeName(LISPSYSTEM_SPACE, SYSTEM_SPACE);
DefTypeName(LISPSYSTEM_SPACE1, SYSTEM_SPACE1);
DefTypeName(LISPSYSTEM_RESERVED, SYSTEM_RESERVED);
DefTypeName(LISPSYSTEM_END, SYSTEM_END);
}
/************************************************************
* type_object.c
************************************************************/
typedef int (*type_object_call)(addr *, addr);
static type_object_call TypeObjectTable[LISPTYPE_SIZE];
static int type_object_error(addr *ret, addr pos)
{
infobit(pos);
return fmte_("Invalid type.", NULL);
}
static int type_object_error_type(addr *ret, addr pos)
{
addr type;
GetArrayType(pos, 1, &type);
if (type != Nil)
return type_object_(ret, type);
GetArrayType(pos, 0, &type);
return Result(ret, type);
}
static int type_object_name(addr *ret, addr pos)
{
constindex index = getdeclname(RefLispDecl(pos));
GetConstant(index, ret);
return 0;
}
static int type_object_optimized(addr *ret, addr pos)
{
get_type_optimized(&pos, pos);
return type_object_(ret, pos);
}
static int type_object_subtypep(addr *ret, addr pos)
{
get_type_subtypep(&pos, pos);
return type_object_(ret, pos);
}
static int type_object_type(addr *ret, addr pos)
{
GetConst(SYSTEM_TYPE, ret);
return 0;
}
static int type_object_clos(addr *ret, addr pos)
{
GetArrayType(pos, 0, &pos);
if (type_asterisk_p(pos)) {
GetConst(COMMON_STANDARD_OBJECT, ret);
}
else {
Return(stdget_class_name_(pos, ret));
}
return 0;
}
static int type_object_vectortype_(addr *ret, addr name, addr pos)
{
addr array, root, temp;
size_t size;
GetArrayType(pos, 0, &array);
LenArrayA4(array, &size);
for (root = Nil; size; ) {
size--;
GetArrayA4(array, size, &temp);
Return(type_object_(&temp, temp));
cons_heap(&root, temp, root);
}
cons_heap(ret, name, root);
return 0;
}
static int type_object_and(addr *ret, addr pos)
{
addr name;
GetConst(COMMON_AND, &name);
return type_object_vectortype_(ret, name, pos);
}
static int type_object_or(addr *ret, addr pos)
{
addr name;
GetConst(COMMON_OR, &name);
return type_object_vectortype_(ret, name, pos);
}
static int type_object_operator1_(addr *ret, constindex index, addr pos)
{
addr name;
GetConstant(index, &name);
GetArrayType(pos, 0, &pos);
copyheap(&pos, pos);
list_heap(ret, name, pos, NULL);
return 0;
}
static int type_object_eql(addr *ret, addr pos)
{
return type_object_operator1_(ret, CONSTANT_COMMON_EQL, pos);
}
static int type_object_member(addr *ret, addr pos)
{
addr array, root, temp;
size_t size;
GetArrayType(pos, 0, &array);
LenArrayA4(array, &size);
for (root = Nil; size; ) {
size--;
GetArrayA4(array, size, &temp);
copyheap(&temp, temp);
cons_heap(&root, temp, root);
}
GetConst(COMMON_MEMBER, &temp);
cons_heap(ret, temp, root);
return 0;
}
static int type_object_mod(addr *ret, addr pos)
{
return type_object_operator1_(ret, CONSTANT_COMMON_MOD, pos);
}
static int type_object_not(addr *ret, addr pos)
{
addr name;
GetConst(COMMON_NOT, &name);
GetArrayType(pos, 0, &pos);
Return(type_object_(&pos, pos));
list_heap(ret, name, pos, NULL);
return 0;
}
static int type_object_satisfies(addr *ret, addr pos)
{
return type_object_operator1_(ret, CONSTANT_COMMON_SATISFIES, pos);
}
static int type_object_values(addr *ret, addr pos)
{
addr root, list, value;
/* first */
GetConst(COMMON_VALUES, &value);
conscar_heap(&root, value);
/* variable */
GetArrayType(pos, 0, &list);
while (list != Nil) {
GetCons(list, &value, &list);
Return(type_object_(&value, value));
cons_heap(&root, value, root);
}
/* &optional */
GetArrayType(pos, 1, &list);
if (list != Nil) {
GetConst(AMPERSAND_OPTIONAL, &value);
cons_heap(&root, value, root);
}
while (list != Nil) {
GetCons(list, &value, &list);
Return(type_object_(&value, value));
cons_heap(&root, value, root);
}
/* &rest */
GetArrayType(pos, 2, &list);
if (list != Nil) {
GetConst(AMPERSAND_REST, &value);
cons_heap(&root, value, root);
Return(type_object_(&list, list));
cons_heap(&root, list, root);
}
/* &allow-other-keys (always nil) */
GetArrayType(pos, 3, &list);
if (list != Nil) {
GetConst(AMPERSAND_ALLOW, &value);
cons_heap(&root, value, root);
}
/* result */
nreverse(ret, root);
return 0;
}
static int type_object_vector(addr *ret, addr pos)
{
addr name, type;
GetConst(COMMON_VECTOR, &name);
GetArrayType(pos, 0, &type);
GetArrayType(pos, 1, &pos);
if (type_asterisk_p(type) && type_asterisk_p(pos))
return Result(ret, name);
Return(type_object_(&type, type));
if (type_asterisk_p(pos))
GetConst(COMMON_ASTERISK, &pos);
list_heap(ret, name, type, pos, NULL);
return 0;
}
static int type_object_size_(addr *ret, constindex index, addr pos)
{
addr name;
GetConstant(index, &name);
GetArrayType(pos, 0, &pos);
if (type_asterisk_p(pos))
return Result(ret, name);
list_heap(ret, name, pos, NULL);
return 0;
}
static int type_object_simple_vector(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_SIMPLE_VECTOR, pos);
}
static int type_object_bit_vector(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_BIT_VECTOR, pos);
}
static int type_object_simple_bit_vector(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_SIMPLE_BIT_VECTOR, pos);
}
static int type_object_string(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_STRING, pos);
}
static int type_object_base_string(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_BASE_STRING, pos);
}
static int type_object_simple_string(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_SIMPLE_STRING, pos);
}
static int type_object_simple_base_string(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_SIMPLE_BASE_STRING, pos);
}
static int type_object_signed_byte(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_SIGNED_BYTE, pos);
}
static int type_object_unsigned_byte(addr *ret, addr pos)
{
return type_object_size_(ret, CONSTANT_COMMON_UNSIGNED_BYTE, pos);
}
static int type_object_cons(addr *ret, addr pos)
{
addr name, car, cdr;
GetConst(COMMON_CONS, &name);
GetArrayType(pos, 0, &car);
GetArrayType(pos, 1, &cdr);
if (type_asterisk_p(car) && type_asterisk_p(cdr))
return Result(ret, name);
Return(type_object_(&car, car));
Return(type_object_(&cdr, cdr));
list_heap(ret, name, car, cdr, NULL);
return 0;
}
static int type_object_function_args_(addr *ret, addr type)
{
addr root, list, pos, value;
CheckType(type, LISPTYPE_VECTOR);
root = Nil;
/* var */
GetArrayA2(type, 0, &list);
while (list != Nil) {
GetCons(list, &pos, &list);
Return(type_object_(&pos, pos));
cons_heap(&root, pos, root);
}
/* opt */
GetArrayA2(type, 1, &list);
if (list != Nil) {
GetConst(AMPERSAND_OPTIONAL, &pos);
cons_heap(&root, pos, root);
while (list != Nil) {
GetCons(list, &pos, &list);
Return(type_object_(&pos, pos));
cons_heap(&root, pos, root);
}
}
/* rest */
GetArrayA2(type, 2, &list);
if (list != Nil) {
GetConst(AMPERSAND_REST, &pos);
cons_heap(&root, pos, root);
Return(type_object_(&list, list));
cons_heap(&root, list, root);
}
/* key */
GetArrayA2(type, 3, &list);
if (list != Nil) {
GetConst(AMPERSAND_KEY, &pos);
cons_heap(&root, pos, root);
while (list != Nil) {
GetCons(list, &pos, &list);
GetCons(pos, &pos, &value);
Return(type_object_(&value, value));
list_heap(&pos, pos, value, NULL);
cons_heap(&root, pos, root);
}
}
/* result */
nreverse(ret, root);
return 0;
}
static int type_object_functiontype_(addr *ret, constindex index, addr pos)
{
addr name, type;
/* name */
GetConstant(index, &name);
/* argument */
GetArrayType(pos, 0, &type);
GetArrayType(pos, 1, &pos);
if (type_asterisk_p(type) && type_asterisk_p(pos))
return Result(ret, name);
if (type_asterisk_p(type)) {
GetConst(COMMON_ASTERISK, &type);
}
else {
Return(type_object_function_args_(&type, type));
}
/* values */
if (type_asterisk_p(pos)) {
GetConst(COMMON_ASTERISK, &pos);
}
else {
Return(type_object_(&pos, pos));
}
/* result */
list_heap(ret, name, type, pos, NULL);
return 0;
}
static int type_object_function(addr *ret, addr pos)
{
return type_object_functiontype_(ret, CONSTANT_COMMON_FUNCTION, pos);
}
static int type_object_compiled_function(addr *ret, addr pos)
{
return type_object_functiontype_(ret, CONSTANT_COMMON_COMPILED_FUNCTION, pos);
}
static void type_object_arraydimension(addr pos, addr *ret)
{
addr root, temp;
size_t size;
if (GetType(pos) == LISPTYPE_FIXNUM) {
copyheap(ret, pos);
return;
}
Check(GetType(pos) != LISPTYPE_VECTOR, "type error");
LenArrayA4(pos, &size);
for (root = Nil; size; ) {
size--;
GetArrayA4(pos, size, &temp);
copyheap(&temp, temp);
cons_heap(&root, temp, root);
}
*ret = root;
}
static int type_object_arraytype_(addr *ret, constindex index, addr pos)
{
addr name, type;
/* name */
GetConstant(index, &name);
/* type */
GetArrayType(pos, 0, &type);
GetArrayType(pos, 1, &pos);
if (type_asterisk_p(type) && type_asterisk_p(pos))
return Result(ret, name);
if (type_asterisk_p(type)) {
GetConst(COMMON_ASTERISK, &type);
}
else {
Return(type_object_(&type, type));
}
/* dimension */
if (type_asterisk_p(pos)) {
GetConst(COMMON_ASTERISK, &pos);
}
else {
type_object_arraydimension(pos, &pos);
}
/* result */
list_heap(ret, name, type, pos, NULL);
return 0;
}
static int type_object_array(addr *ret, addr pos)
{
return type_object_arraytype_(ret, CONSTANT_COMMON_ARRAY, pos);
}
static int type_object_simple_array(addr *ret, addr pos)
{
return type_object_arraytype_(ret, CONSTANT_COMMON_SIMPLE_ARRAY, pos);
}
static void type_object_realtype(addr *ret, constindex index, addr pos)
{
addr name, left1, left2, right1, right2;
/* name */
GetConstant(index, &name);
/* argument */
GetArrayType(pos, 0, &left1);
GetArrayType(pos, 1, &left2);
GetArrayType(pos, 2, &right1);
GetArrayType(pos, 3, &right2);
if (type_asterisk_p(left1) && type_asterisk_p(right1)) {
*ret = name;
return;
}
/* left */
if (type_asterisk_p(left1))
GetConst(COMMON_ASTERISK, &left2);
else if (left1 == T)
conscar_heap(&left2, left2);
/* right */
if (type_asterisk_p(right1))
GetConst(COMMON_ASTERISK, &right2);
else if (right1 == T)
conscar_heap(&right2, right2);
/* result */
list_heap(ret, name, left2, right2, NULL);
}
static int type_object_real(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_REAL, pos);
return 0;
}
static int type_object_rational(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_RATIONAL, pos);
return 0;
}
static int type_object_integer(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_INTEGER, pos);
return 0;
}
static int type_object_float(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_FLOAT, pos);
return 0;
}
static int type_object_short_float(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_SHORT_FLOAT, pos);
return 0;
}
static int type_object_single_float(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_SINGLE_FLOAT, pos);
return 0;
}
static int type_object_double_float(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_DOUBLE_FLOAT, pos);
return 0;
}
static int type_object_long_float(addr *ret, addr pos)
{
type_object_realtype(ret, CONSTANT_COMMON_LONG_FLOAT, pos);
return 0;
}
static int type_object_complex(addr *ret, addr pos)
{
addr name;
GetConst(COMMON_COMPLEX, &name);
GetArrayType(pos, 0, &pos);
if (type_asterisk_p(pos))
return Result(ret, name);
Return(type_object_(&pos, pos));
list_heap(ret, name, pos, NULL);
return 0;
}
int type_object_(addr *ret, addr pos)
{
type_object_call call;
addr result, notp;
Check(GetType(pos) != LISPTYPE_TYPE, "type error");
call = TypeObjectTable[(int)RefLispDecl(pos)];
Return((*call)(&result, pos));
if (RefNotDecl(pos)) {
GetConst(COMMON_NOT, ¬p);
list_heap(ret, notp, result, NULL);
}
else {
*ret = result;
}
Check(*ret == Unbound, "unbound error");
return 0;
}
void init_type_object(void)
{
int i;
for (i = 0; i < LISPDECL_SIZE; i++)
TypeObjectTable[i] = type_object_name;
/* object */
TypeObjectTable[LISPDECL_EMPTY] = type_object_error;
TypeObjectTable[LISPDECL_ERROR] = type_object_error_type;
TypeObjectTable[LISPDECL_INVALID] = type_object_name;
TypeObjectTable[LISPDECL_OPTIMIZED] = type_object_optimized;
TypeObjectTable[LISPDECL_SUBTYPEP] = type_object_subtypep;
TypeObjectTable[LISPDECL_TYPE] = type_object_type;
TypeObjectTable[LISPDECL_CLOS] = type_object_clos;
TypeObjectTable[LISPDECL_ASTERISK] = type_object_name;
/* Compound-type */
TypeObjectTable[LISPDECL_AND] = type_object_and;
TypeObjectTable[LISPDECL_OR] = type_object_or;
TypeObjectTable[LISPDECL_EQL] = type_object_eql;
TypeObjectTable[LISPDECL_MEMBER] = type_object_member;
TypeObjectTable[LISPDECL_MOD] = type_object_mod;
TypeObjectTable[LISPDECL_NOT] = type_object_not;
TypeObjectTable[LISPDECL_SATISFIES] = type_object_satisfies;
TypeObjectTable[LISPDECL_VALUES] = type_object_values;
/* Extract-type */
TypeObjectTable[LISPDECL_ATOM] = type_object_name;
TypeObjectTable[LISPDECL_LIST] = type_object_name;
TypeObjectTable[LISPDECL_BOOLEAN] = type_object_name;
TypeObjectTable[LISPDECL_VECTOR] = type_object_vector;
TypeObjectTable[LISPDECL_SIMPLE_VECTOR] = type_object_simple_vector;
TypeObjectTable[LISPDECL_BIT_VECTOR] = type_object_bit_vector;
TypeObjectTable[LISPDECL_SIMPLE_BIT_VECTOR] = type_object_simple_bit_vector;
TypeObjectTable[LISPDECL_EXTENDED_CHAR] = type_object_name;
TypeObjectTable[LISPDECL_STRING] = type_object_string;
TypeObjectTable[LISPDECL_BASE_STRING] = type_object_base_string;
TypeObjectTable[LISPDECL_SIMPLE_STRING] = type_object_simple_string;
TypeObjectTable[LISPDECL_SIMPLE_BASE_STRING] = type_object_simple_base_string;
TypeObjectTable[LISPDECL_SIGNED_BYTE] = type_object_signed_byte;
TypeObjectTable[LISPDECL_UNSIGNED_BYTE] = type_object_unsigned_byte;
TypeObjectTable[LISPDECL_BIT] = type_object_name;
TypeObjectTable[LISPDECL_FIXNUM] = type_object_name;
TypeObjectTable[LISPDECL_BIGNUM] = type_object_name;
/* Atomic-type */
TypeObjectTable[LISPDECL_NIL] = type_object_name;
TypeObjectTable[LISPDECL_T] = type_object_name;
TypeObjectTable[LISPDECL_NULL] = type_object_name;
TypeObjectTable[LISPDECL_CONS] = type_object_cons;
TypeObjectTable[LISPDECL_HASH_TABLE] = type_object_name;
TypeObjectTable[LISPDECL_SYMBOL] = type_object_name;
TypeObjectTable[LISPDECL_KEYWORD] = type_object_name;
TypeObjectTable[LISPDECL_PACKAGE] = type_object_name;
TypeObjectTable[LISPDECL_RANDOM_STATE] = type_object_name;
TypeObjectTable[LISPDECL_READTABLE] = type_object_name;
TypeObjectTable[LISPDECL_FUNCTION] = type_object_function;
TypeObjectTable[LISPDECL_COMPILED_FUNCTION] = type_object_compiled_function;
TypeObjectTable[LISPDECL_PATHNAME] = type_object_name;
TypeObjectTable[LISPDECL_LOGICAL_PATHNAME] = type_object_name;
TypeObjectTable[LISPDECL_SEQUENCE] = type_object_name;
TypeObjectTable[LISPDECL_ARRAY] = type_object_array;
TypeObjectTable[LISPDECL_SIMPLE_ARRAY] = type_object_simple_array;
TypeObjectTable[LISPDECL_CHARACTER] = type_object_name;
TypeObjectTable[LISPDECL_BASE_CHAR] = type_object_name;
TypeObjectTable[LISPDECL_STANDARD_CHAR] = type_object_name;
TypeObjectTable[LISPDECL_NUMBER] = type_object_name;
TypeObjectTable[LISPDECL_REAL] = type_object_real;
TypeObjectTable[LISPDECL_RATIONAL] = type_object_rational;
TypeObjectTable[LISPDECL_RATIO] = type_object_name;
TypeObjectTable[LISPDECL_INTEGER] = type_object_integer;
TypeObjectTable[LISPDECL_COMPLEX] = type_object_complex;
TypeObjectTable[LISPDECL_FLOAT] = type_object_float;
TypeObjectTable[LISPDECL_SHORT_FLOAT] = type_object_short_float;
TypeObjectTable[LISPDECL_SINGLE_FLOAT] = type_object_single_float;
TypeObjectTable[LISPDECL_DOUBLE_FLOAT] = type_object_double_float;
TypeObjectTable[LISPDECL_LONG_FLOAT] = type_object_long_float;
TypeObjectTable[LISPDECL_RESTART] = type_object_name;
TypeObjectTable[LISPDECL_ENVIRONMENT] = type_object_name;
TypeObjectTable[LISPDECL_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_BROADCAST_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_CONCATENATED_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_ECHO_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_FILE_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_STRING_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_SYNONYM_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_TWO_WAY_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_PROMPT_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_PRETTY_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_MEMORY_STREAM] = type_object_name;
TypeObjectTable[LISPDECL_QUOTE] = type_object_error;
TypeObjectTable[LISPDECL_BYTESPEC] = type_object_name;
TypeObjectTable[LISPDECL_PRINT_DISPATCH] = type_object_name;
TypeObjectTable[LISPDECL_EVAL] = type_object_name;
}
/************************************************************
* type_parse.c
************************************************************/
static int localhold_parse_type(LocalHold hold,
Execute ptr, addr *ret, addr pos, addr env)
{
Return(parse_type(ptr, ret, pos, env));
localhold_push(hold, *ret);
return 0;
}
/*
* and/or
*/
static int typelist_array4(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr pos, aster, list, array;
size_t size;
LocalHold hold;
GetConst(COMMON_ASTERISK, &aster);
for (size = 0, list = right; list != Nil; size++) {
if (! consp(list))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(list, &pos, &list);
if (pos == aster)
return fmte_("~A arguments don't use *.", left, NULL);
}
if (0xFFFFFFFFUL < size)
return fmte_("~A arguments S~ too long.", left, right, NULL);
vector4_heap(&array, size);
hold = LocalHold_local_push(ptr, array);
for (size = 0; right != Nil; size++) {
GetCons(right, &pos, &right);
Return(parse_type(ptr, &pos, pos, env));
SetArrayA4(array, size, pos);
}
localhold_end(hold);
type1_heap(type, array, ret);
return 0;
}
/*
* eql
*/
static int typelist_eql(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr pos, list;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &pos, &list);
if (list != Nil)
return fmte_("~A type must be a one argument ~S.", left, right, NULL);
copyheap(&pos, pos);
type_eql_heap(pos, ret);
return 0;
}
/*
* member
*/
static int typelist_member(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
size_t size;
addr pos, array;
for (size = 0, pos = right; pos != Nil; size++) {
if (! consp(pos))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCdr(pos, &pos);
}
if (0xFFFFFFFFUL < size)
return fmte_("~A arguments ~S too long.", left, right, NULL);
vector4_heap(&array, size);
for (size = 0; right != Nil; size++) {
GetCons(right, &pos, &right);
copyheap(&pos, pos);
SetArrayA4(array, size, pos);
}
type1_heap(type, array, ret);
return 0;
}
/*
* mod
*/
static int typelist_mod(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
int check;
addr pos, list;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &pos, &list);
if (list != Nil)
return fmte_("~A arguments ~S must be one integer.", right, NULL);
if (! integerp(pos))
return fmte_("~A argument ~S must be an integer type.", left, pos, NULL);
Return(plusp_integer_(pos, &check));
if (! check)
return fmte_("~A argument ~S must be a plus integer.", left, pos, NULL);
copyheap(&pos, pos);
type1_heap(type, pos, ret);
return 0;
}
/*
* not
*/
static int typelist_not(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr pos, list;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &pos, &list);
if (list != Nil)
return fmte_("~A arguments ~S must be one argument.", left, right, NULL);
GetConst(COMMON_ASTERISK, &list);
if (pos == list)
return fmte_("~A argument don't be *.", left, NULL);
Return(parse_type(ptr, &pos, pos, env));
type1_heap(type, pos, ret);
return 0;
}
/*
* satisfies
*/
static int typelist_satisfies(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr pos, list;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &pos, &list);
if (list != Nil)
return fmte_("~A arguments ~S must be one symbol.", left, right, NULL);
if (! symbolp(pos))
return fmte_("~A argument ~S must be a symbol.", left, pos, NULL);
copyheap(&pos, pos);
type_satisfies_heap(pos, ret);
return 0;
}
/*
* cons
*/
static int typelist_cons(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, car, cdr, aster;
LocalHold hold;
/* no arguments */
if (right == Nil)
goto asterisk;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &car, &list);
GetConst(COMMON_ASTERISK, &aster);
hold = LocalHold_local(ptr);
if (list == Nil) {
/* one argument */
if (car == aster)
goto asterisk;
Return(localhold_parse_type(hold, ptr, &car, car, env));
GetTypeTable(&cdr, Asterisk);
}
else {
/* two arguments */
if (! consp(list))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(list, &cdr, &list);
if (list != Nil) {
return fmte_("~A arguments ~S must have 1 or 2 arguments.",
left, right, NULL);
}
if (car == aster && cdr == aster)
goto asterisk;
Return(localhold_parse_type(hold, ptr, &car, car, env));
Return(localhold_parse_type(hold, ptr, &cdr, cdr, env));
}
localhold_end(hold);
type2_heap(type, car, cdr, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* function
*/
static int type_function_lambda(Execute ptr, addr *ret, addr list, addr env)
{
addr const_opt, const_rest, const_key;
addr var, opt, rest, key, one, name, type;
LocalHold hold;
GetConst(AMPERSAND_OPTIONAL, &const_opt);
GetConst(AMPERSAND_REST, &const_rest);
GetConst(AMPERSAND_KEY, &const_key);
var = opt = rest = key = one = Nil;
hold = LocalHold_array(ptr, 5);
var_label:
if (list == Nil)
goto final;
Return_getcons(list, &one, &list);
if (one == const_opt)
goto opt_label;
if (one == const_rest)
goto rest_label;
if (one == const_key)
goto key_label;
Return(parse_type(ptr, &one, one, env));
cons_heap(&var, one, var);
localhold_set(hold, 0, var);
goto var_label;
opt_label:
if (list == Nil)
goto final;
Return_getcons(list, &one, &list);
if (one == const_opt)
return fmte_("&optional parameter don't allow this place.", NULL);
if (one == const_rest)
goto rest_label;
if (one == const_key)
goto key_label;
Return(parse_type(ptr, &one, one, env));
cons_heap(&opt, one, opt);
localhold_set(hold, 1, opt);
goto opt_label;
rest_label:
if (list == Nil)
return fmte_("After &rest parameter must be have a typespec.", NULL);
Return_getcons(list, &one, &list);
if (one == const_opt || one == const_rest || one == const_key)
return fmte_("After &rest parameter don't allow to be a &-symbol.", NULL);
Return(parse_type(ptr, &rest, one, env));
localhold_set(hold, 2, rest);
if (list == Nil)
goto final;
Return_getcons(list, &one, &list);
if (one != const_key)
return fmte_("After &rest argument don't allow to be a type.", NULL);
goto key_label;
key_label:
if (list == Nil)
goto final;
Return_getcons(list, &one, &list);
if (one == const_opt || one == const_rest || one == const_key)
return fmte_("After &key parameter don't allow to be a &-symbol.", NULL);
if (! consp(one))
return fmte_("After &key parameter must be a list.", NULL);
Return_getcons(one, &name, &one);
copyheap(&name, name);
localhold_set(hold, 3, name);
Return_getcons(one, &type, &one);
if (one != Nil)
return fmte_("&key parameter must be a (key type) list.", NULL);
Return(parse_type(ptr, &type, type, env));
cons_heap(&one, name, type);
cons_heap(&key, one, key);
localhold_set(hold, 4, key);
goto key_label;
final:
localhold_end(hold);
vector2_heap(&one, 4);
nreverse(&var, var);
nreverse(&opt, opt);
nreverse(&key, key);
SetArrayA2(one, 0, var);
SetArrayA2(one, 1, opt);
SetArrayA2(one, 2, rest);
SetArrayA2(one, 3, key);
return Result(ret, one);
}
static int type_function_list(Execute ptr, addr *ret, addr right, addr env)
{
addr aster;
GetConst(COMMON_ASTERISK, &aster);
CheckType(aster, LISPTYPE_SYMBOL);
if (right == aster) {
GetTypeTable(ret, Asterisk);
return 0;
}
return type_function_lambda(ptr, ret, right, env);
}
/* typespec* [&optional typespec*] [&rest typespec]
* typespec* [&optional typespec*] [&rest typespec] [&allow-other-keys]
*/
#undef LISP_VALUES_ALLOW_ENABLE
static int type_values_typespec(Execute ptr, addr list, addr env,
addr *retvar, addr *retopt, addr *retrest, addr *retallow)
{
addr var, vars, opt, rest, allow;
addr const_opt, const_rest;
#ifdef LISP_VALUES_ALLOW_ENABLE
addr const_allow;
#endif
LocalHold hold;
GetConst(AMPERSAND_OPTIONAL, &const_opt);
GetConst(AMPERSAND_REST, &const_rest);
#ifdef LISP_VALUES_ALLOW_ENABLE
GetConst(AMPERSAND_ALLOW, &const_allow);
#endif
vars = opt = rest = allow = Nil;
hold = LocalHold_array(ptr, 3);
var_label:
if (list == Nil)
goto final;
Return_getcons(list, &var, &list);
if (var == const_opt)
goto optional_label;
if (var == const_rest)
goto rest_label;
#ifdef LISP_VALUES_ALLOW_ENABLE
if (var == const_allow)
goto allow_label;
#endif
Return(parse_type(ptr, &var, var, env));
cons_heap(&vars, var, vars);
localhold_set(hold, 0, vars);
goto var_label;
optional_label:
if (list == Nil)
goto final;
Return_getcons(list, &var, &list);
if (var == const_rest)
goto rest_label;
#ifdef LISP_VALUES_ALLOW_ENABLE
if (var == const_allow)
goto allow_label;
#endif
Return(parse_type(ptr, &var, var, env));
cons_heap(&opt, var, opt);
localhold_set(hold, 1, opt);
goto optional_label;
rest_label:
if (list == Nil)
return fmte_("After &rest argument must be a type.", NULL);
Return_getcons(list, &var, &list);
if (var == const_opt || var == const_rest)
return fmte_("After &rest argument must be a type.", NULL);
#ifdef LISP_VALUES_ALLOW_ENABLE
if (var == const_allow)
return fmte_("After &rest argument must be a type.", NULL);
#endif
Return(parse_type(ptr, &rest, var, env));
localhold_set(hold, 2, rest);
if (list == Nil)
goto final;
Return_getcons(list, &var, &list);
#ifdef LISP_VALUES_ALLOW_ENABLE
if (var == const_allow)
goto allow_label;
#endif
return fmte_("Invalid values form.", NULL);
#ifdef LISP_VALUES_ALLOW_ENABLE
allow_label:
allow = T;
if (list != Nil)
return fmte_("After &allow-other-keys must be nil.", NULL);
goto final;
#endif
final:
localhold_end(hold);
nreverse(retvar, vars);
nreverse(retopt, opt);
*retrest = rest;
*retallow = allow;
return 0;
}
static int type_values(Execute ptr, addr *ret, addr right, addr env)
{
addr var, opt, rest, allow;
var = opt = rest = allow = Nil;
Return(type_values_typespec(ptr, right, env, &var, &opt, &rest, &allow));
if (rest == Nil)
GetTypeTable(&rest, T);
type_values_heap(var, opt, rest, allow, ret);
return 0;
}
static int type_function_values(Execute ptr, addr *ret, addr type, addr env)
{
addr pos, check, list;
if (! consp(type))
return parse_type(ptr, ret, type, env);
Return_getcons(type, &pos, &list);
GetConst(COMMON_VALUES, &check);
if (check != pos)
return parse_type(ptr, ret, type, env);
else
return type_values(ptr, ret, list, env);
}
static int typelist_function(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, aster, first, second;
LocalHold hold;
/* no arguments */
if (right == Nil)
goto asterisk;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first, &list);
GetConst(COMMON_ASTERISK, &aster);
if (list == Nil) {
/* one argument */
if (first == aster)
goto asterisk;
Return(type_function_list(ptr, &first, first, env));
GetTypeTable(&second, Asterisk);
}
else {
/* two arguments */
if (! consp(list))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(list, &second, &list);
if (list != Nil) {
return fmte_("~A arguments ~S must have 1 or 2 arguments.",
left, right, NULL);
}
if (first == aster && second == aster)
goto asterisk;
Return(type_function_list(ptr, &first, first, env));
hold = LocalHold_local_push(ptr, first);
Return(type_function_values(ptr, &second, second, env));
localhold_end(hold);
}
type3_heap(type, first, second, Nil, ret);
return 0;
asterisk:
GetTypeTable(&aster, Asterisk);
type3_heap(type, aster, aster, Nil, ret);
return 0;
}
/*
* array
*/
static int parse_array_length(addr right, size_t *rsize, int *ret)
{
addr aster, left;
size_t size;
GetConst(COMMON_ASTERISK, &aster);
for (size = 0; right != Nil; size++) {
if (! consp(right)) {
*ret = 0;
*rsize = 0;
return fmte_("The dimension parameter ~S must be a list.", right, NULL);
}
GetCons(right, &left, &right);
if (left != aster)
return Result(ret, 0);
}
*rsize = size;
return Result(ret, 1);
}
static int parse_array_fixnum_check(addr *ret, addr pos)
{
if ((! fixnump(pos)) || RefFixnum(pos) < 0) {
return fmte_("The dimension value ~S "
"must be a non-negative fixnum.", pos, NULL);
}
copyheap(ret, pos);
return 0;
}
static int parse_array_dimension(addr *ret, addr right)
{
addr aster, left, array;
size_t size;
/* length */
for (size = 0, left = right; left != Nil; size++) {
if (! consp(left))
return fmte_("The dimension parameter ~S must be a list.", left, NULL);
GetCdr(left, &left);
}
/* make vector */
GetConst(COMMON_ASTERISK, &aster);
vector4_heap(&array, size);
for (size = 0; right != Nil; size++) {
GetCons(right, &left, &right);
if (left == aster) {
GetTypeTable(&left, Asterisk);
}
else {
Return(parse_array_fixnum_check(&left, left));
}
SetArrayA4(array, size, left);
}
return Result(ret, array);
}
static int parse_array_second(addr *ret, addr right)
{
int check;
addr aster;
size_t size;
GetConst(COMMON_ASTERISK, &aster);
if (right == Nil) {
/* dimension arguments, 0 */
fixnum_heap(ret, 0);
}
else if (consp(right)) {
/* dimension arguments */
Return(parse_array_length(right, &size, &check));
if (check) {
if (FIXNUM_MAX < size)
return fmte_("size overflow.", NULL);
fixnum_heap(ret, (fixnum)size);
}
else {
Return(parse_array_dimension(ret, right));
}
}
else {
/* finxum arguments */
Return(parse_array_fixnum_check(ret, right));
}
return 0;
}
static int typelist_array(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, aster, first, second;
/* no arguments */
if (right == Nil)
goto asterisk;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first, &list);
GetConst(COMMON_ASTERISK, &aster);
if (list == Nil) {
/* one argument */
if (first == aster)
goto asterisk;
Return(parse_type(ptr, &first, first, env));
GetTypeTable(&second, Asterisk);
}
else {
/* two arguments */
if (! consp(list))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(list, &second, &list);
if (list != Nil)
return fmte_("~A type arguments too long.", left, NULL);
if (first == aster && second == aster)
goto asterisk;
if (first == aster) {
GetTypeTable(&first, Asterisk);
}
else {
Return(parse_type(ptr, &first, first, env));
}
if (second == aster) {
GetTypeTable(&second, Asterisk);
}
else {
Return(parse_array_second(&second, second));
}
}
if (! type_asterisk_p(first)) {
Return(upgraded_array_type_(first, &first));
}
type2_heap(type, first, second, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* vector
*/
static int typelist_vector(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, aster, first, second;
/* no arguments */
if (right == Nil)
goto asterisk;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first, &list);
GetConst(COMMON_ASTERISK, &aster);
if (list == Nil) {
/* one argument */
if (first == aster)
goto asterisk;
Return(parse_type(ptr, &first, first, env));
GetTypeTable(&second, Asterisk);
}
else {
/* two arguments */
if (! consp(list))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(list, &second, &list);
if (list != Nil)
return fmte_("~A arguments ~S too long.", left, right, NULL);
if (first == aster && second == aster)
goto asterisk;
if (first == aster) {
GetTypeTable(&first, Asterisk);
}
else {
Return(parse_type(ptr, &first, first, env));
}
if (second == aster) {
GetTypeTable(&second, Asterisk);
}
else {
Return(parse_array_fixnum_check(&second, second));
}
}
if (! type_asterisk_p(first)) {
Return(upgraded_array_type_(first, &first));
}
type2_heap(type, first, second, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* size
*/
static int typelist_size(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, aster, first;
/* no arguments */
if (right == Nil)
goto asterisk;
/* one argument */
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first, &list);
if (list != Nil)
return fmte_("~A arguments ~S too long.", left, right, NULL);
GetConst(COMMON_ASTERISK, &aster);
if (first == aster)
goto asterisk;
Return(parse_array_fixnum_check(&first, first));
type1_heap(type, first, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* range
*/
static int type_range_element(addr left, addr right, int (*call)(addr),
addr *ret1, addr *ret2)
{
addr pos, list;
if (consp(right)) {
GetCons(right, &pos, &list);
if (list != Nil) {
return fmte_("~A argument ~S "
"must be a real or (real) form.", left, right, NULL);
}
Return((*call)(pos));
*ret1 = T;
copyheap(ret2, pos);
}
else {
Return((*call)(right));
*ret1 = Nil;
copyheap(ret2, right);
}
return 0;
}
/* (integer 10 (20)) -> (integer nil 10 t 20) */
static int typelist_range(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env,
int (*call)(addr))
{
addr list, aster, first1, first2, second1, second2;
/* no arguments */
if (right == Nil)
goto asterisk;
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first1, &list);
GetConst(COMMON_ASTERISK, &aster);
if (list == Nil) {
/* one argument */
if (first1 == aster)
goto asterisk;
Return(type_range_element(left, first1, call, &first1, &first2));
GetTypeTable(&second1, Asterisk);
second2 = second1;
}
else {
/* two arguments */
if (! consp(list))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(list, &second1, &list);
if (list != Nil)
return fmte_("~A arguments ~S too long.", left, right, NULL);
if (first1 == aster && second1 == aster)
goto asterisk;
if (first1 == aster) {
GetTypeTable(&first1, Asterisk);
first2 = first1;
}
else {
Return(type_range_element(left, first1, call, &first1, &first2));
}
if (second1 == aster) {
GetTypeTable(&second1, Asterisk);
second2 = second1;
}
else {
Return(type_range_element(left, second1, call, &second1, &second2));
}
}
type4_heap(type, first1, first2, second1, second2, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* real
*/
static int typelist_real_p(addr pos)
{
if (! realp(pos))
return fmte_("REAL argument ~S must be a real.", pos, NULL);
return 0;
}
static int typelist_real(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_real_p);
}
/*
* rational
*/
static int typelist_rational_p(addr pos)
{
if (! rationalp(pos))
return fmte_("RATIONAL argument ~S must be a rational.", pos, NULL);
return 0;
}
static int typelist_rational(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_rational_p);
}
/*
* integer
*/
static int typelist_integer_p(addr pos)
{
if (! integerp(pos))
return fmte_("INTEGER argument ~S must be an integer.", pos, NULL);
return 0;
}
static int typelist_integer(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_integer_p);
}
/*
* float
*/
static int typelist_float_p(addr pos)
{
if (! floatp(pos))
return fmte_("FLOAT argument ~S must be a float.", pos, NULL);
return 0;
}
static int typelist_float(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_float_p);
}
/*
* short-float
*/
static int typelist_short_float_p(addr pos)
{
if (GetType(pos) != LISPTYPE_SHORT_FLOAT)
return fmte_("SHORT-FLOAT argument ~S must be a short-float.", pos, NULL);
return 0;
}
static int typelist_short(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_short_float_p);
}
/*
* single-float
*/
static int typelist_single_float_p(addr pos)
{
if (GetType(pos) != LISPTYPE_SINGLE_FLOAT)
return fmte_("SINGLE-FLOAT argument ~S must be a single-float.", pos, NULL);
return 0;
}
static int typelist_single(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_single_float_p);
}
/*
* double-float
*/
static int typelist_double_float_p(addr pos)
{
if (GetType(pos) != LISPTYPE_DOUBLE_FLOAT)
return fmte_("DOUBLE-FLOAT argument ~S must be a double-float.", pos, NULL);
return 0;
}
static int typelist_double(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_double_float_p);
}
/*
* long-float
*/
static int typelist_long_float_p(addr pos)
{
if (GetType(pos) != LISPTYPE_LONG_FLOAT)
return fmte_("LONG-FLOAT argument ~S must be a long-float.", pos, NULL);
return 0;
}
static int typelist_long(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
return typelist_range(ptr, ret, type, left, right, env, typelist_long_float_p);
}
/*
* byte
*/
static int type_byte_integer_check(addr *ret, addr pos)
{
int check;
if (GetType(pos) != LISPTYPE_FIXNUM)
goto error;
Return(plusp_integer_(pos, &check));
if (! check)
goto error;
copyheap(ret, pos);
return 0;
error:
*ret = Nil;
return fmte_("The value ~S must be a positive integer.", pos, NULL);
}
static int typelist_byte(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, aster, first;
/* no arguments */
if (right == Nil)
goto asterisk;
/* one argument */
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first, &list);
if (list != Nil)
return fmte_("~A arguments ~S too long.", left, right, NULL);
GetConst(COMMON_ASTERISK, &aster);
if (first == aster)
goto asterisk;
Return(type_byte_integer_check(&first, first));
type1_heap(type, first, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* complex
*/
static int typelist_complex(Execute ptr, addr *ret,
enum LISPDECL type, addr left, addr right, addr env)
{
addr list, aster, first;
/* no arguments */
if (right == Nil)
goto asterisk;
/* one argument */
if (! consp(right))
return fmte_("Invalid ~A form ~S.", left, right, NULL);
GetCons(right, &first, &list);
if (list != Nil)
return fmte_("~A arguments ~S too long.", left, right, NULL);
GetConst(COMMON_ASTERISK, &aster);
if (first == aster)
goto asterisk;
Return(parse_type(ptr, &first, first, env));
Return(upgraded_complex_type_(ptr, env, first, &first));
type1_heap(type, first, ret);
return 0;
asterisk:
return parse_type(ptr, ret, left, env);
}
/*
* parse-type
*/
typedef int (*call_typelist)(Execute, addr *, enum LISPDECL, addr, addr, addr);
static call_typelist TypeParseList[LISPDECL_SIZE];
#define DefListInit(a, b) (TypeParseList[LISPDECL_##a] = typelist_##b)
void init_type_parse(void)
{
/* Compound-type */
DefListInit(AND, array4 );
DefListInit(OR, array4 );
DefListInit(EQL, eql );
DefListInit(MEMBER, member );
DefListInit(MOD, mod );
DefListInit(NOT, not );
DefListInit(SATISFIES, satisfies );
/* LispInit(VALUES, values ); */
/* Atomic-type */
DefListInit(CONS, cons );
DefListInit(FUNCTION, function );
DefListInit(COMPILED_FUNCTION, function );
DefListInit(ARRAY, array );
DefListInit(SIMPLE_ARRAY, array );
DefListInit(VECTOR, vector );
DefListInit(SIMPLE_VECTOR, size );
DefListInit(BIT_VECTOR, size );
DefListInit(SIMPLE_BIT_VECTOR, size );
DefListInit(STRING, size );
DefListInit(BASE_STRING, size );
DefListInit(SIMPLE_STRING, size );
DefListInit(SIMPLE_BASE_STRING, size );
DefListInit(REAL, real );
DefListInit(RATIONAL, rational );
DefListInit(INTEGER, integer );
DefListInit(SIGNED_BYTE, byte );
DefListInit(UNSIGNED_BYTE, byte );
DefListInit(COMPLEX, complex );
DefListInit(FLOAT, float );
DefListInit(SHORT_FLOAT, short );
DefListInit(SINGLE_FLOAT, single );
DefListInit(DOUBLE_FLOAT, double );
DefListInit(LONG_FLOAT, long );
}
#define SetTypeParseObject(x,v) (*(enum LISPDECL *)PtrBodyB2(x) = (v))
#define GetTypeParseObject(x,r) (*(r) = *(enum LISPDECL *)PtrBodyB2(x))
static void make_type_parse_object(addr *ret, enum LISPDECL type)
{
addr pos;
heap_body2(&pos, LISPSYSTEM_TYPE_PARSE, sizeoft(enum LISPDECL));
SetTypeParseObject(pos, type);
*ret = pos;
}
static void define_type_parse_object(enum LISPDECL type, constindex name)
{
addr symbol, pos;
GetConstant(name, &symbol);
CheckType(symbol, LISPTYPE_SYMBOL);
make_type_parse_object(&pos, type);
setlisttype_symbol(symbol, pos);
}
#define DefListType(a) define_type_parse_object(LISPDECL_##a, CONSTANT_COMMON_##a)
void build_type_parse(void)
{
/* Compound-type */
DefListType(AND );
DefListType(OR );
DefListType(EQL );
DefListType(MEMBER );
DefListType(MOD );
DefListType(NOT );
DefListType(SATISFIES );
/* ListType(VALUES );*/
/* Atomic-type */
DefListType(CONS );
DefListType(FUNCTION );
DefListType(COMPILED_FUNCTION );
DefListType(ARRAY );
DefListType(SIMPLE_ARRAY );
DefListType(VECTOR );
DefListType(SIMPLE_VECTOR );
DefListType(BIT_VECTOR );
DefListType(SIMPLE_BIT_VECTOR );
DefListType(STRING );
DefListType(BASE_STRING );
DefListType(SIMPLE_STRING );
DefListType(SIMPLE_BASE_STRING );
DefListType(REAL );
DefListType(RATIONAL );
DefListType(INTEGER );
DefListType(SIGNED_BYTE );
DefListType(UNSIGNED_BYTE );
DefListType(COMPLEX );
DefListType(FLOAT );
DefListType(SHORT_FLOAT );
DefListType(SINGLE_FLOAT );
DefListType(DOUBLE_FLOAT );
DefListType(LONG_FLOAT );
}
static int parse_type_default(Execute ptr,
addr *ret, addr symbol, addr args, addr env)
{
enum LISPDECL type;
call_typelist call;
addr pos;
CheckType(symbol, LISPTYPE_SYMBOL);
getlisttype_symbol(symbol, &pos);
if (pos == Nil)
return Result(ret, NULL);
CheckType(pos, LISPSYSTEM_TYPE_PARSE);
GetTypeParseObject(pos, &type);
call = TypeParseList[type];
return (*call)(ptr, ret, type, symbol, args, env);
}
static int parse_type_list(Execute ptr, addr *ret, addr pos, addr env)
{
addr symbol, args, check;
GetCons(pos, &symbol, &args);
if (! symbolp(symbol))
return TypeError_(symbol, SYMBOL);
/* lisp type */
Return(parse_type_default(ptr, &check, symbol, args, env));
if (check)
return Result(ret, check);
/* deftype */
Return(execute_list_deftype(ptr, &check, pos, env));
if (check)
return parse_type(ptr, ret, check, env);
/* error */
type_error_heap(pos, ret);
return 0;
}
static int parse_type_symbol(Execute ptr, addr *ret, addr pos, addr env)
{
addr check;
Return(find_symbol_type(ptr, &check, pos, env));
if (check)
return parse_type(ptr, ret, check, env);
/* error */
type_error_heap(pos, ret);
return 0;
}
static int parse_type_type(Execute ptr, addr *ret, addr pos)
{
addr x, y, z;
/* type */
type_throw_heap(pos, &pos);
if (RefLispDecl(pos) != LISPDECL_CLOS)
return Result(ret, pos);
/* clos */
GetArrayType(pos, 0, &x);
if (type_asterisk_p(x))
return Result(ret, pos);
GetClassOfClos(x, &y);
GetConst(CLOS_BUILT_IN_CLASS, &z);
if (y != z)
return Result(ret, pos);
/* built-in-class */
Return(stdget_class_name_(x, &x));
return parse_type(ptr, ret, x, Nil); /* don't use env */
}
static int parse_type_clos(Execute ptr, addr *ret, addr pos)
{
addr x, y;
GetClassOfClos(pos, &x);
GetConst(CLOS_BUILT_IN_CLASS, &y);
if (x != y) {
type_clos_heap(pos, ret);
return 0;
}
/* built-in-class */
Return(stdget_class_name_(pos, &x));
return parse_type(ptr, ret, x, Nil); /* don't use env */
}
static int parse_type_null(Execute ptr, addr *ret, addr pos, addr env)
{
switch (GetType(pos)) {
case LISPTYPE_NIL:
case LISPTYPE_T:
case LISPTYPE_SYMBOL:
return parse_type_symbol(ptr, ret, pos, env);
case LISPTYPE_CONS:
return parse_type_list(ptr, ret, pos, env);
case LISPTYPE_TYPE:
return parse_type_type(ptr, ret, pos);
case LISPTYPE_CLOS:
return parse_type_clos(ptr, ret, pos);
default:
return Result(ret, NULL);
}
}
int parse_type(Execute ptr, addr *ret, addr pos, addr env)
{
LocalHold hold;
hold = LocalHold_local(ptr);
localhold_pushva_force(hold, pos, env, NULL);
Return(parse_type_null(ptr, ret, pos, env));
localhold_end(hold);
if (*ret == NULL)
return fmte_("Invalid type-spec ~S.", pos, NULL);
return 0;
}
int parse_type_not(Execute ptr, addr *ret, addr pos, addr env)
{
Return(parse_type(ptr, &pos, pos, env));
type_copy_unsafe_heap(&pos, pos);
type_revnotdecl(pos);
return Result(ret, pos);
}
int parse_type_noaster(Execute ptr, addr *ret, addr pos, addr env)
{
addr aster;
GetConst(COMMON_ASTERISK, &aster);
if (pos == aster)
return fmte_("Don't allow to use asterisk type.", NULL);
return parse_type(ptr, ret, pos, env);
}
void parse_type_unsafe(addr *ret, addr pos)
{
if (parse_type(Execute_Thread, ret, pos, Nil)) {
Abort("parse-type error.");
}
}
/* debug */
int parse_type_values(Execute ptr, addr *ret, addr type, addr env)
{
LocalHold hold;
hold = LocalHold_local(ptr);
localhold_pushva_force(hold, type, env, NULL);
Return(type_function_values(ptr, ret, type, env));
localhold_end(hold);
return 0;
}
/************************************************************
* type_symbol.c
************************************************************/
/*
* build-type-symbol
*/
#define DefSymbolType(a,b) define_symbol_type(CONSTANT_##a, TypeTable_##b)
static void define_symbol_type(constindex name, enum TypeTable type)
{
addr symbol, value;
GetConstant(name, &symbol);
gettypetable(type, &value);
setsymboltype_symbol(symbol, value);
}
void build_type_symbol(void)
{
DefSymbolType(SYSTEM_INVALID, Invalid );
DefSymbolType(COMMON_ASTERISK, Asterisk );
/* Extract-type */
DefSymbolType(COMMON_ATOM, Atom );
DefSymbolType(COMMON_LIST, List );
DefSymbolType(COMMON_BOOLEAN, Boolean );
DefSymbolType(COMMON_VECTOR, Vector );
DefSymbolType(COMMON_SIMPLE_VECTOR, SimpleVector );
DefSymbolType(COMMON_BIT_VECTOR, BitVector );
DefSymbolType(COMMON_SIMPLE_BIT_VECTOR, SimpleBitVector );
DefSymbolType(COMMON_EXTENDED_CHAR, ExtendedChar );
DefSymbolType(COMMON_STRING, String );
DefSymbolType(COMMON_BASE_STRING, BaseString );
DefSymbolType(COMMON_SIMPLE_STRING, SimpleString );
DefSymbolType(COMMON_SIMPLE_BASE_STRING, SimpleBaseString );
DefSymbolType(COMMON_SIGNED_BYTE, SignedByte );
DefSymbolType(COMMON_UNSIGNED_BYTE, UnsignedByte );
DefSymbolType(COMMON_BIT, Bit );
DefSymbolType(COMMON_FIXNUM, Fixnum );
DefSymbolType(COMMON_BIGNUM, Bignum );
/* Atomic-type */
DefSymbolType(COMMON_NIL, Nil );
DefSymbolType(COMMON_T, T );
DefSymbolType(COMMON_NULL, Null );
DefSymbolType(COMMON_CONS, Cons );
DefSymbolType(COMMON_HASH_TABLE, Hashtable );
DefSymbolType(COMMON_SYMBOL, Symbol );
DefSymbolType(COMMON_KEYWORD, Keyword );
DefSymbolType(COMMON_PACKAGE, Package );
DefSymbolType(COMMON_RANDOM_STATE, RandomState );
DefSymbolType(COMMON_READTABLE, Readtable );
DefSymbolType(COMMON_FUNCTION, Function );
DefSymbolType(COMMON_COMPILED_FUNCTION, CompiledFunction );
DefSymbolType(COMMON_PATHNAME, Pathname );
DefSymbolType(COMMON_LOGICAL_PATHNAME, LogicalPathname );
DefSymbolType(COMMON_SEQUENCE, Sequence );
DefSymbolType(COMMON_ARRAY, Array );
DefSymbolType(COMMON_SIMPLE_ARRAY, SimpleArray );
DefSymbolType(COMMON_CHARACTER, Character );
DefSymbolType(COMMON_BASE_CHAR, BaseChar );
DefSymbolType(COMMON_STANDARD_CHAR, StandardChar );
DefSymbolType(COMMON_NUMBER, Number );
DefSymbolType(COMMON_REAL, Real );
DefSymbolType(COMMON_RATIONAL, Rational );
DefSymbolType(COMMON_RATIO, Ratio );
DefSymbolType(COMMON_INTEGER, Integer );
DefSymbolType(COMMON_COMPLEX, Complex );
DefSymbolType(COMMON_FLOAT, Float );
DefSymbolType(COMMON_SHORT_FLOAT, ShortFloat );
DefSymbolType(COMMON_SINGLE_FLOAT, SingleFloat );
DefSymbolType(COMMON_DOUBLE_FLOAT, DoubleFloat );
DefSymbolType(COMMON_LONG_FLOAT, LongFloat );
DefSymbolType(COMMON_RESTART, Restart );
DefSymbolType(SYSTEM_ENVIRONMENT, Environment );
DefSymbolType(COMMON_STREAM, Stream );
DefSymbolType(COMMON_BROADCAST_STREAM, BroadcastStream );
DefSymbolType(COMMON_CONCATENATED_STREAM, ConcatenatedStream );
DefSymbolType(COMMON_ECHO_STREAM, EchoStream );
DefSymbolType(COMMON_FILE_STREAM, FileStream );
DefSymbolType(COMMON_STRING_STREAM, StringStream );
DefSymbolType(COMMON_SYNONYM_STREAM, SynonymStream );
DefSymbolType(COMMON_TWO_WAY_STREAM, TwoWayStream );
DefSymbolType(SYSTEM_PROMPT_STREAM, PromptStream );
DefSymbolType(SYSTEM_PRETTY_STREAM, PrettyStream );
DefSymbolType(SYSTEM_MEMORY_STREAM, MemoryStream );
DefSymbolType(SYSTEM_TERMINAL_STREAM, TerminalStream );
DefSymbolType(SYSTEM_QUOTE, Quote );
DefSymbolType(SYSTEM_BYTESPEC, ByteSpec );
DefSymbolType(SYSTEM_PRINT_DISPATCH, PrintDispatch );
DefSymbolType(SYSTEM_EVAL, Eval );
}
/*
* init-type-symbol
*/
static constindex TypeSymbolTable[LISPDECL_SIZE];
#define DefTypeSymbol(a,b) define_type_symbol(LISPDECL_##a, CONSTANT_##b)
static void define_type_symbol(enum LISPDECL type, constindex name)
{
TypeSymbolTable[(int)type] = name;
}
void init_type_symbol(void)
{
DefTypeSymbol(EMPTY, EMPTY );
DefTypeSymbol(INVALID, SYSTEM_INVALID );
DefTypeSymbol(OPTIMIZED, EMPTY );
DefTypeSymbol(SUBTYPEP, EMPTY );
DefTypeSymbol(TYPE, SYSTEM_TYPE );
DefTypeSymbol(CLOS, EMPTY );
DefTypeSymbol(ASTERISK, COMMON_ASTERISK );
/* Compound-type */
DefTypeSymbol(AND, EMPTY );
DefTypeSymbol(EQL, EMPTY );
DefTypeSymbol(MEMBER, EMPTY );
DefTypeSymbol(MOD, EMPTY );
DefTypeSymbol(NOT, EMPTY );
DefTypeSymbol(OR, EMPTY );
DefTypeSymbol(SATISFIES, EMPTY );
DefTypeSymbol(VALUES, EMPTY );
/* Extract-type */
DefTypeSymbol(ATOM, COMMON_ATOM );
DefTypeSymbol(LIST, COMMON_LIST );
DefTypeSymbol(BOOLEAN, COMMON_BOOLEAN );
DefTypeSymbol(VECTOR, COMMON_VECTOR );
DefTypeSymbol(SIMPLE_VECTOR, COMMON_SIMPLE_VECTOR );
DefTypeSymbol(BIT_VECTOR, COMMON_BIT_VECTOR );
DefTypeSymbol(SIMPLE_BIT_VECTOR, COMMON_SIMPLE_BIT_VECTOR );
DefTypeSymbol(EXTENDED_CHAR, COMMON_EXTENDED_CHAR );
DefTypeSymbol(STRING, COMMON_STRING );
DefTypeSymbol(BASE_STRING, COMMON_BASE_STRING );
DefTypeSymbol(SIMPLE_STRING, COMMON_SIMPLE_STRING );
DefTypeSymbol(SIMPLE_BASE_STRING, COMMON_SIMPLE_BASE_STRING );
DefTypeSymbol(SIGNED_BYTE, COMMON_SIGNED_BYTE );
DefTypeSymbol(UNSIGNED_BYTE, COMMON_UNSIGNED_BYTE );
DefTypeSymbol(BIT, COMMON_BIT );
DefTypeSymbol(FIXNUM, COMMON_FIXNUM );
DefTypeSymbol(BIGNUM, COMMON_BIGNUM );
/* Atomic-type */
DefTypeSymbol(NIL, COMMON_NIL );
DefTypeSymbol(T, COMMON_T );
DefTypeSymbol(NULL, COMMON_NULL );
DefTypeSymbol(CONS, COMMON_CONS );
DefTypeSymbol(HASH_TABLE, COMMON_HASH_TABLE );
DefTypeSymbol(SYMBOL, COMMON_SYMBOL );
DefTypeSymbol(KEYWORD, COMMON_KEYWORD );
DefTypeSymbol(PACKAGE, COMMON_PACKAGE );
DefTypeSymbol(RANDOM_STATE, COMMON_RANDOM_STATE );
DefTypeSymbol(READTABLE, COMMON_READTABLE );
DefTypeSymbol(FUNCTION, COMMON_FUNCTION );
DefTypeSymbol(COMPILED_FUNCTION, COMMON_COMPILED_FUNCTION );
DefTypeSymbol(PATHNAME, COMMON_PATHNAME );
DefTypeSymbol(LOGICAL_PATHNAME, COMMON_LOGICAL_PATHNAME );
DefTypeSymbol(SEQUENCE, COMMON_SEQUENCE );
DefTypeSymbol(ARRAY, COMMON_ARRAY );
DefTypeSymbol(SIMPLE_ARRAY, COMMON_SIMPLE_ARRAY );
DefTypeSymbol(CHARACTER, COMMON_CHARACTER );
DefTypeSymbol(BASE_CHAR, COMMON_BASE_CHAR );
DefTypeSymbol(STANDARD_CHAR, COMMON_STANDARD_CHAR );
DefTypeSymbol(NUMBER, COMMON_NUMBER );
DefTypeSymbol(REAL, COMMON_REAL );
DefTypeSymbol(RATIONAL, COMMON_RATIONAL );
DefTypeSymbol(RATIO, COMMON_RATIO );
DefTypeSymbol(INTEGER, COMMON_INTEGER );
DefTypeSymbol(COMPLEX, COMMON_COMPLEX );
DefTypeSymbol(FLOAT, COMMON_FLOAT );
DefTypeSymbol(SHORT_FLOAT, COMMON_SHORT_FLOAT );
DefTypeSymbol(SINGLE_FLOAT, COMMON_SINGLE_FLOAT );
DefTypeSymbol(DOUBLE_FLOAT, COMMON_DOUBLE_FLOAT );
DefTypeSymbol(LONG_FLOAT, COMMON_LONG_FLOAT );
DefTypeSymbol(RESTART, COMMON_RESTART );
DefTypeSymbol(ENVIRONMENT, SYSTEM_ENVIRONMENT );
DefTypeSymbol(STREAM, COMMON_STREAM );
DefTypeSymbol(BROADCAST_STREAM, COMMON_BROADCAST_STREAM );
DefTypeSymbol(CONCATENATED_STREAM, COMMON_CONCATENATED_STREAM );
DefTypeSymbol(ECHO_STREAM, COMMON_ECHO_STREAM );
DefTypeSymbol(FILE_STREAM, COMMON_FILE_STREAM );
DefTypeSymbol(STRING_STREAM, COMMON_STRING_STREAM );
DefTypeSymbol(SYNONYM_STREAM, COMMON_SYNONYM_STREAM );
DefTypeSymbol(TWO_WAY_STREAM, COMMON_TWO_WAY_STREAM );
DefTypeSymbol(PROMPT_STREAM, SYSTEM_PROMPT_STREAM );
DefTypeSymbol(PRETTY_STREAM, SYSTEM_PRETTY_STREAM );
DefTypeSymbol(MEMORY_STREAM, SYSTEM_MEMORY_STREAM );
DefTypeSymbol(TERMINAL_STREAM, SYSTEM_TERMINAL_STREAM );
DefTypeSymbol(QUOTE, SYSTEM_QUOTE );
DefTypeSymbol(BYTESPEC, SYSTEM_BYTESPEC );
DefTypeSymbol(PRINT_DISPATCH, SYSTEM_PRINT_DISPATCH );
DefTypeSymbol(EVAL, SYSTEM_EVAL );
}
/*
* symbol -> type
* 1. find symbol.
* 2. find clos.
* 3. find deftype.
* 4. return unbound.
*/
int find_symbol_type(Execute ptr, addr *ret, addr symbol, addr env)
{
addr check;
Check(! symbolp(symbol), "type error");
/* find symbol */
getsymboltype_symbol(symbol, &check);
if (check != Nil)
return Result(ret, check);
/* find clos */
clos_find_class_nil(symbol, &check);
if (check != Nil) {
type_clos_heap(check, ret);
return 0;
}
/* find deftype */
Return(execute_symbol_deftype(ptr, &check, symbol, env));
if (check)
return parse_type(ptr, ret, check, env);
/* error */
return Result(ret, NULL);
}
/*
* type -> symbol
*/
constindex getdeclname(enum LISPDECL type)
{
Check(LISPDECL_SIZE <= type, "index error");
return TypeSymbolTable[type];
}
/*
* function
*/
int type_symbol_p(addr symbol)
{
addr check;
/* symbol check */
if (! symbolp(symbol))
return 0;
/* find symbol */
getsymboltype_symbol(symbol, &check);
if (check != Nil)
return 1;
/* find clos */
clos_find_class_nil(symbol, &check);
if (check != Nil)
return 1;
/* find deftype */
return symbol_deftypep(symbol);
}
/************************************************************
* type_table.c
************************************************************/
/*
* interface
*/
static void getroot_typetable(addr *ret)
{
*ret = LispRoot(TYPETABLE);
CheckType(*ret, LISPTYPE_VECTOR);
}
addr reftypetable(enum TypeTable index)
{
addr pos;
gettypetable(index, &pos);
return pos;
}
void gettypetable(enum TypeTable index, addr *ret)
{
addr table;
getroot_typetable(&table);
GetArrayA4(table, (size_t)index, ret);
Check(*ret == Nil, "type error");
}
void settypetable(enum TypeTable index, addr pos)
{
addr table;
getroot_typetable(&table);
SetArrayA4(table, (size_t)index, pos);
SetStatusReadOnly(pos);
}
void keytypetable(constindex name, enum TypeTable type, addr *ret)
{
addr value1, value2;
GetConstant(name, &value1);
gettypetable(type, &value2);
cons_heap(ret, value1, value2);
}
void build_type_table(void)
{
addr pos;
vector4_heap(&pos, TypeTable_Size);
SetLispRoot(TYPETABLE, pos);
}
/*
* arguments
*/
void typeargs_empty(addr *ret)
{
vector2_heap(ret, 4);
}
void typeargs_full(addr *ret, addr var, addr opt, addr rest, addr key)
{
addr pos;
vector2_heap(&pos, 4);
SetArrayA2(pos, 0, var);
SetArrayA2(pos, 1, opt);
SetArrayA2(pos, 2, rest);
SetArrayA2(pos, 3, key);
*ret = pos;
}
void typeargs_var1(addr *ret, addr v1)
{
conscar_heap(&v1, v1);
typeargs_full(ret, v1, Nil, Nil, Nil);
}
void typeargs_var2(addr *ret, addr v1, addr v2)
{
list_heap(&v1, v1, v2, NULL);
typeargs_full(ret, v1, Nil, Nil, Nil);
}
void typeargs_var3(addr *ret, addr v1, addr v2, addr v3)
{
list_heap(&v1, v1, v2, v3, NULL);
typeargs_full(ret, v1, Nil, Nil, Nil);
}
void typeargs_var4(addr *ret, addr v1, addr v2, addr v3, addr v4)
{
list_heap(&v1, v1, v2, v3, v4, NULL);
typeargs_full(ret, v1, Nil, Nil, Nil);
}
void typeargs_var5(addr *ret, addr v1, addr v2, addr v3, addr v4, addr v5)
{
list_heap(&v1, v1, v2, v3, v4, v5, NULL);
typeargs_full(ret, v1, Nil, Nil, Nil);
}
void typeargs_var1key(addr *ret, addr v1, addr key)
{
conscar_heap(&v1, v1);
typeargs_full(ret, v1, Nil, Nil, key);
}
void typeargs_var2key(addr *ret, addr v1, addr v2, addr key)
{
list_heap(&v1, v1, v2, NULL);
typeargs_full(ret, v1, Nil, Nil, key);
}
void typeargs_var3key(addr *ret, addr v1, addr v2, addr var3, addr key)
{
list_heap(&v1, v1, v2, var3, NULL);
typeargs_full(ret, v1, Nil, Nil, key);
}
void typeargs_var4key(addr *ret, addr v1, addr v2, addr v3, addr v4, addr key)
{
list_heap(&v1, v1, v2, v3, v4, NULL);
typeargs_full(ret, v1, Nil, Nil, key);
}
void typeargs_opt1(addr *ret, addr v1)
{
conscar_heap(&v1, v1);
typeargs_full(ret, Nil, v1, Nil, Nil);
}
void typeargs_opt2(addr *ret, addr v1, addr v2)
{
list_heap(&v1, v1, v2, NULL);
typeargs_full(ret, Nil, v1, Nil, Nil);
}
void typeargs_opt3(addr *ret, addr v1, addr v2, addr v3)
{
list_heap(&v1, v1, v2, v3, NULL);
typeargs_full(ret, Nil, v1, Nil, Nil);
}
void typeargs_opt4(addr *ret, addr v1, addr v2, addr v3, addr v4)
{
list_heap(&v1, v1, v2, v3, v4, NULL);
typeargs_full(ret, Nil, v1, Nil, Nil);
}
void typeargs_opt5(addr *ret, addr v1, addr v2, addr v3, addr v4, addr v5)
{
list_heap(&v1, v1, v2, v3, v4, v5, NULL);
typeargs_full(ret, Nil, v1, Nil, Nil);
}
void typeargs_var1opt1(addr *ret, addr var1, addr opt1)
{
conscar_heap(&var1, var1);
conscar_heap(&opt1, opt1);
typeargs_full(ret, var1, opt1, Nil, Nil);
}
void typeargs_var1opt2(addr *ret, addr var1, addr opt1, addr opt2)
{
conscar_heap(&var1, var1);
list_heap(&opt1, opt1, opt2, NULL);
typeargs_full(ret, var1, opt1, Nil, Nil);
}
void typeargs_var1opt2key(addr *ret, addr var1, addr opt1, addr opt2, addr key)
{
conscar_heap(&var1, var1);
list_heap(&opt1, opt1, opt2, NULL);
typeargs_full(ret, var1, opt1, Nil, key);
}
void typeargs_var2opt1(addr *ret, addr var1, addr var2, addr opt1)
{
list_heap(&var1, var1, var2, NULL);
conscar_heap(&opt1, opt1);
typeargs_full(ret, var1, opt1, Nil, Nil);
}
void typeargs_var2opt2(addr *ret, addr var1, addr var2, addr opt1, addr opt2)
{
list_heap(&var1, var1, var2, NULL);
list_heap(&opt1, opt1, opt2, NULL);
typeargs_full(ret, var1, opt1, Nil, Nil);
}
void typeargs_var2opt3(addr *ret, addr v1, addr v2, addr o1, addr o2, addr o3)
{
list_heap(&v1, v1, v2, NULL);
list_heap(&o1, o1, o2, o3, NULL);
typeargs_full(ret, v1, o1, Nil, Nil);
}
void typeargs_var3opt1(addr *ret, addr var1, addr var2, addr var3, addr opt1)
{
list_heap(&var1, var1, var2, var3, NULL);
conscar_heap(&opt1, opt1);
typeargs_full(ret, var1, opt1, Nil, Nil);
}
void typeargs_var4opt1(addr *ret, addr v1, addr v2, addr v3, addr v4, addr opt1)
{
list_heap(&v1, v1, v2, v3, v4, NULL);
conscar_heap(&opt1, opt1);
typeargs_full(ret, v1, opt1, Nil, Nil);
}
void typeargs_var1rest(addr *ret, addr v1, addr rest)
{
conscar_heap(&v1, v1);
typeargs_full(ret, v1, Nil, rest, Nil);
}
void typeargs_var2rest(addr *ret, addr v1, addr v2, addr rest)
{
list_heap(&v1, v1, v2, NULL);
typeargs_full(ret, v1, Nil, rest, Nil);
}
void typeargs_var3rest(addr *ret, addr v1, addr v2, addr v3, addr rest)
{
list_heap(&v1, v1, v2, v3, NULL);
typeargs_full(ret, v1, Nil, rest, Nil);
}
void typeargs_var4rest(addr *ret, addr v1, addr v2, addr v3, addr v4, addr rest)
{
list_heap(&v1, v1, v2, v3, v4, NULL);
typeargs_full(ret, v1, Nil, rest, Nil);
}
void typeargs_opt1rest(addr *ret, addr opt1, addr rest)
{
conscar_heap(&opt1, opt1);
typeargs_full(ret, Nil, opt1, rest, Nil);
}
void typeargs_var1rest_allow(addr *ret, addr v1, addr rest)
{
conscar_heap(&v1, v1);
typeargs_full(ret, v1, Nil, rest, T);
}
void typeargs_var2rest_allow(addr *ret, addr v1, addr v2, addr rest)
{
list_heap(&v1, v1, v2, NULL);
typeargs_full(ret, v1, Nil, rest, T);
}
void typeargs_var3rest_allow(addr *ret, addr v1, addr v2, addr v3, addr rest)
{
list_heap(&v1, v1, v2, v3, NULL);
typeargs_full(ret, v1, Nil, rest, T);
}
void typeargs_var4rest_allow(addr *ret, addr v1, addr v2, addr v3, addr v4, addr rest)
{
list_heap(&v1, v1, v2, v3, v4, NULL);
typeargs_full(ret, v1, Nil, rest, T);
}
void typeargs_rest(addr *ret, addr rest)
{
typeargs_full(ret, Nil, Nil, rest, Nil);
}
void typeargs_key(addr *ret, addr key)
{
typeargs_full(ret, Nil, Nil, Nil, key);
}
void typeargs_method(addr pos)
{
addr var, method1, method2;
GetArrayA2(pos, 0, &var); /* var */
GetTypeTable(&method1, Method1);
GetTypeTable(&method2, Method2);
lista_heap(&var, method1, method2, var, NULL);
SetArrayA2(pos, 0, var); /* var */
}
void typeargs_methodkey(addr pos)
{
addr rest;
typeargs_method(pos);
GetArrayA2(pos, 2, &rest); /* rest */
if (rest == Nil) {
GetTypeTable(&rest, T);
SetArrayA2(pos, 2, rest); /* rest */
}
}
/*
* values
*/
void typevalues_result(addr *ret, addr v1)
{
/* (values v1 &rest nil) */
addr pos;
GetTypeTable(&pos, Nil);
conscar_heap(&v1, v1);
type_values_heap(v1, Nil, pos, Nil, ret);
SetStatusReadOnly(*ret);
}
void typevalues_values2(addr *ret, addr v1, addr v2)
{
/* (values v1 v2 &rest nil) */
addr pos;
GetTypeTable(&pos, Nil);
list_heap(&v1, v1, v2, NULL);
type_values_heap(v1, Nil, pos, Nil, ret);
SetStatusReadOnly(*ret);
}
void typevalues_values3(addr *ret, addr v1, addr v2, addr v3)
{
/* (values v1 v2 v3 &rest nil) */
addr pos;
GetTypeTable(&pos, Nil);
list_heap(&v1, v1, v2, v3, NULL);
type_values_heap(v1, Nil, pos, Nil, ret);
SetStatusReadOnly(*ret);
}
void typevalues_values4(addr *ret, addr v1, addr v2, addr v3, addr v4)
{
/* (values v1 v2 v3 v4 &rest nil) */
addr pos;
GetTypeTable(&pos, Nil);
list_heap(&v1, v1, v2, v3, v4, NULL);
type_values_heap(v1, Nil, pos, Nil, ret);
SetStatusReadOnly(*ret);
}
void typevalues_values5(addr *ret, addr v1, addr v2, addr v3, addr v4, addr v5)
{
/* (values v1 v2 v3 v4 v5 &rest nil) */
addr pos;
GetTypeTable(&pos, Nil);
list_heap(&v1, v1, v2, v3, v4, v5, NULL);
type_values_heap(v1, Nil, pos, Nil, ret);
SetStatusReadOnly(*ret);
}
void typevalues_values_va(addr *ret, ...)
{
/* (values ... &rest nil) */
addr args, type;
va_list va;
/* args */
va_start(va, ret);
list_stdarg_alloc(NULL, &args, va);
va_end(va);
/* type */
GetTypeTable(&type, Nil);
type_values_heap(args, Nil, type, Nil, ret);
SetStatusReadOnly(*ret);
}
void typevalues_rest(addr *ret, addr type)
{
/* (values &rest type) */
type_values_heap(Nil, Nil, type, Nil, ret);
SetStatusReadOnly(*ret);
}
/* type asterisk */
void type1aster_alloc(LocalRoot local, enum LISPDECL type, addr *ret)
{
addr aster;
GetTypeTable(&aster, Asterisk);
CheckType(aster, LISPTYPE_TYPE);
type1_alloc(local, type, aster, ret);
}
void type2aster_alloc(LocalRoot local, enum LISPDECL type, addr *ret)
{
addr aster;
GetTypeTable(&aster, Asterisk);
CheckType(aster, LISPTYPE_TYPE);
type2_alloc(local, type, aster, aster, ret);
}
void type3aster_alloc(LocalRoot local, enum LISPDECL type, addr *ret)
{
addr aster;
GetTypeTable(&aster, Asterisk);
CheckType(aster, LISPTYPE_TYPE);
type3_alloc(local, type, aster, aster, aster, ret);
}
void type4aster_alloc(LocalRoot local, enum LISPDECL type, addr *ret)
{
addr aster;
GetTypeTable(&aster, Asterisk);
CheckType(aster, LISPTYPE_TYPE);
type4_alloc(local, type, aster, aster, aster, aster, ret);
}
void type1aster_local(LocalRoot local, enum LISPDECL type, addr *ret)
{
CheckLocal(local);
type1aster_alloc(local, type, ret);
}
void type2aster_local(LocalRoot local, enum LISPDECL type, addr *ret)
{
CheckLocal(local);
type2aster_alloc(local, type, ret);
}
void type3aster_local(LocalRoot local, enum LISPDECL type, addr *ret)
{
CheckLocal(local);
type3aster_alloc(local, type, ret);
}
void type4aster_local(LocalRoot local, enum LISPDECL type, addr *ret)
{
CheckLocal(local);
type4aster_alloc(local, type, ret);
}
void type1aster_heap(enum LISPDECL type, addr *ret)
{
type1aster_alloc(NULL, type, ret);
}
void type2aster_heap(enum LISPDECL type, addr *ret)
{
type2aster_alloc(NULL, type, ret);
}
void type3aster_heap(enum LISPDECL type, addr *ret)
{
type3aster_alloc(NULL, type, ret);
}
void type4aster_heap(enum LISPDECL type, addr *ret)
{
type4aster_alloc(NULL, type, ret);
}
/*
* and/or
*/
void type2and_alloc(LocalRoot local, addr a, addr b, addr *ret)
{
enum LISPDECL decl;
addr array;
CheckType2(a, LISPTYPE_TYPE, "type left error");
CheckType2(b, LISPTYPE_TYPE, "type right error");
decl = LowLispDecl(a);
if (decl == LISPDECL_ASTERISK || decl == LISPDECL_T) {
*ret = b;
return;
}
if (decl == LISPDECL_NIL) {
GetTypeTable(ret, Nil);
return;
}
decl = LowLispDecl(b);
if (decl == LISPDECL_ASTERISK || decl == LISPDECL_T) {
*ret = a;
return;
}
if (decl == LISPDECL_NIL) {
GetTypeTable(ret, Nil);
return;
}
vector4_alloc(local, &array, 2);
SetArrayA4(array, 0, a);
SetArrayA4(array, 1, b);
type1_alloc(local, LISPDECL_AND, array, ret);
}
void type2or_alloc(LocalRoot local, addr a, addr b, addr *ret)
{
enum LISPDECL decl;
addr array;
CheckType2(a, LISPTYPE_TYPE, "type left error");
CheckType2(b, LISPTYPE_TYPE, "type right error");
decl = LowLispDecl(a);
if (decl == LISPDECL_ASTERISK || decl == LISPDECL_T) {
GetTypeTable(ret, T);
return;
}
if (decl == LISPDECL_NIL) {
*ret = b;
return;
}
decl = LowLispDecl(b);
if (decl == LISPDECL_ASTERISK || decl == LISPDECL_T) {
GetTypeTable(ret, T);
return;
}
if (decl == LISPDECL_NIL) {
*ret = a;
return;
}
vector4_alloc(local, &array, 2);
SetArrayA4(array, 0, a);
SetArrayA4(array, 1, b);
type1_alloc(local, LISPDECL_OR, array, ret);
}
void type3and_alloc(LocalRoot local, addr a, addr b, addr c, addr *ret)
{
addr array;
vector4_alloc(local, &array, 3);
SetArrayA4(array, 0, a);
SetArrayA4(array, 1, b);
SetArrayA4(array, 2, c);
type1_alloc(local, LISPDECL_AND, array, ret);
}
void type3or_alloc(LocalRoot local, addr a, addr b, addr c, addr *ret)
{
addr array;
vector4_alloc(local, &array, 3);
SetArrayA4(array, 0, a);
SetArrayA4(array, 1, b);
SetArrayA4(array, 2, c);
type1_alloc(local, LISPDECL_OR, array, ret);
}
void type4or_alloc(LocalRoot local, addr a, addr b, addr c, addr d, addr *ret)
{
addr array;
vector4_alloc(local, &array, 4);
SetArrayA4(array, 0, a);
SetArrayA4(array, 1, b);
SetArrayA4(array, 2, c);
SetArrayA4(array, 3, d);
type1_alloc(local, LISPDECL_OR, array, ret);
}
void type2and_local(LocalRoot local, addr a, addr b, addr *ret)
{
CheckLocal(local);
type2and_alloc(local, a, b, ret);
}
void type2or_local(LocalRoot local, addr a, addr b, addr *ret)
{
CheckLocal(local);
type2or_alloc(local, a, b, ret);
}
void type3and_local(LocalRoot local, addr a, addr b, addr c, addr *ret)
{
CheckLocal(local);
type3and_alloc(local, a, b, c, ret);
}
void type3or_local(LocalRoot local, addr a, addr b, addr c, addr *ret)
{
CheckLocal(local);
type3or_alloc(local, a, b, c, ret);
}
void type4or_local(LocalRoot local, addr a, addr b, addr c, addr d, addr *ret)
{
CheckLocal(local);
type4or_alloc(local, a, b, c, d, ret);
}
void type2and_heap(addr a, addr b, addr *ret)
{
type2and_alloc(NULL, a, b, ret);
}
void type2or_heap(addr a, addr b, addr *ret)
{
type2or_alloc(NULL, a, b, ret);
}
void type3and_heap(addr a, addr b, addr c, addr *ret)
{
type3and_alloc(NULL, a, b, c, ret);
}
void type3or_heap(addr a, addr b, addr c, addr *ret)
{
type3or_alloc(NULL, a, b, c, ret);
}
void type4or_heap(addr a, addr b, addr c, addr d, addr *ret)
{
type4or_alloc(NULL, a, b, c, d, ret);
}
/*
* range
*/
void type1real_heap(enum LISPDECL type, addr value, addr *ret)
{
type4_heap(type, Nil, value, Nil, value, ret);
}
void type4integer_heap(addr a, fixnum b, addr c, fixnum d, addr *ret)
{
addr x, y;
Check(a != Nil && a != T, "left1 error");
Check(c != Nil && c != T, "right1 error");
fixnum_heap(&x, b);
fixnum_heap(&y, d);
type4_heap(LISPDECL_INTEGER, a, x, c, y, ret);
}
void type2integer_ab_heap(addr a, fixnum b, addr *ret)
{
addr x, aster;
Check(a != Nil && a != T, "left1 error");
GetTypeTable(&aster, Asterisk);
fixnum_heap(&x, b);
type4_heap(LISPDECL_INTEGER, a, x, aster, aster, ret);
}
void type2integer_cd_heap(addr c, fixnum d, addr *ret)
{
addr y, aster;
Check(c != Nil && c != T, "right1 error");
GetTypeTable(&aster, Asterisk);
fixnum_heap(&y, d);
type4_heap(LISPDECL_INTEGER, aster, aster, c, y, ret);
}
static void type4declf_heap(enum LISPDECL type,
addr a, float b, addr c, float d, addr *ret)
{
addr x, y;
Check(a != Nil && a != T, "left1 error");
Check(c != Nil && c != T, "right1 error");
single_float_heap(&x, b);
single_float_heap(&y, d);
type4_heap(type, a, x, c, y, ret);
}
static void type2declf_ab_heap(enum LISPDECL type, addr a, float b, addr *ret)
{
addr x, aster;
Check(a != Nil && a != T, "left1 error");
GetTypeTable(&aster, Asterisk);
single_float_heap(&x, b);
type4_heap(type, a, x, aster, aster, ret);
}
static void type2declf_cd_heap(enum LISPDECL type, addr c, float d, addr *ret)
{
addr y, aster;
Check(c != Nil && c != T, "right1 error");
GetTypeTable(&aster, Asterisk);
single_float_heap(&y, d);
type4_heap(type, aster, aster, c, y, ret);
}
void type4float_heap(addr a, float b, addr c, float d, addr *ret)
{
type4declf_heap(LISPDECL_FLOAT, a, b, c, d, ret);
}
void type2float_ab_heap(addr a, float b, addr *ret)
{
type2declf_ab_heap(LISPDECL_FLOAT, a, b, ret);
}
void type2float_cd_heap(addr c, float d, addr *ret)
{
type2declf_cd_heap(LISPDECL_FLOAT, c, d, ret);
}
void type4realf_heap(addr a, float b, addr c, float d, addr *ret)
{
type4declf_heap(LISPDECL_REAL, a, b, c, d, ret);
}
void type2realf_ab_heap(addr a, float b, addr *ret)
{
type2declf_ab_heap(LISPDECL_REAL, a, b, ret);
}
void type2realf_cd_heap(addr c, float d, addr *ret)
{
type2declf_cd_heap(LISPDECL_REAL, c, d, ret);
}
/*
* vector
*/
void type_vector1_heap(size_t size, addr *ret)
{
addr first, second;
GetTypeTable(&first, Asterisk);
vector4_heap(&second, 1);
SetArrayA4(second, 0, intsizeh(size));
type2_heap(LISPDECL_ARRAY, first, second, ret);
}
/************************************************************
* type_typep.c
************************************************************/
static int typep_call_(Execute ptr, addr value, addr type, int asterisk, int *ret);
typedef int (*call_type_typep)(Execute ptr, addr value, addr type, int *ret);
static call_type_typep TypeTypep[LISPDECL_SIZE];
static int typep_invalid_(Execute ptr, addr value, addr type, int *ret)
{
infobit(type);
*ret = 0;
return fmte_("Invalid type.", NULL);
}
static int typep_error_(Execute ptr, addr value, addr type, int *ret)
{
Return(get_error_type_(ptr, type, &type));
return typep_call_(ptr, value, type, 1, ret);
}
static int typep_type_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_TYPE);
return 0;
}
static int typep_clos_(Execute ptr, addr value, addr type, int *ret)
{
if (GetType(value) != LISPTYPE_CLOS)
return Result(ret, 0);
GetArrayType(type, 0, &type);
if (type_asterisk_p(type))
return Result(ret, 1);
return clos_subtype_p_(value, type, ret);
}
static int typep_asterisk_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, 1);
}
static int typep_optimized_(Execute ptr, addr value, addr type, int *ret)
{
GetArrayType(type, 0, &type);
return typep_call_(ptr, value, type, 1, ret);
}
/*
* Compound-type
*/
static int typep_and_(Execute ptr, addr value, addr type, int *ret)
{
int result;
addr check;
size_t i, size;
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
Return(typep_call_(ptr, value, check, 1, &result));
if (! result)
return Result(ret, 0);
}
return Result(ret, 1);
}
static int typep_or_(Execute ptr, addr value, addr type, int *ret)
{
int result;
addr check;
size_t i, size;
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
Return(typep_call_(ptr, value, check, 1, &result));
if (result)
return Result(ret, 1);
}
return Result(ret, 0);
}
static int typep_eql_(Execute ptr, addr value, addr type, int *ret)
{
GetArrayType(type, 0, &type);
*ret = eql_function(value, type);
return 0;
}
static int typep_member_(Execute ptr, addr value, addr type, int *ret)
{
addr check;
size_t i, size;
GetArrayType(type, 0, &type);
LenArrayA4(type, &size);
for (i = 0; i < size; i++) {
GetArrayA4(type, i, &check);
if (eql_function(value, check))
return Result(ret, 1);
}
return Result(ret, 0);
}
static int typep_mod_(Execute ptr, addr value, addr type, int *ret)
{
int check;
if (! integerp(value))
return Result(ret, 0);
Return(minusp_integer_(value, &check));
if (check)
return Result(ret, 0);
GetArrayType(type, 0, &type);
return less_integer_(value, type, ret);
}
static int typep_not_(Execute ptr, addr value, addr type, int *ret)
{
int check;
GetArrayType(type, 0, &type);
Return(typep_call_(ptr, value, type, 1, &check));
return Result(ret, ! check);
}
static int typep_satisfies_(Execute ptr, addr value, addr type, int *ret)
{
GetArrayType(type, 0, &type);
Return(callclang_funcall(ptr, &type, type, value, NULL));
return Result(ret, (type != Nil));
}
static int typep_values_(Execute ptr, addr value, addr type, int *ret)
{
*ret = 0;
return fmte_("The values type don't use in typep context.", NULL);
}
/*
* Extract-type
*/
static int typep_atom_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, (! IsCons(value)));
}
static int typep_list_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, IsList(value));
}
static int typep_boolean_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, (value == Nil || value == T));
}
static int typep_vector_vector_(addr value, addr type, int *ret)
{
enum LISPDECL left;
addr check;
fixnum size2;
size_t size1;
GetArrayType(type, 0, &check);
GetLispDecl(check, &left);
if ((left != LISPDECL_ASTERISK) && (left != LISPDECL_T))
return Result(ret, 0);
GetArrayType(type, 1, &check);
if (type_asterisk_p(check))
return Result(ret, 1);
lenarray(value, &size1);
GetFixnum(check, &size2);
return Result(ret, (size1 == (size_t)size2));
}
static int typep_vector_string_(addr value, addr type, int *ret)
{
enum LISPDECL decl;
addr check;
fixnum size2;
size_t size1;
GetArrayType(type, 0, &check);
GetLispDecl(check, &decl);
if ((decl != LISPDECL_ASTERISK) && (! decl_character_p(decl)))
return Result(ret, 0);
GetArrayType(type, 1, &check);
if (type_asterisk_p(check))
return Result(ret, 1);
string_length(value, &size1);
GetFixnum(check, &size2);
return Result(ret, (size1 == (size_t)size2));
}
static int typep_vector_bitvector_(addr value, addr type, int *ret)
{
enum LISPDECL decl;
addr check;
fixnum size2;
size_t size1;
GetArrayType(type, 0, &check);
GetLispDecl(check, &decl);
if ((decl != LISPDECL_ASTERISK) && (decl != LISPDECL_BIT))
return Result(ret, 0);
GetArrayType(type, 1, &check);
if (type_asterisk_p(check))
return Result(ret, 1);
bitmemory_length(value, &size1);
GetFixnum(check, &size2);
return Result(ret, (size1 == (size_t)size2));
}
static int typep_vector_dimension_(addr value, addr type, int *ret)
{
/* asterisk */
if (type_asterisk_p(type)) {
*ret = array_vector_p(value);
return 0;
}
/* fixnum */
if (GetType(type) == LISPTYPE_FIXNUM) {
*ret = array_size_vector_p(value, (size_t)RefFixnum(type));
return 0;
}
/* error */
*ret = 0;
return fmte_("type error", NULL);
}
static int typep_vector_array_(addr value, addr type, int *ret)
{
addr left, right;
GetArrayType(type, 0, &left);
GetArrayInfo(value, ARRAY_INDEX_TYPE, &right);
if ((! type_asterisk_p(left)) && (! upgraded_array0_equal(left, right)))
return Result(ret, 0);
GetArrayType(type, 1, &type);
return typep_vector_dimension_(value, type, ret);
}
static int typep_vector_(Execute ptr, addr value, addr type, int *ret)
{
switch (GetType(value)) {
case LISPTYPE_VECTOR:
return typep_vector_vector_(value, type, ret);
case LISPTYPE_STRING:
return typep_vector_string_(value, type, ret);
case LISPTYPE_ARRAY:
if (strarrayp(value))
return typep_vector_string_(value, type, ret);
return typep_vector_array_(value, type, ret);
case LISPTYPE_BITVECTOR:
return typep_vector_bitvector_(value, type, ret);
default:
return Result(ret, 0);
}
}
static int typep_simple_vector_vector_(addr value, addr type, int *ret)
{
fixnum size2;
size_t size1;
GetArrayType(type, 0, &type);
if (type_asterisk_p(type))
return Result(ret, 1);
lenarray(value, &size1);
GetFixnum(type, &size2);
return Result(ret, (size1 == (size_t)size2));
}
static int typep_type_vector_array_(addr value, addr type, enum LISPDECL decl, int *ret)
{
addr check;
GetArrayInfo(value, ARRAY_INDEX_TYPE, &check);
if ((! type_asterisk_p(check)) && (RefLispDecl(check) != decl))
return Result(ret, 0);
GetArrayType(type, 0, &check);
return typep_vector_dimension_(value, check, ret);
}
static int typep_simple_vector_(Execute ptr, addr value, addr type, int *ret)
{
switch (GetType(value)) {
case LISPTYPE_VECTOR:
return typep_simple_vector_vector_(value, type, ret);
case LISPTYPE_ARRAY:
if (! array_simple_p(value))
return Result(ret, 0);
return typep_type_vector_array_(value, type, LISPDECL_T, ret);
default:
return Result(ret, 0);
}
}
static int typep_bit_vector_bit_vector_(addr value, addr type, int *ret)
{
fixnum size2;
size_t size1;
GetArrayType(type, 0, &type);
if (type_asterisk_p(type))
return Result(ret, 1);
bitmemory_length(value, &size1);
GetFixnum(type, &size2);
return Result(ret, (size1 == (size_t)size2));
}
static int typep_bit_vector_(Execute ptr, addr value, addr type, int *ret)
{
switch (GetType(value)) {
case LISPTYPE_ARRAY:
return typep_type_vector_array_(value, type, LISPDECL_BIT, ret);
case LISPTYPE_BITVECTOR:
return typep_bit_vector_bit_vector_(value, type, ret);
default:
return Result(ret, 0);
}
}
static int typep_simple_bit_vector_(Execute ptr, addr value, addr type, int *ret)
{
switch (GetType(value)) {
case LISPTYPE_ARRAY:
if (! array_simple_p(value))
return Result(ret, 0);
return typep_type_vector_array_(value, type, LISPDECL_BIT, ret);
case LISPTYPE_BITVECTOR:
return typep_bit_vector_bit_vector_(value, type, ret);
default:
return Result(ret, 0);
}
}
static int typep_extended_char_(Execute ptr, addr value, addr type, int *ret)
{
*ret = extended_char_p(value);
return 0;
}
static int typep_string_size_(addr value, addr type, int *ret)
{
fixnum size2;
size_t size1;
GetArrayType(type, 0, &type);
if (type_asterisk_p(type))
return Result(ret, 1);
string_length(value, &size1);
GetFixnum(type, &size2);
return Result(ret, (size1 == (size_t)size2));
}
static int typep_string_(Execute ptr, addr value, addr type, int *ret)
{
if (! stringp(value))
return Result(ret, 0);
return typep_string_size_(value, type, ret);
}
static int typep_base_string_size_(addr value, addr type, int *ret)
{
enum CHARACTER_TYPE check;
Return(string_character_type_(value, &check));
if (check == CHARACTER_TYPE_EMPTY ||
check == CHARACTER_TYPE_STANDARD ||
check == CHARACTER_TYPE_BASE) {
return typep_string_size_(value, type, ret);
}
return Result(ret, 0);
}
static int typep_base_string_(Execute ptr, addr value, addr type, int *ret)
{
if (! stringp(value))
return Result(ret, 0);
return typep_base_string_size_(value, type, ret);
}
static int typep_simple_string_(Execute ptr, addr value, addr type, int *ret)
{
enum LISPTYPE check;
check = GetType(value);
if (check == LISPTYPE_STRING)
return typep_string_size_(value, type, ret);
if (strarrayp(value) && array_simple_p(value))
return typep_string_size_(value, type, ret);
return Result(ret, 0);
}
static int typep_simple_base_string_(Execute ptr, addr value, addr type, int *ret)
{
enum LISPTYPE check;
check = GetType(value);
if (check == LISPTYPE_STRING)
return typep_base_string_size_(value, type, ret);
if (strarrayp(value) && array_simple_p(value))
return typep_base_string_size_(value, type, ret);
return Result(ret, 0);
}
static int typep_signed_byte_(Execute ptr, addr value, addr type, int *ret)
{
addr check;
enum LISPTYPE listtype;
listtype = GetType(value);
if (listtype == LISPTYPE_FIXNUM) {
GetArrayType(type, 0, &check);
if (type_asterisk_p(check))
return Result(ret, 1);
*ret = fixnum_signed_byte_p(value, RefFixnum(check));
return 0;
}
if (listtype == LISPTYPE_BIGNUM) {
GetArrayType(type, 0, &check);
if (type_asterisk_p(check))
return Result(ret, 1);
*ret = bignum_signed_byte_p(value, RefFixnum(check));
return 0;
}
return Result(ret, 0);
}
static int typep_unsigned_byte_(Execute ptr, addr value, addr type, int *ret)
{
addr check;
enum LISPTYPE listtype;
listtype = GetType(value);
if (listtype == LISPTYPE_FIXNUM) {
GetArrayType(type, 0, &check);
if (type_asterisk_p(check))
return Result(ret, (0 <= RefFixnum(value)));
*ret = fixnum_unsigned_byte_p(value, RefFixnum(check));
return 0;
}
if (listtype == LISPTYPE_BIGNUM) {
GetArrayType(type, 0, &check);
if (type_asterisk_p(check))
return Result(ret, zerop_or_plusp_bignum(value));
*ret = bignum_unsigned_byte_p(value, RefFixnum(check));
return 0;
}
return Result(ret, 0);
}
static int typep_bit_(Execute ptr, addr value, addr type, int *ret)
{
enum LISPTYPE lisptype;
fixnum check;
lisptype = GetType(value);
if (lisptype == LISPTYPE_FIXNUM) {
GetFixnum(value, &check);
return Result(ret, (check == 0 || check == 1));
}
if (lisptype == LISPTYPE_BIGNUM) {
*ret = zerop_bignum(value) || equal_value_bignum(value, signplus_bignum, 1);
return 0;
}
return Result(ret, 0);
}
static int fbf_bignum(fixnum left, addr value, fixnum right)
{
return compare_value_bignum(left, value) <= 0
&& compare_bignum_value(value, right) <= 0;
}
static int typep_fixnum_(Execute ptr, addr value, addr type, int *ret)
{
enum LISPTYPE lisptype;
lisptype = GetType(value);
if (lisptype == LISPTYPE_FIXNUM)
return Result(ret, 1);
if (lisptype == LISPTYPE_BIGNUM) {
*ret = fbf_bignum(FIXNUM_MIN, value, FIXNUM_MAX);
return 0;
}
return Result(ret, 0);
}
static int typep_bignum_(Execute ptr, addr value, addr type, int *ret)
{
enum LISPTYPE lisptype;
lisptype = GetType(value);
if (lisptype == LISPTYPE_FIXNUM)
return Result(ret, 0);
if (lisptype == LISPTYPE_BIGNUM) {
*ret = (! fbf_bignum(FIXNUM_MIN, value, FIXNUM_MAX));
return 0;
}
return Result(ret, 0);
}
/*
* Atomic-type
*/
static int typep_nil_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, 0);
}
static int typep_t_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, 1);
}
static int typep_null_(Execute ptr, addr value, addr type, int *ret)
{
return Result(ret, (value == Nil));
}
static int typep_cons_(Execute ptr, addr value, addr type, int *ret)
{
int result;
addr left, check;
if (! IsCons(value))
return Result(ret, 0);
GetCons(value, &left, &value);
GetArrayType(type, 0, &check);
Return(typep_call_(ptr, left, check, 1, &result));
if (! result)
return Result(ret, 0);
GetArrayType(type, 1, &check);
return typep_call_(ptr, value, check, 1, ret);
}
static int typep_hash_table_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_HASHTABLE);
return 0;
}
static int typep_symbol_(Execute ptr, addr value, addr type, int *ret)
{
*ret = symbolp(value);
return 0;
}
static int typep_keyword_(Execute ptr, addr value, addr type, int *ret)
{
*ret = keywordp(value);
return 0;
}
static int typep_package_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_PACKAGE);
return 0;
}
static int typep_random_state_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_RANDOM_STATE);
return 0;
}
static int typep_readtable_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_READTABLE);
return 0;
}
static int typep_function_check_(Execute ptr, addr value, addr right, int *ret)
{
addr left;
gettype_function(value, &left);
if (left == Nil) {
if (compiled_function_p(value))
GetTypeTable(&left, CompiledFunction);
else
GetTypeTable(&left, Function);
}
return subtypep_check_(ptr, left, right, Nil, ret, NULL);
}
static int typep_function_(Execute ptr, addr value, addr type, int *ret)
{
addr check;
GetArrayType(type, 2, &check);
if (check == Nil) {
*ret = 0;
return fmte_("The cons type (FUNCTION ? ?) don't accept.", NULL);
}
if (! functionp(value))
return Result(ret, 0);
return typep_function_check_(ptr, value, type, ret);
}
static int typep_compiled_function_(Execute ptr, addr value, addr type, int *ret)
{
addr check;
GetArrayType(type, 2, &check);
if (check == Nil) {
*ret = 0;
return fmte_("The cons type (COMPILED-FUNCTION ? ?) don't accept.", NULL);
}
if (! compiled_function_p(value))
return Result(ret, 0);
return typep_function_check_(ptr, value, type, ret);
}
static int typep_pathname_(Execute ptr, addr value, addr type, int *ret)
{
*ret = pathnamep(value);
return 0;
}
static int typep_logical_pathname_(Execute ptr, addr value, addr type, int *ret)
{
*ret = pathname_logical_p(value);
return 0;
}
static int typep_sequence_(Execute ptr, addr value, addr type, int *ret)
{
*ret = sequencep(value);
return 0;
}
static int equal_array_dimension(addr value, addr right)
{
addr left, check;
size_t i, rank, index, *psize;
struct array_struct *str;
/* rank check */
GetArrayInfo(value, ARRAY_INDEX_DIMENSION, &left);
str = ArrayInfoStruct(value);
rank = ArrayInfoStruct(value)->dimension;
LenArrayA4(right, &i);
if (rank != i)
return 0;
/* no-dimension */
if (rank == 0) {
return 0;
}
/* sequence */
if (rank == 1) {
GetArrayA4(right, 0, &check);
if (type_asterisk_p(check))
return 1;
if (GetIndex_integer(check, &index))
return 0;
return str->size == index;
}
/* multi-dimension */
CheckType(left, LISPSYSTEM_ARRAY_DIMENSION);
psize = arraysize_ptr(left);
for (i = 0; i < rank; i++) {
GetArrayA4(right, i, &check);
if (type_asterisk_p(check))
continue;
if (GetIndex_integer(check, &index))
return 0;
if (psize[i] != index)
return 0;
}
return 1;
}
static int typep_array_dimension(addr value, addr type)
{
/* asterisk */
if (type_asterisk_p(type)) {
return 1;
}
/* fixnum */
if (GetType(type) == LISPTYPE_FIXNUM) {
return ArrayInfoStruct(value)->dimension == (size_t)RefFixnum(type);
}
/* arraydimension */
if (GetType(type) == LISPTYPE_VECTOR) {
return equal_array_dimension(value, type);
}
/* error */
Abort("type error");
return 0;
}
static int typep_array_array(addr value, addr type)
{
addr left, right;
GetArrayType(type, 0, &left);
GetArrayInfo(value, ARRAY_INDEX_TYPE, &right);
if ((! type_asterisk_p(left)) && (! upgraded_array0_equal(left, right)))
return 0;
GetArrayType(type, 1, &type);
return typep_array_dimension(value, type);
}
static int equal_fixnum_index(addr left, size_t right)
{
fixnum value;
GetFixnum(left, &value);
if (value < 0)
return 0;
return (size_t)value == right;
}
static int typep_array_vector(addr value, addr type)
{
enum LISPDECL decl;
addr left;
size_t size;
/* type */
GetArrayType(type, 0, &left);
GetLispDecl(left, &decl);
if (decl != LISPDECL_ASTERISK && decl != LISPDECL_T)
return 0;
/* dimension */
GetArrayType(type, 1, &left);
if (type_asterisk_p(left))
return 1;
/* fixnum */
if (GetType(left) == LISPTYPE_FIXNUM) {
return RefFixnum(left) == 1;
}
/* vector */
if (GetType(left) == LISPTYPE_VECTOR) {
LenArrayA4(left, &size);
if (size != 1)
return 0;
GetArrayA4(left, 0, &left);
if (type_asterisk_p(left))
return 1;
return equal_fixnum_index(left, lenarrayr(value));
}
/* error */
Abort("Invalid array type.");
return 0;
}
static int typep_array_string(addr value, addr type)
{
enum LISPDECL decl;
addr left;
size_t size;
/* type */
GetArrayType(type, 0, &left);
GetLispDecl(left, &decl);
if ((decl != LISPDECL_ASTERISK) && (! decl_character_p(decl)))
return 0;
/* dimension */
GetArrayType(type, 1, &left);
if (type_asterisk_p(left))
return 1;
/* fixnum */
if (GetType(left) == LISPTYPE_FIXNUM) {
return RefFixnum(left) == 1;
}
/* vector */
if (GetType(left) == LISPTYPE_VECTOR) {
LenArrayA4(left, &size);
if (size != 1)
return 0;
GetArrayA4(left, 0, &left);
if (type_asterisk_p(left))
return 1;
string_length(value, &size);
return equal_fixnum_index(left, size);
}
/* error */
Abort("Invalid array type.");
return 0;
}
static int typep_array_bitvector(addr value, addr type)
{
enum LISPDECL decl;
addr left;
size_t size;
/* type */
GetArrayType(type, 0, &left);
GetLispDecl(left, &decl);
if (decl != LISPDECL_ASTERISK && decl != LISPDECL_BIT)
return 0;
/* dimension */
GetArrayType(type, 1, &left);
if (type_asterisk_p(left))
return 1;
/* fixnum */
if (GetType(left) == LISPTYPE_FIXNUM) {
return RefFixnum(left) == 1;
}
/* vector */
if (GetType(left) == LISPTYPE_VECTOR) {
LenArrayA4(left, &size);
if (size != 1)
return 0;
GetArrayA4(left, 0, &left);
if (type_asterisk_p(left))
return 1;
bitmemory_length(value, &size);
return equal_fixnum_index(left, size);
}
/* error */
Abort("Invalid array type.");
return 0;
}
static int typep_array_result(addr value, addr type)
{
switch (GetType(value)) {
case LISPTYPE_ARRAY:
return typep_array_array(value, type);
case LISPTYPE_VECTOR:
return typep_array_vector(value, type);
case LISPTYPE_STRING:
return typep_array_string(value, type);
case LISPTYPE_BITVECTOR:
return typep_array_bitvector(value, type);
default:
break;
}
return 0;
}
static int typep_array_(Execute ptr, addr value, addr type, int *ret)
{
*ret = typep_array_result(value, type);
return 0;
}
static int typep_simple_array_result(addr value, addr type)
{
switch (GetType(value)) {
case LISPTYPE_ARRAY:
return array_simple_p(value) && typep_array_array(value, type);
case LISPTYPE_VECTOR:
return typep_array_vector(value, type);
case LISPTYPE_STRING:
return typep_array_string(value, type);
case LISPTYPE_BITVECTOR:
return typep_array_bitvector(value, type);
default:
break;
}
return 0;
}
static int typep_simple_array_(Execute ptr, addr value, addr type, int *ret)
{
*ret = typep_simple_array_result(value, type);
return 0;
}
static int typep_character_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_CHARACTER);
return 0;
}
static int typep_base_char_(Execute ptr, addr value, addr type, int *ret)
{
*ret = base_char_p(value);
return 0;
}
static int typep_standard_char_(Execute ptr, addr value, addr type, int *ret)
{
*ret = standard_char_p(value);
return 0;
}
static int typep_number_(Execute ptr, addr value, addr type, int *ret)
{
*ret = numberp(value);
return 0;
}
static int typep_ratio_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_RATIO);
return 0;
}
static int typep_complex_(Execute ptr, addr value, addr type, int *ret)
{
int result;
addr check;
if (GetType(value) != LISPTYPE_COMPLEX)
return Result(ret, 0);
GetRealComplex(value, &check);
GetArrayType(type, 0, &type);
Return(typep_call_(ptr, check, type, 1, &result));
if (! result)
return Result(ret, 0);
GetImagComplex(value, &check);
return typep_call_(ptr, check, type, 1, ret);
}
/*
* range
*/
static int less_mode_nolocal_(addr mode, addr left, addr right, int *ret,
int (*call_less_)(addr, addr, int *),
int (*call_less_equal_)(addr, addr, int *))
{
if (type_asterisk_p(mode))
return Result(ret, 1);
if (mode == Nil)
return (*call_less_equal_)(left, right, ret);
else
return (*call_less_)(left, right, ret);
}
static int typep_range_nolocal_(addr value, addr type, int *ret,
int (*typecheck)(addr),
int (*call_less_)(addr, addr, int *),
int (*call_less_equal_)(addr, addr, int *))
{
int check;
addr mode, pos;
/* type */
if (! (*typecheck)(value))
return Result(ret, 0);
/* left */
GetArrayType(type, 0, &mode);
GetArrayType(type, 1, &pos);
Return(less_mode_nolocal_(mode, pos, value, &check,
call_less_, call_less_equal_));
if (! check)
return Result(ret, 0);
/* right */
GetArrayType(type, 2, &mode);
GetArrayType(type, 3, &pos);
return less_mode_nolocal_(mode, value, pos, ret,
call_less_, call_less_equal_);
}
static int less_mode_local_(LocalRoot local,
addr mode, addr left, addr right, int *ret,
int (*call_less_)(LocalRoot, addr, addr, int *),
int (*call_less_equal_)(LocalRoot, addr, addr, int *))
{
if (type_asterisk_p(mode))
return Result(ret, 1);
if (mode == Nil)
return (*call_less_equal_)(local, left, right, ret);
else
return (*call_less_)(local, left, right, ret);
}
static int typep_range_local_(LocalRoot local, addr value, addr type, int *ret,
int (*typecheck)(addr),
int (*call_less_)(LocalRoot, addr, addr, int *),
int (*call_less_equal_)(LocalRoot, addr, addr, int *))
{
int check;
addr mode, pos;
/* type */
if (! (*typecheck)(value))
return Result(ret, 0);
/* left */
GetArrayType(type, 0, &mode);
GetArrayType(type, 1, &pos);
Return(less_mode_local_(local, mode, pos, value, &check,
call_less_, call_less_equal_));
if (! check)
return Result(ret, 0);
/* right */
GetArrayType(type, 2, &mode);
GetArrayType(type, 3, &pos);
return less_mode_local_(local, mode, value, pos, ret,
call_less_, call_less_equal_);
}
static int typep_integer_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_nolocal_(value, type, ret,
integerp,
less_integer_,
less_equal_integer_);
}
static int typep_rational_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_local_(ptr->local, value, type, ret,
rationalp,
less_rational_,
less_equal_rational_);
}
static int typep_real_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_local_(ptr->local, value, type, ret,
realp,
less_real_,
less_equal_real_);
}
static int typep_float_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_nolocal_(value, type, ret,
floatp,
less_float_clang_,
less_equal_float_clang_);
}
static int single_float_p_clang(addr value)
{
return (GetType(value) == LISPTYPE_SINGLE_FLOAT);
}
static int typep_single_float_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_nolocal_(value, type, ret,
single_float_p_clang,
less_float_clang_,
less_equal_float_clang_);
}
static int double_float_p_clang(addr value)
{
return (GetType(value) == LISPTYPE_DOUBLE_FLOAT);
}
static int typep_double_float_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_nolocal_(value, type, ret,
double_float_p_clang,
less_float_clang_,
less_equal_float_clang_);
}
static int long_float_p_clang(addr value)
{
return (GetType(value) == LISPTYPE_LONG_FLOAT);
}
static int typep_long_float_(Execute ptr, addr value, addr type, int *ret)
{
return typep_range_nolocal_(value, type, ret,
long_float_p_clang,
less_float_clang_,
less_equal_float_clang_);
}
static int typep_restart_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_RESTART);
return 0;
}
static int typep_environment_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_ENVIRONMENT);
return 0;
}
static int typep_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = streamp(value);
return 0;
}
static int typep_broadcast_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = broadcast_stream_p(value);
return 0;
}
static int typep_concatenated_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = concatenated_stream_p(value);
return 0;
}
static int typep_echo_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = echo_stream_p(value);
return 0;
}
static int typep_file_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = file_stream_p(value);
return 0;
}
static int typep_string_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = string_stream_p(value);
return 0;
}
static int typep_synonym_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = synonym_stream_p(value);
return 0;
}
static int typep_two_way_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = twoway_stream_p(value);
return 0;
}
static int typep_prompt_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = prompt_stream_p(value);
return 0;
}
static int typep_pretty_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = pretty_stream_p(value);
return 0;
}
static int typep_memory_stream_(Execute ptr, addr value, addr type, int *ret)
{
*ret = memory_stream_p(value);
return 0;
}
static int typep_byte_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_BYTESPEC);
return 0;
}
static int typep_print_dispatch_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_PRINT_DISPATCH);
return 0;
}
static int typep_eval_(Execute ptr, addr value, addr type, int *ret)
{
*ret = (GetType(value) == LISPTYPE_EVAL);
return 0;
}
/*
* typep-clang
*/
int typep_table_(Execute ptr, addr value, addr type, int *ret)
{
call_type_typep call;
CheckType(type, LISPTYPE_TYPE);
call = TypeTypep[(int)RefLispDecl(type)];
Check(call == NULL, "build error");
return (*call)(ptr, value, type, ret);
}
void init_type_typep(void)
{
int i;
for (i = 0; i < LISPDECL_SIZE; i++)
TypeTypep[i] = typep_invalid_;
TypeTypep[LISPDECL_ERROR] = typep_error_;
TypeTypep[LISPDECL_TYPE] = typep_type_;
TypeTypep[LISPDECL_CLOS] = typep_clos_;
TypeTypep[LISPDECL_ASTERISK] = typep_asterisk_;
TypeTypep[LISPDECL_OPTIMIZED] = typep_optimized_;
TypeTypep[LISPDECL_SUBTYPEP] = typep_optimized_;
/* Compound-type */
TypeTypep[LISPDECL_AND] = typep_and_;
TypeTypep[LISPDECL_OR] = typep_or_;
TypeTypep[LISPDECL_EQL] = typep_eql_;
TypeTypep[LISPDECL_MEMBER] = typep_member_;
TypeTypep[LISPDECL_MOD] = typep_mod_;
TypeTypep[LISPDECL_NOT] = typep_not_;
TypeTypep[LISPDECL_SATISFIES] = typep_satisfies_;
TypeTypep[LISPDECL_VALUES] = typep_values_;
/* Extract-type */
TypeTypep[LISPDECL_ATOM] = typep_atom_;
TypeTypep[LISPDECL_LIST] = typep_list_;
TypeTypep[LISPDECL_BOOLEAN] = typep_boolean_;
TypeTypep[LISPDECL_VECTOR] = typep_vector_;
TypeTypep[LISPDECL_SIMPLE_VECTOR] = typep_simple_vector_;
TypeTypep[LISPDECL_BIT_VECTOR] = typep_bit_vector_;
TypeTypep[LISPDECL_SIMPLE_BIT_VECTOR] = typep_simple_bit_vector_;
TypeTypep[LISPDECL_EXTENDED_CHAR] = typep_extended_char_;
TypeTypep[LISPDECL_STRING] = typep_string_;
TypeTypep[LISPDECL_BASE_STRING] = typep_base_string_;
TypeTypep[LISPDECL_SIMPLE_STRING] = typep_simple_string_;
TypeTypep[LISPDECL_SIMPLE_BASE_STRING] = typep_simple_base_string_;
TypeTypep[LISPDECL_SIGNED_BYTE] = typep_signed_byte_;
TypeTypep[LISPDECL_UNSIGNED_BYTE] = typep_unsigned_byte_;
TypeTypep[LISPDECL_BIT] = typep_bit_;
TypeTypep[LISPDECL_FIXNUM] = typep_fixnum_;
TypeTypep[LISPDECL_BIGNUM] = typep_bignum_;
/* Atomic-type */
TypeTypep[LISPDECL_NIL] = typep_nil_;
TypeTypep[LISPDECL_T] = typep_t_;
TypeTypep[LISPDECL_NULL] = typep_null_;
TypeTypep[LISPDECL_CONS] = typep_cons_;
TypeTypep[LISPDECL_HASH_TABLE] = typep_hash_table_;
TypeTypep[LISPDECL_SYMBOL] = typep_symbol_;
TypeTypep[LISPDECL_KEYWORD] = typep_keyword_;
TypeTypep[LISPDECL_PACKAGE] = typep_package_;
TypeTypep[LISPDECL_RANDOM_STATE] = typep_random_state_;
TypeTypep[LISPDECL_READTABLE] = typep_readtable_;
TypeTypep[LISPDECL_FUNCTION] = typep_function_;
TypeTypep[LISPDECL_COMPILED_FUNCTION] = typep_compiled_function_;
TypeTypep[LISPDECL_PATHNAME] = typep_pathname_;
TypeTypep[LISPDECL_LOGICAL_PATHNAME] = typep_logical_pathname_;
TypeTypep[LISPDECL_SEQUENCE] = typep_sequence_;
TypeTypep[LISPDECL_ARRAY] = typep_array_;
TypeTypep[LISPDECL_SIMPLE_ARRAY] = typep_simple_array_;
TypeTypep[LISPDECL_CHARACTER] = typep_character_;
TypeTypep[LISPDECL_BASE_CHAR] = typep_base_char_;
TypeTypep[LISPDECL_STANDARD_CHAR] = typep_standard_char_;
TypeTypep[LISPDECL_NUMBER] = typep_number_;
TypeTypep[LISPDECL_REAL] = typep_real_;
TypeTypep[LISPDECL_RATIO] = typep_ratio_;
TypeTypep[LISPDECL_INTEGER] = typep_integer_;
TypeTypep[LISPDECL_RATIONAL] = typep_rational_;
TypeTypep[LISPDECL_COMPLEX] = typep_complex_;
TypeTypep[LISPDECL_FLOAT] = typep_float_;
TypeTypep[LISPDECL_SHORT_FLOAT] = typep_single_float_;
TypeTypep[LISPDECL_SINGLE_FLOAT] = typep_single_float_;
TypeTypep[LISPDECL_DOUBLE_FLOAT] = typep_double_float_;
TypeTypep[LISPDECL_LONG_FLOAT] = typep_long_float_;
TypeTypep[LISPDECL_RESTART] = typep_restart_;
TypeTypep[LISPDECL_ENVIRONMENT] = typep_environment_;
TypeTypep[LISPDECL_STREAM] = typep_stream_;
TypeTypep[LISPDECL_BROADCAST_STREAM] = typep_broadcast_stream_;
TypeTypep[LISPDECL_CONCATENATED_STREAM] = typep_concatenated_stream_;
TypeTypep[LISPDECL_ECHO_STREAM] = typep_echo_stream_;
TypeTypep[LISPDECL_FILE_STREAM] = typep_file_stream_;
TypeTypep[LISPDECL_STRING_STREAM] = typep_string_stream_;
TypeTypep[LISPDECL_SYNONYM_STREAM] = typep_synonym_stream_;
TypeTypep[LISPDECL_TWO_WAY_STREAM] = typep_two_way_stream_;
TypeTypep[LISPDECL_PROMPT_STREAM] = typep_prompt_stream_;
TypeTypep[LISPDECL_PRETTY_STREAM] = typep_pretty_stream_;
TypeTypep[LISPDECL_MEMORY_STREAM] = typep_memory_stream_;
TypeTypep[LISPDECL_BYTESPEC] = typep_byte_;
TypeTypep[LISPDECL_PRINT_DISPATCH] = typep_print_dispatch_;
TypeTypep[LISPDECL_EVAL] = typep_eval_;
}
static int typep_call_(Execute ptr, addr value, addr type, int asterisk, int *ret)
{
int result;
LocalHold hold;
if ((! asterisk) && type_asterisk_p(type))
return fmte_("typep don't allow to be asterisk *.", NULL);
hold = LocalHold_local(ptr);
localhold_pushva_force(hold, value, type, NULL);
Return(typep_table_(ptr, value, type, &result));
*ret = RefNotDecl(type)? (! result): result;
localhold_end(hold);
return 0;
}
int typep_clang_(Execute ptr, addr value, addr type, int *ret)
{
CheckType(type, LISPTYPE_TYPE);
return typep_call_(ptr, value, type, 0, ret);
}
int typep_asterisk_clang_(Execute ptr, addr value, addr type, int *ret)
{
CheckType(type, LISPTYPE_TYPE);
return typep_call_(ptr, value, type, 1, ret);
}
/************************************************************
* type_upgraded.c
************************************************************/
/*
* build
*/
#define SetConstCommon(a) { \
addr __pos; \
GetConst(COMMON_##a, &__pos); \
SetConst(ARRAY_##a, __pos); \
}
#define SetConstCommonN(a,b,n) { \
addr __pos, __value; \
GetConst(COMMON_##a, &__pos); \
fixnum_heap(&__value, n); \
list_heap(&__pos, __pos, __value, NULL); \
SetStatusReadOnly(__pos); \
SetConst(ARRAY_##b##n, __pos); \
}
void build_type_upgraded(void)
{
SetConstCommon(T);
SetConstCommon(BIT);
SetConstCommon(CHARACTER);
SetConstCommon(SINGLE_FLOAT);
SetConstCommon(DOUBLE_FLOAT);
SetConstCommon(LONG_FLOAT);
SetConstCommonN(SIGNED_BYTE, SIGNED, 8);
SetConstCommonN(SIGNED_BYTE, SIGNED, 16);
SetConstCommonN(SIGNED_BYTE, SIGNED, 32);
SetConstCommonN(UNSIGNED_BYTE, UNSIGNED, 8);
SetConstCommonN(UNSIGNED_BYTE, UNSIGNED, 16);
SetConstCommonN(UNSIGNED_BYTE, UNSIGNED, 32);
#ifdef LISP_64BIT
SetConstCommonN(SIGNED_BYTE, SIGNED, 64);
SetConstCommonN(UNSIGNED_BYTE, UNSIGNED, 64);
#endif
}
/*
* upgraded-array-element-type
*/
int upgraded_array0_equal(addr left, addr right)
{
enum LISPDECL decl;
decl = LowLispDecl(left);
if (decl != LowLispDecl(right)) {
return 0;
}
if (decl == LISPDECL_SIGNED_BYTE || decl == LISPDECL_UNSIGNED_BYTE) {
GetArrayType(left, 0, &left);
GetArrayType(right, 0, &right);
CheckType(left, LISPTYPE_FIXNUM);
CheckType(right, LISPTYPE_FIXNUM);
return RefFixnum(left) == RefFixnum(right);
}
return 1;
}
static int upgraded_array_unsigned(bigtype value)
{
if (value <= UINT8_MAX) return 8;
if (value <= UINT16_MAX) return 16;
#ifdef LISP_64BIT
if (value <= UINT32_MAX) return 32;
return 64;
#else
return 32;
#endif
}
static int upgraded_array_signed(int sign, bigtype value)
{
if (IsPlus(sign)) {
if (value <= INT8_MAX) return 8;
if (value <= INT16_MAX) return 16;
if (value <= INT32_MAX) return 32;
#ifdef LISP_64BIT
if (value <= INT64_MAX) return 64;
#endif
}
else {
if (value <= ((bigtype)INT8_MAX) + 1UL) return 8;
if (value <= ((bigtype)INT16_MAX) + 1UL) return 16;
if (value <= ((bigtype)INT32_MAX) + 1UL) return 32;
#ifdef LISP_64BIT
if (value <= ((bigtype)INT64_MAX) + 1ULL) return 64;
#endif
}
return 0;
}
static enum ARRAY_TYPE upgraded_array_integer(addr type, int *size)
{
int sign1, sign2, size1, size2;
addr left1, left2, right1, right2;
bigtype value1, value2;
/* asterisk check */
GetArrayType(type, 0, &left1);
if (type_asterisk_p(left1))
return ARRAY_TYPE_T;
GetArrayType(type, 2, &right1);
if (type_asterisk_p(right1))
return ARRAY_TYPE_T;
/* left */
GetArrayType(type, 1, &left2);
if (castfixed_integer(left2, &sign1, &value1))
return ARRAY_TYPE_T;
if (left1 == T)
value1++;
/* right */
GetArrayType(type, 3, &right2);
if (castfixed_integer(right2, &sign2, &value2))
return ARRAY_TYPE_T;
if (right1 == T)
value2--;
/* value */
if (IsPlus(sign1)) {
if (value1 == 0 && value2 == 1)
return ARRAY_TYPE_BIT;
size1 = upgraded_array_unsigned(value1);
size2 = upgraded_array_unsigned(value2);
*size = (size1 < size2)? size2: size1;
return ARRAY_TYPE_UNSIGNED;
}
else {
size1 = upgraded_array_signed(sign1, value1);
size2 = upgraded_array_signed(sign2, value2);
if (size1 == 0 || size2 == 0)
return ARRAY_TYPE_T;
*size = (size1 < size2)? size2: size1;
return ARRAY_TYPE_SIGNED;
}
}
static enum ARRAY_TYPE upgraded_array_decl(addr type, int *size)
{
/* not */
if (RefNotDecl(type))
return ARRAY_TYPE_T;
/* upgraded */
switch (LowLispDecl(type)) {
case LISPDECL_CHARACTER:
case LISPDECL_BASE_CHAR:
case LISPDECL_STANDARD_CHAR:
return ARRAY_TYPE_CHARACTER;
case LISPDECL_INTEGER:
return upgraded_array_integer(type, size);
case LISPDECL_SINGLE_FLOAT:
return ARRAY_TYPE_SINGLE_FLOAT;
case LISPDECL_DOUBLE_FLOAT:
return ARRAY_TYPE_DOUBLE_FLOAT;
case LISPDECL_LONG_FLOAT:
return ARRAY_TYPE_LONG_FLOAT;
default:
break;
}
return ARRAY_TYPE_T;
}
static int upgraded_array_optimize_(LocalRoot local,
addr type, enum ARRAY_TYPE *ret, int *size)
{
int ignore;
LocalStack stack;
CheckType(type, LISPTYPE_TYPE);
/* local */
push_local(local, &stack);
/* upgraded-array */
Return(type_optimize_local_(local, type, &type, &ignore));
Check(! type_optimized_p(type), "optimize error");
get_type_optimized(&type, type);
*size = 0;
*ret = upgraded_array_decl(type, size);
/* free */
rollback_local(local, stack);
return 0;
}
int upgraded_array_value_(addr type, enum ARRAY_TYPE *ret, int *size)
{
return upgraded_array_optimize_(Local_Thread, type, ret, size);
}
static void upgraded_array_type_signed(int size, addr *ret)
{
switch (size) {
case 8:
GetTypeTable(ret, Array_Signed8);
break;
case 16:
GetTypeTable(ret, Array_Signed16);
break;
case 32:
GetTypeTable(ret, Array_Signed32);
break;
#ifdef LISP_64BIT
case 64:
GetTypeTable(ret, Array_Signed64);
break;
#endif
default:
GetTypeTable(ret, Array_T);
break;
}
}
static void upgraded_array_type_unsigned(int size, addr *ret)
{
switch (size) {
case 8:
GetTypeTable(ret, Array_Unsigned8);
break;
case 16:
GetTypeTable(ret, Array_Unsigned16);
break;
case 32:
GetTypeTable(ret, Array_Unsigned32);
break;
#ifdef LISP_64BIT
case 64:
GetTypeTable(ret, Array_Unsigned64);
break;
#endif
default:
GetTypeTable(ret, Array_T);
break;
}
}
void upgraded_array_object(enum ARRAY_TYPE type, int size, addr *ret)
{
switch (type) {
case ARRAY_TYPE_BIT:
GetTypeTable(ret, Array_Bit);
break;
case ARRAY_TYPE_CHARACTER:
GetTypeTable(ret, Array_Character);
break;
case ARRAY_TYPE_SIGNED:
upgraded_array_type_signed(size, ret);
break;
case ARRAY_TYPE_UNSIGNED:
upgraded_array_type_unsigned(size, ret);
break;
case ARRAY_TYPE_SINGLE_FLOAT:
GetTypeTable(ret, Array_SingleFloat);
break;
case ARRAY_TYPE_DOUBLE_FLOAT:
GetTypeTable(ret, Array_DoubleFloat);
break;
case ARRAY_TYPE_LONG_FLOAT:
GetTypeTable(ret, Array_LongFloat);
break;
default:
GetTypeTable(ret, Array_T);
break;
}
}
static int type_upgraded_type_local_(LocalRoot local, addr type, addr *ret)
{
enum ARRAY_TYPE value;
int size;
CheckType(type, LISPTYPE_TYPE);
size = 0;
Return(upgraded_array_optimize_(local, type, &value, &size));
upgraded_array_object(value, size, ret);
return 0;
}
int upgraded_array_type_(addr type, addr *ret)
{
CheckType(type, LISPTYPE_TYPE);
return type_upgraded_type_local_(Local_Thread, type, ret);
}
static void upgraded_array_const_signed(int size, addr *ret)
{
switch (size) {
case 8:
GetConst(ARRAY_SIGNED8, ret);
break;
case 16:
GetConst(ARRAY_SIGNED16, ret);
break;
case 32:
GetConst(ARRAY_SIGNED32, ret);
break;
#ifdef LISP_64BIT
case 64:
GetConst(ARRAY_SIGNED64, ret);
break;
#endif
default:
GetConst(ARRAY_T, ret);
break;
}
}
static void upgraded_array_const_unsigned(int size, addr *ret)
{
switch (size) {
case 8:
GetConst(ARRAY_UNSIGNED8, ret);
break;
case 16:
GetConst(ARRAY_UNSIGNED16, ret);
break;
case 32:
GetConst(ARRAY_UNSIGNED32, ret);
break;
#ifdef LISP_64BIT
case 64:
GetConst(ARRAY_UNSIGNED64, ret);
break;
#endif
default:
GetConst(ARRAY_T, ret);
break;
}
}
void upgraded_array_const(enum ARRAY_TYPE type, int size, addr *ret)
{
switch (type) {
case ARRAY_TYPE_BIT:
GetConst(ARRAY_BIT, ret);
break;
case ARRAY_TYPE_CHARACTER:
GetConst(ARRAY_CHARACTER, ret);
break;
case ARRAY_TYPE_SIGNED:
upgraded_array_const_signed(size, ret);
break;
case ARRAY_TYPE_UNSIGNED:
upgraded_array_const_unsigned(size, ret);
break;
case ARRAY_TYPE_SINGLE_FLOAT:
GetConst(ARRAY_SINGLE_FLOAT, ret);
break;
case ARRAY_TYPE_DOUBLE_FLOAT:
GetConst(ARRAY_DOUBLE_FLOAT, ret);
break;
case ARRAY_TYPE_LONG_FLOAT:
GetConst(ARRAY_LONG_FLOAT, ret);
break;
default:
GetConst(ARRAY_T, ret);
break;
}
}
int upgraded_array_common(Execute ptr, addr env, addr pos, addr *ret)
{
int size;
enum ARRAY_TYPE type;
if (env == Unbound)
env = Nil;
Return(parse_type(ptr, &pos, pos, env));
Return(upgraded_array_optimize_(ptr->local, pos, &type, &size));
upgraded_array_const(type, size, ret);
return 0;
}
/* make local */
void upgraded_array_t_local(LocalRoot local, addr *ret)
{
type0_local(local, LISPDECL_T, ret);
}
void upgraded_array_bit_local(LocalRoot local, addr *ret)
{
type0_local(local, LISPDECL_BIT, ret);
}
void upgraded_array_character_local(LocalRoot local, addr *ret)
{
type0_local(local, LISPDECL_CHARACTER, ret);
}
/*
* upgraded-complex-part-type
*/
int upgraded_complex_type_(Execute ptr, addr env, addr type, addr *ret)
{
int value;
addr right;
CheckType(type, LISPTYPE_TYPE);
/* integer */
GetTypeTable(&right, Integer);
Return(subtypep_check_(ptr, type, right, env, &value, NULL));
if (value)
return Result(ret, right);
/* rational */
GetTypeTable(&right, Rational);
Return(subtypep_check_(ptr, type, right, env, &value, NULL));
if (value)
return Result(ret, right);
/* single-float */
GetTypeTable(&right, SingleFloat);
Return(subtypep_check_(ptr, type, right, env, &value, NULL));
if (value)
return Result(ret, right);
/* double-float */
GetTypeTable(&right, DoubleFloat);
Return(subtypep_check_(ptr, type, right, env, &value, NULL));
if (value)
return Result(ret, right);
/* long-float */
GetTypeTable(&right, LongFloat);
Return(subtypep_check_(ptr, type, right, env, &value, NULL));
if (value)
return Result(ret, right);
/* Real */
GetTypeTable(&right, Real);
Return(subtypep_check_(ptr, type, right, env, &value, NULL));
if (value) {
GetTypeTable(ret, SingleFloat); /* single-float */
return 0;
}
/* error */
*ret = 0;
Return(type_object_(&type, type));
return fmte_("COMPLEX type ~S must be a subtype of a real.", type, NULL);
}
static int upgraded_complex_const_(Execute ptr, addr env, addr pos, addr *ret)
{
int value;
addr right;
CheckType(pos, LISPTYPE_TYPE);
/* integer */
GetTypeTable(&right, Integer);
Return(subtypep_check_(ptr, pos, right, env, &value, NULL));
if (value) {
GetConst(COMMON_INTEGER, ret);
return 0;
}
/* rational */
GetTypeTable(&right, Rational);
Return(subtypep_check_(ptr, pos, right, env, &value, NULL));
if (value) {
GetConst(COMMON_RATIONAL, ret);
return 0;
}
/* single-float */
GetTypeTable(&right, SingleFloat);
Return(subtypep_check_(ptr, pos, right, env, &value, NULL));
if (value) {
GetConst(COMMON_SINGLE_FLOAT, ret);
return 0;
}
/* double-float */
GetTypeTable(&right, DoubleFloat);
Return(subtypep_check_(ptr, pos, right, env, &value, NULL));
if (value) {
GetConst(COMMON_DOUBLE_FLOAT, ret);
return 0;
}
/* long-float */
GetTypeTable(&right, LongFloat);
Return(subtypep_check_(ptr, pos, right, env, &value, NULL));
if (value) {
GetConst(COMMON_LONG_FLOAT, ret);
return 0;
}
/* short-float */
GetTypeTable(&right, Real);
Return(subtypep_check_(ptr, pos, right, env, &value, NULL));
if (value) {
GetConst(COMMON_SINGLE_FLOAT, ret); /* single-float */
return 0;
}
/* error */
*ret = 0;
Return(type_object_(&pos, pos));
return fmte_("COMPLEX type ~S must be a subtype of a real.", pos, NULL);
}
int upgraded_complex_common(Execute ptr, addr env, addr pos, addr *ret)
{
Return(parse_type(ptr, &pos, pos, env));
Return(upgraded_complex_const_(ptr, env, pos, ret));
CheckType(*ret, LISPTYPE_SYMBOL);
return 0;
}
/************************************************************
* type_value.c
************************************************************/
typedef int (*type_value_call)(addr *, addr);
static type_value_call TypeValueTable[LISPTYPE_SIZE];
/* nil */
void type_value_nil(addr *ret)
{
GetTypeTable(ret, Null);
}
static int type_value_nil_(addr *ret, addr value)
{
GetTypeTable(ret, Null);
return 0;
}
/* t */
void type_value_t(addr *ret)
{
GetTypeTable(ret, Boolean);
}
static int type_value_t_(addr *ret, addr value)
{
GetTypeTable(ret, Boolean);
return 0;
}
/* clos */
int type_value_clos_(addr *ret, addr value)
{
Return(clos_class_of_(value, &value));
type_clos_heap(value, ret);
return 0;
}
/* cons */
static int type_value_cons_(addr *ret, addr value)
{
GetTypeTable(ret, Cons);
return 0;
}
/* array */
static int type_value_strarray_(addr *ret, addr value)
{
enum LISPDECL decl;
enum CHARACTER_TYPE type;
int simple;
addr arg, pos;
size_t size;
Check(GetType(value) != LISPTYPE_ARRAY, "type error");
Check(! strarrayp(value), "type array error");
simple = ArrayInfoStruct(value)->simple;
strarray_length(value, &size);
make_index_integer_heap(&arg, size);
Return(strarray_character_type_(value, &type));
switch (type) {
case CHARACTER_TYPE_STANDARD:
case CHARACTER_TYPE_BASE:
decl = simple? LISPDECL_SIMPLE_BASE_STRING: LISPDECL_BASE_STRING;
type1_heap(decl, arg, &pos);
break;
default:
decl = simple? LISPDECL_SIMPLE_STRING: LISPDECL_STRING;
type1_heap(decl, arg, &pos);
break;
}
return Result(ret, pos);
}
static void type_value_array_nil(addr *ret, addr value)
{
enum LISPDECL decl;
struct array_struct *str;
addr type, pos;
GetArrayInfo(value, ARRAY_INDEX_TYPE, &type);
str = ArrayInfoStruct(value);
decl = str->simple? LISPDECL_SIMPLE_ARRAY: LISPDECL_ARRAY;
fixnum_heap(&pos, 0);
type2_heap(decl, type, pos, ret);
}
static void type_value_array_single(addr *ret, addr value)
{
enum LISPDECL decl;
struct array_struct *str;
addr type, pos, array;
GetArrayInfo(value, ARRAY_INDEX_TYPE, &type);
GetArrayInfo(value, ARRAY_INDEX_DIMENSION, &pos);
str = ArrayInfoStruct(value);
decl = str->simple? LISPDECL_SIMPLE_ARRAY: LISPDECL_ARRAY;
make_index_integer_heap(&pos, str->size);
vector4_heap(&array, 1);
SetArrayA4(array, 0, pos);
type2_heap(decl, type, array, ret);
}
static void type_value_array_multiple(addr *ret, addr value)
{
enum LISPDECL decl;
struct array_struct *str;
addr type, pos, array;
size_t *psize, size, i;
GetArrayInfo(value, ARRAY_INDEX_TYPE, &type);
GetArrayInfo(value, ARRAY_INDEX_DIMENSION, &pos);
str = ArrayInfoStruct(value);
decl = str->simple? LISPDECL_SIMPLE_ARRAY: LISPDECL_ARRAY;
size = str->dimension;
Check(GetType(pos) != LISPSYSTEM_ARRAY_DIMENSION, "type dimension error");
psize = arraysize_ptr(pos);
vector4_heap(&array, size);
for (i = 0; i < size; i++) {
make_index_integer_heap(&pos, psize[i]);
SetArrayA4(array, i, pos);
}
type2_heap(decl, type, array, ret);
}
int type_value_array_(addr *ret, addr value)
{
size_t size;
Check(GetType(value) != LISPTYPE_ARRAY, "type error");
size = ArrayInfoStruct(value)->dimension;
if (array_stringp(value)) {
Return(type_value_strarray_(ret, value));
}
else if (size == 0) {
type_value_array_nil(ret, value);
}
else if (size == 1) {
type_value_array_single(ret, value);
}
else {
type_value_array_multiple(ret, value);
}
return 0;
}
/* vector */
void type_value_vector(addr *ret, addr value)
{
addr arg;
size_t size;
Check(GetType(value) != LISPTYPE_VECTOR, "type error");
lenarray(value, &size);
make_index_integer_heap(&arg, size);
type1_heap(LISPDECL_SIMPLE_VECTOR, arg, ret);
}
static int type_value_vector_(addr *ret, addr value)
{
type_value_vector(ret, value);
return 0;
}
/* character */
void type_value_character(addr *ret, addr value)
{
enum CHARACTER_TYPE type;
Check(GetType(value) != LISPTYPE_CHARACTER, "type error");
get_character_type(value, &type);
switch (type) {
case CHARACTER_TYPE_STANDARD:
GetTypeTable(ret, StandardChar);
break;
case CHARACTER_TYPE_BASE:
GetTypeTable(ret, BaseChar);
break;
case CHARACTER_TYPE_EXTENDED:
GetTypeTable(ret, ExtendedChar);
break;
default:
GetTypeTable(ret, Character);
break;
}
}
static int type_value_character_(addr *ret, addr value)
{
type_value_character(ret, value);
return 0;
}
/* string */
static int type_value_string_(addr *ret, addr value)
{
enum CHARACTER_TYPE type;
addr arg, pos;
size_t size;
Check(GetType(value) != LISPTYPE_STRING, "type error");
strvect_length(value, &size);
make_index_integer_heap(&arg, size);
Return(strvect_character_type_(value, &type));
switch (type) {
case CHARACTER_TYPE_STANDARD:
case CHARACTER_TYPE_BASE:
type1_heap(LISPDECL_SIMPLE_BASE_STRING, arg, &pos);
break;
default:
type1_heap(LISPDECL_SIMPLE_STRING, arg, &pos);
break;
}
return Result(ret, pos);
}
/* hashtable */
static int type_value_hashtable_(addr *ret, addr value)
{
GetTypeTable(ret, Hashtable);
return 0;
}
/* readtable */
static int type_value_readtable_(addr *ret, addr value)
{
GetTypeTable(ret, Readtable);
return 0;
}
/* symbol */
static int type_value_symbol_(addr *ret, addr value)
{
Check(GetType(value) != LISPTYPE_SYMBOL, "type error");
if (keywordp(value))
GetTypeTable(ret, Keyword);
else
GetTypeTable(ret, Symbol);
return 0;
}
/* integer */
static void type_realvalue(enum LISPDECL type, addr value, addr *ret)
{
type4_heap(type, Nil, value, Nil, value, ret);
}
void type_value_integer(addr *ret, addr value)
{
Check(! integerp(value), "type error");
type_realvalue(LISPDECL_INTEGER, value, ret);
}
static int type_value_integer_(addr *ret, addr value)
{
type_value_integer(ret, value);
return 0;
}
/* rational */
void type_value_rational(addr *ret, addr value)
{
Check(! rationalp(value), "type error");
type_realvalue(LISPDECL_RATIONAL, value, ret);
}
static int type_value_rational_(addr *ret, addr value)
{
type_value_rational(ret, value);
return 0;
}
/* single */
static int type_value_single_(addr *ret, addr value)
{
CheckType(value, LISPTYPE_SINGLE_FLOAT);
type_realvalue(LISPDECL_SINGLE_FLOAT, value, ret);
return 0;
}
/* double */
static int type_value_double_(addr *ret, addr value)
{
CheckType(value, LISPTYPE_DOUBLE_FLOAT);
type_realvalue(LISPDECL_DOUBLE_FLOAT, value, ret);
return 0;
}
/* long */
static int type_value_long_(addr *ret, addr value)
{
CheckType(value, LISPTYPE_LONG_FLOAT);
type_realvalue(LISPDECL_LONG_FLOAT, value, ret);
return 0;
}
void type_value_float(addr *ret, addr value)
{
switch (GetType(value)) {
case LISPTYPE_SINGLE_FLOAT:
(void)type_value_single_(ret, value);
break;
case LISPTYPE_DOUBLE_FLOAT:
(void)type_value_double_(ret, value);
break;
case LISPTYPE_LONG_FLOAT:
(void)type_value_long_(ret, value);
break;
default:
Abort("type error");
break;
}
}
/* complex */
int type_value_complex_(addr *ret, addr value)
{
addr real, imag, type;
GetRealComplex(value, &real);
GetImagComplex(value, &imag);
Return(type_value_(&real, real));
Return(type_value_(&imag, imag));
type2or_heap(real, imag, &type);
type1_heap(LISPDECL_COMPLEX, type, ret);
return 0;
}
/* function */
static int type_value_function_(addr *ret, addr value)
{
Check(! functionp(value), "type error");
gettype_function(value, ret);
if (*ret == Nil) {
if (compiled_function_p(value))
GetTypeTable(ret, CompiledFunction);
else
GetTypeTable(ret, Function);
}
return 0;
}
/* package */
void type_value_package(addr *ret, addr value)
{
GetTypeTable(ret, Package);
}
static int type_value_package_(addr *ret, addr value)
{
type_value_package(ret, value);
return 0;
}
/* random-state */
void type_value_random_state(addr *ret, addr value)
{
GetTypeTable(ret, RandomState);
}
static int type_value_random_state_(addr *ret, addr value)
{
type_value_random_state(ret, value);
return 0;
}
/* pathname */
void type_value_pathname(addr *ret, addr value)
{
Check(! pathnamep(value), "type error");
if (pathname_pathname_p(value))
GetTypeTable(ret, Pathname);
else
GetTypeTable(ret, LogicalPathname);
}
static int type_value_pathname_(addr *ret, addr value)
{
type_value_pathname(ret, value);
return 0;
}
/* environment */
void type_value_environment(addr *ret, addr value)
{
GetTypeTable(ret, Environment);
}
static int type_value_environment_(addr *ret, addr value)
{
type_value_environment(ret, value);
return 0;
}
/* stream */
static int type_value_stream_(addr *ret, addr value)
{
CheckType(value, LISPTYPE_STREAM);
switch (getstreamtype(value)) {
case StreamType_BroadCast:
GetTypeTable(ret, BroadcastStream);
return 0;
case StreamType_Concatenated:
GetTypeTable(ret, ConcatenatedStream);
return 0;
case StreamType_Echo:
GetTypeTable(ret, EchoStream);
return 0;
case StreamType_StringInput:
case StreamType_StringOutput:
GetTypeTable(ret, StringStream);
return 0;
case StreamType_Synonym:
GetTypeTable(ret, SynonymStream);
return 0;
case StreamType_TwoWay:
GetTypeTable(ret, TwoWayStream);
return 0;
case StreamType_Prompt:
GetTypeTable(ret, PromptStream);
return 0;
case StreamType_Pretty:
GetTypeTable(ret, PrettyStream);
return 0;
case StreamType_Terminal:
GetTypeTable(ret, TerminalStream);
return 0;
default:
break;
}
GetPathnameStream(value, &value);
if (value != Nil)
GetTypeTable(ret, FileStream);
else
GetTypeTable(ret, Stream);
return 0;
}
/* restart */
static int type_value_restart_(addr *ret, addr value)
{
GetTypeTable(ret, Restart);
return 0;
}
/* eval */
static int type_value_eval_(addr *ret, addr value)
{
GetTypeTable(ret, Eval);
return 0;
}
/* bit-vector */
void type_value_bitvector(addr *ret, addr value)
{
addr arg;
size_t size;
Check(GetType(value) != LISPTYPE_BITVECTOR, "type error");
bitmemory_length(value, &size);
make_index_integer_heap(&arg, size);
type1_heap(LISPDECL_SIMPLE_BIT_VECTOR, arg, ret);
}
static int type_value_bitvector_(addr *ret, addr value)
{
type_value_bitvector(ret, value);
return 0;
}
/* quote */
static int type_value_quote_(addr *ret, addr value)
{
GetTypeTable(ret, Quote);
return 0;
}
static int type_value_bytespec_(addr *ret, addr value)
{
GetTypeTable(ret, ByteSpec);
return 0;
}
static int type_value_print_dispatch_(addr *ret, addr value)
{
GetTypeTable(ret, PrintDispatch);
return 0;
}
static int type_value_argument_(addr *ret, addr value)
{
GetTypeTable(ret, T);
return 0;
}
static int type_value_error_(addr *ret, addr value)
{
infobit(value);
return fmte_("Invalid type-value.", NULL);
}
int type_value_(addr *ret, addr value)
{
type_value_call call;
call = TypeValueTable[GetType(value)];
if (call == NULL)
return type_value_error_(ret, value);
else
return (*call)(ret, value);
}
void init_type_value(void)
{
TypeValueTable[LISPTYPE_NIL] = type_value_nil_;
TypeValueTable[LISPTYPE_T] = type_value_t_;
TypeValueTable[LISPTYPE_CLOS] = type_value_clos_;
TypeValueTable[LISPTYPE_CONS] = type_value_cons_;
TypeValueTable[LISPTYPE_ARRAY] = type_value_array_;
TypeValueTable[LISPTYPE_VECTOR] = type_value_vector_;
TypeValueTable[LISPTYPE_CHARACTER] = type_value_character_;
TypeValueTable[LISPTYPE_STRING] = type_value_string_;
TypeValueTable[LISPTYPE_HASHTABLE] = type_value_hashtable_;
TypeValueTable[LISPTYPE_READTABLE] = type_value_readtable_;
TypeValueTable[LISPTYPE_SYMBOL] = type_value_symbol_;
TypeValueTable[LISPTYPE_FIXNUM] = type_value_integer_;
TypeValueTable[LISPTYPE_BIGNUM] = type_value_integer_;
TypeValueTable[LISPTYPE_RATIO] = type_value_rational_;
TypeValueTable[LISPTYPE_SHORT_FLOAT] = type_value_error_;
TypeValueTable[LISPTYPE_SINGLE_FLOAT] = type_value_single_;
TypeValueTable[LISPTYPE_DOUBLE_FLOAT] = type_value_double_;
TypeValueTable[LISPTYPE_LONG_FLOAT] = type_value_long_;
TypeValueTable[LISPTYPE_COMPLEX] = type_value_complex_;
TypeValueTable[LISPTYPE_CONTROL] = type_value_error_;
TypeValueTable[LISPTYPE_CODE] = type_value_error_;
TypeValueTable[LISPTYPE_CALLNAME] = type_value_error_;
TypeValueTable[LISPTYPE_FUNCTION] = type_value_function_;
TypeValueTable[LISPTYPE_INDEX] = type_value_error_;
TypeValueTable[LISPTYPE_PACKAGE] = type_value_package_;
TypeValueTable[LISPTYPE_RANDOM_STATE] = type_value_random_state_;
TypeValueTable[LISPTYPE_PATHNAME] = type_value_pathname_;
TypeValueTable[LISPTYPE_STREAM] = type_value_stream_;
TypeValueTable[LISPTYPE_RESTART] = type_value_restart_;
TypeValueTable[LISPTYPE_EVAL] = type_value_eval_;
TypeValueTable[LISPTYPE_ENVIRONMENT] = type_value_environment_;
TypeValueTable[LISPTYPE_BITVECTOR] = type_value_bitvector_;
TypeValueTable[LISPTYPE_QUOTE] = type_value_quote_;
TypeValueTable[LISPTYPE_BYTESPEC] = type_value_bytespec_;
TypeValueTable[LISPTYPE_PRINT_DISPATCH] = type_value_print_dispatch_;
TypeValueTable[LISPSYSTEM_ARGUMENT] = type_value_argument_;
}
/************************************************************
* unicode.c
************************************************************/
/*
* UTF-8
*/
int string8_size_alloc_(LocalRoot local, addr *ret, const char *name, size_t size)
{
addr pos;
unicode *destroy;
size_t allsize;
if (UTF8_size_strlen((const byte *)name, size, &allsize))
return fmte_("UTF8 encoding error (length).", NULL);
strvect_alloc(local, &pos, allsize);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF8_size_makeunicode(destroy, (const byte *)name, size))
return fmte_("UTF8 encoding error (make).", NULL);
return Result(ret, pos);
}
int string8_size_local_(LocalRoot local, addr *ret, const char *name, size_t size)
{
CheckLocal(local);
return string8_size_alloc_(local, ret, name, size);
}
int string8_size_heap_(addr *ret, const char *name, size_t size)
{
return string8_size_alloc_(NULL, ret, name, size);
}
int string8_null_alloc_(LocalRoot local, addr *ret, const char *name)
{
addr pos;
unicode *destroy;
size_t size;
if (UTF8_null_strlen((const byte *)name, &size))
return fmte_("UTF8 encoding error (length).", NULL);
strvect_alloc(local, &pos, size);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF8_null_makeunicode(destroy, (const byte *)name))
return fmte_("UTF8 encoding error (make).", NULL);
return Result(ret, pos);
}
int string8_null_local_(LocalRoot local, addr *ret, const char *name)
{
CheckLocal(local);
return string8_null_alloc_(local, ret, name);
}
int string8_null_heap_(addr *ret, const char *name)
{
return string8_null_alloc_(NULL, ret, name);
}
int string8_null_char1_heap_(addr *ret, const char *name, unicode c)
{
addr pos;
unicode *destroy;
size_t size;
if (UTF8_null_strlen((const byte *)name, &size))
return fmte_("UTF8 encoding error (length).", NULL);
strvect_alloc(NULL, &pos, size + 1UL);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF8_null_makeunicode(destroy, (const byte *)name))
return fmte_("UTF8 encoding error (make).", NULL);
destroy[size] = c;
return Result(ret, pos);
}
/*
* UTF-16
*/
int string16_size_alloc_(LocalRoot local, addr *ret, const byte16 *name, size_t size)
{
addr pos;
unicode *destroy;
size_t allsize;
if (UTF16_size_strlen(name, size, &allsize))
return fmte_("UTF16 encoding error (length).", NULL);
strvect_alloc(local, &pos, allsize);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF16_size_makeunicode(destroy, name, size))
return fmte_("UTF16 encoding error (make).", NULL);
return Result(ret, pos);
}
int string16_size_local_(LocalRoot local, addr *ret, const byte16 *name, size_t size)
{
CheckLocal(local);
return string16_size_alloc_(local, ret, name, size);
}
int string16_size_heap_(addr *ret, const byte16 *name, size_t size)
{
return string16_size_alloc_(NULL, ret, name, size);
}
int string16_null_alloc_(LocalRoot local, addr *ret, const byte16 *name)
{
addr pos;
unicode *destroy;
size_t size;
if (UTF16_null_strlen(name, &size))
return fmte_("UTF16 encoding error (length).", NULL);
strvect_alloc(local, &pos, size);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF16_null_makeunicode(destroy, name))
return fmte_("UTF16 encoding error (make).", NULL);
return Result(ret, pos);
}
int string16_null_local_(LocalRoot local, addr *ret, const byte16 *name)
{
CheckLocal(local);
return string16_null_alloc_(local, ret, name);
}
int string16_null_heap_(addr *ret, const byte16 *name)
{
return string16_null_alloc_(NULL, ret, name);
}
/*
* UTF-32
*/
int string32_size_alloc_(LocalRoot local, addr *ret, const unicode *name, size_t size)
{
addr pos;
unicode *destroy;
size_t allsize;
if (UTF32_size_strlen(name, size, &allsize))
return fmte_("UTF32 encoding error (length).", NULL);
strvect_alloc(local, &pos, allsize);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF32_size_makeunicode(destroy, name, size))
return fmte_("UTF32 encoding error (make).", NULL);
return Result(ret, pos);
}
int string32_size_local_(LocalRoot local, addr *ret, const unicode *name, size_t size)
{
CheckLocal(local);
return string32_size_alloc_(local, ret, name, size);
}
int string32_size_heap_(addr *ret, const unicode *name, size_t size)
{
return string32_size_alloc_(NULL, ret, name, size);
}
int string32_null_alloc_(LocalRoot local, addr *ret, const unicode *name)
{
addr pos;
unicode *destroy;
size_t size;
if (UTF32_null_strlen(name, &size))
return fmte_("UTF32 encoding error (length).", NULL);
strvect_alloc(local, &pos, size);
GetStringUnicode(pos, (const unicode **)&destroy);
if (UTF32_null_makeunicode(destroy, name))
return fmte_("UTF32 encoding error (make).", NULL);
return Result(ret, pos);
}
int string32_null_local_(LocalRoot local, addr *ret, const unicode *name)
{
CheckLocal(local);
return string32_null_alloc_(local, ret, name);
}
int string32_null_heap_(addr *ret, const unicode *name)
{
return string32_null_alloc_(NULL, ret, name);
}
/************************************************************
* variable.c
************************************************************/
/*
* build
*/
int lisp_initialize = 0;
addr lisp_root[LISPINDEX_SIZE];
addr lisp_nil_object = 0;
addr lisp_t_object = 0;
int lisp_info_enable = 1;
enum GcMode lisp_gcsync = GcMode_Off;
/*
* heap
*/
void *heap_alloc = 0;
addr heap_root = 0;
addr heap_front = 0;
addr heap_pos = 0;
addr heap_tail = 0;
addr heap_range = 0;
size_t heap_object = 0;
size_t heap_count = 0;
size_t heap_gc_count = 0;
size_t heap_gc_partial = 0;
size_t heap_gc_full = 0;
size_t heap_cons_count = 0;
size_t heap_symbol_count = 0;
/*
* control
*/
#ifdef LISP_DEBUG_FORCE_GC
size_t GcCounterForce = 0;
#endif
size_t ControlCounter = 0;
/*
* clos
*/
addr Clos_standard_class = 0;
addr Clos_standard_generic = 0;
addr Clos_standard_method = 0;
addr Clos_standard_combination = 0;
addr Clos_standard_specializer = 0;
/*
* execute
*/
threadlocal ThreadLocal_Execute;
threadlocal ThreadLocal_Index;
threadlocal ThreadLocal_Local;
lisp_abort_calltype Lisp_abort_handler = NULL;
/*
* pointer
*/
struct callbind_struct pointer_table[SizePointer];
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 23.07786 | 88 | 0.70095 | [
"object",
"vector"
] |
c29ead0db29bc19a120fb7f32bb738f3f6e4593d | 4,200 | h | C | engine/aer/rendering/mesh.h | tcoppex/aer-engine | bd52892d353f395e3de960a50371300a95d4ac95 | [
"MIT"
] | 36 | 2015-08-16T17:17:29.000Z | 2021-07-25T07:28:37.000Z | engine/aer/rendering/mesh.h | tcoppex/aer-engine | bd52892d353f395e3de960a50371300a95d4ac95 | [
"MIT"
] | 1 | 2020-06-14T17:38:27.000Z | 2020-06-14T17:38:27.000Z | engine/aer/rendering/mesh.h | tcoppex/aer-engine | bd52892d353f395e3de960a50371300a95d4ac95 | [
"MIT"
] | 7 | 2017-11-03T04:01:16.000Z | 2021-03-14T18:49:03.000Z | // -----------------------------------------------------------------------------
// CreativeCommons BY-SA 3.0 2013 <Thibault Coppex>
//
// -----------------------------------------------------------------------------
#ifndef AER_RENDERING_MESH_H_
#define AER_RENDERING_MESH_H_
#include <vector>
#include "aer/common.h"
#include "aer/rendering/drawable.h"
#include "aer/device/vertex_array.h"
#include "aer/device/device_buffer.h"
namespace aer {
/// + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ +
///
/// Represent a mesh on the device
///
/// + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ + ~ +
class Mesh : public Drawable {
public:
Mesh();
~Mesh();
/// Generate the number of vertex buffer needed by the mesh
/// + a index buffer if needed.
void init(U32 nBuffer, bool bUseIBO);
// Set the number of vertex sent to the device
void set_vertex_count(U32 nvertices) {
nvertices_ = nvertices;
}
/// Set the number of indices sent to the device
void set_index_count(U32 nindices) {
AER_CHECK(use_indices());
nindices_ = nindices;
}
// Specify how the vertices are rendered, default to GL_TRIANGLES
void set_primitive_mode(GLenum mode) {
primitive_mode_ = mode;
}
// Specify the internal type of indices, default to GL_UNSIGNED_INT
void set_indices_type(GLenum type) {
indices_type_ = type;
}
// Geometry attributes updates must be processed between those call
// to be valid.
void begin_update();
void end_update();
// Return a vbo given by index, fails if index is out of bound
DeviceBuffer& vbo(U32 index = 0u);
// Return the ibo, fails if it does not exist.
DeviceBuffer& ibo();
// Draw the whole mesh
void draw() const override;
// Draw the whole mesh n-time
void draw_instances(const U32 count) const override;
// Add a submesh
// - offset & nelems are relatives to indices OR vertices
// depending wether an index buffer is provided or not.
// - tag is optional and can be used to mark submesh properties (eg. materials)
// - Return the submesh's index
U32 add_submesh(UPTR offset, U32 nelems, I32 tag=0);
// Draw a single sub-mesh
void draw_submesh(U32 id) const;
// Return the number of vbo
U32 vbo_count() const { return vbos_.size(); }
// Return a submesh's tag
I32 submesh_tag(U32 id) const { return submeshes_[id].tag; }
// Return the number of submesh
U32 submesh_count() const { return submeshes_.size(); }
// Return true if index buffer is use for rendering
bool use_indices() const { return ibo_.is_generated(); }
private:
struct SubMeshInfo_t {
SubMeshInfo_t(UPTR offset, U32 nelems, I32 tag) :
offset(offset),
nelems(nelems),
tag(tag)
{}
UPTR offset;
U32 nelems;
I32 tag;
};
VertexArray vao_; // Vertex array
DeviceBuffer ibo_; // Indices buffer
std::vector<DeviceBuffer> vbos_; // Collection of vertex buffer
GLenum primitive_mode_; // How to render the vertices
GLenum indices_type_; // Indices internal type
U32 nvertices_; // Total number of vertices
U32 nindices_; // Total number of indices
std::vector<SubMeshInfo_t> submeshes_; // Collection of submesh infos
bool bInitialized;
};
} // namespace aer
#endif // AER_RENDERING_MESH_H_
#if 0
mesh.begin_update();
mesh.vbo().allocate(bytesize, GL_STATIC_READ);
mesh.vbo().upload(offset, bytesize, data);
//mesh.vbo().map();
//mesh.vbo().unmap();
mesh.set_vertex_count(nVertex);
glBindVertexBuffer(0, mesh.vbo().id(), baseOffset, sizeof(Vertex));
glVertexAttribFormat(0, 3, GL_FLOAT, GL_FALSE, offsetof(position, Vertex));
glVertexAttribFormat(1, 3, GL_FLOAT, GL_FALSE, offsetof(normal, Vertex));
glVertexAttribFormat(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, offsetof(color, Vertex));
glVertexAttribIFormat(3, 4, GL_UNSIGNED_BYTE, offsetof(index, Vertex));
for (U32 i = 0u; i < nAttribs; ++i) {
glVertexAttribBinding(i, 0); //attrib_binding[i];
glEnableVertexAttribArray(i)
}
mesh.end_update();
#endif | 29.370629 | 81 | 0.624524 | [
"mesh",
"geometry",
"render",
"vector"
] |
c2b0066674401cbcbd4bdf1a789988df9b42b7ce | 6,070 | h | C | src/ParametersForSolver.h | g1257/PsimagLite | 1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010 | [
"Unlicense"
] | 8 | 2015-08-19T16:06:52.000Z | 2021-12-05T02:37:47.000Z | src/ParametersForSolver.h | g1257/PsimagLite | 1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010 | [
"Unlicense"
] | 5 | 2016-02-02T20:28:21.000Z | 2019-07-08T22:56:12.000Z | src/ParametersForSolver.h | g1257/PsimagLite | 1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010 | [
"Unlicense"
] | 5 | 2016-04-29T17:28:00.000Z | 2019-11-22T03:33:19.000Z | /*
Copyright (c) 2009-2011, UT-Battelle, LLC
All rights reserved
[PsimagLite, Version 1.0.0]
[by G.A., Oak Ridge National Laboratory]
UT Battelle Open Source Software License 11242008
OPEN SOURCE LICENSE
Subject to the conditions of this License, each
contributor to this software hereby grants, free of
charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), a
perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable copyright license to use, copy,
modify, merge, publish, distribute, and/or sublicense
copies of the Software.
1. Redistributions of Software must retain the above
copyright and license notices, this list of conditions,
and the following disclaimer. Changes or modifications
to, or derivative works of, the Software should be noted
with comments and the contributor and organization's
name.
2. Neither the names of UT-Battelle, LLC or the
Department of Energy nor the names of the Software
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission of UT-Battelle.
3. The software and the end-user documentation included
with the redistribution, with or without modification,
must include the following acknowledgment:
"This product includes software produced by UT-Battelle,
LLC under Contract No. DE-AC05-00OR22725 with the
Department of Energy."
*********************************************************
DISCLAIMER
THE SOFTWARE IS SUPPLIED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER, CONTRIBUTORS, UNITED STATES GOVERNMENT,
OR THE UNITED STATES DEPARTMENT OF ENERGY 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.
NEITHER THE UNITED STATES GOVERNMENT, NOR THE UNITED
STATES DEPARTMENT OF ENERGY, NOR THE COPYRIGHT OWNER, NOR
ANY OF THEIR EMPLOYEES, REPRESENTS THAT THE USE OF ANY
INFORMATION, DATA, APPARATUS, PRODUCT, OR PROCESS
DISCLOSED WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS.
*********************************************************
*/
/** \ingroup PsimagLite */
/*@{*/
/*! \file ParametersForSolver.h
*
* Parameters to be able to use LanczosSolver and ChebyshevSolver together
*
* Note: This is a struct: Add no functions except ctor/dtor!
*/
#ifndef PARAMETERS_FOR_SOLVER_H
#define PARAMETERS_FOR_SOLVER_H
#include "ProgressIndicator.h"
#include "TridiagonalMatrix.h"
#include "Vector.h"
#include "Matrix.h"
#include "Random48.h"
#include "TypeToString.h"
namespace PsimagLite {
template<typename RealType_>
struct ParametersForSolver {
typedef RealType_ RealType;
static const SizeType MaxLanczosSteps = 1000000; // max number of internal Lanczos steps
static const SizeType LanczosSteps = 200; // max number of external Lanczos steps
ParametersForSolver()
: steps(LanczosSteps),
minSteps(4),
tolerance(1e-12),
stepsForEnergyConvergence(MaxLanczosSteps),
eigsForStop(1),
options(""),
oneOverA(0),
b(0),
Eg(0),
weight(0),
isign(0),
lotaMemory(false)
{}
template<typename IoInputType>
ParametersForSolver(IoInputType& io, String prefix, int ind = -1)
: steps(LanczosSteps),
minSteps(4),
tolerance(1e-12),
stepsForEnergyConvergence(MaxLanczosSteps),
eigsForStop(1),
options("none"),
oneOverA(0),
b(0),
Eg(0),
weight(0),
isign(0),
lotaMemory(true)
{
rabbitHole(steps, prefix, ind, "Steps", io);
rabbitHole(minSteps, prefix, ind, "MinSteps", io);
rabbitHole(tolerance, prefix, ind, "Eps", io);
rabbitHole(stepsForEnergyConvergence, prefix, ind, "StepsForEnergyConvergence", io);
rabbitHole(eigsForStop, prefix, ind, "EigsForStop", io);
rabbitHole(options, prefix, ind, "Options", io);
rabbitHole(oneOverA, prefix, ind, "OneOverA", io);
rabbitHole(b, prefix, ind, "B", io);
rabbitHole(Eg, prefix, ind, "Energy", io);
int x = 0;
rabbitHole(x, prefix, ind, "NoSaveLanczosVectors", io);
lotaMemory = (x > 0) ? 0 : 1;
}
template<typename T, typename IoInputType>
static void rabbitHole(T& t, String prefix, int ind, String postfix, IoInputType& io)
{
if (ind >= 0) {
bunnie(t, prefix, ind, postfix, io);
} else {
hare(t, prefix, postfix, io);
}
}
template<typename T, typename IoInputType>
static void hare(T& t, String prefix, String postfix, IoInputType& io)
{
// if prefix + postfix exists use it
try {
io.readline(t, prefix + postfix + "=");
return;
} catch (std::exception&) {}
}
template<typename T, typename IoInputType>
static void bunnie(T& t, String prefix, SizeType ind, String postfix, IoInputType& io)
{
// if prefix + ind + postfix exists --> use it and return
try {
io.readline(t, prefix + ttos(ind) + postfix + "=");
return;
} catch (std::exception&) {}
// if prefix + jnd + postfix exists with jnd < ind --> use the largest jnd and return
for (SizeType i = 0; i < ind; ++i) {
const SizeType jnd = ind - i - 1;
try {
io.readline(t, prefix + ttos(jnd) + postfix + "=");
return;
} catch (std::exception&) {}
}
hare(t, prefix, postfix, io);
}
SizeType steps;
SizeType minSteps;
RealType tolerance;
SizeType stepsForEnergyConvergence;
SizeType eigsForStop;
String options;
RealType oneOverA,b;
RealType Eg;
RealType weight;
int isign;
bool lotaMemory;
}; // class ParametersForSolver
} // namespace PsimagLite
/*@}*/
#endif //PARAMETERS_FOR_SOLVER_H
| 28.497653 | 89 | 0.709226 | [
"vector"
] |
c2b2c79e6a7167887895548720807483d0a407ab | 10,881 | c | C | ext/cumo/narray/gen/tmpl/gemm.c | Watson1978/cumo | df1c27a088911477809cee7d7c887e4b20fd4ab8 | [
"MIT"
] | null | null | null | ext/cumo/narray/gen/tmpl/gemm.c | Watson1978/cumo | df1c27a088911477809cee7d7c887e4b20fd4ab8 | [
"MIT"
] | null | null | null | ext/cumo/narray/gen/tmpl/gemm.c | Watson1978/cumo | df1c27a088911477809cee7d7c887e4b20fd4ab8 | [
"MIT"
] | null | null | null | <%
func_prefix =
case type_name
when 'sfloat'
'S'
when 'dfloat'
'D'
when 'scomplex'
'C'
when 'dcomplex'
'Z'
end
cutype =
case type_name
when 'sfloat'
'float'
when 'dfloat'
'double'
when 'scomplex'
'cuComplex'
when 'dcomplex'
'cuDoubleComplex'
end
%>
#define ROW_SIZE(na) ((na)->shape[(na)->ndim-2])
#define COL_SIZE(na) ((na)->shape[(na)->ndim-1])
#define CHECK_NARRAY_TYPE(x,t) \
if (CLASS_OF(x)!=(t)) { \
rb_raise(rb_eTypeError,"invalid NArray type (class)"); \
}
// Error Class ??
#define CHECK_DIM_GE(na,nd) \
if ((na)->ndim<(nd)) { \
rb_raise(cumo_na_eShapeError, \
"n-dimension=%d, but >=%d is expected", \
(na)->ndim, (nd)); \
}
#define CHECK_DIM_EQ(na1,nd) \
if ((na1)->ndim != (nd)) { \
rb_raise(cumo_na_eShapeError, \
"dimention mismatch: %d != %d", \
(na1)->ndim, (nd)); \
}
#define CHECK_SQUARE(name,na) \
if ((na)->shape[(na)->ndim-1] != (na)->shape[(na)->ndim-2]) { \
rb_raise(cumo_na_eShapeError,"%s is not square matrix",name); \
}
#define CHECK_SIZE_GE(na,sz) \
if ((na)->size < (size_t)(sz)) { \
rb_raise(cumo_na_eShapeError, \
"NArray size must be >= %"SZF"u",(size_t)(sz));\
}
#define CHECK_NON_EMPTY(na) \
if ((na)->size==0) { \
rb_raise(cumo_na_eShapeError,"empty NArray"); \
}
#define CHECK_SIZE_EQ(n,m) \
if ((n)!=(m)) { \
rb_raise(cumo_na_eShapeError, \
"size mismatch: %"SZF"d != %"SZF"d", \
(size_t)(n),(size_t)(m)); \
}
#define CHECK_SAME_SHAPE(na1,na2) \
{ int i; \
CHECK_DIM_EQ(na1,na2->ndim); \
for (i=0; i<na1->ndim; i++) { \
CHECK_SIZE_EQ(na1->shape[i],na2->shape[i]); \
} \
}
#define CHECK_INT_EQ(sm,m,sn,n) \
if ((m) != (n)) { \
rb_raise(cumo_na_eShapeError, \
"%s must be == %s: %s=%d %s=%d", \
sm,sn,sm,m,sn,n); \
}
// Error Class ??
#define CHECK_LEADING_GE(sld,ld,sn,n) \
if ((ld) < (n)) { \
rb_raise(cumo_na_eShapeError, \
"%s must be >= max(%s,1): %s=%d %s=%d", \
sld,sn,sld,ld,sn,n); \
}
#define COPY_OR_CAST_TO(a,T) \
{ \
if (CLASS_OF(a) == (T)) { \
if (!CUMO_TEST_INPLACE(a)) { \
a = cumo_na_copy(a); \
} \
} else { \
a = rb_funcall(T,rb_intern("cast"),1,a); \
} \
}
typedef struct {
dtype alpha, beta;
int m, n, k;
} gemm_args_t;
typedef struct {
int ld;
int stride; // in element count
cublasOperation_t trans;
VALUE a;
} gemm_layout_t;
static bool
is_f_contiguous(VALUE a)
{
int i;
ssize_t s0;
cumo_narray_t *na;
switch(CUMO_RNARRAY_TYPE(a)) {
case CUMO_NARRAY_DATA_T:
case CUMO_NARRAY_FILEMAP_T:
return CUMO_TEST_COLUMN_MAJOR(a);
case CUMO_NARRAY_VIEW_T:
CumoGetNArray(a, na);
// not contiguous if it has index
for (i = 0; i < CUMO_NA_NDIM(na); ++i) {
if (CUMO_NA_IS_INDEX_AT(na, i)) return false;
}
// check f-contiguous
s0 = cumo_na_element_stride(a);
for (i = 0; i < CUMO_NA_NDIM(na); ++i) {
if (CUMO_NA_SHAPE(na)[i] == 1) continue;
if (CUMO_NA_STRIDE_AT(na, i) != s0) return false;
s0 *= CUMO_NA_SHAPE(na)[i];
}
return true;
default:
rb_raise(rb_eArgError, "NArray type : %d is not supported", CUMO_RNARRAY_TYPE(a));
}
}
static bool
is_c_contiguous(VALUE a)
{
return cumo_na_check_contiguous(a) == Qtrue;
}
static gemm_layout_t
make_gemm_layout(VALUE a)
{
cumo_narray_t *na;
gemm_layout_t layout;
CumoGetNArray(a, na);
if (cumo_na_debug_flag) {
printf("ndim==2 && f_contiguous:%d, c_contiguous:%d\n",
CUMO_NA_NDIM(na) == 2 && is_f_contiguous(a), is_c_contiguous(a));
}
if (CUMO_NA_NDIM(na) == 2 && is_f_contiguous(a)) {
layout.ld = ROW_SIZE(na);
layout.trans = CUBLAS_OP_T;
layout.a = a;
} else {
layout.ld = COL_SIZE(na);
layout.trans = CUBLAS_OP_N; // transposed
// force c-contiguous
layout.a = is_c_contiguous(a) ? a : rb_funcall(a, rb_intern("dup"), 0);
}
layout.stride = ROW_SIZE(na) * COL_SIZE(na);
return layout;
}
extern int cumo_na_debug_flag; // narray.c
static void
print_gemm_args(gemm_args_t* g, gemm_layout_t* a_layout, gemm_layout_t* b_layout, int stridec, int batch_count)
{
printf("transb=%d transa=%d, n=%d, m=%d, k=%d, ldb=%d, lda=%d, ldc=n=%d, strideb=%d, stridea=%d stridec=%d batch_count=%d\n",
(int)b_layout->trans,
(int)a_layout->trans,
(int)g->n,
(int)g->m,
(int)g->k,
(int)b_layout->ld,
(int)a_layout->ld,
(int)g->n,
(int)b_layout->stride,
(int)a_layout->stride,
(int)stridec,
(int)batch_count);
}
static void
<%=c_iter%>(VALUE a, VALUE b, VALUE c, gemm_args_t *g)
{
gemm_layout_t a_layout, b_layout;
cublasHandle_t handle = 0;
cublasStatus_t status = 0;
cumo_narray_t* nc;
// Note that cuBLAS uses the column major matrix representation.
// We use technic which following site describes:
// https://www.christophlassner.de/using-blas-from-c-with-row-major-data.html
//
// b^T = nxk matrix
// a^T = kxm matrix
// c^T = nxm matrix
// c^T = b^T * a^T
//
// cublasSgemm(handle,transb,transa,n,m,k,&alpha,b,ldb,a,lda,&beta,c,ldc=n);
a_layout = make_gemm_layout(a);
b_layout = make_gemm_layout(b);
CumoGetNArray(c, nc);
int stridec = ROW_SIZE(nc) * COL_SIZE(nc);
int batch_count = CUMO_NA_SIZE(nc) / stridec;
if (cumo_na_debug_flag) print_gemm_args(g, &a_layout, &b_layout, stridec, batch_count);
handle = cumo_cuda_cublas_handle();
status = cublas<%=func_prefix%>gemmStridedBatched(
handle,
b_layout.trans,
a_layout.trans,
g->n,
g->m,
g->k,
(<%=cutype%>*)(&g->alpha),
(<%=cutype%>*)(cumo_na_get_pointer_for_read(b_layout.a) + cumo_na_get_offset(b_layout.a)),
b_layout.ld,
b_layout.stride,
(<%=cutype%>*)(cumo_na_get_pointer_for_read(a_layout.a) + cumo_na_get_offset(a_layout.a)),
a_layout.ld,
a_layout.stride,
(<%=cutype%>*)(&g->beta),
(<%=cutype%>*)(cumo_na_get_pointer_for_write(c) + cumo_na_get_offset(c)),
g->n,
stridec,
batch_count);
cumo_cuda_cublas_check_status(status);
}
/*
<%
# ext/numo/linalg/blas/gen/decl.rb
def mat(v,*a,**h)
tp = h[:type] || class_name
a.map!{|x| x==:inplace ? "inplace allowed" : x}
a.unshift ">=2-dimentional NArray"
"@param #{v} [#{tp}] matrix (#{a.join(', ')})."
end
def opt(v,tp=nil,*a)
tp ||= "String or Symbol"
case v
when "alpha"
"@param #{v} [Float] (default=1.0)"
when "beta"
"@param #{v} [Float] (default=0.0)"
else
"@param #{v} [#{tp}] #{a[0]}"
end
end
%>
<%
args_v = "a, b, [c, alpha:1, beta:0]"
params = [
mat("a"),
mat("b"),
mat("c","optional",:inplace),
opt("alpha"),
opt("beta"),
].select{|x| x}.join("\n ")
%>
@overload <%=name%>(<%=args_v%>)
<%=params%>
@return [<%=class_name%>] returns c = alpha\*op( A )\*op( B ) + beta\*C.
<%=description%>
*/
static VALUE
<%=c_func(-1)%>(int argc, VALUE argv[], VALUE self)
{
VALUE a=self, b, c=Qnil, alpha, beta;
cumo_narray_t *na, *nb;
gemm_args_t g;
VALUE kw_hash = Qnil;
ID kw_table[2] = {rb_intern("alpha"), rb_intern("beta")};
VALUE opts[2] = {Qundef, Qundef};
rb_scan_args(argc, argv, "11:", &b, &c, &kw_hash);
rb_get_kwargs(kw_hash, kw_table, 0, 2, opts);
alpha = cumo_cuda_cublas_option_value(opts[0],Qnil);
g.alpha = RTEST(alpha) ? m_num_to_data(alpha) : m_one;
beta = cumo_cuda_cublas_option_value(opts[1],Qnil);
g.beta = RTEST(beta) ? m_num_to_data(beta) : m_zero;
CumoGetNArray(a, na);
CumoGetNArray(b, nb);
CHECK_DIM_GE(na, 2);
CHECK_DIM_GE(nb, 2);
if (ROW_SIZE(nb) != COL_SIZE(na)) {
rb_raise(cumo_na_eShapeError,"ROW_SIZE(b)=%d must equal to COL_SIZE(a)=%d",
(int)ROW_SIZE(nb), (int)COL_SIZE(na));
}
g.m = ROW_SIZE(na);
g.k = COL_SIZE(na);
g.n = COL_SIZE(nb);
if (c == Qnil) { // c is not given.
int ndim = CUMO_NA_NDIM(na);
size_t *shape = ALLOCA_N(size_t, ndim);
memcpy(shape, CUMO_NA_SHAPE(na), sizeof(size_t) * (ndim - 1)); // ... x m x k
shape[ndim - 1] = g.n; // ... x m x n
c = cumo_na_new(cT, ndim, shape);
} else {
cumo_narray_t *nc;
COPY_OR_CAST_TO(c, cT);
CumoGetNArray(c, nc);
CHECK_DIM_GE(nc, 2);
if (ROW_SIZE(nc) != ROW_SIZE(na)) {
rb_raise(cumo_na_eShapeError,"ROW_SIZE(c)=%d must equal to ROW_SIZE(a)=%d",
(int)ROW_SIZE(nc), (int)ROW_SIZE(na));
}
if (COL_SIZE(nc) != COL_SIZE(nb)) {
rb_raise(cumo_na_eShapeError,"COL_SIZE(c)=%d must equal to COL_SIZE(b)=%d",
(int)COL_SIZE(nc), (int)COL_SIZE(nc));
}
}
<%=c_iter%>(a, b, c, &g);
return c;
}
| 31.447977 | 129 | 0.475416 | [
"shape"
] |
c2b3c88737e961ec89396edf583cac83027524bb | 5,404 | h | C | intecplot.h | nompelis/INTecplotLib | 0f415816b7969450b11e3eb387a6519207f6c259 | [
"BSD-4-Clause"
] | 4 | 2018-06-08T13:45:35.000Z | 2019-04-26T17:46:28.000Z | intecplot.h | nompelis/INTecplotLib | 0f415816b7969450b11e3eb387a6519207f6c259 | [
"BSD-4-Clause"
] | null | null | null | intecplot.h | nompelis/INTecplotLib | 0f415816b7969450b11e3eb387a6519207f6c259 | [
"BSD-4-Clause"
] | null | null | null | /******************************************************************************
Copyright (c) 2017-2020, Ioannis Nompelis
All rights reserved.
Redistribution and use in source and binary forms, with or without any
modification, are permitted provided that the following conditions are met:
1. Redistribution of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistribution in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
"This product includes software developed by Ioannis Nompelis."
4. Neither the name of Ioannis Nompelis and his partners/affiliates nor the
names of other contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
5. Redistribution or use of source code and binary forms for profit must
have written permission of the copyright holder.
THIS SOFTWARE IS PROVIDED BY IOANNIS NOMPELIS ''AS IS'' AND ANY
EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL IOANNIS NOMPELIS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef _INTECPLOT_H_
#define _INTECPLOT_H_
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <vector>
#include <map>
#include <string>
#ifdef __cplusplus
extern "C" {
#endif
//
// a zone object
//
class inTec_File; // forward declaration
class inTec_Zone {
public:
inTec_Zone( inTec_File* file_ );
virtual ~inTec_Zone();
int GetState( void ) const;
int GetType( void ) const; // return value is enum-ed
long GetPositionInFile( void ) const;
int NotifyPositionInFile( long ipos_ );
long GetDataPositionInFile( void ) const;
int NotifyDataPositionInFile( long ipos_data_ );
int ParseKeywords( char *buf );
int HandleKeyword( char *buf );
int SetState_Reading( void );
int ParseNumericData( char *buf );
int Dump( const char *file );
int WriteFileSTL( char filename_[], double rdir ) const;
const double* GetVariablePtr( int ivar_ ) const;
int GetNumVariables() const;
unsigned long GetNumIndices( int idir ) const;
unsigned long GetNumNodes() const;
unsigned long GetNumElements() const;
unsigned long GetNumNodesPerElement() const;
const unsigned long* GetConnectivityPtr() const;
void clear();
protected:
void InitKeywords();
int istate;
char *tkey;
int ietype,idatapack;
int num_var, parent_zone, nv;
unsigned long im,jm,km,nodes,elems;
std::map< int, int > ivar_loc;
std::vector< double * > var_vec;
unsigned long *icon,ncon;
// old-style variables
unsigned long iold_n, iold_e;
int iold_et, iold_f;
private:
inTec_File *file;
long ipos,ipos_data,ipos_conn;
std::map< std::string, std::string > keywords;
int CheckCharForNum( char c ) const;
int ManageInternals( void );
int HandleKeyword_T( const char *string );
int HandleKeyword_ET( const char *string );
int HandleKeyword_Varlocation( const char *string );
int HandleKeyword_Datapacking( const char *string );
int HandleKeyword_Zonetype( const char *string );
int HandleKeyword_Varsharelist( const char *string );
int ConsistencyCheck( void );
// variables to aid in the parsing of numeric part
int iparse_num;
unsigned long node_cnt, elem_cnt;
int var_cnt;
unsigned long icon_cnt;
// various methods that act as helpers
int GetElementNodes( unsigned long n, int & no, unsigned long *icon_ );
};
//
// a file object
//
class inTec_File {
public:
inTec_File( char *fname_ );
virtual ~inTec_File();
int OpenRead();
int Close();
int Parse();
int GetState( void ) const;
FILE* GetFP( void ) const;
int GetNumVariables( void ) const;
const char* GetVariableName( int nvar_ ) const;
inTec_Zone* GetZone( int i );
protected:
int ParseLoop();
int IdentifyComponent( char *line_buf );
int IsComponent( char *line_buf );
int ParseComponent_Header( int iop, char *line_buf );
int ParseComponent_HeaderVariables( char *line_buf );
int ParseComponent_Zone();
int ParseComponent_Text();
int ParseComponent_Geometry();
private:
int istate;
char name[256]; // "infinity is set to 256"
FILE *fp;
long nline,iline;
long ipos;
std::map< unsigned long, std::string > strings;
std::vector< std::string > variables;
std::vector< inTec_Zone * > zones;
// std::vector< inTec_Text * > texts;
// std::vector< inTec_Geometry * > geometries;
};
#ifdef __cplusplus
}
#endif
#endif
| 30.189944 | 80 | 0.705774 | [
"object",
"vector"
] |
c2c4d76c22aa0e75e0695b76916a1cd4f32f1ddf | 3,309 | h | C | avstream/avscamera/sys/Ref.h | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 3,084 | 2015-03-18T04:40:32.000Z | 2019-05-06T17:14:33.000Z | avstream/avscamera/sys/Ref.h | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 275 | 2015-03-19T18:44:41.000Z | 2019-05-06T14:13:26.000Z | avstream/avscamera/sys/Ref.h | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 3,091 | 2015-03-19T00:08:54.000Z | 2019-05-06T16:42:01.000Z | /**************************************************************************
A/V Stream Camera Sample
Copyright (c) 2014, Microsoft Corporation.
File:
ref.h
Abstract:
Implement a reference counting base class. Also implement something
similar to ComPtr<>, called a CRefPtr<>. The implementation may not
be as robust as ComPtr<>, but it should do the job here.
History:
created 12/8/2014
**************************************************************************/
#pragma once
class CRef : public CNonCopyable
{
private:
EX_RUNDOWN_REF m_Rundown;
public:
// Initialize.
CRef()
{
Reset();
}
// Prevent deletion until the last reference is gone.
~CRef()
{
Wait();
}
// Increment the reference.
BOOLEAN
Acquire()
{
return ExAcquireRundownProtection( &m_Rundown );
}
// Decrement the reference.
void
Release()
{
return ExReleaseRundownProtection( &m_Rundown );
}
// Wait for the last reference to go away.
// Note: This must be called by the child object's destructor.
void
Wait()
{
ExWaitForRundownProtectionRelease( &m_Rundown );
}
// Reinitialize to reuse the associated object.
void
Reset()
{
ExInitializeRundownProtection( &m_Rundown );
}
};
template<class T>
class CRefPtr
{
private:
T *m_ptr;
public:
CRefPtr()
: m_ptr(nullptr)
{}
// Copy constructor.
CRefPtr( const CRefPtr<T> &ptr )
: m_ptr(nullptr)
{
// Make an initial assignment.
if( ptr && ptr->Acquire() )
{
m_ptr = ptr;
}
}
// Initial construction with a T object.
CRefPtr( T *ptr )
: m_ptr(nullptr)
{
// Make an initial assignment.
if( ptr && ptr->Acquire() )
{
m_ptr = ptr;
}
}
// Decrement the reference on destruction.
~CRefPtr()
{
// Free any ptr.
if( m_ptr )
{
m_ptr->Release();
}
}
// Assignment
CRefPtr<T> &
operator = ( T *ptr )
{
if( m_ptr )
{
m_ptr->Release();
}
if( ptr )
{
ptr->Acquire();
}
m_ptr = ptr;
return *this;
}
// Assignment
CRefPtr<T> &
operator = ( CRefPtr<T> &ptr )
{
return
(*this = ptr.m_ptr);
}
// Dereference the pointer.
T *
operator -> ()
{
return m_ptr;
}
// Test for nullptr.
operator bool()
{
return m_ptr != nullptr;
}
// Test for !nullptr.
bool
operator !()
{
return !m_ptr;
}
// Test for equality.
bool
operator ==( T *ptr )
{
return m_ptr == ptr;
}
// Unsafe accessor. Use sparingly.
T *
get()
{
return m_ptr;
}
};
// Test for equality.
template <class T>
inline
bool
operator ==( T *ptr1, CRefPtr<T> &ptr2 )
{
return ptr2 == ptr1;
}
| 17.790323 | 78 | 0.453007 | [
"object"
] |
9053525511c7983776198b87db927adcd7f2d597 | 592 | h | C | RecoTracker/TkDetLayers/src/TIDLayerBuilder.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoTracker/TkDetLayers/src/TIDLayerBuilder.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoTracker/TkDetLayers/src/TIDLayerBuilder.h | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #ifndef TkDetLayers_TIDLayerBuilder_h
#define TkDetLayers_TIDLayerBuilder_h
#include "TIDLayer.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
#include "Geometry/TrackerNumberingBuilder/interface/GeometricDet.h"
/** A concrete builder for TIDLayer
*/
#pragma GCC visibility push(hidden)
class TIDLayerBuilder {
public:
TIDLayerBuilder(){};
TIDLayer* build(const GeometricDet* aTIDLayer,
const TrackerGeometry* theGeomDetGeometry) __attribute__ ((cold));
};
#pragma GCC visibility pop
#endif
| 21.925926 | 70 | 0.787162 | [
"geometry"
] |
9055f75f8d87a4748da3d63e36ba4186f2553fd0 | 1,478 | h | C | Lite Foundation/Source/LFArchiver.h | JustSid/Lite-C | 3ae5cc2fda2ebcd4f5b0f532ffec8a37e37512b6 | [
"MIT"
] | 1 | 2021-12-31T16:30:38.000Z | 2021-12-31T16:30:38.000Z | Lite Foundation/Source/LFArchiver.h | JustSid/Lite-C | 3ae5cc2fda2ebcd4f5b0f532ffec8a37e37512b6 | [
"MIT"
] | null | null | null | Lite Foundation/Source/LFArchiver.h | JustSid/Lite-C | 3ae5cc2fda2ebcd4f5b0f532ffec8a37e37512b6 | [
"MIT"
] | null | null | null | //
// LFArchiver.h
// Lite Foundation
//
// Created by Sidney Just on 22.06.11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#ifndef _LFARCHIVER_H_
#define _LFARCHIVER_H_
#include "LFBase.h"
#include "LFRuntime.h"
#include "LFProtocol.h"
#include "LFString.h"
#include "LFData.h"
#include "LFDictionary.h"
struct __LFArchiver
{
LFRuntimeBase base;
LFDictionaryRef objects;
LFDataRef data;
uint8_t finished;
};
typedef struct __LFArchiver* LFArchiverRef;
LF_EXPORT LFProtocolSel LFArchiverArchiveSelector();
LF_EXPORT LFProtocolID LFArchiverGetProtocolID();
LF_EXPORT LFArchiverRef LFArchiverCreateWithData(LFDataRef data);
LF_EXPORT LFDataRef LFArchiverArchivedObject(LFTypeRef object);
LF_EXPORT void LFArchiverArchiveBytes(LFArchiverRef archiver, uint8_t *bytes, uint32_t length, LFStringRef key);
LF_EXPORT void LFArchiverArchiveInt(LFArchiverRef archiver, int value, LFStringRef key);
LF_EXPORT void LFArchiverArchiveShort(LFArchiverRef archiver, short value, LFStringRef key);
LF_EXPORT void LFArchiverArchiveChar(LFArchiverRef archiver, char value, LFStringRef key);
LF_EXPORT void LFArchiverArchiveFloat(LFArchiverRef archiver, float value, LFStringRef key);
LF_EXPORT void LFArchiverArchiveDouble(LFArchiverRef archiver, double value, LFStringRef key);
LF_EXPORT void LFArchiverArchiveObject(LFArchiverRef archiver, LFTypeRef value, LFStringRef key);
LF_EXPORT void LFArchiverFinish(LFArchiverRef archiver);
#endif
| 30.791667 | 112 | 0.811908 | [
"object"
] |
905c64c86675d880244b3915a6f79f1385238705 | 6,369 | c | C | lab6/3d trans/trans_p1.c | rahul0324/Computer-Graphics-Lab | eeff1749c32a1cbd3e1e481a40e280c8b945688e | [
"MIT"
] | null | null | null | lab6/3d trans/trans_p1.c | rahul0324/Computer-Graphics-Lab | eeff1749c32a1cbd3e1e481a40e280c8b945688e | [
"MIT"
] | null | null | null | lab6/3d trans/trans_p1.c | rahul0324/Computer-Graphics-Lab | eeff1749c32a1cbd3e1e481a40e280c8b945688e | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<math.h>
#include<GL/glut.h>
typedef float Matrix4 [4][4];
Matrix4 theMatrix;
GLfloat input[5][3]=
{
{0,25,0},{-25,-25,25},{25,-25,25},{25,-25,-25},{-25,-25,-25}
};
float output[5][3];
float tx,ty,tz;
float sx,sy,sz;
float angle;
int choice,choiceRot;
void setIdentityM(Matrix4 m)
{
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
m[i][j]=(i==j);
}
void translate(int tx,int ty,int tz)
{
for(int i=0;i<8;i++)
{
output[i][0]=input[i][0]+tx;
output[i][1]=input[i][1]+ty;
output[i][2]=input[i][2]+tz;
}
}
void scale(int sx,int sy,int sz)
{
theMatrix[0][0]=sx;
theMatrix[1][1]=sy;
theMatrix[2][2]=sz;
}
void RotateX(float angle) //Parallel to x
{
angle = angle*3.142/180;
theMatrix[1][1] = cos(angle);
theMatrix[1][2] = -sin(angle);
theMatrix[2][1] = sin(angle);
theMatrix[2][2] = cos(angle);
}
void RotateY(float angle) //parallel to y
{
angle = angle*3.14/180;
theMatrix[0][0] = cos(angle);
theMatrix[0][2] = -sin(angle);
theMatrix[2][0] = sin(angle);
theMatrix[2][2] = cos(angle);
}
void RotateZ(float angle) //parallel to z
{
angle = angle*3.14/180;
theMatrix[0][0] = cos(angle);
theMatrix[0][1] = sin(angle);
theMatrix[1][0] = -sin(angle);
theMatrix[1][1] = cos(angle);
}
void ReflectX()
{
for(int i=0;i<8;i++)
for(int j=0;j<3;j++)
{ if(j==0)
output[i][j]=-1*input[i][j];
else
output[i][j]=input[i][j];
}
}
void ReflectY()
{
for(int i=0;i<8;i++)
for(int j=0;j<3;j++)
{ if(j==1)
output[i][j]=-1*input[i][j];
else
output[i][j]=input[i][j];
}
}
void ReflectZ()
{
for(int i=0;i<8;i++)
for(int j=0;j<3;j++)
{ if(j==2)
output[i][j]=-1*input[i][j];
else
output[i][j]=input[i][j];
}
}
void multiplyM()
{
for(int i=0;i<8;i++)
{
for(int j=0;j<3;j++)
{
output[i][j]=0;
for(int k=0;k<3;k++)
{
output[i][j]=output[i][j]+input[i][k]*theMatrix[k][j];
//printf("%f ",output[i][j]+input[i][k]*theMatrix[k][j]);
}
}
}
}
void scalenew(int sx,int sy,int sz)
{
for(int i=0;i<8;i++)
{
for(int j=0;j<3;j++)
{ if(i==0)
output[i][j]=input[i][j]*sx;
if(i==1)
output[i][j]=input[i][j]*sy;
if(i==2)
output[i][j]=input[i][j]*sz;
}
}
}
void Axes(void)
{
glColor3f (0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex2s(-1000 ,0);
glVertex2s( 1000 ,0);
glEnd();
glBegin(GL_LINES);
glVertex2s(0 ,-1000);
glVertex2s(0 , 1000);
glEnd();
}
void draw2()
{
glBegin(GL_TRIANGLES);
// Front
glColor3f(1,0,0);
glVertex3fv(input[0]);
glVertex3fv(input[1]);
glVertex3fv(input[2]);
glColor3f(1,1,0);
glVertex3fv(input[0]);
glVertex3fv(input[2]);
glVertex3fv(input[3]);
glColor3f(0,1,0);
glVertex3fv(input[0]);
glVertex3fv(input[3]);
glVertex3fv(input[4]);
glColor3f(1,0,1);
glVertex3fv(input[0]);
glVertex3fv(input[4]);
glVertex3fv(input[1]);
// glColor3f(1.0f, 0.0f, 0.0f); // Red
// glVertex3f( 0.0f+sx, 1.0f+sy, 0.0f+sz);
// glVertex3f(-1.0f+sx, -1.0f+sy, 1.0f+sz);
// glVertex3f(1.0f+sx, -1.0f+sy, 1.0f+sz);
// Right
// glColor3f(0.0f, 1.0f, 0.0f); // Green
// glVertex3f(0.0f+sx, 1.0f+sy, 0.0f+sz);
// glVertex3f(1.0f+sx, -1.0f+sy, 1.0f+sz);
// glVertex3f(1.0f+sx, -1.0f+sy, -1.0f+sz);
// // Back
// glColor3f(0.0f, 0.0f, 1.0f); // Blue
// glVertex3f(0.0f+sx, 1.0f+sy, 0.0f+sz);
// glVertex3f(1.0f+sx, -1.0f+sy, -1.0f+sz);
// glVertex3f(-1.0f+sx, -1.0f+sy, -1.0f+sz);
// // Left
// glColor3f(1.0f,1.0f,0.0f); // Yellow
// glVertex3f( 0.0f+sx, 1.0f+sy, 0.0f+sz);
// glVertex3f(-1.0f+sx,-1.0f+sy,-1.0f+sz);
// glVertex3f(-1.0f+sx,-1.0f+sy, 1.0f+sz);
glEnd();
}
void draw1()
{glBegin(GL_TRIANGLES);
// Front
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
// Right
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, 1.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
// Back
glColor3f(0.0f, 0.0f, 1.0f); // Blue
glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(1.0f, -1.0f, -1.0f);
glVertex3f(-1.0f, -1.0f, -1.0f);
// Left
glColor3f(1.0f,1.0f,0.0f); // Yellow
glVertex3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glEnd();
}
void init()
{
glClearColor(1.0,1.0,1.0,1.0); //set backgrond color to white
glOrtho(-454.0,454.0,-250.0,250.0,-250.0,250.0);
glEnable(GL_DEPTH_TEST);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
Axes();
glColor3f(1.0,0.0,0.0);
draw1();
setIdentityM(theMatrix);
switch(choice)
{
case 1:
draw2();
break;
case 2:{
//scalenew(sx,sy,sz);
scale(sx,sy,sz);
multiplyM();
break;}
case 3:
// ReflectX();
// break;
switch(choiceRot)
{
case 1:ReflectX();
break;
case 2:ReflectY();
break;
case 3:ReflectZ();
break;
}
break;
}
draw2();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(1362,750);
glutInitWindowPosition(0,0);
glutCreateWindow("3D TRANSFORMATIONS");
init();
printf("Enter your choice number:\n1.Translation\n2.Scaling\n3.Reflection\n=>");
scanf("%d",&choice);
switch (choice) {
case 1:
printf("\nEnter Tx,Ty &Tz: \n");
scanf("%f%f%f",&sx,&sy,&sz);
break;
case 2:
printf("\nEnter Sx,Sy & Sz: \n");
scanf("%f%f%f",&sx,&sy,&sz);
break;
case 3:
printf("axis:1.X-axis.2.Y-axis.3.Z-axis.\n");
scanf("%d",&choiceRot);
break;
default:
break;
}
glutDisplayFunc(display);
glutMainLoop();
return 0;
} | 21.019802 | 84 | 0.507301 | [
"3d"
] |
90646d9907e2f31db9bc2427a252402c0be1ca04 | 6,684 | h | C | avr/core/lib/AVRTools/RingBufferT.h | MatzeS/blackbird_java | 9c7e50b2e1fa99ccfb2aa7beefe420d8cc4b74ee | [
"MIT"
] | 1 | 2019-04-27T13:46:52.000Z | 2019-04-27T13:46:52.000Z | avr/core/lib/AVRTools/RingBufferT.h | MatzeS/blackbird_java | 9c7e50b2e1fa99ccfb2aa7beefe420d8cc4b74ee | [
"MIT"
] | null | null | null | avr/core/lib/AVRTools/RingBufferT.h | MatzeS/blackbird_java | 9c7e50b2e1fa99ccfb2aa7beefe420d8cc4b74ee | [
"MIT"
] | null | null | null | /*
RingBufferT.h - A ring buffer template class for AVR processors.
For AVR ATMega328p (Arduino Uno) and ATMega2560 (Arduino Mega).
This is part of the AVRTools library.
Copyright (c) 2014 Igor Mikolic-Torreira. All right reserved.
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*!
* \file
*
* \brief This file provides a very flexible, template-based ring buffer implementation.
*
* Ring buffers are versatile storage structures. This file provides a template-based
* ring buffer implementation that can store different kinds of objects in
* buffers of whatever size is needed.
*/
#ifndef RingBufferT_h
#define RingBufferT_h
#include <util/atomic.h>
/*!
* \brief a template-based ring buffer class that can store different kinds of objects in
* buffers of whatever size is needed.
*
* The implementation of RingBufferT is interrupt safe: the key operations are atomic, allowing for RingBuffer
* objects to be shared between interrupt functions and ordinary code.
*
* The template-based RingBufferT class provides a very flexible ring buffer implementation; however
* different instantiations of RingBufferT (e.g., RingBufferT\< char, int, 32 \> and RingBufferT\< char, int, 16 \>)
* result in replicated code for each instantiation, even when they could logically share code. For
* a more efficient ring buffer that avoids such code bloat but can only store bytes, use RingBuffer.
*
* \tparam T is the type of object that will be stored in the RingBufferT instantiation.
* \tparam N is the integer type that will be used to index the RingBufferT elements.
* \tparam SIZE is an integer indicating the size of the RingBufferT instantiation.
*
*/
template< typename T, typename N, unsigned int SIZE > class RingBufferT
{
public:
/*!
* \brief Construct a ring buffer to store elements of type T indexed by
* integer type N, with size SIZE. All of these are passed as template parameters. *
*/
RingBufferT()
: mSize( SIZE ), mLength( 0 ), mIndex( 0 )
{}
/*!
* \brief Extract the next (first) element from the ring buffer.
*
* \note There is no
* general purpose safe value to return to indicate an empty buffer, so before
* calling pull() be sure to check the ring buffer is not empty.
*
* \returns the next element.
*/
T pull()
{
T element = 0;
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
if ( mLength )
{
element = mBuffer[ mIndex ];
mIndex++;
if ( mIndex >= mSize )
{
mIndex -= mSize;
}
--mLength;
}
}
return element;
}
/*!
* \brief Examine an element in the ring buffer.
*
* \arg \c index the element to examine; 0 means the first (= next) element in the buffer.
* The default if the argument is omitted is to return the first element.
*
* \note There is no
* general purpose safe value to return to indicate an empty element, so before
* calling peek() be sure the element exists.
*
* \returns the next element.
*/
T peek( N index = 0 )
{
T element;
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
element = mBuffer[ ( mIndex + index ) % mSize ];
}
return element;
}
/*!
* \brief Push an element into the ring buffer. The element is appended to the back
* of the buffer.
*
* \arg \c element is the item to append to the ring buffer.
*
* \returns 0 (false) if it succeeds; 1 (true) if it fails because the buffer is full.
*/
bool push( T element )
{
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
if ( mLength < mSize )
{
mBuffer[ ( mIndex + mLength ) % mSize ] = element;
++mLength;
return 0;
}
}
// True = failure
return 1;
}
/*!
* \brief Determine if the buffer is empty .
*
* \returns true if the buffer is empty; false if not.
*/
bool isEmpty()
{
return !static_cast<bool>( mLength );
}
/*!
* \brief Determine if the buffer is not empty.
*
* \returns true if the buffer is not empty; false if it is empty.
*/
bool isNotEmpty()
{
return static_cast<bool>( mLength );
}
/*!
* \brief Determine if the buffer is full and cannot accept more bytes.
*
* \returns true if the buffer is full; false if not.
*/
bool isFull()
{
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
return ( mSize - mLength ) <= 0;
}
}
/*!
* \brief Determine if the buffer is not full and can accept more bytes.
*
* \returns true if the buffer is not full; false if it is full.
*/
bool isNotFull()
{
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
return ( mSize - mLength ) > 0;
}
}
/*!
* \brief discard a number of elements from the front of the ring buffer.
*
* \arg \c nbrElements the number of elements to discard.
*/
void discardFromFront( N nbrElements )
{
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
if ( nbrElements < mLength )
{
mIndex += nbrElements;
if( mIndex >= mSize )
{
mIndex -= mSize;
}
mLength -= nbrElements;
}
else
{
// flush the whole buffer
mLength = 0;
}
}
}
/*!
* \brief Clear the ring buffer, leaving it empty.
*/
void clear()
{
ATOMIC_BLOCK( ATOMIC_RESTORESTATE )
{
mLength = 0;
}
}
private:
T mBuffer[ SIZE ] ;
volatile N mSize;
volatile N mLength;
volatile N mIndex;
};
#endif
| 26.418972 | 116 | 0.587672 | [
"object"
] |
907252b5d4e8eccc5e16d7dd239b83f0bbfc36f7 | 16,980 | h | C | src/qt/walletmodel.h | maxmaxj/ipchain | 99c1943ca65fd4acdef5b4eb5e75c4bee3d59365 | [
"MIT"
] | 34 | 2018-01-25T10:29:35.000Z | 2021-04-22T18:40:40.000Z | src/qt/walletmodel.h | joshuabond/ipchain | 5bd6792b1754890fae6648bec9d60519b55406cd | [
"MIT"
] | 9 | 2018-07-25T09:41:40.000Z | 2021-03-05T16:13:01.000Z | src/qt/walletmodel.h | joshuabond/ipchain | 5bd6792b1754890fae6648bec9d60519b55406cd | [
"MIT"
] | 11 | 2018-01-28T03:02:44.000Z | 2022-01-09T04:26:23.000Z | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_WALLETMODEL_H
#define BITCOIN_QT_WALLETMODEL_H
#include "paymentrequestplus.h"
#include "walletmodeltransaction.h"
#include "support/allocators/secure.h"
#include <map>
#include <vector>
#include <QVector>
#include <QObject>
#include <QDate>
class AddressTableModel;
class OptionsModel;
class PlatformStyle;
class RecentRequestsTableModel;
class TransactionTableModel;
class WalletModelTransaction;
class CValidationState;
class CCoinControl;
class CKeyID;
class COutPoint;
class COutput;
class CPubKey;
class CWallet;
class uint256;
class CWalletTx;
class UnionAddressInfo;
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
class SendCoinsRecipient
{
public:
explicit SendCoinsRecipient() : amount(0), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) { }
explicit SendCoinsRecipient(const QString &addr, const QString &_label, const CAmount& _amount, const QString &_message):
address(addr), label(_label), amount(_amount), message(_message), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) {}
QString address;
QString label;
CAmount amount;
// If from a payment request, this is used for storing the memo
QString message;
// If from a payment request, paymentRequest.IsInitialized() will be true
PaymentRequestPlus paymentRequest;
// Empty if no authentication or invalid signature/cert/etc.
QString authenticatedMerchant;
bool fSubtractFeeFromAmount; // memory only
static const int CURRENT_VERSION = 1;
int nVersion;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
std::string sAddress = address.toStdString();
std::string sLabel = label.toStdString();
std::string sMessage = message.toStdString();
std::string sPaymentRequest;
if (!ser_action.ForRead() && paymentRequest.IsInitialized())
paymentRequest.SerializeToString(&sPaymentRequest);
std::string sAuthenticatedMerchant = authenticatedMerchant.toStdString();
READWRITE(this->nVersion);
READWRITE(sAddress);
READWRITE(sLabel);
READWRITE(amount);
READWRITE(sMessage);
READWRITE(sPaymentRequest);
READWRITE(sAuthenticatedMerchant);
if (ser_action.ForRead())
{
address = QString::fromStdString(sAddress);
label = QString::fromStdString(sLabel);
message = QString::fromStdString(sMessage);
if (!sPaymentRequest.empty())
paymentRequest.parse(QByteArray::fromRawData(sPaymentRequest.data(), sPaymentRequest.size()));
authenticatedMerchant = QString::fromStdString(sAuthenticatedMerchant);
}
}
};
/** Interface to Bitcoin wallet from Qt view code. */
class WalletModel : public QObject
{
Q_OBJECT
public:
explicit WalletModel(const PlatformStyle *platformStyle, CWallet *wallet, OptionsModel *optionsModel, QObject *parent = 0);
~WalletModel();
enum StatusCode // Returned by sendCoins
{
OK,
InvalidAmount,
InvalidAddress,
AmountExceedsBalance,
AmountWithFeeExceedsBalance,
DuplicateAddress,
TransactionCreationFailed, // Error returned when wallet is still locked
TransactionCommitFailed,
AbsurdFee,
PaymentRequestExpired,
PsdErr,
NumErr,
InitErr
};
enum EncryptionStatus
{
Unencrypted, // !wallet->IsCrypted()
Locked, // wallet->IsCrypted() && wallet->IsLocked()
Unlocked // wallet->IsCrypted() && !wallet->IsLocked()
};
OptionsModel *getOptionsModel();
AddressTableModel *getAddressTableModel();
TransactionTableModel *getTransactionTableModel();
RecentRequestsTableModel *getRecentRequestsTableModel();
CAmount getBalance(const CCoinControl *coinControl = NULL) const;
CAmount GetDetained() const;
int GetDepth() const;
uint64_t getpow10(uint64_t oldnum,int n);
CAmount getUnconfirmedBalance() const;
CAmount getImmatureBalance() const;
bool haveWatchOnly() const;
CAmount getWatchBalance() const;
CAmount getWatchUnconfirmedBalance() const;
CAmount getWatchImmatureBalance() const;
EncryptionStatus getEncryptionStatus() const;
// Check address for validity
bool validateAddress(const QString &address);
// Return status record for SendCoins, contains error id + information
struct SendCoinsReturn
{
SendCoinsReturn(StatusCode _status = OK, QString _reasonCommitFailed = "")
: status(_status),
reasonCommitFailed(_reasonCommitFailed)
{
}
StatusCode status;
QString reasonCommitFailed;
};
struct CBookKeep
{
std::string time;
std::string award;
};
struct keepupaccountInfo{
CAmount Coin_;
QString Add_;
};
void getbookkeepList(std::vector<WalletModel::CBookKeep>& bookkeeplist);
//20180201
void startTimerControl();
QString processeCoinsCreateReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn);
SendCoinsReturn prepareeCoinsCreate(QString coin_name,QString coin_md5,QString coin_label,QString timestr,QString add1,QString &msg,int inttimr,int accuracy,uint64_t amount1);
//20180201
// prepare transaction for getting txfee before sending coins
SendCoinsReturn prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareBookkeepingTransaction(QString add1,CAmount amount1,std::string &error,WalletModelTransaction &transaction, const CCoinControl *coinControl);
SendCoinsReturn sendBookkeeping(QString add2,WalletModelTransaction &transaction);
SendCoinsReturn prepareExitBookkeeping(const CCoinControl *coinControl,std::string &error);
SendCoinsReturn ExitBookkeeping(WalletModelTransaction &transaction);
SendCoinsReturn prepareeCoinsCreateTransaction(QStringList label,QString add1,WalletModelTransaction &transaction, const CCoinControl *coinControl);
SendCoinsReturn prepareeCoinsSendCreateTransaction(std::string& Txid,int Index,uint64_t eCount,WalletModelTransaction &transaction, std::string &error, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareNormalTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareIPCRegTransaction(WalletModelTransaction &transaction, uint8_t ExtendType, uint32_t startTime, uint32_t stopTime, uint8_t reAuthorize, uint8_t uniqueAuthorize, std::string hash, std::string labelTitle, std::string txLabel, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareIPCSendTransaction(std::string& IPCSendvinTxid,int Index, WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareIPCAuthorizationTransaction(WalletModelTransaction &transaction,std::string txid,int txi, QStringList data, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareTokenRegTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
SendCoinsReturn prepareTokenTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
SendCoinsReturn sendIpcTransfer();
SendCoinsReturn sendCoins(WalletModelTransaction &transaction);
SendCoinsReturn sendcreateeCoins();
bool setWalletEncrypted(bool encrypted, const SecureString &passphrase);
// Passphrase only needed when unlocking
bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString());
bool changePassphrase(const SecureString &oldPass, const SecureString &newPass);
// Wallet backup
bool backupWallet(const QString &filename);
void getScript(std::string add,int& sign_num,int &nRequired,std::string& script);
bool analyTransaction(const std::string& str,std::string& strFailReason,std::string& address,CAmount& money,int haveSigned,std::string& sourceaddress);
SendCoinsReturn prepareUnionaccountCreateTransaction(QString addfrom,WalletModelTransaction &transaction, const CCoinControl *coinControl,ScriptError &serror,std::string &strtx,std::string &m_error);
WalletModel::SendCoinsReturn repreparUnionaccountCreate(QString addfrom,QString add,CAmount num,ScriptError &serror,std::string &strtx);
bool commitUnionaccounttra(const std::string& strtx, std::string& strFailReason, ScriptError& serror, std::string& strtxout,CMutableTransaction& mergedTx);
bool commitUnionaccounttra_plus(CMutableTransaction& mergedTx,std::string& error);
// RAI object for unlocking wallet, returned by requestUnlock()
class UnlockContext
{
public:
UnlockContext(WalletModel *wallet, bool valid, bool relock);
~UnlockContext();
bool isValid() const { return valid; }
// Copy operator and constructor transfer the context
UnlockContext(const UnlockContext& obj) { CopyFrom(obj); }
UnlockContext& operator=(const UnlockContext& rhs) { CopyFrom(rhs); return *this; }
private:
WalletModel *wallet;
bool valid;
mutable bool relock; // mutable, as it can be set to false by copying
void CopyFrom(const UnlockContext& rhs);
};
UnlockContext requestUnlock();
bool getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
bool havePrivKey(const CKeyID &address) const;
bool getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const;
void getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs);
bool isSpent(const COutPoint& outpoint) const;
void listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const;
bool isLockedCoin(uint256 hash, unsigned int n) const;
void lockCoin(COutPoint& output);
void unlockCoin(COutPoint& output);
void listLockedCoins(std::vector<COutPoint>& vOutpts);
void loadReceiveRequests(std::vector<std::string>& vReceiveRequests);
bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest);
bool transactionCanBeAbandoned(uint256 hash) const;
bool abandonTransaction(uint256 hash) const;
static bool isWalletEnabled();
bool hdEnabled() const;
int getDefaultConfirmTarget() const;
//ipclist
std::vector<COutput> m_ipcCoins;
std::vector<COutput> m_eCoins;
//get ipc list
void getIpcListCoins(QVector<QStringList>&);
void getTokenListCoins(std::map<std::string, uint64_t>&);
QStringList getInfoFromIpcList(int index);
bool CreateIpcRegister(QString,QString,QString,QString,int,QString &msg,int &fee);
bool CreateWalletFromFile(QString);
QString IntTimeToQStringTime(int);
QString IntTimeToLocalQStringTime(int inttime);
QString IntTimeToQStringTimeForDetilDialog(int);
bool sendIpcCoins();
bool LoadWalletFromFile(QString filepath);
bool transferIpc(QString address,QString &errstr);
//20180201
void lookuphistory(std::map<uint256,const CWalletTx*> &vCoins ,std::string add);
bool preparetransferIpc(QString address,QString &msg);
bool prepareauthorizationIpc(QString address,int license,int exclusive,int intstart,int intend,QString& msg);
bool sendauthorizationIpc(QString &msg);
WalletModel::SendCoinsReturn prepareecoinaffrim(QString num,QString add,QString name);
WalletModel::SendCoinsReturn sendecoinaffrim();
WalletModel::SendCoinsReturn sendtransferIpc();
//20180201
bool authorizationIpc(QString,int,int,int,int,QString&);
CAmount getTotal(QList<SendCoinsRecipient>&,QSet<QString>&,int &);
bool ExportWalletToFile(std::string);
bool CheckPassword();
bool CheckIsCrypted();
int GetAccuracyBySymbol(std::string tokensymbol);
std::string m_sendcoinerror;
QString getAccuracyNumstr(QString name ,QString num);
QString getDeposit(QString address);
void setUpdataFinished();
bool m_bFinishedLoading;
int GetDepthInMainChain(int iIndex);
QString GetECoinCanUseNum(QString name);
QString GetIssueDateBySymbol(QString name);
QString GetTimeOfTokenInChain(int iIndex);
QDate getSySQDate();
bool CanIPCTransaction(int iIndex);
bool copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist,bool flushwallet);
QString getCreditValue(QString strDeposit);
QString GetHashBySymbol(QString tokensymbol);
bool addtopubkey(std::string& add,std::string& key, std::string& strFailReason);
bool CreateUnionAddress(unsigned int nRequired, const std::vector<std::string>& strPubkeys, std::string& multiscript, std::string& strmultiaddress,std::string& strFailReason );
bool joinunionaccount(std::string union_script, std::string& strFailReason ,std::string name);
void getUnionAddressinfo(std::vector<UnionAddressInfo> &addinfo);
void getAccounttrainfo(std::map<std::string,CAmount> &addinfo);
bool isMyPk(std::string addpk);
bool vinsFindAddress(const std::vector<CTxIn>& vin,std::string address);
int64_t GetBlockTime(const CWalletTx& wtx);
QString FormatTxTimeP2SH(const CWalletTx& wtx);
QString FormatTxStatus(const CWalletTx& wtx);
bool importprivkeybibipay(std::string strSecret,std::string& strError,std::string strLabel = "",bool fRescan = true);
private:
CWallet *wallet;
WalletModelTransaction *m_WalletModelTransactionIpcRegister;
WalletModelTransaction *m_WalletModelTransactioneCoinRegister;
WalletModelTransaction *m_WalletModelTransactioneCoinSend1;
WalletModelTransaction *m_WalletModelTransactionIpcTransfer;
WalletModelTransaction *currentTransaction1;
bool fHaveWatchOnly;
bool fForceCheckBalanceChanged;
bool ipcSendIsValidState;
int ipcSelectFromList;
// Wallet has an options model for wallet-specific options
// (transaction fee, for example)
OptionsModel *optionsModel;
AddressTableModel *addressTableModel;
TransactionTableModel *transactionTableModel;
RecentRequestsTableModel *recentRequestsTableModel;
// Cache some values to be able to detect changes
CAmount cachedBalance;
CAmount cachedUnconfirmedBalance;
CAmount cachedImmatureBalance;
CAmount cachedWatchOnlyBalance;
CAmount cachedWatchUnconfBalance;
CAmount cachedWatchImmatureBalance;
CAmount cachednewDepositBalance;
EncryptionStatus cachedEncryptionStatus;
int cachedNumBlocks;
QTimer *pollTimer;
QTimer *pollTimer_;
void subscribeToCoreSignals();
void unsubscribeFromCoreSignals();
void checkBalanceChanged();
Q_SIGNALS:
// Signal that balance in wallet changed
void balanceChanged(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance,const CAmount& depositBalance);
// Encryption status of wallet changed
void encryptionStatusChanged(int status);
// Signal emitted when wallet needs to be unlocked
// It is valid behaviour for listeners to keep the wallet locked after this signal;
// this means that the unlocking failed or was cancelled.
void requireUnlock();
// Fired when a message should be reported to the user
void message(const QString &title, const QString &message, unsigned int style);
// Coins sent: from wallet, to recipient, in (serialized) transaction:
void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction);
// Show progress dialog e.g. for rescan
void showProgress(const QString &title, int nProgress);
// Watch-only address added
void notifyWatchonlyChanged(bool fHaveWatchonly);
void updateIpcList();
void updataLoadingFinished();
void updataLater();
public Q_SLOTS:
/* Wallet status might have changed */
void updateStatus();
/* New transaction, or transaction changed status */
void updateTransaction();
/* New, updated or removed address book entry */
void updateAddressBook(const QString &address, const QString &label, bool isMine, const QString &purpose, int status);
/* Watch-only added */
void updateWatchOnlyFlag(bool fHaveWatchonly);
/* Current, immature or unconfirmed balance might have changed - emit 'balanceChanged' if so */
void pollBalanceChanged();
void updateTimer();
};
#endif // BITCOIN_QT_WALLETMODEL_H
| 40.915663 | 290 | 0.738104 | [
"object",
"vector",
"model"
] |
90742b1b5084b2b4ec1d4c1c56eae4f5d0763ccb | 19,888 | h | C | iv/lv5/railgun/operation.h | ste72phen/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | [
"MIT",
"BSD-2-Clause",
"BSD-3-Clause"
] | 248 | 2015-01-06T00:05:11.000Z | 2022-03-03T23:33:32.000Z | iv/lv5/railgun/operation.h | ste72phen/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | [
"MIT",
"BSD-2-Clause",
"BSD-3-Clause"
] | 3 | 2015-01-10T09:37:33.000Z | 2018-08-17T14:28:22.000Z | iv/lv5/railgun/operation.h | Constellation/iv | 64c3a9c7c517063f29d90d449180ea8f6f4d946f | [
"MIT",
"BSD-2-Clause",
"BSD-3-Clause"
] | 32 | 2015-07-19T13:32:12.000Z | 2022-03-17T19:52:45.000Z | #ifndef IV_LV5_RAILGUN_OPERATION_H_
#define IV_LV5_RAILGUN_OPERATION_H_
#include <iv/arith.h>
#include <iv/platform_math.h>
#include <iv/lv5/arguments.h>
#include <iv/lv5/jsval.h>
#include <iv/lv5/chain.h>
#include <iv/lv5/jsglobal.h>
#include <iv/lv5/railgun/fwd.h>
#include <iv/lv5/railgun/instruction_fwd.h>
namespace iv {
namespace lv5 {
namespace railgun {
namespace detail {
template<int Target>
inline bool IsIncrementOverflowSafe(int32_t val);
template<>
inline bool IsIncrementOverflowSafe<-1>(int32_t val) {
return val > INT32_MIN;
}
template<>
inline bool IsIncrementOverflowSafe<1>(int32_t val) {
return val < INT32_MAX;
}
class VMArguments : public lv5::Arguments {
public:
VMArguments(lv5::Context* ctx, pointer ptr, std::size_t n)
: lv5::Arguments(ctx, ptr, n) {
}
};
} // namespace detail
class Operation {
public:
explicit Operation(lv5::Context* ctx) : ctx_(ctx) { }
JSVal Invoke(JSFunction* func, JSVal* arg, int argc_with_this, Error* e) {
detail::VMArguments args(ctx_,
arg + (argc_with_this - 1),
argc_with_this - 1);
return func->Call(&args, args.this_binding(), e);
}
JSVal InvokeMaybeEval(JSFunction* func,
JSVal* arg, int argc_with_this,
Frame* prev, Error* e) {
detail::VMArguments args(ctx_,
arg + (argc_with_this - 1),
argc_with_this - 1);
const JSAPI native = func->NativeFunction();
if (native && native == &GlobalEval) {
// direct call to eval point
args.set_this_binding(args.this_binding());
return DirectCallToEval(args, prev, e);
}
return func->Call(&args, args.this_binding(), e);
}
JSVal Construct(JSFunction* func, JSVal* arg, int argc_with_this, Error* e) {
detail::VMArguments args(ctx_,
arg + (argc_with_this - 1),
argc_with_this - 1);
args.set_constructor_call(true);
return func->Construct(&args, e);
}
void RaiseReferenceError(Symbol name, Error* e) const {
core::UStringBuilder builder;
builder.Append('"');
builder.Append(symbol::GetSymbolString(name));
builder.Append("\" not defined");
e->Report(Error::Reference, builder.BuildPiece());
}
void RaiseReferenceError(Error* e) const {
core::UStringBuilder builder;
builder.Append("Invalid left-hand side expression");
e->Report(Error::Reference, builder.BuildPiece());
}
JSEnv* GetEnv(JSEnv* env, Symbol name) const {
JSEnv* current = env;
while (current) {
if (current->HasBinding(ctx_, name)) {
return current;
} else {
current = current->outer();
}
}
return nullptr;
}
JSDeclEnv* GetHeapEnv(JSEnv* env, uint32_t scope_nest_count) const {
for (uint32_t i = 0; i < scope_nest_count; ++i) {
env = env->outer();
}
assert(env->AsJSDeclEnv());
return static_cast<JSDeclEnv*>(env);
}
#define CHECK IV_LV5_ERROR(e)
JSVal LoadName(JSEnv* env, Symbol name, bool strict, Error* e) {
if (JSEnv* current = GetEnv(env, name)) {
return current->GetBindingValue(ctx_, name, strict, e);
}
RaiseReferenceError(name, e);
return JSEmpty;
}
JSVal LoadHeap(JSEnv* env, Symbol name,
bool strict, uint32_t offset,
uint32_t scope_nest_count, Error* e) {
return GetHeapEnv(env, scope_nest_count)->GetByOffset(offset, strict, e);
}
JSVal LoadProp(JSVal base, Symbol s, bool strict, Error* e) {
base.CheckObjectCoercible(CHECK);
return LoadPropImpl(base, s, strict, e);
}
template<OP::Type own, OP::Type proto, OP::Type chain, OP::Type generic>
JSVal LoadProp(Instruction* instr,
JSVal base, Symbol s, bool strict, Error* e) {
// opcode | (dst | base | name) | nop | nop | nop
base.CheckObjectCoercible(CHECK);
Slot slot;
const JSVal res = base.GetSlot(ctx_, s, &slot, IV_LV5_ERROR(e));
if (slot.IsNotFound()) {
return res;
}
// property found
if (!slot.IsLoadCacheable() || symbol::IsArrayIndexSymbol(s)) {
// bailout to generic
instr[0] = Instruction::GetOPInstruction(generic);
return slot.value();
}
assert(!symbol::IsArrayIndexSymbol(s));
JSObject* obj = nullptr;
if (base.IsPrimitive()) {
// if base is primitive, property not found in "this" object
// so, lookup from proto
obj = base.GetPrimitiveProto(ctx_);
} else {
obj = base.object();
}
// cache phase
// own property / proto property / chain lookup property
if (slot.base() == obj) {
// own property
instr[0] = Instruction::GetOPInstruction(own);
instr[2].map = obj->map();
instr[3].u32[0] = slot.offset();
return slot.value();
}
if (slot.base() == obj->prototype()) {
// proto property
obj->FlattenMap();
instr[0] = Instruction::GetOPInstruction(proto);
instr[2].map = obj->map();
instr[3].map = slot.base()->map();
instr[4].u32[0] = slot.offset();
return slot.value();
}
// chain property
instr[0] = Instruction::GetOPInstruction(chain);
instr[2].chain = Chain::New(obj, slot.base());
instr[3].map = slot.base()->map();
instr[4].u32[0] = slot.offset();
return slot.value();
}
JSVal LoadElement(JSVal base,
JSVal element, bool strict, Error* e) {
base.CheckObjectCoercible(CHECK);
const Symbol s = element.ToSymbol(ctx_, CHECK);
return LoadPropImpl(base, s, strict, e);
}
JSVal LoadPropImpl(JSVal base,
Symbol s, bool strict, Error* e) {
if (base.IsPrimitive()) {
return LoadPropPrimitive(base, s, strict, e);
} else {
return base.object()->Get(ctx_, s, e);
}
}
JSVal LoadPropPrimitive(JSVal base,
Symbol s, bool strict, Error* e) {
JSVal res;
if (GetPrimitiveOwnProperty(base, s, &res)) {
return res;
}
// if base is primitive, property not found in "this" object
// so, lookup from proto
Slot slot;
JSObject* const proto = base.GetPrimitiveProto(ctx_);
if (proto->GetPropertySlot(ctx_, s, &slot)) {
return slot.Get(ctx_, base, e);
} else {
return JSUndefined;
}
}
#undef CHECK
#define CHECK IV_LV5_ERROR_VOID(e)
void StoreName(JSEnv* env, Symbol name,
JSVal stored, bool strict, Error* e) {
if (JSEnv* current = GetEnv(env, name)) {
current->SetMutableBinding(ctx_, name, stored, strict, e);
} else {
if (strict) {
e->Report(Error::Reference,
"putting to unresolvable reference "
"not allowed in strict reference");
} else {
ctx_->global_obj()->Put(ctx_, name, stored, strict, e);
}
}
}
void StoreHeap(JSEnv* env, Symbol name,
JSVal stored, bool strict,
uint32_t offset, uint32_t scope_nest_count, Error* e) {
GetHeapEnv(env, scope_nest_count)->SetByOffset(offset, stored, strict, e);
}
void StoreElement(JSVal base, JSVal element,
JSVal stored, bool strict, Error* e) {
base.CheckObjectCoercible(CHECK);
const Symbol s = element.ToSymbol(ctx_, CHECK);
StorePropImpl(base, s, stored, strict, e);
}
void StoreProp(JSVal base, Symbol s,
JSVal stored, bool strict, Error* e) {
base.CheckObjectCoercible(CHECK);
StorePropImpl(base, s, stored, strict, e);
}
void StoreProp(JSVal base,
Instruction* instr,
OP::Type generic,
Symbol name, JSVal src, bool strict, Error* e) {
// opcode | (base | src | index) | nop | nop
base.CheckObjectCoercible(CHECK);
if (base.IsPrimitive()) {
StorePropPrimitive(base, name, src, strict, e);
return;
}
// cache patten
JSObject* obj = base.object();
if (instr[2].map == obj->map()) {
// map is cached, so use previous index code
obj->Direct(instr[3].u32[0]) = src;
return;
}
Map* previous = obj->map();
Slot slot;
obj->PutSlot(ctx(), name, src, &slot, strict, CHECK);
const Slot::PutResultType put_result_type = slot.put_result_type();
// uncacheable pattern
if (!slot.IsPutCacheable() || !symbol::IsArrayIndexSymbol(name)) {
return;
}
assert(put_result_type != Slot::PUT_NONE);
// TODO(Constellation) VM only store replace pattern.
if (put_result_type == Slot::PUT_REPLACE) {
if (previous == obj->map()) {
instr[2].map = obj->map();
instr[3].u32[0] = slot.offset();
}
}
return;
}
void StorePropImpl(JSVal base, Symbol s,
JSVal stored, bool strict, Error* e) {
if (base.IsPrimitive()) {
StorePropPrimitive(base, s, stored, strict, e);
} else {
base.object()->Put(ctx_, s, stored, strict, e);
}
}
void StorePropPrimitive(JSVal base, Symbol s,
JSVal stored, bool strict, Error* e) {
assert(base.IsPrimitive());
Slot slot;
JSObject* const o = base.ToObject(ctx_, CHECK);
if (!o->CanPut(ctx_, s, &slot)) {
if (strict) {
e->Report(Error::Type, "cannot put value to object");
}
return;
}
if (slot.IsNotFound() || slot.attributes().IsData()) {
if (strict) {
e->Report(Error::Type, "value to symbol in transient object");
}
return;
}
const Accessor* ac = slot.accessor();
assert(ac->setter());
ScopedArguments args(ctx_, 1, IV_LV5_ERROR_VOID(e));
args[0] = stored;
static_cast<JSFunction*>(ac->setter())->Call(&args, base, e);
}
#undef CHECK
#define CHECK IV_LV5_ERROR(e)
JSVal BinaryAdd(JSVal lhs, JSVal rhs, Error* e) const {
if (lhs.IsNumber() && rhs.IsNumber()) {
return lhs.number() + rhs.number();
}
if (lhs.IsString()) {
if (rhs.IsString()) {
return JSString::NewCons(ctx_, lhs.string(), rhs.string(), e);
} else {
const JSVal rp = rhs.ToPrimitive(ctx_, Hint::NONE, CHECK);
JSString* const rs = rp.ToString(ctx_, CHECK);
return JSString::NewCons(ctx_, lhs.string(), rs, e);
}
}
const JSVal lprim = lhs.ToPrimitive(ctx_, Hint::NONE, CHECK);
const JSVal rprim = rhs.ToPrimitive(ctx_, Hint::NONE, CHECK);
if (lprim.IsString() || rprim.IsString()) {
JSString* const lstr = lprim.ToString(ctx_, CHECK);
JSString* const rstr = rprim.ToString(ctx_, CHECK);
return JSString::NewCons(ctx_, lstr, rstr, e);
}
const double left = lprim.ToNumber(ctx_, CHECK);
return left + rprim.ToNumber(ctx_, e);
}
JSVal BinarySub(JSVal lhs, JSVal rhs, Error* e) const {
const double left = lhs.ToNumber(ctx_, CHECK);
return left - rhs.ToNumber(ctx_, e);
}
JSVal BinaryMultiply(JSVal lhs, JSVal rhs, Error* e) const {
const double left = lhs.ToNumber(ctx_, CHECK);
return left * rhs.ToNumber(ctx_, e);
}
JSVal BinaryDivide(JSVal lhs, JSVal rhs, Error* e) const {
const double left = lhs.ToNumber(ctx_, CHECK);
return left / rhs.ToNumber(ctx_, e);
}
JSVal BinaryModulo(JSVal lhs, JSVal rhs, Error* e) const {
const double left = lhs.ToNumber(ctx_, CHECK);
return core::math::Modulo(left, rhs.ToNumber(ctx_, e));
}
JSVal BinaryLShift(JSVal lhs, JSVal rhs, Error* e) const {
const int32_t left = lhs.ToInt32(ctx_, CHECK);
return JSVal::Int32(left << (rhs.ToInt32(ctx_, e) & 0x1f));
}
JSVal BinaryRShift(JSVal lhs, JSVal rhs, Error* e) const {
const int32_t left = lhs.ToInt32(ctx_, CHECK);
return JSVal::Int32(left >> (rhs.ToInt32(ctx_, e) & 0x1f));
}
JSVal BinaryRShiftLogical(JSVal lhs,
JSVal rhs, Error* e) const {
const uint32_t left = lhs.ToUInt32(ctx_, CHECK);
return JSVal::UInt32(left >> (rhs.ToInt32(ctx_, e) & 0x1f));
}
bool BinaryCompareLT(JSVal lhs,
JSVal rhs, Error* e) const {
return JSVal::Compare<true>(ctx_, lhs, rhs, e) == CMP_TRUE;
}
bool BinaryCompareLTE(JSVal lhs,
JSVal rhs, Error* e) const {
return JSVal::Compare<false>(ctx_, rhs, lhs, e) == CMP_FALSE;
}
bool BinaryCompareGT(JSVal lhs,
JSVal rhs, Error* e) const {
return JSVal::Compare<false>(ctx_, rhs, lhs, e) == CMP_TRUE;
}
bool BinaryCompareGTE(JSVal lhs,
JSVal rhs, Error* e) const {
return JSVal::Compare<true>(ctx_, lhs, rhs, e) == CMP_FALSE;
}
bool BinaryInstanceof(JSVal lhs,
JSVal rhs, Error* e) const {
if (!rhs.IsObject()) {
e->Report(Error::Type, "instanceof requires object");
return false;
}
JSObject* const robj = rhs.object();
if (!robj->IsCallable()) {
e->Report(Error::Type, "instanceof requires constructor");
return false;
}
return static_cast<JSFunction*>(robj)->HasInstance(ctx_, lhs, e);
}
bool BinaryIn(JSVal lhs,
JSVal rhs, Error* e) const {
if (!rhs.IsObject()) {
e->Report(Error::Type, "in requires object");
return false;
}
const Symbol s = lhs.ToSymbol(ctx_, IV_LV5_ERROR(e));
return rhs.object()->HasProperty(ctx_, s);
}
bool BinaryEqual(JSVal lhs,
JSVal rhs, Error* e) const {
return JSVal::AbstractEqual(ctx_, lhs, rhs, e);
}
bool BinaryStrictEqual(JSVal lhs,
JSVal rhs) const {
return JSVal::StrictEqual(lhs, rhs);
}
bool BinaryNotEqual(JSVal lhs,
JSVal rhs, Error* e) const {
return !JSVal::AbstractEqual(ctx_, lhs, rhs, e);
}
bool BinaryStrictNotEqual(JSVal lhs,
JSVal rhs) const {
return !JSVal::StrictEqual(lhs, rhs);
}
int32_t BinaryBitAnd(JSVal lhs,
JSVal rhs, Error* e) const {
const int32_t left = lhs.ToInt32(ctx_, IV_LV5_ERROR(e));
return left & rhs.ToInt32(ctx_, e);
}
int32_t BinaryBitXor(JSVal lhs,
JSVal rhs, Error* e) const {
const int32_t left = lhs.ToInt32(ctx_, IV_LV5_ERROR(e));
return left ^ rhs.ToInt32(ctx_, e);
}
int32_t BinaryBitOr(JSVal lhs,
JSVal rhs, Error* e) const {
const int32_t left = lhs.ToInt32(ctx_, IV_LV5_ERROR(e));
return left | rhs.ToInt32(ctx_, e);
}
template<int Target, std::size_t Returned>
JSVal IncrementName(JSEnv* env, Symbol s, bool strict, Error* e) {
if (JSEnv* current = GetEnv(env, s)) {
const JSVal w = current->GetBindingValue(ctx_, s, strict, CHECK);
if (w.IsInt32() && detail::IsIncrementOverflowSafe<Target>(w.int32())) {
std::tuple<JSVal, JSVal> results;
const int32_t target = w.int32();
std::get<0>(results) = w;
std::get<1>(results) = JSVal::Int32(target + Target);
current->SetMutableBinding(
ctx_, s,
std::get<1>(results), strict, e);
return std::get<Returned>(results);
} else {
std::tuple<double, double> results;
std::get<0>(results) = w.ToNumber(ctx_, CHECK);
std::get<1>(results) = std::get<0>(results) + Target;
current->SetMutableBinding(ctx_, s,
std::get<1>(results), strict, e);
return std::get<Returned>(results);
}
}
RaiseReferenceError(s, e);
return 0.0;
}
template<int Target, std::size_t Returned>
JSVal IncrementHeap(JSEnv* env, Symbol s,
bool strict, uint32_t offset,
uint32_t scope_nest_count, Error* e) {
JSDeclEnv* decl = GetHeapEnv(env, scope_nest_count);
const JSVal w = decl->GetByOffset(offset, strict, CHECK);
if (w.IsInt32() && detail::IsIncrementOverflowSafe<Target>(w.int32())) {
std::tuple<JSVal, JSVal> results;
const int32_t target = w.int32();
std::get<0>(results) = w;
std::get<1>(results) = JSVal::Int32(target + Target);
decl->SetByOffset(offset, std::get<1>(results), strict, e);
return std::get<Returned>(results);
} else {
std::tuple<double, double> results;
std::get<0>(results) = w.ToNumber(ctx_, CHECK);
std::get<1>(results) = std::get<0>(results) + Target;
decl->SetByOffset(offset, std::get<1>(results), strict, e);
return std::get<Returned>(results);
}
}
template<int Target, std::size_t Returned>
JSVal IncrementElement(JSVal base,
JSVal element, bool strict, Error* e) {
base.CheckObjectCoercible(CHECK);
const Symbol s = element.ToSymbol(ctx_, CHECK);
const JSVal w = LoadPropImpl(base, s, strict, CHECK);
if (w.IsInt32() && detail::IsIncrementOverflowSafe<Target>(w.int32())) {
std::tuple<JSVal, JSVal> results;
const int32_t target = w.int32();
std::get<0>(results) = w;
std::get<1>(results) = JSVal::Int32(target + Target);
StorePropImpl(base, s, std::get<1>(results), strict, e);
return std::get<Returned>(results);
} else {
std::tuple<double, double> results;
std::get<0>(results) = w.ToNumber(ctx_, CHECK);
std::get<1>(results) = std::get<0>(results) + Target;
StorePropImpl(base, s, std::get<1>(results), strict, e);
return std::get<Returned>(results);
}
}
template<int Target, std::size_t Returned>
JSVal IncrementProp(JSVal base,
Symbol s, bool strict, Error* e) {
base.CheckObjectCoercible(CHECK);
const JSVal w = LoadPropImpl(base, s, strict, CHECK);
if (w.IsInt32() && detail::IsIncrementOverflowSafe<Target>(w.int32())) {
std::tuple<JSVal, JSVal> results;
const int32_t target = w.int32();
std::get<0>(results) = w;
std::get<1>(results) = JSVal::Int32(target + Target);
StorePropImpl(base, s, std::get<1>(results), strict, e);
return std::get<Returned>(results);
} else {
std::tuple<double, double> results;
std::get<0>(results) = w.ToNumber(ctx_, CHECK);
std::get<1>(results) = std::get<0>(results) + Target;
StorePropImpl(base, s, std::get<1>(results), strict, e);
return std::get<Returned>(results);
}
}
JSVal LoadGlobal(JSGlobal* global,
Instruction* instr, const Symbol& s, bool strict, Error* e) {
// opcode | (dst | index) | nop | nop
if (instr[2].map == global->map()) {
// map is cached, so use previous index code
return global->Direct(instr[3].u32[0]);
} else {
// now Own Property Pattern only implemented
Slot slot;
assert(!symbol::IsArrayIndexSymbol(s));
if (global->GetOwnPropertySlot(ctx_, s, &slot)) {
if (slot.IsLoadCacheable()) {
instr[2].map = global->map();
instr[3].u32[0] = slot.offset();
return slot.value();
}
return slot.Get(ctx_, global, e);
} else {
instr[2].map = nullptr;
return LoadName(ctx_->global_env(), s, strict, e);
}
}
}
bool GetPrimitiveOwnProperty(JSVal base, const Symbol& s, JSVal* res) {
// section 8.7.1 special [[Get]]
assert(base.IsPrimitive());
if (base.IsString()) {
// string short circuit
JSString* str = base.string();
if (s == symbol::length()) {
*res = JSVal::UInt32(static_cast<uint32_t>(str->size()));
return true;
}
if (symbol::IsArrayIndexSymbol(s)) {
const uint32_t index = symbol::GetIndexFromSymbol(s);
if (index < static_cast<uint32_t>(str->size())) {
*res = JSString::New(ctx_, str->At(index));
return true;
}
}
}
return false;
}
#undef CHECK
inline lv5::Context* ctx() const { return ctx_; }
private:
lv5::Context* ctx_;
};
} } } // namespace iv::lv5::railgun
#endif // IV_LV5_RAILGUN_OPERATION_H_
| 31.769968 | 80 | 0.599055 | [
"object"
] |
907867adde3770d075e8ac017ff8ba80a5028135 | 2,221 | h | C | include/VideoInspector.h | wonsik3686/FeatureCatcher | 12a417f930204ffe3b95c6cea061b65bf8734414 | [
"Apache-2.0"
] | null | null | null | include/VideoInspector.h | wonsik3686/FeatureCatcher | 12a417f930204ffe3b95c6cea061b65bf8734414 | [
"Apache-2.0"
] | null | null | null | include/VideoInspector.h | wonsik3686/FeatureCatcher | 12a417f930204ffe3b95c6cea061b65bf8734414 | [
"Apache-2.0"
] | 3 | 2020-10-26T10:25:41.000Z | 2020-11-01T11:38:46.000Z | #ifndef VIDEOINSPECTOR_H
#define VIDEOINSPECTOR_H
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include "ThreadPool.h"
#include "DataManager.h"
class VideoInspector {
public:
VideoInspector(int thread_num);
~VideoInspector();
int loadModels();
int process(cv::Mat& frame, DataManager& dataManager,
std::string frameCount, std::string millisec,
std::string yourWebServerPath, int& framePerSaving);
void visualize(cv::Mat& frame);
void setFramePerSaving(int frame_per_saving);
private:
void clearVars();
void beforeProcess();
void processOnePerson(cv::Mat& frame, int idx);
int detectPeople(cv::Mat& frame);
int detectFace(cv::Mat& personFrame, cv::Rect person, int idx);
int recognizeAgeGender(cv::Mat& frame, cv::Rect face, int idx);
int findColor(cv::Mat& personFrame, cv::Rect person, int idx);
int identifyPeople(cv::Mat& personframe, int idx);
std::vector<std::vector<float>> globalReIdVec;
template <typename T>
float cosineSimilarity(const std::vector<T>& vecA, const std::vector<T>& vecB);
uint findMatchingPerson(const std::vector<float>& newReIdVec);
std::unique_ptr<cv::dnn::Net> personDetector;
std::vector<std::unique_ptr<cv::dnn::Net>> personIdentifier;
std::vector<std::unique_ptr<cv::dnn::Net>> faceDetector;
std::vector<std::unique_ptr<cv::dnn::Net>> attributesRecognizer;
std::vector<std::unique_ptr<cv::dnn::Net>> ageGenderRecognizer;
int framePerSaving;
int threadNum;
std::unique_ptr<ThreadPool::ThreadPool> pool;
public:
std::vector<cv::Rect> people;
std::vector<cv::Rect> faces;
std::vector<std::pair<std::string, std::string>> ageGender;
std::vector<std::string> peopleId;
std::vector<std::pair<cv::Point, cv::Point>> clothesPoint;
std::vector<std::pair<cv::Vec3b, cv::Vec3b>> clothesColor;
std::mutex mInit;
std::mutex mFace;
std::mutex mAgeGender;
std::mutex mId;
std::mutex mGlobalId;
std::mutex mPoint;
std::mutex mColor;
};
#endif | 29.613333 | 83 | 0.689329 | [
"vector"
] |
908bb9192caa326fbe9cda36016066954ca42cc1 | 17,410 | h | C | src_revised/util.h | yaohsiaopid/rtl2uspec | c68189af60f0c8a1c3f5da8d966d74e4e4a23424 | [
"BSD-3-Clause"
] | 3 | 2021-11-03T09:19:57.000Z | 2022-02-08T23:45:38.000Z | src_revised/util.h | yaohsiaopid/rtl2uspec | c68189af60f0c8a1c3f5da8d966d74e4e4a23424 | [
"BSD-3-Clause"
] | null | null | null | src_revised/util.h | yaohsiaopid/rtl2uspec | c68189af60f0c8a1c3f5da8d966d74e4e4a23424 | [
"BSD-3-Clause"
] | null | null | null | #ifndef UTIL_H
#define UTIL_H
#include "kernel/yosys.h"
#include "kernel/sigtools.h"
#include "kernel/celltypes.h"
#include "backends/ilang/ilang_backend.h"
#include <string>
#include <map>
#include <set>
#include <functional>
#include <queue>
#include <cassert>
#include <algorithm>
#include <sstream>
#include "design.h"
#include "container.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
bool isreg(const RTLIL::Cell* c) {
// warn about latches, will treat as std cell
if (c->type.in(
ID($adff), ID($adffe), ID($dffsr), ID($dffsre), ID($dlatch), ID($adlatch), ID($dlatchsr), ID($sr)))
log("[warn] latches.....\n\n");
return c->type.in(
ID($dff), ID($dffe), ID($sdff), ID($sdffe), ID($sdffce));
}
bool ismem(const RTLIL::Cell* c) {
return c->type.in(ID($mem), ID($memrd), ID($memwr), ID($meminit), ID($mem_v2));
}
void cat(const RTLIL::SigSpec* sig, RTLIL::Cell* cell, const string &s, const string &prefix="") {
string s2, s3;
if (cell != NULL)
s2 = RTLIL::id2cstr(cell->name);
if (sig != NULL)
s3 = log_signal(*sig);
log("%s[warn] %s; cell: %s; wire: %s\n",prefix.c_str(), s.c_str(), s2.c_str(), s3.c_str());
}
void getWires(const RTLIL::SigSpec s, vector<RTLIL::Wire*> &ret) {
ret.clear();
for (auto &chunk: s.chunks()) {
if (chunk.wire != NULL) ret.push_back(chunk.wire);
}
}
struct RTL2USPEC_STAT: public Pass {
RTL2USPEC_STAT(): Pass("ff_stat") {}
void execute(vector<string> args, RTLIL::Design *design) override
{
log("=============[PASS] ff_stat =============\n");
pool<RTLIL::Cell*> dffs;
auto top_mod = design->top_module();
for (auto &item: top_mod->cells_) {
if (isreg(item.second)) {
dffs.insert(item.second);
log("%s\n", log_signal(item.second->getPort(ID::Q)));
}
}
int bitcnt = 0;
for (auto &cc: dffs) {
int width = cc->getParam(ID::WIDTH).as_int();
bitcnt += width;
}
log("total # of flipflop: %d\n", bitcnt);
log("total # of register: %d\n", dffs.size());
log("============================================\n");
}
} rtl2uspec_stat;
void dump_sigpool(pool<RTLIL::SigSpec> p, const string &ss) {
log("dump sigpool for %s {\n", ss.c_str());
for (auto &s : p) {
log("- %s,\n", log_signal(s));
}
log(" cnt: %zu }\n", p.size());
};
void dump_cellpool(pool<RTLIL::Cell*> p, const string &ss) {
log("\n\tdump cellpool for %s {\n", ss.c_str());
for (auto &s : p) {
log(" %s,\n", s->name.c_str());
}
log(" cnt: %zu }\n", p.size());
};
RTLIL::SigSpec get_sig_by_str(const string &s, RTLIL::Module* module_, SigMap sigmap_) {
if (s.size() < 2) return RTLIL::SigSpec();
RTLIL::Wire* wire_;
wire_ = module_->wires_[
RTLIL::IdString(s[0] == '\\' ? s : "\\" + s)];
if (wire_ != nullptr) {
RTLIL::SigSpec s_ = sigmap_(wire_);
return s_;
}
return RTLIL::SigSpec();
};
struct s_map {
// replace map
int c;
string s;
string match;
s_map(const string match, int c):
match(match), s(""), c(c) {}
s_map(const string match, string s):
match(match), s(s), c(-1000) {}
};
void substr_replace(string& str, const string& from, const string &to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
void substr_replace(string& s, const string& from, int num) {
substr_replace(s, from, std::to_string(num));
}
string replace_template(const string prop, vector<s_map> rep_list) {
string ret = prop;
for (auto &it: rep_list) {
// if (it.c < 0 && it.s.size() == 0) assert(0);
if (it.c < 0)
substr_replace(ret, it.match, it.s);
else
substr_replace(ret, it.match, it.c);
}
return ret;
}
#define X_SCALE 15
#define Y_SCALE 3.0
class MyGraph {
private:
int depth = 0;
int sgraph = 0;
dict<string, string> node_sty;
dict<string, int> column_node;
dict<pair<string, string>, string> edge_sty;
dict<string, pool<string>> edges; // edges.u = {v | (u, v) in E} down edge
dict<string, pool<string>> parent_edges; // edges.v = {u | (u, v) in E} up edge
dict<string, RTLIL::Cell*> node_map_mem_;
dict<string, RTLIL::SigSpec> node_map;
std::vector<pool < pair <string,string>>> subgraphs;
vector<string> subgraph_label;
vector<pool<string>> seq_uhb; // updated node at idx = depth
vector<My_Disjoint_Set<string>> seq_uhb_sets;
void addEdge_(const string &u, const string &v, const string &u_sty, const string &v_sty, const string &e_sty, int overwrite=1) {
auto u_ = trans(u);
auto v_ = trans(v);
if (v_ == u_) return;
auto e_ = make_pair(u_, v_);
if (!overwrite && edge_sty.find(e_) != edge_sty.end()) return;
node_sty[u_] = u_sty; // node_sty[u_] + "," + u_sty;
node_sty[v_] = v_sty; // node_sty[v_] + "," + v_sty;
edge_sty[e_] = e_sty;
edges[u_].insert(v_);
parent_edges[v_].insert(u_);
if (sgraph) {
subgraphs[sgraph-1].insert(e_);
}
// outfile << "\"" << u_ << "\" [" << u_sty << "]; \n";
// outfile << "\"" << v_ << "\" [" << v_sty << "]; \n";
// outfile << "\"" << u_ << "\"->\"" << v_ << "\" [" << e_sty << "];\n";
}
struct node_info {
int dep;
bool write;
inline bool operator==(const node_info& other) const {
return (dep == other.dep && write == other.write);
}
inline unsigned int hash() const {
return mkhash(hash_ops<int>::hash(dep), hash_ops<int>::hash(write ? 1 : 0));
}
};
dict<string, pool<node_info>> loc_per_reg; // loc in dataflow depths write(T) / read(F)
public:
const dict<string, RTLIL::Cell*> node_map_mem() const {
return node_map_mem_;
}
pool<string> upstream(const string &node_, const string &percore="") {
pool<string> tmp;
for (auto &e: edges) {
if (e.second.find(node_) != e.second.end() &&
(percore.size() == 0 || (percore.size() != 0 && e.first.find(percore) == std::string::npos)))
tmp.insert(e.first);
}
return tmp;
}
inline pool<string> downstream(const string &node_) {
return edges[node_];
}
inline int uhb_sz() { return seq_uhb.size(); }
inline pool<string> uhb_item(int i) {
if (i < seq_uhb.size())
return seq_uhb[i];
else
return pool<string>();
}
void dsj_union(int idx, string loc_a, string loc_b) {
// operates on seq_uhb_sets[idx]
seq_uhb_sets[idx].ds_union(loc_b, loc_a);
}
bool ds_find_check(int idx, string loc_a, string loc_b) {
return (seq_uhb_sets[idx].ds_find(loc_a) == seq_uhb_sets[idx].ds_find(loc_b));
}
pool<string> dsj_dump(int idx) {
// log("// dsj_dump %d\n", idx);
return seq_uhb_sets[idx].dump_stat();
// log("// dsj_dump %d END\n", idx);
}
MyGraph() {
}
void subgraph(string s) {
sgraph++;
subgraph_label.push_back(s);
pool<pair<string,string>> npool;
subgraphs.push_back(npool);
// string name = "cluster"+std::to_string(j) + "_" + std::to_string(i);
// outfile << "subgraph " << name << "{ \n";
}
void samerank(pair<RTLIL::SigSpec, RTLIL::Cell*> &pr, RTLIL::SigSpec &r2) {
if (pr.second == nullptr) {
samerank(pr.first, r2);
} else {
string s1_ = pr.second->name.str().substr(1);
string s2_ = string(log_signal(r2)).substr(1);
samerank(s1_, s2_);
}
}
void samerank(pair<RTLIL::SigSpec, RTLIL::Cell*> &pr, RTLIL::Cell* &r2) {
if (pr.second == nullptr) {
samerank(pr.first, r2);
} else {
string s1_ = pr.second->name.str().substr(1);
string s2_ = r2->name.str().substr(1);
samerank(s1_, s2_);
}
}
void samerank(RTLIL::SigSpec &r1, RTLIL::Cell* &r2) {
string s1_ = string(log_signal(r1)).substr(1);
string s2_ = r2->name.str().substr(1);
samerank(s1_, s2_);
//log("s1_: %s s2 %s", s1_.c_str(), s2_.c_str());
}
void samerank(RTLIL::SigSpec &r1, RTLIL::SigSpec &r2) {
string s1_ = string(log_signal(r1)).substr(1);
string s2_ = string(log_signal(r2)).substr(1);
samerank(s1_, s2_);
}
void samerank(const string &s1, const string &s2) {
bool s1_ = !(column_node.find(s1) == column_node.end());
bool s2_ = !(column_node.find(s2) == column_node.end());
if (s1_ && s2_) return;
if (s1_) {
column_node[s2] = column_node[s1];
} else if (s2_) {
column_node[s1] = column_node[s2];
} else {
//log("samr rank %s %s\n", s1.c_str(), s2.c_str());
column_node[s1] = depth;
column_node[s2] = depth;
depth++;
}
}
string trans(const string &s) {
return s;
}
void addEdge(RTLIL::SigSpec &r1, RTLIL::SigSpec &r2, const string &u_sty, const string &v_sty, const string &e_sty, int overwrite=1) {
string s1 = string(log_signal(r1)).substr(1);
string s2 = string(log_signal(r2)).substr(1);
node_map[s1] = r1;
node_map[s2] = r2;
addEdge_(s1, s2, u_sty, v_sty, e_sty, overwrite);
}
void addEdge(RTLIL::Cell *r1, RTLIL::SigSpec &r2, const string &u_sty, const string &v_sty, const string &e_sty, int overwrite=1) {
string s1 = r1->name.str().substr(1);
string s2 = string(log_signal(r2)).substr(1);
node_map_mem_[s1] = r1;
node_map[s2] = r2;
addEdge_(s1, s2, u_sty, v_sty, e_sty, overwrite);
}
void addEdge(RTLIL::SigSpec &r1, RTLIL::Cell *r2, const string &u_sty, const string &v_sty, const string &e_sty, int overwrite=1) {
string s1 = string(log_signal(r1)).substr(1);
string s2 = r2->name.str().substr(1);
node_map[s1] = r1;
node_map_mem_[s2] = r2;
addEdge_(s1, s2, u_sty, v_sty, e_sty, overwrite);
}
void addEdge(RTLIL::Cell *r1, RTLIL::Cell *r2, const string &u_sty, const string &v_sty, const string &e_sty, int overwrite=1) {
string s1 = r1->name.str().substr(1);
string s2 = r2->name.str().substr(1);
node_map_mem_[s1] = r1;
node_map_mem_[s2] = r2;
addEdge_(s1, s2, u_sty, v_sty, e_sty, overwrite);
}
vector<string> color = { "#984ea3","#ff7f00","#ffff33","#e41a1c","#377eb8","#4daf4a","#a65628","#f781bf","#999999" };
vector<pool<string>> uhb_stages;
void uhb_anchor(string const &inst_) {
// assume all nodes are uhb nodes
// collect seq_uhb
pool<string> visited;
pool<string> cur_pool, next_pool;
cur_pool = edges[inst_];
while (!cur_pool.empty()) {
for (auto &c_: cur_pool) {
for (auto &r_: edges[c_]) {
if (visited.find(r_) != visited.end()) continue;
visited.insert(r_);
next_pool.insert(r_);
}
visited.insert(c_);
}
seq_uhb.push_back(cur_pool);
cur_pool = next_pool;
next_pool.clear();
}
}
void deps_anchor(string const &inst_) {
pool<string> visited;
int stidx = 1;
for (auto &cur_pool: seq_uhb) {
int dep = stidx; // 1 is 1 cycle from instn reg
for (auto &c_: cur_pool) {
loc_per_reg[c_].insert({dep, true});
for (auto &p_: parent_edges[c_]) {
loc_per_reg[p_].insert({dep-1, false});
}
}
stidx++;
}
log("deps_anchor loc_per_reg: %d\n", loc_per_reg.size());
for (auto &itm_: loc_per_reg) {
log("node %s\n", itm_.first.c_str());
for (auto &ele: itm_.second)
log("(%d,%d),", ele.dep, ele.write ? 1 : 0);
log("\n");
}
log("gen uhb:\n");
int i = 0;
for (auto &st_: seq_uhb) {
My_Disjoint_Set<string> locations;
for (auto &s_: st_) {
log("%s\n", s_.c_str());
i++;
locations.ds_makeset(s_);
}
locations.dump_stat();
seq_uhb_sets.push_back(locations);
log("---------\n");
}
log("-~~~~~~ nun of nodes: %d ~~~~~~~~\n", i);
log("%d\n", loc_per_reg.size());
for (auto &itm_: loc_per_reg) {
log("node %s\n", itm_.first.c_str());
for (auto &ele: itm_.second)
log("(%d,%d),", ele.dep, ele.write ? 1 : 0);
log("\n");
}
}
void gen_uhb(string const &inst_) {
pool<string> visited;
pool<string> cur_pool, next_pool;
cur_pool = edges[inst_];
while (!cur_pool.empty()) {
for (auto &c_: cur_pool) {
for (auto &r_: edges[c_]) {
if (visited.find(r_) != visited.end()) continue;
visited.insert(r_);
next_pool.insert(r_);
}
visited.insert(c_);
}
seq_uhb.push_back(cur_pool);
int dep = seq_uhb.size(); // 1 is 1 cycle from instn reg
for (auto &c_: cur_pool) {
loc_per_reg[c_].insert({dep, true});
for (auto &p_: parent_edges[c_]) {
loc_per_reg[p_].insert({dep-1, false});
}
}
cur_pool = next_pool;
next_pool.clear();
}
log("gen uhb:\n");
int i = 0;
for (auto &st_: seq_uhb) {
My_Disjoint_Set<string> locations;
for (auto &s_: st_) {
log("%s\n", s_.c_str());
i++;
locations.ds_makeset(s_);
}
locations.dump_stat();
seq_uhb_sets.push_back(locations);
log("---------\n");
}
log("-~~~~~~ nun of nodes: %d ~~~~~~~~\n", i);
log("%d\n", loc_per_reg.size());
for (auto &itm_: loc_per_reg) {
log("node %s\n", itm_.first.c_str());
for (auto &ele: itm_.second)
log("(%d,%d),", ele.dep, ele.write ? 1 : 0);
log("\n");
}
}
const dict<string, pool<node_info>> get_loc_per_reg() {
return loc_per_reg;
}
void finish(std::ofstream &outfile) {
outfile << "digraph G {\n"
"// aliceblue: RD_ADDR\n"
"// orange: mem\n"
" edge [penwidth=2];"
"\n node [ shape=box, fontsize=20, penwidth=3, fontname=\"roboto\"]; \n rankdir=LR;\n"
"\"annotation\" [pos=\"0,50!\", label=\"black:unconditiona or instn_dep\nblue: wr_data\ngreen: wr_addrs\ngray: rd_addr\ngold: array\ngold1:rd_data\"];\n";
vector<int> grid, cal_h;
grid.resize(depth+2); cal_h.resize(depth+2);
for (auto &n: node_sty) {
int px = column_node.find(n.first) == column_node.end() ? depth+1 : column_node[n.first];
cal_h[px] += 1;
}
int hmax = *std::max_element(cal_h.begin(), cal_h.end());
for (auto &n: node_sty) {
char pos_s[100];
int px = column_node.find(n.first) == column_node.end() ? depth+1 : column_node[n.first];
float t = 2 * hmax / (cal_h[px] + 1);
sprintf(pos_s, " pos=\"%d,%f!\"", px * X_SCALE, t + Y_SCALE * grid[px]);
if (n.second.find("color") == string::npos) {
if (px < color.size())
sprintf(pos_s, "color=\"%s\", pos=\"%d,%f!\"", color[px].c_str(), px * X_SCALE, t + Y_SCALE * grid[px]);
}
grid[px] += 1;
outfile << "\"" << n.first << "\" [" << n.second;
if (n.second.length()) outfile << ",";
outfile << pos_s << "]; \n";
}
pool<pair<string, string>> e_exists;
for (int i = 0; i < sgraph; i++) {
auto epool = subgraphs[i];
outfile << "subgraph cluster" << i << "{ \n";
for (auto &e: epool) {
outfile << "\"" << e.first << "\"->\"" << e.second << "\" [" << edge_sty[e] << "];\n";
e_exists.insert(e);
}
outfile << "label = \"" << subgraph_label[i] << "\"; } \n";
}
for (auto e: edge_sty) {
if (e_exists.find(e.first) == e_exists.end()) {
outfile << "\"" << e.first.first << "\"->\"" << e.first.second << "\" [" << e.second << "];\n";
}
}
outfile << "}\n";
outfile.close();
}
int get_bitwidth(string &s) {
bool b1 = node_map.find(s) == node_map.end();
bool b2 = node_map_mem_.find(s) == node_map_mem_.end();
if (b1 && b2) return -1;
if (!(b1 || b2)) { log("well a sigspec or cell !!\n"); return -1;}
if (!b1)
return node_map[s].size();
else
return node_map_mem_[s]->parameters[ID::WIDTH].as_int();
}
int ismem(const string &s) {
bool b1 = node_map.find(s) == node_map.end();
bool b2 = node_map_mem_.find(s) == node_map_mem_.end();
if (!b1 && b2) return 0;
if (b1 && !b2) return 1;
return -1;
}
};
enum acc_type_ {read, write};
enum hbi_type_ {structural_spatial, structural_temporal, data};
enum hbi_rsrc_type {intercore, intracore};
enum assertion_res_ {proven, cex, error, undetermined, na};
struct hbi_res {
int file_seqno;
hbi_type_ hbi_type;
int i1_idx;
int i2_idx; // instn idx -> type
string i1_loc;
string i2_loc;
bool samecore; // true -> reference order is program order
assertion_res_ assertion_res;
int file_seqno_next;
hbi_res(): file_seqno(-3) {}
// temporal on inter-core, array, request ordered by same core
hbi_res(int file_seqno, hbi_type_ hbi, int i1_idx, int i2_idx, string i1_loc, string i2_loc, int file_seqno_next):
file_seqno(file_seqno), hbi_type(hbi), i1_idx(i1_idx), i2_idx(i2_idx), i1_loc(i1_loc), i2_loc(i2_loc), file_seqno_next(file_seqno_next), samecore(true) {}
hbi_res(int file_seqno, hbi_type_ hbi, int i1_idx, int i2_idx,
string i1_loc, string i2_loc, bool samecore):
file_seqno(file_seqno), hbi_type(hbi), i1_idx(i1_idx), i2_idx(i2_idx), i1_loc(i1_loc), i2_loc(i2_loc), file_seqno_next(-1), samecore(samecore) {}
string tostr() {
char buff[150];
sprintf(buff, "%d,%d,%d,%d,%d,%s,%s,%d", file_seqno, hbi_type, samecore, i1_idx, i2_idx, i1_loc.c_str(), i2_loc.c_str(), file_seqno_next);
return string(buff);
}
static string header() {
char buff[150];
// 0 1 2 3 4 5 6 7
sprintf(buff, "file_#,hbi_type,samecore,i0_type,i1_type,i0_loc,i1_loc,relevant_file_#");
return string(buff);
}
inline bool operator==(const hbi_res& other) const {
return (
file_seqno == other.file_seqno &&
hbi_type == other.hbi_type &&
i1_idx == other.i1_idx &&
i2_idx == other.i2_idx && // instn idx -> type
i1_loc == other.i1_loc &&
i2_loc == other.i2_loc &&
samecore == other.samecore &&
1
);
}
inline unsigned int hash() const {
// return hash_ops<int>::hash(file_seqno);
return mkhash(mkhash(
mkhash(hash_ops<int>::hash(file_seqno),hash_ops<int>::hash(hbi_type)),
mkhash(hash_ops<int>::hash(i1_idx),hash_ops<int>::hash(i2_idx)))
,
mkhash(
mkhash(hash_ops<string>::hash(i1_loc),hash_ops<string>::hash(i2_loc)),
hash_ops<int>::hash(samecore)
));
}
};
PRIVATE_NAMESPACE_END
#endif
| 30.651408 | 157 | 0.613441 | [
"shape",
"vector"
] |
90927dfa62d3a4ada838df32fd171bd87176ba75 | 3,360 | h | C | devices/shutter.h | MouseLightProject/Fetch | 48114d648db6794aae91554310172680b8c5b1af | [
"BSD-3-Clause"
] | 2 | 2015-08-18T18:07:32.000Z | 2016-03-24T23:07:18.000Z | devices/shutter.h | MouseLightProject/MouseLight_Microscope_Software | 48114d648db6794aae91554310172680b8c5b1af | [
"BSD-3-Clause"
] | 57 | 2016-08-17T21:10:51.000Z | 2020-03-11T15:00:51.000Z | devices/shutter.h | MouseLightProject/MouseLight_Microscope_Software | 48114d648db6794aae91554310172680b8c5b1af | [
"BSD-3-Clause"
] | 2 | 2017-10-21T20:17:50.000Z | 2019-12-29T16:27:04.000Z | /*
* Shutter.h
*
* Created on: Apr 19, 2010
* Author: Nathan Clack <clackn@janelia.hhmi.org>
*/
/*
* Copyright 2010 Howard Hughes Medical Institute.
* All rights reserved.
* Use is subject to Janelia Farm Research Campus Software Copyright 1.1
* license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
#pragma once
#include "object.h"
#include "DAQChannel.h"
#include "shutter.pb.h"
#define SHUTTER_DEFAULT_TIMEOUT INFINITY
#define SHUTTER_MAX_CHAN_STRING 32
#define SHUTTER_DEFAULT_OPEN_DELAY_MS 50
namespace fetch
{
bool operator==(const cfg::device::NIDAQShutter& a, const cfg::device::NIDAQShutter& b) ;
bool operator==(const cfg::device::SimulatedShutter& a, const cfg::device::SimulatedShutter& b);
bool operator==(const cfg::device::Shutter& a, const cfg::device::Shutter& b) ;
bool operator!=(const cfg::device::NIDAQShutter& a, const cfg::device::NIDAQShutter& b) ;
bool operator!=(const cfg::device::SimulatedShutter& a, const cfg::device::SimulatedShutter& b);
bool operator!=(const cfg::device::Shutter& a, const cfg::device::Shutter& b) ;
namespace device
{
class IShutter
{
public:
virtual void Set(u8 val) = 0;
virtual void Shut() = 0;
virtual void Open() = 0 ;
};
template<class T>
class ShutterBase:public IShutter,public IConfigurableDevice<T>
{
public:
ShutterBase(Agent *agent) : IConfigurableDevice<T>(agent) {}
ShutterBase(Agent *agent, Config *cfg) :IConfigurableDevice<T>(agent,cfg) {}
};
class NIDAQShutter:public ShutterBase<cfg::device::NIDAQShutter>
{
NIDAQChannel daq;
IDAQPhysicalChannel _do;
public:
NIDAQShutter(Agent *agent);
NIDAQShutter(Agent *agent, Config *cfg);
unsigned int on_attach();
unsigned int on_detach();
virtual void _set_config(Config IN *cfg) {_do.set(cfg->do_channel());}
void Set (u8 val);
void Shut (void);
void Open (void);
void Bind (void); // Binds the digital output channel to the daq task. - called by on_attach()
};
class SimulatedShutter:public ShutterBase<cfg::device::SimulatedShutter>
{
public:
SimulatedShutter(Agent *agent);
SimulatedShutter(Agent *agent, Config *cfg);
unsigned int on_attach() {return 0;}
unsigned int on_detach() {return 0;}
void update(void) {}
void Set (u8 val);
void Shut (void);
void Open (void);
};
class Shutter:public ShutterBase<cfg::device::Shutter>
{
NIDAQShutter *_nidaq;
SimulatedShutter *_simulated;
IDevice *_idevice;
IShutter *_ishutter;
public:
Shutter(Agent *agent);
Shutter(Agent *agent, Config *cfg);
~Shutter();
virtual unsigned int on_attach() {return _idevice->on_attach();}
virtual unsigned int on_detach() {return _idevice->on_detach();}
void _set_config( Config IN *cfg );
void _set_config( const Config &cfg );
void setKind(Config::ShutterType kind);
void Set (u8 val);
void Shut (void);
void Open (void);
};
//end namespace fetch::device
}
}
| 29.217391 | 110 | 0.619643 | [
"object"
] |
9098281a89ee8b26e382e13a85f9b0768e644bec | 2,450 | h | C | RecoTracker/TkTrackingRegions/plugins/GlobalTrackingRegionProducer.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | RecoTracker/TkTrackingRegions/plugins/GlobalTrackingRegionProducer.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | RecoTracker/TkTrackingRegions/plugins/GlobalTrackingRegionProducer.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef RecoTracker_TkTrackingRegions_GlobalTrackingRegionProducer_H
#define RecoTracker_TkTrackingRegions_GlobalTrackingRegionProducer_H
#include "RecoTracker/TkTrackingRegions/interface/TrackingRegionProducer.h"
#include "RecoTracker/TkTrackingRegions/interface/GlobalTrackingRegion.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
class GlobalTrackingRegionProducer : public TrackingRegionProducer {
public:
GlobalTrackingRegionProducer(const edm::ParameterSet& cfg,
edm::ConsumesCollector && iC) {
edm::ParameterSet regionPSet = cfg.getParameter<edm::ParameterSet>("RegionPSet");
thePtMin = regionPSet.getParameter<double>("ptMin");
theOriginRadius = regionPSet.getParameter<double>("originRadius");
theOriginHalfLength = regionPSet.getParameter<double>("originHalfLength");
double xPos = regionPSet.getParameter<double>("originXPos");
double yPos = regionPSet.getParameter<double>("originYPos");
double zPos = regionPSet.getParameter<double>("originZPos");
thePrecise = regionPSet.getParameter<bool>("precise");
theOrigin = GlobalPoint(xPos,yPos,zPos);
}
virtual ~GlobalTrackingRegionProducer(){}
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add<bool>("precise", true);
desc.add<bool>("useMultipleScattering", false);
desc.add<double>("originHalfLength", 21.2);
desc.add<double>("originRadius", 0.2);
desc.add<double>("originXPos", 0.0);
desc.add<double>("originYPos", 0.0);
desc.add<double>("originZPos", 0.0);
desc.add<double>("ptMin", 0.9);
// Only for backwards-compatibility
edm::ParameterSetDescription descRegion;
descRegion.add<edm::ParameterSetDescription>("RegionPSet", desc);
descriptions.add("globalTrackingRegion", descRegion);
}
virtual std::vector<std::unique_ptr<TrackingRegion> > regions(const edm::Event&, const edm::EventSetup&) const override {
std::vector<std::unique_ptr<TrackingRegion> > result;
result.push_back(
std::make_unique<GlobalTrackingRegion>( thePtMin, theOrigin, theOriginRadius, theOriginHalfLength, thePrecise) );
return result;
}
private:
double thePtMin;
GlobalPoint theOrigin;
double theOriginRadius;
double theOriginHalfLength;
bool thePrecise;
};
#endif
| 37.692308 | 123 | 0.740408 | [
"vector"
] |
909f608b42d110aefa2e3ab0a585d782fdb036e7 | 10,104 | h | C | third_party/blink/renderer/platform/geometry/float_point.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | third_party/blink/renderer/platform/geometry/float_point.h | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | third_party/blink/renderer/platform/geometry/float_point.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | /*
* Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2005 Nokia. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_FLOAT_POINT_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_FLOAT_POINT_H_
#include <iosfwd>
#include "build/build_config.h"
#include "third_party/blink/renderer/platform/geometry/float_size.h"
#include "third_party/blink/renderer/platform/geometry/int_point.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/hash_traits.h"
#include "third_party/skia/include/core/SkPoint.h"
#include "ui/gfx/geometry/point3_f.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#if defined(OS_MAC)
typedef struct CGPoint CGPoint;
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#endif
#endif
namespace blink {
class PLATFORM_EXPORT FloatPoint {
DISALLOW_NEW();
public:
constexpr FloatPoint() : x_(0), y_(0) {}
constexpr FloatPoint(float x, float y) : x_(x), y_(y) {}
constexpr explicit FloatPoint(const IntPoint& p) : x_(p.x()), y_(p.y()) {}
explicit FloatPoint(const SkPoint& p) : x_(p.x()), y_(p.y()) {}
constexpr explicit FloatPoint(const FloatSize& s)
: x_(s.width()), y_(s.height()) {}
constexpr explicit FloatPoint(const IntSize& s)
: x_(s.width()), y_(s.height()) {}
constexpr explicit FloatPoint(const gfx::PointF& p) : x_(p.x()), y_(p.y()) {}
constexpr explicit FloatPoint(const gfx::Vector2dF& v)
: x_(v.x()), y_(v.y()) {}
// We also have conversion operators to FloatPoint defined LayoutPoint,
// LayoutSize and DoublePoint.
static constexpr FloatPoint Zero() { return FloatPoint(); }
static FloatPoint NarrowPrecision(double x, double y);
bool IsValid() const {
return x_ != -std::numeric_limits<float>::infinity() &&
y_ != -std::numeric_limits<float>::infinity();
}
constexpr float x() const { return x_; }
constexpr float y() const { return y_; }
void set_x(float x) { x_ = x; }
void set_y(float y) { y_ = y; }
void SetPoint(float x, float y) {
x_ = x;
y_ = y;
}
void Offset(float dx, float dy) {
x_ += dx;
y_ += dy;
}
void Offset(const IntSize& a) {
x_ += a.width();
y_ += a.height();
}
void Offset(const FloatSize& a) {
x_ += a.width();
y_ += a.height();
}
void MoveBy(const IntPoint& a) {
x_ += a.x();
y_ += a.y();
}
void MoveBy(const FloatPoint& a) {
x_ += a.x();
y_ += a.y();
}
void Scale(float sx, float sy) {
x_ *= sx;
y_ *= sy;
}
float Dot(const FloatPoint& a) const { return x_ * a.x() + y_ * a.y(); }
float SlopeAngleRadians() const;
float length() const;
float LengthSquared() const { return x_ * x_ + y_ * y_; }
FloatPoint ExpandedTo(const FloatPoint& other) const;
FloatPoint ShrunkTo(const FloatPoint& other) const;
FloatPoint TransposedPoint() const { return FloatPoint(y_, x_); }
FloatPoint ScaledBy(float scale) const {
return FloatPoint(x_ * scale, y_ * scale);
}
#if defined(OS_MAC)
FloatPoint(const CGPoint&);
operator CGPoint() const;
#endif
explicit operator SkPoint() const { return SkPoint::Make(x_, y_); }
// These are deleted during blink geometry type to gfx migration.
// Use ToGfxPointF(), ToGfxPoint3F() and ToGfxVector2dF() instead.
operator gfx::PointF() const = delete;
operator gfx::Point3F() const = delete;
operator gfx::Vector2dF() const = delete;
String ToString() const;
private:
float x_, y_;
friend struct ::WTF::DefaultHash<blink::FloatSize>;
friend struct ::WTF::HashTraits<blink::FloatSize>;
};
inline FloatPoint& operator+=(FloatPoint& a, const FloatSize& b) {
a.Offset(b.width(), b.height());
return a;
}
inline FloatPoint& operator+=(FloatPoint& a, const FloatPoint& b) {
a.Offset(b.x(), b.y());
return a;
}
inline FloatPoint& operator-=(FloatPoint& a, const FloatSize& b) {
a.Offset(-b.width(), -b.height());
return a;
}
constexpr FloatPoint operator+(const FloatPoint& a, const FloatSize& b) {
return FloatPoint(a.x() + b.width(), a.y() + b.height());
}
constexpr FloatPoint operator+(const FloatPoint& a, const IntSize& b) {
return FloatPoint(a.x() + b.width(), a.y() + b.height());
}
constexpr FloatPoint operator+(const IntPoint& a, const FloatSize& b) {
return FloatPoint(a.x() + b.width(), a.y() + b.height());
}
constexpr FloatPoint operator+(const FloatPoint& a, const FloatPoint& b) {
return FloatPoint(a.x() + b.x(), a.y() + b.y());
}
constexpr FloatPoint operator+(const FloatPoint& a, const IntPoint& b) {
return FloatPoint(a.x() + b.x(), a.y() + b.y());
}
constexpr FloatSize operator-(const FloatPoint& a, const FloatPoint& b) {
return FloatSize(a.x() - b.x(), a.y() - b.y());
}
constexpr FloatSize operator-(const FloatPoint& a, const IntPoint& b) {
return FloatSize(a.x() - b.x(), a.y() - b.y());
}
constexpr FloatPoint operator-(const FloatPoint& a, const FloatSize& b) {
return FloatPoint(a.x() - b.width(), a.y() - b.height());
}
constexpr FloatPoint operator-(const FloatPoint& a) {
return FloatPoint(-a.x(), -a.y());
}
constexpr bool operator==(const FloatPoint& a, const FloatPoint& b) {
return a.x() == b.x() && a.y() == b.y();
}
constexpr bool operator!=(const FloatPoint& a, const FloatPoint& b) {
return !(a == b);
}
inline float operator*(const FloatPoint& a, const FloatPoint& b) {
// dot product
return a.Dot(b);
}
inline IntPoint RoundedIntPoint(const FloatPoint& p) {
return IntPoint(ClampTo<int>(roundf(p.x())), ClampTo<int>(roundf(p.y())));
}
inline IntSize RoundedIntSize(const FloatPoint& p) {
return IntSize(ClampTo<int>(roundf(p.x())), ClampTo<int>(roundf(p.y())));
}
inline IntPoint FlooredIntPoint(const FloatPoint& p) {
return IntPoint(ClampTo<int>(floorf(p.x())), ClampTo<int>(floorf(p.y())));
}
inline IntPoint FlooredIntPoint(const gfx::PointF& p) {
return IntPoint(ClampTo<int>(floorf(p.x())), ClampTo<int>(floorf(p.y())));
}
inline IntPoint CeiledIntPoint(const FloatPoint& p) {
return IntPoint(ClampTo<int>(ceilf(p.x())), ClampTo<int>(ceilf(p.y())));
}
inline IntSize FlooredIntSize(const FloatPoint& p) {
return IntSize(ClampTo<int>(floorf(p.x())), ClampTo<int>(floorf(p.y())));
}
inline FloatSize ToFloatSize(const FloatPoint& a) {
return FloatSize(a.x(), a.y());
}
// Find point where lines through the two pairs of points intersect.
// Returns false if the lines don't intersect.
PLATFORM_EXPORT bool FindIntersection(const FloatPoint& p1,
const FloatPoint& p2,
const FloatPoint& d1,
const FloatPoint& d2,
FloatPoint& intersection);
constexpr gfx::PointF ToGfxPointF(const FloatPoint& p) {
return gfx::PointF(p.x(), p.y());
}
constexpr gfx::Point3F ToGfxPoint3F(const FloatPoint& p) {
return gfx::Point3F(p.x(), p.y(), 0.f);
}
constexpr gfx::Vector2dF ToGfxVector2dF(const FloatPoint& p) {
return gfx::Vector2dF(p.x(), p.y());
}
PLATFORM_EXPORT std::ostream& operator<<(std::ostream&, const FloatPoint&);
PLATFORM_EXPORT WTF::TextStream& operator<<(WTF::TextStream&,
const FloatPoint&);
} // namespace blink
namespace WTF {
template <>
struct DefaultHash<blink::FloatPoint> {
STATIC_ONLY(DefaultHash);
struct Hash {
STATIC_ONLY(Hash);
typedef typename IntTypes<sizeof(float)>::UnsignedType Bits;
static unsigned GetHash(const blink::FloatPoint& key) {
return HashInts(bit_cast<Bits>(key.x()), bit_cast<Bits>(key.y()));
}
static bool Equal(const blink::FloatPoint& a, const blink::FloatPoint& b) {
return bit_cast<Bits>(a.x()) == bit_cast<Bits>(b.x()) &&
bit_cast<Bits>(a.y()) == bit_cast<Bits>(b.y());
}
static const bool safe_to_compare_to_empty_or_deleted = true;
};
};
template <>
struct HashTraits<blink::FloatPoint> : GenericHashTraits<blink::FloatPoint> {
STATIC_ONLY(HashTraits);
static const bool kEmptyValueIsZero = false;
static blink::FloatPoint EmptyValue() {
return blink::FloatPoint(std::numeric_limits<float>::infinity(),
std::numeric_limits<float>::infinity());
}
static void ConstructDeletedValue(blink::FloatPoint& slot, bool) {
slot = blink::FloatPoint(-std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity());
}
static bool IsDeletedValue(const blink::FloatPoint& value) {
return !value.IsValid();
}
};
} // namespace WTF
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GEOMETRY_FLOAT_POINT_H_
| 32.805195 | 79 | 0.676762 | [
"geometry"
] |
90a47cf8684ecd0f1211c7da4962f417bc4b1dc5 | 1,012 | h | C | argos/source/iAnt_pheromone.h | AdaptiveComputationLab/neatfa | ede584b0fe5d1d68f4260761a772a9672c31fd44 | [
"MIT"
] | 1 | 2019-02-15T16:52:45.000Z | 2019-02-15T16:52:45.000Z | argos/source/iAnt_pheromone.h | AdaptiveComputationLab/neatfa | ede584b0fe5d1d68f4260761a772a9672c31fd44 | [
"MIT"
] | null | null | null | argos/source/iAnt_pheromone.h | AdaptiveComputationLab/neatfa | ede584b0fe5d1d68f4260761a772a9672c31fd44 | [
"MIT"
] | 1 | 2019-07-17T22:24:27.000Z | 2019-07-17T22:24:27.000Z | #ifndef IANT_PHEROMONE_H_
#define IANT_PHEROMONE_H_
#include <argos3/core/utility/math/vector2.h>
using namespace argos;
using namespace std;
/*****
* Implementation of the iAnt Pheromone object used by the iAnt CPFA. iAnts build and maintain a list of these pheromone waypoint objects to use during
* the informed search component of the CPFA algorithm.
*****/
class iAnt_pheromone {
public:
/* constructor function */
iAnt_pheromone(CVector2 newLocation, Real newTime, Real newDecayRate);
/* public helper functions */
void Update(Real time);
void Deactivate();
CVector2 GetLocation();
Real GetWeight();
bool IsActive();
void Reset(Real time);
private:
/* pheromone position variables */
CVector2 location;
/* pheromone component variables */
Real lastUpdated;
Real decayRate;
Real weight;
Real threshold;
};
#endif /* IANT_PHEROMONE_H_ */ | 25.3 | 151 | 0.644269 | [
"object"
] |
60fa73aa91ff3fbbe9ec125c41d409149b50abb4 | 592 | h | C | src/DescentEngine/src/Visuals/SpriteVisualList.h | poseidn/KungFoo-legacy | 9b79d65b596acc9dff4725ef5bfab8ecc4164afb | [
"MIT"
] | 1 | 2017-11-24T03:01:31.000Z | 2017-11-24T03:01:31.000Z | src/DescentEngine/src/Visuals/SpriteVisualList.h | poseidn/KungFoo-legacy | 9b79d65b596acc9dff4725ef5bfab8ecc4164afb | [
"MIT"
] | null | null | null | src/DescentEngine/src/Visuals/SpriteVisualList.h | poseidn/KungFoo-legacy | 9b79d65b596acc9dff4725ef5bfab8ecc4164afb | [
"MIT"
] | null | null | null | #pragma once
//#include <boost/tr_container/ptr_vector.hpp>
#include <list>
#include <vector>
#include "LayerPriority.h"
#include "../DataTypes/StaticVector.h"
#include "../DataTypes/StaticList.h"
class SpriteVisual;
// todo: maybe faster to use std :: deque here
typedef std::list<SpriteVisual *> SpriteVisualList;
typedef std::vector<SpriteVisual *> SpriteVisualVector;
typedef StaticVector<SpriteVisual> SpriteVisualSVector;
typedef SpriteVisualSVector::Ref SpriteVisualRef;
//typedef StaticList<SpriteVisual> SpriteVisualSVector;
//typedef SpriteVisualSVector::Ref SpriteVisualRef;
| 26.909091 | 55 | 0.795608 | [
"vector"
] |
880be5e7a8b8a56414da56688f050efc9be3a511 | 4,289 | h | C | roswrap/src/rossimu/kinetic/include/dynamic_reconfigure/config_tools.h | wdross/sick_scan_xd | 4359c3db964972c6e562767525eeec7ecfbc3628 | [
"Apache-2.0"
] | 18 | 2019-12-03T02:34:08.000Z | 2022-01-24T01:36:44.000Z | roswrap/src/rossimu/kinetic/include/dynamic_reconfigure/config_tools.h | wdross/sick_scan_xd | 4359c3db964972c6e562767525eeec7ecfbc3628 | [
"Apache-2.0"
] | 29 | 2021-11-04T03:35:50.000Z | 2022-03-30T08:13:44.000Z | roswrap/src/rossimu/kinetic/include/dynamic_reconfigure/config_tools.h | wdross/sick_scan_xd | 4359c3db964972c6e562767525eeec7ecfbc3628 | [
"Apache-2.0"
] | 17 | 2019-08-14T06:54:01.000Z | 2022-01-19T03:15:53.000Z | #ifndef __DYNAMIC_RECONFIGURE__CONFIG_TOOLS__
#define __DYNAMIC_RECONFIGURE__CONFIG_TOOLS__
#include <string>
#include <vector>
#include <dynamic_reconfigure/Config.h>
#include <dynamic_reconfigure/Group.h>
namespace dynamic_reconfigure
{
class ConfigTools
{
public:
static std::vector<dynamic_reconfigure::BoolParameter> &getVectorForType(dynamic_reconfigure::Config &set, const bool /*val*/)
{
return set.bools;
}
static std::vector<dynamic_reconfigure::IntParameter> &getVectorForType(dynamic_reconfigure::Config &set, const int /*val*/)
{
return set.ints;
}
static std::vector<dynamic_reconfigure::StrParameter> &getVectorForType(dynamic_reconfigure::Config &set, const std::string& /*val*/)
{
return set.strs;
}
static std::vector<dynamic_reconfigure::DoubleParameter> &getVectorForType(dynamic_reconfigure::Config &set, const double /*val*/)
{
return set.doubles;
}
static const std::vector<dynamic_reconfigure::BoolParameter> &getVectorForType(const dynamic_reconfigure::Config &set, const bool /*val*/)
{
return set.bools;
}
static const std::vector<dynamic_reconfigure::IntParameter> &getVectorForType(const dynamic_reconfigure::Config &set, const int /*val*/)
{
return set.ints;
}
static const std::vector<dynamic_reconfigure::StrParameter> &getVectorForType(const dynamic_reconfigure::Config &set, const std::string& /*val*/)
{
return set.strs;
}
static const std::vector<dynamic_reconfigure::DoubleParameter> &getVectorForType(const dynamic_reconfigure::Config &set, const double /*val*/)
{
return set.doubles;
}
static dynamic_reconfigure::BoolParameter makeKeyValuePair(const std::string &name, const bool val)
{
dynamic_reconfigure::BoolParameter param;
param.name = name;
param.value = val ;
return param;
}
static dynamic_reconfigure::IntParameter makeKeyValuePair(const std::string &name, const int val)
{
dynamic_reconfigure::IntParameter param;
param.name = name;
param.value = val ;
return param;
}
static dynamic_reconfigure::StrParameter makeKeyValuePair(const std::string &name, const std::string &val)
{
dynamic_reconfigure::StrParameter param;
param.name = name;
param.value = val ;
return param;
}
static dynamic_reconfigure::DoubleParameter makeKeyValuePair(const std::string &name, const double val)
{
dynamic_reconfigure::DoubleParameter param;
param.name = name;
param.value = val ;
return param;
}
template <class T>
static void appendParameter(dynamic_reconfigure::Config &set, const std::string &name, const T &val)
{
getVectorForType(set, val).push_back(makeKeyValuePair(name, val));
}
template <class VT, class T>
static bool getParameter(const std::vector<VT> &vec, const std::string &name, T &val)
{
for (typename std::vector<VT>::const_iterator i = vec.begin(); i != vec.end(); ++i)
if (i->name == name)
{
val = i->value;
return true;
}
return false;
}
template <class T>
static bool getParameter(const dynamic_reconfigure::Config &set, const std::string &name, T &val)
{
return getParameter(getVectorForType(set, val), name, val);
}
template<class T>
static void appendGroup(dynamic_reconfigure::Config &set, const std::string &name, int id, int parent, const T &val)
{
dynamic_reconfigure::GroupState msg;
msg.name = name;
msg.id= id;
msg.parent = parent;
msg.state = val.state;
set.groups.push_back(msg);
}
template<class T>
static bool getGroupState(const dynamic_reconfigure::Config &msg, const std::string &name, T &val)
{
for(std::vector<dynamic_reconfigure::GroupState>::const_iterator i = msg.groups.begin(); i != msg.groups.end(); ++i)
if(i->name == name)
{
val.state = i->state;
return true;
}
return false;
}
static int size(dynamic_reconfigure::Config &msg)
{
size_t curSize = msg.bools.size() + msg.doubles.size() + msg.ints.size() + msg.strs.size();
return (int)curSize;
}
static void clear(dynamic_reconfigure::Config &msg)
{
msg.bools.clear();
msg.ints.clear();
msg.strs.clear();
msg.doubles.clear();
msg.groups.clear();
}
};
}
#endif
| 28.03268 | 147 | 0.694101 | [
"vector"
] |
881186d18bea884e740eab319333189758b7caab | 736 | c | C | lib/wizards/tiergon/dungeon/monsters/bcamazonian2.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/tiergon/dungeon/monsters/bcamazonian2.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/tiergon/dungeon/monsters/bcamazonian2.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "obj/monster";
reset(arg) {
object weapon;
object armour;
::reset(arg);
if(arg) { return; }
set_level(22);
set_gender(2);
set_name("guard");
set_alias("woman");
set_short("A female guard of the Black Circle");
set_long("This stunningly beautiful woman is a member of the commander's personal bodyguard.\n He's a lucky bastard.\n");
set_al(-30);
set_aggressive(1);
set_race("human");
set_block_dir("west");
weapon = clone_object("/wizards/tiergon/eq/bcsword");
move_object(weapon, this_object());
init_command("wield pick");
armour = clone_object("/wizards/tiergon/eq/bcplate");
move_object(armour, this_object());
init_command("wear plate");
}
| 26.285714 | 125 | 0.654891 | [
"object"
] |
881320e6805ccd73988585e2e299ea88c73c79de | 457 | h | C | FRY/Touch/FRYPointInTime.h | Raizlabs/FRY | 7a29e57226d3775329cf3ef2c92c54bb3b4f225f | [
"MIT"
] | 17 | 2015-01-12T17:15:22.000Z | 2017-05-13T10:49:38.000Z | FRY/Touch/FRYPointInTime.h | Rightpoint/FRY | 7a29e57226d3775329cf3ef2c92c54bb3b4f225f | [
"MIT"
] | 3 | 2015-02-25T01:15:29.000Z | 2015-04-08T02:20:09.000Z | FRY/Touch/FRYPointInTime.h | Rightpoint/FRY | 7a29e57226d3775329cf3ef2c92c54bb3b4f225f | [
"MIT"
] | 5 | 2015-01-21T16:09:42.000Z | 2019-03-03T15:39:22.000Z | //
// PointInTime.h
// FRY
//
// Created by Brian King on 10/3/14.
// Copyright (c) 2014 Raizlabs. All rights reserved.
//
@import UIKit;
/**
* Simple model object associating a point in time.
*/
@interface FRYPointInTime : NSObject
- (id)initWithLocation:(CGPoint)location offset:(NSTimeInterval)offset;
@property (assign, nonatomic) CGPoint location;
@property (assign, nonatomic) NSTimeInterval offset;
- (NSArray *)arrayRepresentation;
@end
| 19.041667 | 71 | 0.722101 | [
"object",
"model"
] |
881a25175351d7ad6e69dbc5e1069e22381f4e69 | 1,380 | h | C | Engine/Utility/MeshSampler.h | techmatt/Provincial | 3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2 | [
"MIT"
] | 27 | 2015-09-03T18:41:03.000Z | 2022-01-17T20:38:54.000Z | Engine/Utility/MeshSampler.h | techmatt/Provincial | 3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2 | [
"MIT"
] | null | null | null | Engine/Utility/MeshSampler.h | techmatt/Provincial | 3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2 | [
"MIT"
] | 8 | 2015-02-23T10:04:30.000Z | 2020-09-04T10:56:22.000Z |
struct MeshSample
{
Vec3f pos;
Vec3f normal;
};
struct MeshUVSample
{
UINT meshIndex;
UINT triangleIndex;
Vec2f uv;
Vec3f pos;
Vec3f normal;
};
class MeshSampler
{
public:
static void Sample(const BaseMesh &m, UINT sampleCount, Vector<MeshSample> &samples);
static void Sample(const Vector< pair<const BaseMesh *, Matrix4> > &geometry, UINT sampleCount, Vector<MeshSample> &samples);
static void Sample(const BaseMesh &m, UINT& sampleCount, float densityThresh, const Vec3f &direction, float targetOrientation, float orientThresh, Vector<MeshUVSample> &samples);
static void Sample(const Vector< pair<const BaseMesh *, Matrix4> > &geometry, UINT sampleCount, float densityThresh, const Vec3f &direction, float targetOrientation, float orientThresh, Vector<MeshUVSample> &samples);
private:
static double DirectionalSurfaceArea(const BaseMesh &m, const Vec3f &direction, float targetOrientation, float orientThresh);
static float GetTriangleArea(const BaseMesh &m, UINT triangleIndex);
static Vec3f GetTriangleNormal(const BaseMesh &m, UINT triangleIndex);
static MeshSample SampleTriangle(const BaseMesh &m, UINT triangleIndex, double sampleValue);
static MeshUVSample SampleTriangleUV(const BaseMesh &m, UINT triangleIndex, double sampleValue);
static Vec2f StratifiedSample2D(double s, UINT depth = 0);
}; | 41.818182 | 221 | 0.762319 | [
"geometry",
"vector"
] |
881f2a5dafbe0c0ebd17e361b55df5d333830d57 | 2,578 | h | C | src/Generic/edt/discmodel/featuretypes/HWMatchGPEModMatchFT.h | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Generic/edt/discmodel/featuretypes/HWMatchGPEModMatchFT.h | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Generic/edt/discmodel/featuretypes/HWMatchGPEModMatchFT.h | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#ifndef HW_MATCH_GPEMODMATCH_FT_H
#define HW_MATCH_GPEMODMATCH_FT_H
#include "Generic/common/Symbol.h"
#include "Generic/common/SymbolConstants.h"
#include "Generic/edt/discmodel/DTCorefFeatureType.h"
#include "Generic/discTagger/DTMonogramFeature.h"
#include "Generic/discTagger/DTState.h"
#include "Generic/edt/discmodel/DTCorefObservation.h"
#include "Generic/edt/DescLinkFeatureFunctions.h"
#include "Generic/theories/EntitySet.h"
#include "Generic/theories/Mention.h"
class HWMatchGPEModMatchFT : public DTCorefFeatureType {
public:
HWMatchGPEModMatchFT() : DTCorefFeatureType(Symbol(L"p1desclinker-hw-match-gpe-mod-match")) {
}
virtual DTFeature *makeEmptyFeature() const {
return _new DTMonogramFeature(this, SymbolConstants::nullSymbol);
}
virtual int extractFeatures(const DTState &state,
DTFeature **resultArray) const
{
DTCorefObservation *o = static_cast<DTCorefObservation*>(
state.getObservation(0));
Symbol results[5];
const Mention* thismention = o->getMention();
const MentionSet* thismentionset = o->getMentionSet();
Entity* thisentity = o->getEntity();
const EntitySet* thisentityset = o->getEntitySet();
bool val = DescLinkFeatureFunctions::testHeadWordMatch( thismention, thisentity,
thisentityset );
if(!val)
return 0;
std::vector<const Mention*> mention_gpe_names = DescLinkFeatureFunctions::getGPEModNames(thismention);
if (mention_gpe_names.empty()) {
return 0;
}
//get Entity Names
int nment_in_ent = thisentity->getNMentions();
Symbol name_buffer_1[10];
Symbol name_buffer_2[10];
for(int i=0; i<nment_in_ent; i++){
Mention* m = thisentityset->getMention(thisentity->getMention(i));
std::vector<const Mention*> entity_gpe_names = DescLinkFeatureFunctions::getModNames(m);
for(size_t j=0; j< entity_gpe_names.size(); j++){
//get gpe_name
int n1 = entity_gpe_names[j]->getNode()->getTerminalSymbols(name_buffer_1,10);
for(size_t k=0; k<mention_gpe_names.size(); k++){
int n2 = mention_gpe_names[k]->getNode()->getTerminalSymbols(name_buffer_2, 10);
if(n1 == n2){
bool allmatch = true;
for(int p = 0; p< n1; p++){
if(name_buffer_1[p] != name_buffer_2[p]){
allmatch = false;
break;
}
}
if(allmatch){
resultArray[0] = _new DTMonogramFeature(this, state.getTag());
return 1;
}
}
}
}
}
return 0;
}
};
#endif
| 31.060241 | 105 | 0.687742 | [
"vector"
] |
8825bf8712c9b54b1f96ee6637a3e4893f55be6c | 2,187 | h | C | GUI/SettingsBlock.h | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | GUI/SettingsBlock.h | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | GUI/SettingsBlock.h | jwillemsen/sidecar | 941d9f3b84d05ca405df1444d4d9fd0bde03887f | [
"MIT"
] | null | null | null | #ifndef SIDECAR_GUI_SETTINGSBLOCK_H // -*- C++ -*-
#define SIDECAR_GUI_SETTINGSBLOCK_H
#include "QtCore/QObject"
namespace SideCar {
namespace GUI {
class Setting;
/** Base class for a collection of Setting objects that conceptually belong together as a unit. The
SettingsBlock::add() method allows one to add a Setting object to it. SettingsBlock objects do not keep
around pointers to the added Setting objects, rather the SettingsBlock object will receive notification via
its postSettingChanged() slot when a Setting object changes its held value. The postSettingChanged() method
will register a one-shot QTimer object that will invoke the emitSettingChanged() slot as soon as the
application's event loop is reentered. Only one QTime registration will take place, regardless of how many
setting changes there are before the application's event loop is entered.
*/
class SettingsBlock : public QObject {
Q_OBJECT
using Super = QObject;
public:
/** Constructor.
*/
SettingsBlock(QObject* parent = 0) : Super(parent), pendingNotification_(false) {}
signals:
/** Notification sent out when a registered value has changed.
*/
void settingChanged();
protected slots:
/** Notification handler invoked when a Setting object that was registered with one of the add() methods
emits its valueChanged() signal. Sets up a QTimer to call emitSettingChanged() when the application
event loop had nothing more to do. The emitSettingChanged() resets the one-shot boolean
pendingNotification_ attribute and then emits the settingChanged() signal.
*/
virtual void postSettingChanged();
/** Notification handler invoked when the QTimer object registered by the postSettingChanged() method fires.
Resets the pendingNotification_ attribute and emits the settingChanged() signal.
*/
virtual void emitSettingChanged();
protected:
/** Relate a Setting object to this SettingsBlock object.
\param setting the object to connect
*/
void add(Setting* setting);
private:
bool pendingNotification_;
};
} // end namespace GUI
} // end namespace SideCar
#endif
| 34.171875 | 112 | 0.738455 | [
"object"
] |
88280af1eb454174da2fa223c68ff4d600f860a0 | 7,629 | h | C | toonz/sources/include/tcg/pool.h | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/include/tcg/pool.h | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/include/tcg/pool.h | ss23/opentoonz | b42e43d4b8d9fedc26022d145218b9a147a30985 | [
"BSD-3-Clause"
] | 1 | 2019-10-07T17:12:30.000Z | 2019-10-07T17:12:30.000Z |
#ifndef TCG_POOL_H
#define TCG_POOL_H
// STD includes
#include "assert.h"
#include <vector>
#include <algorithm>
#include <functional>
// Discriminate rvalues support - either use Boost's config.hpp for automatic lookup,
// or deal with it manually
#ifndef TCG_RVALUES_SUPPORT
#include <boost/config.hpp>
#ifdef BOOST_NO_RVALUE_REFERENCES
#define TCG_RVALUES_SUPPORT 0
#else
#define TCG_RVALUES_SUPPORT 1
#endif
#endif
/*!
\file pool.h
\brief This file contains an implementation of the \a pool container concept.
\details A pool is a container that supports two fundamental operations, acquire() and
release(), whose purpose is that of marking access operations to a resource
that <I>should not be destroyed</I> when the access operation ends.
Creation and destruction of resources can be a time-consuming task that could
be avoided when it is known that resources could be reused - which is the very
reason why caching can be a useful approach to some problems.
The classical cache concept is nothing more than that of a standard associative
map, tweaked to accomodate specific commodities - such as managing the cache
size.
However, sometimes resources could be considered to be effectively indentical,
to the point that assigning a key is merely a way to keep the objects
distinct in the cache. Users are in the condition to require only two functions,
one to acquire() a resource, the other to release() it.
The Pool concept we are introducing satisfies the following ruleset:
<UL>
<LI> The pool is a dynamical container which allocates resources by invoking the
objects' default constructor. </LI>
<LI> Objects in the pool are \b not destructed, except when the pool is explicitly
\a squeezed by the user.</LI>
<LI> Keys are indices, returned by the pool with an incremental ordering. </LI>
<LI> An object which has been acquired cannot be acquired again until it has been
released </LI>
</UL>
*/
namespace tcg
{
//****************************************************************************
// TCG Indices Pool class
//****************************************************************************
template <typename T = size_t, typename Cont = std::vector<T>>
class indices_pool
{
public:
typedef T value_type;
typedef Cont container_type;
private:
T m_start; //!< First index to be acquired
T m_size; //!< Current indices count
Cont m_releasedIndices; //!< Priority queue of released indices
public:
indices_pool(value_type start = 0) : m_start(start), m_size(0) {}
~indices_pool() {}
template <typename iter>
indices_pool(value_type size, iter releasedBegin, iter releasedEnd, value_type start = 0)
: m_start(start), m_size(size), m_releasedIndices(releasedBegin, releasedEnd)
{
std::make_heap(m_releasedIndices.begin(), m_releasedIndices.end(), std::greater<T>());
}
template <typename iter>
indices_pool(iter acquiredBegin, iter acquiredEnd, value_type start = 0)
: m_start(start)
{
if (acquiredBegin == acquiredEnd)
m_size = 0;
else {
// Sort the acquired indices
std::vector<T> acquired(acquiredBegin, acquiredEnd);
std::sort(acquired.begin(), acquired.end());
assert(acquired.front() >= m_start);
// Scan them, adding holes in the acquired sequence to released indices
m_size = acquired.back() - m_start + 1;
assert(m_size >= (T)acquired.size());
m_releasedIndices.reserve(m_size - acquired.size());
T curIdx = m_start;
typename std::vector<T>::iterator at, aEnd(acquired.end());
for (at = acquired.begin(); at != aEnd; ++at, ++curIdx)
for (; curIdx != *at; ++curIdx)
m_releasedIndices.push_back(curIdx);
std::make_heap(m_releasedIndices.begin(), m_releasedIndices.end(), std::greater<T>());
}
}
value_type size() const { return m_size; }
value_type releasedSize() const { return m_releasedIndices.size(); }
value_type acquiredSize() const { return size() - releasedSize(); }
const container_type &releasedIndices() const { return m_releasedIndices; }
value_type acquire()
{
if (!m_releasedIndices.empty()) {
value_type idx = m_releasedIndices.front();
pop_heap(m_releasedIndices.begin(), m_releasedIndices.end(), std::greater<T>());
m_releasedIndices.pop_back();
return idx;
}
return m_start + m_size++;
}
void release(value_type idx)
{
m_releasedIndices.push_back(idx);
push_heap(m_releasedIndices.begin(), m_releasedIndices.end(), std::greater<T>());
}
void clear()
{
m_size = 0;
m_releasedIndices.clear();
}
//! Removes pool entries whose index is beyond that of the last acquired one.
void squeeze()
{
if (m_releasedIndices.empty())
return;
std::sort_heap(m_releasedIndices.begin(), m_releasedIndices.end(), std::greater<T>()); // O(n logn)
// Decrease the pool size as long as the back items are unused
T lastIndex = m_start + m_size - 1;
typename Cont::iterator ut, uEnd(m_releasedIndices.end());
for (ut = m_releasedIndices.begin(); ut != uEnd && *ut == lastIndex; ++ut)
--lastIndex, --m_size;
if (ut != m_releasedIndices.begin())
m_releasedIndices.swap(Cont(ut, uEnd));
std::make_heap(m_releasedIndices.begin(), m_releasedIndices.end(), std::greater<T>()); // O(n)
}
#if (TCG_RVALUES_SUPPORT > 0)
indices_pool(const indices_pool &other)
: m_start(other.m_start), m_size(other.m_size), m_releasedIndices(other.m_releasedIndices)
{
}
indices_pool &operator=(const indices_pool &other)
{
m_start = other.m_start, m_size = other.m_size, m_releasedIndices = other.m_releasedIndices;
return *this;
}
indices_pool(indices_pool &&other)
: m_start(other.m_start), m_size(other.m_size), m_releasedIndices(std::forward<container_type &&>(other.m_releasedIndices)) {}
indices_pool &operator=(indices_pool &&other)
{
m_start = other.m_start, m_size = other.m_size;
m_releasedIndices = std::forward<container_type &&>(other.m_releasedIndices);
return *this;
}
#endif
};
//----------------------------------------------------------------
template <typename T, typename Cont = std::vector<T>>
class pool
{
public:
typedef T value_type;
typedef Cont container_type;
typedef size_t size_type;
private:
Cont m_objects; //!< Objects in the pool
tcg::indices_pool<size_t> m_indices; //!< Indices Pool representing m_objects
public:
pool() {}
~pool() {}
const tcg::indices_pool<size_t> &indices() const { return m_indices; }
size_type size() const
{
assert(m_indices.size() <= m_objects.size());
return m_objects.size();
}
size_type releasedSize() const { return m_objects.size() - m_indices.acquiredSize(); }
size_type acquiredSize() const { return m_indices.acquiredSize(); }
const value_type &operator[](size_type idx) const { return m_objects[idx]; }
value_type &operator[](size_type idx) { return m_objects[idx]; }
size_type acquire()
{
size_t result = m_indices.acquire();
if (result >= m_objects.size()) {
assert(result == m_objects.size());
m_objects.push_back(T());
}
return result;
}
void release(size_type idx) { m_indices.release(idx); }
void releaseAll() { m_indices.clear(); }
void clear()
{
releaseAll();
m_objects.clear();
}
//! Removes pool entries whose index is beyond that of the last acquired one.
void squeeze()
{
m_indices.squeeze();
m_objects.resize(m_indices.size());
}
};
} // namespace tcg
#endif // TCG_POOL_H
| 29.118321 | 128 | 0.674007 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.